Skip to content

Commit ada4de4

Browse files
committed
feat(gateway)!: new trustless mode, and by default
1 parent 322c51e commit ada4de4

File tree

7 files changed

+329
-85
lines changed

7 files changed

+329
-85
lines changed

examples/gateway/common/handler.go

+36-24
Original file line numberDiff line numberDiff line change
@@ -9,34 +9,46 @@ import (
99
)
1010

1111
func NewHandler(gwAPI gateway.IPFSBackend) http.Handler {
12-
// Initialize the headers and gateway configuration. For this example, we do
13-
// not add any special headers, but the required ones.
14-
headers := map[string][]string{}
15-
gateway.AddAccessControlHeaders(headers)
1612
conf := gateway.Config{
17-
Headers: headers,
18-
}
13+
// Initialize the headers. For this example, we do not add any special headers,
14+
// only the required ones via gateway.AddAccessControlHeaders.
15+
Headers: map[string][]string{},
1916

20-
// Initialize the public gateways that we will want to have available through
21-
// Host header rewriting. This step is optional and only required if you're
22-
// running multiple public gateways and want different settings and support
23-
// for DNSLink and Subdomain Gateways.
24-
noDNSLink := false // If you set DNSLink to point at the CID from CAR, you can load it!
25-
publicGateways := map[string]*gateway.Specification{
26-
// Support public requests with Host: CID.ipfs.example.net and ID.ipns.example.net
27-
"example.net": {
28-
Paths: []string{"/ipfs", "/ipns"},
29-
NoDNSLink: noDNSLink,
30-
UseSubdomains: true,
31-
},
32-
// Support local requests
33-
"localhost": {
34-
Paths: []string{"/ipfs", "/ipns"},
35-
NoDNSLink: noDNSLink,
36-
UseSubdomains: true,
17+
// If you set DNSLink to point at the CID from CAR, you can load it!
18+
NoDNSLink: false,
19+
20+
// For these examples we have the trusted mode enabled by default. That is,
21+
// all types of requests will be accepted. By default, only Trustless Gateway
22+
// requests work: https://specs.ipfs.tech/http-gateways/trustless-gateway/
23+
TrustedMode: true,
24+
25+
// Initialize the public gateways that we will want to have available through
26+
// Host header rewriting. This step is optional and only required if you're
27+
// running multiple public gateways and want different settings and support
28+
// for DNSLink and Subdomain Gateways.
29+
PublicGateways: map[string]*gateway.Specification{
30+
// Support public requests with Host: CID.ipfs.example.net and ID.ipns.example.net
31+
"example.net": {
32+
Paths: []string{"/ipfs", "/ipns"},
33+
NoDNSLink: false,
34+
UseSubdomains: true,
35+
// This gateway is used for testing and therefore we make non-trustless
36+
// requests. Thus, we have to manually turn on the trusted mode.
37+
TrustedMode: true,
38+
},
39+
// Support local requests
40+
"localhost": {
41+
Paths: []string{"/ipfs", "/ipns"},
42+
NoDNSLink: false,
43+
UseSubdomains: true,
44+
TrustedMode: true,
45+
},
3746
},
3847
}
3948

49+
// Add required access control headers to the configuration.
50+
gateway.AddAccessControlHeaders(conf.Headers)
51+
4052
// Creates a mux to serve the gateway paths. This is not strictly necessary
4153
// and gwHandler could be used directly. However, on the next step we also want
4254
// to add prometheus metrics, hence needing the mux.
@@ -56,7 +68,7 @@ func NewHandler(gwAPI gateway.IPFSBackend) http.Handler {
5668
// or example.net. If you want to expose the metrics on such gateways,
5769
// you will have to add the path "/debug" to the variable Paths.
5870
var handler http.Handler
59-
handler = gateway.WithHostname(mux, gwAPI, publicGateways, noDNSLink)
71+
handler = gateway.WithHostname(conf, gwAPI, mux)
6072

6173
// Finally, wrap with the withConnect middleware. This is required since we use
6274
// http.ServeMux which does not support CONNECT by default.

gateway/gateway.go

+67-2
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,62 @@ import (
1515

1616
// Config is the configuration used when creating a new gateway handler.
1717
type Config struct {
18+
// Headers is a map containing all the headers that should be sent by default
19+
// in all requests. You can define custom headers, as well as add the recommended
20+
// headers via AddAccessControlHeaders.
1821
Headers map[string][]string
22+
23+
// TrustedMode configures this gateway to allow trusted requests. By default,
24+
// the gateway will operate in trustless mode, as defined in the specification:
25+
// https://specs.ipfs.tech/http-gateways/trustless-gateway/.
26+
//
27+
// This only applies to hostnames not defined under PublicGateways. In addition,
28+
// the hostnames localhost, 127.0.0.1 and ::1 are considered trusted by default.
29+
TrustedMode bool
30+
31+
// NoDNSLink configures the gateway to _not_ perform DNS TXT record lookups in
32+
// response to requests with values in `Host` HTTP header. This flag can be
33+
// overridden per FQDN in PublicGateways. To be used with WithHostname.
34+
NoDNSLink bool
35+
36+
// PublicGateways configures the behavior of known public gateways. Each key is
37+
// a fully qualified domain name (FQDN). To be used with WithHostname.
38+
PublicGateways map[string]*Specification
39+
}
40+
41+
// Specification is the specification of an IPFS Public Gateway.
42+
type Specification struct {
43+
// Paths is explicit list of path prefixes that should be handled by
44+
// this gateway. Example: `["/ipfs", "/ipns"]`
45+
// Useful if you only want to support immutable `/ipfs`.
46+
Paths []string
47+
48+
// UseSubdomains indicates whether or not this gateway uses subdomains
49+
// for IPFS resources instead of paths. That is: http://CID.ipfs.GATEWAY/...
50+
//
51+
// If this flag is set, any /ipns/$id and/or /ipfs/$id paths in Paths
52+
// will be permanently redirected to http://$id.[ipns|ipfs].$gateway/.
53+
//
54+
// We do not support using both paths and subdomains for a single domain
55+
// for security reasons (Origin isolation).
56+
UseSubdomains bool
57+
58+
// NoDNSLink configures this gateway to _not_ resolve DNSLink for the
59+
// specific FQDN provided in `Host` HTTP header. Useful when you want to
60+
// explicitly allow or refuse hosting a single hostname. To refuse all
61+
// DNSLinks in `Host` processing, set NoDNSLink in Config instead. This setting
62+
// overrides the global setting.
63+
NoDNSLink bool
64+
65+
// InlineDNSLink configures this gateway to always inline DNSLink names
66+
// (FQDN) into a single DNS label in order to interop with wildcard TLS certs
67+
// and Origin per CID isolation provided by rules like https://publicsuffix.org
68+
// This should be set to true if you use HTTPS.
69+
InlineDNSLink bool
70+
71+
// TrustedMode configures this gateway to allow trusted requests. This setting
72+
// overrides the global setting. Not setting TrustedMode enables Trustless Mode.
73+
TrustedMode bool
1974
}
2075

2176
// TODO: Is this what we want for ImmutablePath?
@@ -221,7 +276,17 @@ func AddAccessControlHeaders(headers map[string][]string) {
221276
type RequestContextKey string
222277

223278
const (
224-
DNSLinkHostnameKey RequestContextKey = "dnslink-hostname"
279+
// GatewayHostnameKey is the key for the hostname at which the gateway is
280+
// operating. It may be a DNSLink, Subdomain or Regular gateway.
225281
GatewayHostnameKey RequestContextKey = "gw-hostname"
226-
ContentPathKey RequestContextKey = "content-path"
282+
283+
// DNSLinkHostnameKey is the key for the hostname of a DNSLink Gateway:
284+
// https://specs.ipfs.tech/http-gateways/dnslink-gateway/
285+
DNSLinkHostnameKey RequestContextKey = "dnslink-hostname"
286+
287+
// SubdomainHostnameKey is the key for the hostname of a Subdomain Gateway:
288+
// https://specs.ipfs.tech/http-gateways/subdomain-gateway/
289+
SubdomainHostnameKey RequestContextKey = "subdomain-hostname"
290+
291+
ContentPathKey RequestContextKey = "content-path"
227292
)

gateway/gateway_test.go

+133-2
Original file line numberDiff line numberDiff line change
@@ -198,14 +198,20 @@ func newTestServerAndNode(t *testing.T, ns mockNamesys) (*httptest.Server, *mock
198198
}
199199

200200
func newTestServer(t *testing.T, api IPFSBackend) *httptest.Server {
201-
config := Config{Headers: map[string][]string{}}
201+
return newTestServerWithConfig(t, api, Config{
202+
Headers: map[string][]string{},
203+
TrustedMode: true,
204+
})
205+
}
206+
207+
func newTestServerWithConfig(t *testing.T, api IPFSBackend, config Config) *httptest.Server {
202208
AddAccessControlHeaders(config.Headers)
203209

204210
handler := NewHandler(config, api)
205211
mux := http.NewServeMux()
206212
mux.Handle("/ipfs/", handler)
207213
mux.Handle("/ipns/", handler)
208-
handler = WithHostname(mux, api, map[string]*Specification{}, false)
214+
handler = WithHostname(config, api, mux)
209215

210216
ts := httptest.NewServer(handler)
211217
t.Cleanup(func() { ts.Close() })
@@ -544,3 +550,128 @@ func TestGoGetSupport(t *testing.T) {
544550
assert.Nil(t, err)
545551
assert.Equal(t, http.StatusOK, res.StatusCode)
546552
}
553+
554+
func TestIpfsTrustlessMode(t *testing.T) {
555+
api, root := newMockAPI(t)
556+
557+
ts := newTestServerWithConfig(t, api, Config{
558+
Headers: map[string][]string{},
559+
NoDNSLink: false,
560+
PublicGateways: map[string]*Specification{
561+
"trustless.com": {
562+
Paths: []string{"/ipfs", "/ipns"},
563+
},
564+
"trusted.com": {
565+
Paths: []string{"/ipfs", "/ipns"},
566+
TrustedMode: true,
567+
},
568+
},
569+
})
570+
t.Logf("test server url: %s", ts.URL)
571+
572+
trustedFormats := []string{"", "dag-json", "dag-cbor", "tar", "json", "cbor"}
573+
trustlessFormats := []string{"raw", "car"}
574+
575+
doRequest := func(t *testing.T, path, host string, expectedStatus int) {
576+
req, err := http.NewRequest(http.MethodGet, ts.URL+path, nil)
577+
assert.Nil(t, err)
578+
579+
if host != "" {
580+
req.Host = host
581+
}
582+
583+
res, err := doWithoutRedirect(req)
584+
assert.Nil(t, err)
585+
defer res.Body.Close()
586+
assert.Equal(t, expectedStatus, res.StatusCode)
587+
}
588+
589+
doIpfsCidRequests := func(t *testing.T, formats []string, host string, expectedStatus int) {
590+
for _, format := range formats {
591+
doRequest(t, "/ipfs/"+root.String()+"/?format="+format, host, expectedStatus)
592+
}
593+
}
594+
595+
doIpfsCidPathRequests := func(t *testing.T, formats []string, host string, expectedStatus int) {
596+
for _, format := range formats {
597+
doRequest(t, "/ipfs/"+root.String()+"/EmptyDir/?format="+format, host, expectedStatus)
598+
}
599+
}
600+
601+
trustedTests := func(t *testing.T, host string) {
602+
doIpfsCidRequests(t, trustlessFormats, host, http.StatusOK)
603+
doIpfsCidRequests(t, trustedFormats, host, http.StatusOK)
604+
doIpfsCidPathRequests(t, trustlessFormats, host, http.StatusOK)
605+
doIpfsCidPathRequests(t, trustedFormats, host, http.StatusOK)
606+
}
607+
608+
trustlessTests := func(t *testing.T, host string) {
609+
doIpfsCidRequests(t, trustlessFormats, host, http.StatusOK)
610+
doIpfsCidRequests(t, trustedFormats, host, http.StatusNotImplemented)
611+
doIpfsCidPathRequests(t, trustlessFormats, host, http.StatusNotImplemented)
612+
doIpfsCidPathRequests(t, trustedFormats, host, http.StatusNotImplemented)
613+
}
614+
615+
t.Run("Explicit Trustless Gateway", func(t *testing.T) {
616+
t.Parallel()
617+
trustlessTests(t, "trustless.com")
618+
})
619+
620+
t.Run("Explicit Trusted Gateway", func(t *testing.T) {
621+
t.Parallel()
622+
trustedTests(t, "trusted.com")
623+
})
624+
625+
t.Run("Implicit Default Trustless Gateway", func(t *testing.T) {
626+
t.Parallel()
627+
trustlessTests(t, "not.configured.com")
628+
trustlessTests(t, "localhost")
629+
trustlessTests(t, "127.0.0.1")
630+
trustlessTests(t, "::1")
631+
})
632+
}
633+
634+
func TestIpnsTrustlessMode(t *testing.T) {
635+
api, root := newMockAPI(t)
636+
api.namesys["/ipns/trustless.com"] = path.FromCid(root)
637+
api.namesys["/ipns/trusted.com"] = path.FromCid(root)
638+
639+
ts := newTestServerWithConfig(t, api, Config{
640+
Headers: map[string][]string{},
641+
NoDNSLink: false,
642+
PublicGateways: map[string]*Specification{
643+
"trustless.com": {
644+
Paths: []string{"/ipfs", "/ipns"},
645+
},
646+
"trusted.com": {
647+
Paths: []string{"/ipfs", "/ipns"},
648+
TrustedMode: true,
649+
},
650+
},
651+
})
652+
t.Logf("test server url: %s", ts.URL)
653+
654+
doRequest := func(t *testing.T, path, host string, expectedStatus int) {
655+
req, err := http.NewRequest(http.MethodGet, ts.URL+path, nil)
656+
assert.Nil(t, err)
657+
658+
if host != "" {
659+
req.Host = host
660+
}
661+
662+
res, err := doWithoutRedirect(req)
663+
assert.Nil(t, err)
664+
defer res.Body.Close()
665+
assert.Equal(t, expectedStatus, res.StatusCode)
666+
}
667+
668+
// DNSLink only. Not supported for trustless. Supported for trusted, except
669+
// format=ipns-record which is unavailable for DNSLink.
670+
doRequest(t, "/", "trustless.com", http.StatusNotImplemented)
671+
doRequest(t, "/EmptyDir/", "trustless.com", http.StatusNotImplemented)
672+
doRequest(t, "/?format=ipns-record", "trustless.com", http.StatusNotImplemented)
673+
674+
doRequest(t, "/", "trusted.com", http.StatusOK)
675+
doRequest(t, "/EmptyDir/", "trusted.com", http.StatusOK)
676+
doRequest(t, "/?format=ipns-record", "trusted.com", http.StatusBadRequest)
677+
}

gateway/handler.go

+64
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
ipath "github.com/ipfs/boxo/coreiface/path"
2020
cid "github.com/ipfs/go-cid"
2121
logging "github.com/ipfs/go-log"
22+
"github.com/libp2p/go-libp2p/core/peer"
2223
prometheus "github.com/prometheus/client_golang/prometheus"
2324
"go.opentelemetry.io/otel/attribute"
2425
"go.opentelemetry.io/otel/trace"
@@ -227,6 +228,13 @@ func (i *handler) getOrHeadHandler(w http.ResponseWriter, r *http.Request) {
227228
i.addUserHeaders(w) // ok, _now_ write user's headers.
228229
w.Header().Set("X-Ipfs-Path", contentPath.String())
229230

231+
// Trustless gateway.
232+
if !i.isTrustedMode(r) && !i.isValidTrustlessRequest(contentPath, responseFormat) {
233+
err := errors.New("only trustless requests are accepted: https://specs.ipfs.tech/http-gateways/trustless-gateway/")
234+
webError(w, err, http.StatusNotImplemented)
235+
return
236+
}
237+
230238
// TODO: Why did the previous code do path resolution, was that a bug?
231239
// TODO: Does If-None-Match apply here?
232240
if responseFormat == "application/vnd.ipfs.ipns-record" {
@@ -310,6 +318,62 @@ func (i *handler) addUserHeaders(w http.ResponseWriter) {
310318
}
311319
}
312320

321+
func (i *handler) isTrustedMode(r *http.Request) bool {
322+
// Get the host, by default the request's Host. If this request went through
323+
// WithHostname, also check for the key in the context. If that is not present,
324+
// also check X-Forwarded-Host to support reverse proxies.
325+
host := r.Host
326+
if h, ok := r.Context().Value(GatewayHostnameKey).(string); ok {
327+
host = h
328+
} else if xHost := r.Header.Get("X-Forwarded-Host"); xHost != "" {
329+
host = xHost
330+
}
331+
332+
// If the gateway is defined, return whatever is set.
333+
if gw, ok := i.config.PublicGateways[host]; ok {
334+
return gw.TrustedMode
335+
}
336+
337+
// Otherwise, the default.
338+
return i.config.TrustedMode
339+
}
340+
341+
func (i *handler) isValidTrustlessRequest(contentPath ipath.Path, responseFormat string) bool {
342+
// Only allow "/{#1}/{#2}"-like paths.
343+
trimmedPath := strings.Trim(contentPath.String(), "/")
344+
pathComponents := strings.Split(trimmedPath, "/")
345+
if len(pathComponents) != 2 {
346+
return false
347+
}
348+
349+
if contentPath.Namespace() == "ipns" {
350+
// Only ipns records allowed until https://github.com/ipfs/specs/issues/369 is resolved
351+
if responseFormat != "application/vnd.ipfs.ipns-record" {
352+
return false
353+
}
354+
355+
// Only valid peers, no DNSLink.
356+
if _, err := peer.Decode(pathComponents[1]); err != nil {
357+
return false
358+
}
359+
360+
return true
361+
}
362+
363+
// Only valid CIDs.
364+
if _, err := cid.Decode(pathComponents[1]); err != nil {
365+
return false
366+
}
367+
368+
switch responseFormat {
369+
case "application/vnd.ipld.raw",
370+
"application/vnd.ipld.car":
371+
return true
372+
default:
373+
return false
374+
}
375+
}
376+
313377
func panicHandler(w http.ResponseWriter) {
314378
if r := recover(); r != nil {
315379
log.Error("A panic occurred in the gateway handler!")

0 commit comments

Comments
 (0)