gateway_test.go 12.9 KB
Newer Older
1 2 3
package corehttp

import (
Jeromy's avatar
Jeromy committed
4
	"context"
5 6 7 8 9 10
	"errors"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
11
	"time"
12

13 14
	core "github.com/ipfs/go-ipfs/core"
	coreunix "github.com/ipfs/go-ipfs/core/coreunix"
Jeromy's avatar
Jeromy committed
15
	dag "github.com/ipfs/go-ipfs/merkledag"
16
	namesys "github.com/ipfs/go-ipfs/namesys"
17
	path "github.com/ipfs/go-ipfs/path"
18 19
	repo "github.com/ipfs/go-ipfs/repo"
	config "github.com/ipfs/go-ipfs/repo/config"
20
	testutil "github.com/ipfs/go-ipfs/thirdparty/testutil"
Jeromy's avatar
Jeromy committed
21

22 23
	ci "gx/ipfs/QmPGxZ1DP2w45WcogpW1h43BvseXbfke9N91qotpoQcUeS/go-libp2p-crypto"
	id "gx/ipfs/QmeWJwi61vii5g8zQUB9UGegfUbmhTKHgeDFP9XuSp5jZ4/go-libp2p/p2p/protocol/identify"
24 25
)

26 27 28
// `ipfs object new unixfs-dir`
var emptyDir = "/ipfs/QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"

29
type mockNamesys map[string]path.Path
30

31
func (m mockNamesys) Resolve(ctx context.Context, name string) (value path.Path, err error) {
32 33 34 35
	return m.ResolveN(ctx, name, namesys.DefaultDepthLimit)
}

func (m mockNamesys) ResolveN(ctx context.Context, name string, depth int) (value path.Path, err error) {
36
	p, ok := m[name]
37 38 39
	if !ok {
		return "", namesys.ErrResolveFailed
	}
40
	return p, nil
41 42
}

43
func (m mockNamesys) Publish(ctx context.Context, name ci.PrivKey, value path.Path) error {
44 45 46
	return errors.New("not implemented for mockNamesys")
}

47 48 49 50
func (m mockNamesys) PublishWithEOL(ctx context.Context, name ci.PrivKey, value path.Path, _ time.Time) error {
	return errors.New("not implemented for mockNamesys")
}

51
func newNodeWithMockNamesys(ns mockNamesys) (*core.IpfsNode, error) {
52 53 54 55 56 57 58 59 60
	c := config.Config{
		Identity: config.Identity{
			PeerID: "Qmfoo", // required by offline node
		},
	}
	r := &repo.Mock{
		C: c,
		D: testutil.ThreadSafeCloserMapDatastore(),
	}
61
	n, err := core.NewNode(context.Background(), &core.BuildCfg{Repo: r})
62
	if err != nil {
63
		return nil, err
64 65
	}
	n.Namesys = ns
66
	return n, nil
67 68
}

69 70 71 72 73 74 75 76
type delegatedHandler struct {
	http.Handler
}

func (dh *delegatedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	dh.Handler.ServeHTTP(w, r)
}

77 78 79 80 81 82 83 84 85 86
func doWithoutRedirect(req *http.Request) (*http.Response, error) {
	tag := "without-redirect"
	c := &http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return errors.New(tag)
		},
	}
	res, err := c.Do(req)
	if err != nil && !strings.Contains(err.Error(), tag) {
		return nil, err
87
	}
88 89
	return res, nil
}
90

91 92
func newTestServerAndNode(t *testing.T, ns mockNamesys) (*httptest.Server, *core.IpfsNode) {
	n, err := newNodeWithMockNamesys(ns)
93 94 95 96
	if err != nil {
		t.Fatal(err)
	}

97 98 99 100 101 102
	cfg, err := n.Repo.Config()
	if err != nil {
		t.Fatal(err)
	}
	cfg.Gateway.PathPrefixes = []string{"/good-prefix"}

103 104 105 106 107 108 109
	// need this variable here since we need to construct handler with
	// listener, and server with handler. yay cycles.
	dh := &delegatedHandler{}
	ts := httptest.NewServer(dh)

	dh.Handler, err = makeHandler(n,
		ts.Listener,
Lars Gierth's avatar
Lars Gierth committed
110
		VersionOption(),
111
		IPNSHostnameOption(),
Lars Gierth's avatar
Lars Gierth committed
112
		GatewayOption(false, "/ipfs", "/ipns"),
113 114 115 116 117
	)
	if err != nil {
		t.Fatal(err)
	}

118 119 120 121 122 123 124 125 126 127 128 129 130 131
	return ts, n
}

func TestGatewayGet(t *testing.T) {
	ns := mockNamesys{}
	ts, n := newTestServerAndNode(t, ns)
	defer ts.Close()

	k, err := coreunix.Add(n, strings.NewReader("fnord"))
	if err != nil {
		t.Fatal(err)
	}
	ns["/ipns/example.com"] = path.FromString("/ipfs/" + k)

132
	t.Log(ts.URL)
133 134 135 136 137 138 139 140 141
	for _, test := range []struct {
		host   string
		path   string
		status int
		text   string
	}{
		{"localhost:5001", "/", http.StatusNotFound, "404 page not found\n"},
		{"localhost:5001", "/" + k, http.StatusNotFound, "404 page not found\n"},
		{"localhost:5001", "/ipfs/" + k, http.StatusOK, "fnord"},
142
		{"localhost:5001", "/ipns/nxdomain.example.com", http.StatusNotFound, "ipfs cat /ipns/nxdomain.example.com: " + namesys.ErrResolveFailed.Error() + "\n"},
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
		{"localhost:5001", "/ipns/example.com", http.StatusOK, "fnord"},
		{"example.com", "/", http.StatusOK, "fnord"},
	} {
		var c http.Client
		r, err := http.NewRequest("GET", ts.URL+test.path, nil)
		if err != nil {
			t.Fatal(err)
		}
		r.Host = test.host
		resp, err := c.Do(r)

		urlstr := "http://" + test.host + test.path
		if err != nil {
			t.Errorf("error requesting %s: %s", urlstr, err)
			continue
		}
		defer resp.Body.Close()
		if resp.StatusCode != test.status {
			t.Errorf("got %d, expected %d from %s", resp.StatusCode, test.status, urlstr)
			continue
		}
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			t.Fatalf("error reading response from %s: %s", urlstr, err)
		}
		if string(body) != test.text {
			t.Errorf("unexpected response body from %s: expected %q; got %q", urlstr, test.text, body)
			continue
		}
	}
}
174 175 176 177 178 179 180 181 182 183 184 185

func TestIPNSHostnameRedirect(t *testing.T) {
	ns := mockNamesys{}
	ts, n := newTestServerAndNode(t, ns)
	t.Logf("test server url: %s", ts.URL)
	defer ts.Close()

	// create /ipns/example.net/foo/index.html
	_, dagn1, err := coreunix.AddWrapped(n, strings.NewReader("_"), "_")
	if err != nil {
		t.Fatal(err)
	}
Jeromy's avatar
Jeromy committed
186

187 188 189 190
	_, dagn2, err := coreunix.AddWrapped(n, strings.NewReader("_"), "index.html")
	if err != nil {
		t.Fatal(err)
	}
Jeromy's avatar
Jeromy committed
191 192

	dagn1.(*dag.ProtoNode).AddNodeLink("foo", dagn2)
193 194 195 196
	if err != nil {
		t.Fatal(err)
	}

197 198 199 200 201 202
	_, err = n.DAG.Add(dagn2)
	if err != nil {
		t.Fatal(err)
	}

	_, err = n.DAG.Add(dagn1)
203 204 205 206
	if err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
207
	k := dagn1.Cid()
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
	t.Logf("k: %s\n", k)
	ns["/ipns/example.net"] = path.FromString("/ipfs/" + k.String())

	// make request to directory containing index.html
	req, err := http.NewRequest("GET", ts.URL+"/foo", nil)
	if err != nil {
		t.Fatal(err)
	}
	req.Host = "example.net"

	res, err := doWithoutRedirect(req)
	if err != nil {
		t.Fatal(err)
	}

	// expect 302 redirect to same path, but with trailing slash
	if res.StatusCode != 302 {
		t.Errorf("status is %d, expected 302", res.StatusCode)
	}
	hdr := res.Header["Location"]
	if len(hdr) < 1 {
		t.Errorf("location header not present")
	} else if hdr[0] != "/foo/" {
		t.Errorf("location header is %v, expected /foo/", hdr[0])
	}
233 234 235 236 237 238 239

	// make request with prefix to directory containing index.html
	req, err = http.NewRequest("GET", ts.URL+"/foo", nil)
	if err != nil {
		t.Fatal(err)
	}
	req.Host = "example.net"
240
	req.Header.Set("X-Ipfs-Gateway-Prefix", "/good-prefix")
241 242 243 244 245 246 247 248 249 250 251 252 253

	res, err = doWithoutRedirect(req)
	if err != nil {
		t.Fatal(err)
	}

	// expect 302 redirect to same path, but with prefix and trailing slash
	if res.StatusCode != 302 {
		t.Errorf("status is %d, expected 302", res.StatusCode)
	}
	hdr = res.Header["Location"]
	if len(hdr) < 1 {
		t.Errorf("location header not present")
254 255
	} else if hdr[0] != "/good-prefix/foo/" {
		t.Errorf("location header is %v, expected /good-prefix/foo/", hdr[0])
256
	}
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
}

func TestIPNSHostnameBacklinks(t *testing.T) {
	ns := mockNamesys{}
	ts, n := newTestServerAndNode(t, ns)
	t.Logf("test server url: %s", ts.URL)
	defer ts.Close()

	// create /ipns/example.net/foo/
	_, dagn1, err := coreunix.AddWrapped(n, strings.NewReader("1"), "file.txt")
	if err != nil {
		t.Fatal(err)
	}
	_, dagn2, err := coreunix.AddWrapped(n, strings.NewReader("2"), "file.txt")
	if err != nil {
		t.Fatal(err)
	}
	_, dagn3, err := coreunix.AddWrapped(n, strings.NewReader("3"), "file.txt")
	if err != nil {
		t.Fatal(err)
	}
Jeromy's avatar
Jeromy committed
278 279
	dagn2.(*dag.ProtoNode).AddNodeLink("bar", dagn3)
	dagn1.(*dag.ProtoNode).AddNodeLink("foo? #<'", dagn2)
280 281 282 283
	if err != nil {
		t.Fatal(err)
	}

284 285 286 287 288 289 290 291 292
	_, err = n.DAG.Add(dagn3)
	if err != nil {
		t.Fatal(err)
	}
	_, err = n.DAG.Add(dagn2)
	if err != nil {
		t.Fatal(err)
	}
	_, err = n.DAG.Add(dagn1)
293 294 295 296
	if err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
297
	k := dagn1.Cid()
298 299 300 301
	t.Logf("k: %s\n", k)
	ns["/ipns/example.net"] = path.FromString("/ipfs/" + k.String())

	// make request to directory listing
302
	req, err := http.NewRequest("GET", ts.URL+"/foo%3F%20%23%3C%27/", nil)
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
	if err != nil {
		t.Fatal(err)
	}
	req.Host = "example.net"

	res, err := doWithoutRedirect(req)
	if err != nil {
		t.Fatal(err)
	}

	// expect correct backlinks
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		t.Fatalf("error reading response: %s", err)
	}
	s := string(body)
	t.Logf("body: %s\n", string(body))

321
	if !strings.Contains(s, "Index of /foo? #&lt;&#39;/") {
322 323 324 325 326
		t.Fatalf("expected a path in directory listing")
	}
	if !strings.Contains(s, "<a href=\"/\">") {
		t.Fatalf("expected backlink in directory listing")
	}
327
	if !strings.Contains(s, "<a href=\"/foo%3F%20%23%3C%27/file.txt\">") {
328 329 330
		t.Fatalf("expected file in directory listing")
	}

331
	// make request to directory listing at root
332 333 334 335 336 337 338 339 340 341 342
	req, err = http.NewRequest("GET", ts.URL, nil)
	if err != nil {
		t.Fatal(err)
	}
	req.Host = "example.net"

	res, err = doWithoutRedirect(req)
	if err != nil {
		t.Fatal(err)
	}

343
	// expect correct backlinks at root
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
	body, err = ioutil.ReadAll(res.Body)
	if err != nil {
		t.Fatalf("error reading response: %s", err)
	}
	s = string(body)
	t.Logf("body: %s\n", string(body))

	if !strings.Contains(s, "Index of /") {
		t.Fatalf("expected a path in directory listing")
	}
	if !strings.Contains(s, "<a href=\"/\">") {
		t.Fatalf("expected backlink in directory listing")
	}
	if !strings.Contains(s, "<a href=\"/file.txt\">") {
		t.Fatalf("expected file in directory listing")
	}

	// make request to directory listing
362
	req, err = http.NewRequest("GET", ts.URL+"/foo%3F%20%23%3C%27/bar/", nil)
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
	if err != nil {
		t.Fatal(err)
	}
	req.Host = "example.net"

	res, err = doWithoutRedirect(req)
	if err != nil {
		t.Fatal(err)
	}

	// expect correct backlinks
	body, err = ioutil.ReadAll(res.Body)
	if err != nil {
		t.Fatalf("error reading response: %s", err)
	}
	s = string(body)
	t.Logf("body: %s\n", string(body))

381
	if !strings.Contains(s, "Index of /foo? #&lt;&#39;/bar/") {
382 383
		t.Fatalf("expected a path in directory listing")
	}
384
	if !strings.Contains(s, "<a href=\"/foo%3F%20%23%3C%27/\">") {
385 386
		t.Fatalf("expected backlink in directory listing")
	}
387
	if !strings.Contains(s, "<a href=\"/foo%3F%20%23%3C%27/bar/file.txt\">") {
388 389
		t.Fatalf("expected file in directory listing")
	}
390 391 392 393 394 395 396

	// make request to directory listing with prefix
	req, err = http.NewRequest("GET", ts.URL, nil)
	if err != nil {
		t.Fatal(err)
	}
	req.Host = "example.net"
397
	req.Header.Set("X-Ipfs-Gateway-Prefix", "/good-prefix")
398 399 400 401 402 403 404 405 406 407 408 409 410 411

	res, err = doWithoutRedirect(req)
	if err != nil {
		t.Fatal(err)
	}

	// expect correct backlinks with prefix
	body, err = ioutil.ReadAll(res.Body)
	if err != nil {
		t.Fatalf("error reading response: %s", err)
	}
	s = string(body)
	t.Logf("body: %s\n", string(body))

412
	if !strings.Contains(s, "Index of /good-prefix") {
413 414
		t.Fatalf("expected a path in directory listing")
	}
415
	if !strings.Contains(s, "<a href=\"/good-prefix/\">") {
416 417
		t.Fatalf("expected backlink in directory listing")
	}
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
	if !strings.Contains(s, "<a href=\"/good-prefix/file.txt\">") {
		t.Fatalf("expected file in directory listing")
	}

	// make request to directory listing with illegal prefix
	req, err = http.NewRequest("GET", ts.URL, nil)
	if err != nil {
		t.Fatal(err)
	}
	req.Host = "example.net"
	req.Header.Set("X-Ipfs-Gateway-Prefix", "/bad-prefix")

	res, err = doWithoutRedirect(req)
	if err != nil {
		t.Fatal(err)
	}

	// make request to directory listing with evil prefix
	req, err = http.NewRequest("GET", ts.URL, nil)
	if err != nil {
		t.Fatal(err)
	}
	req.Host = "example.net"
	req.Header.Set("X-Ipfs-Gateway-Prefix", "//good-prefix/foo")

	res, err = doWithoutRedirect(req)
	if err != nil {
		t.Fatal(err)
	}

	// expect correct backlinks without illegal prefix
	body, err = ioutil.ReadAll(res.Body)
	if err != nil {
		t.Fatalf("error reading response: %s", err)
	}
	s = string(body)
	t.Logf("body: %s\n", string(body))

	if !strings.Contains(s, "Index of /") {
		t.Fatalf("expected a path in directory listing")
	}
	if !strings.Contains(s, "<a href=\"/\">") {
		t.Fatalf("expected backlink in directory listing")
	}
	if !strings.Contains(s, "<a href=\"/file.txt\">") {
463 464
		t.Fatalf("expected file in directory listing")
	}
465
}
Lars Gierth's avatar
Lars Gierth committed
466

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
func TestCacheControlImmutable(t *testing.T) {
	ts, _ := newTestServerAndNode(t, nil)
	t.Logf("test server url: %s", ts.URL)
	defer ts.Close()

	req, err := http.NewRequest("GET", ts.URL+emptyDir+"/", nil)
	if err != nil {
		t.Fatal(err)
	}

	res, err := doWithoutRedirect(req)
	if err != nil {
		t.Fatal(err)
	}

	// check the immutable tag isn't set
	hdrs, ok := res.Header["Cache-Control"]
	if ok {
		for _, hdr := range hdrs {
			if strings.Contains(hdr, "immutable") {
				t.Fatalf("unexpected Cache-Control: immutable on directory listing: %s", hdr)
			}
		}
	}
}

Lars Gierth's avatar
Lars Gierth committed
493
func TestVersion(t *testing.T) {
494 495
	config.CurrentCommit = "theshortcommithash"

Lars Gierth's avatar
Lars Gierth committed
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
	ns := mockNamesys{}
	ts, _ := newTestServerAndNode(t, ns)
	t.Logf("test server url: %s", ts.URL)
	defer ts.Close()

	req, err := http.NewRequest("GET", ts.URL+"/version", nil)
	if err != nil {
		t.Fatal(err)
	}

	res, err := doWithoutRedirect(req)
	if err != nil {
		t.Fatal(err)
	}
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		t.Fatalf("error reading response: %s", err)
	}
	s := string(body)

516 517 518 519
	if !strings.Contains(s, "Commit: theshortcommithash") {
		t.Fatalf("response doesn't contain commit:\n%s", s)
	}

Lars Gierth's avatar
Lars Gierth committed
520 521 522 523
	if !strings.Contains(s, "Client Version: "+id.ClientVersion) {
		t.Fatalf("response doesn't contain client version:\n%s", s)
	}

524
	if !strings.Contains(s, "Protocol Version: "+id.LibP2PVersion) {
Lars Gierth's avatar
Lars Gierth committed
525 526 527
		t.Fatalf("response doesn't contain protocol version:\n%s", s)
	}
}