diff --git a/cli/internal/webui/server_test.go b/cli/internal/webui/server_test.go index 19a06eaad..e6de29bce 100644 --- a/cli/internal/webui/server_test.go +++ b/cli/internal/webui/server_test.go @@ -8,6 +8,7 @@ import ( "encoding/base64" "encoding/json" "errors" + "fmt" "io" "math/rand/v2" "net" @@ -353,21 +354,83 @@ func TestUnreachableDaemonNamesWhyItWasNotFound(t *testing.T) { } } -func TestStaticAssetsAreCachedButTheShellIsNot(t *testing.T) { +// The shell (index.html) must revalidate by its bytes: Nix gives every +// release's files the same epoch mtime, and two releases' pages can have equal +// sizes, so a date or size validator would keep an old page after an upgrade. +// For generated pairs of pages of equal length written with the same mtime, a +// request carrying the earlier page's ETag (strong or weak) and an old +// If-Modified-Since gets 304 only when the bytes are unchanged, and the new +// bytes otherwise; HEAD answers the same without a body. Hashed assets are +// immutable and may revalidate by date. +func TestTheShellRevalidatesByItsBytesAndAssetsAreImmutable(t *testing.T) { server, _ := newServer(t, nil) + index := filepath.Join(server.dist, "index.html") if err := os.MkdirAll(filepath.Join(server.dist, "assets"), 0o700); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(server.dist, "assets", "index-abc.js"), []byte("1"), 0o600); err != nil { + asset := filepath.Join(server.dist, "assets", "index-abc.js") + if err := os.WriteFile(asset, []byte("1"), 0o600); err != nil { t.Fatal(err) } - for path, cache := range map[string]string{"/": "no-cache", "/assets/index-abc.js": "public, max-age=31536000, immutable"} { + epoch := time.Unix(1, 0) + _ = os.Chtimes(asset, epoch, epoch) + const legacyDate = "Thu, 01 Jan 1970 00:00:01 GMT" + serve := func(method, path string, headers map[string]string) *httptest.ResponseRecorder { + call := request(method, path, server.key) + for name, value := range headers { + call.Header.Set(name, value) + } response := httptest.NewRecorder() - server.ServeHTTP(response, request(http.MethodGet, path, "")) - if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != cache { - t.Errorf("%s: %d with cache %q", path, response.Code, response.Header().Get("Cache-Control")) + server.ServeHTTP(response, call) + return response + } + write := func(page string) { + if err := os.WriteFile(index, []byte(page), 0o600); err != nil { + t.Fatal(err) + } + _ = os.Chtimes(index, epoch, epoch) + } + random := rand.New(rand.NewPCG(3, 4)) + for range 50 { + pick := func() string { return "

" + string(rune('a'+random.IntN(3))) + "

" } + before, after := pick(), pick() + write(before) + first := serve(http.MethodGet, "/", nil) + write(after) + for _, etag := range []string{first.Header().Get("ETag"), "W/" + first.Header().Get("ETag")} { + for _, method := range []string{http.MethodGet, http.MethodHead} { + response := serve(method, "/", map[string]string{"If-None-Match": etag, "If-Modified-Since": legacyDate}) + if response.Header().Get("Cache-Control") != "no-cache" || response.Header().Get("Last-Modified") != "" { + t.Fatalf("shell headers %v", response.Header()) + } + if before == after { + if response.Code != http.StatusNotModified || response.Body.Len() != 0 { + t.Fatalf("%s of an unchanged page with %s: %d", method, etag, response.Code) + } + continue + } + body := after + if method == http.MethodHead { + body = "" + } + if response.Code != http.StatusOK || response.Body.String() != body || response.Header().Get("Content-Length") != fmt.Sprint(len(after)) || response.Header().Get("ETag") == first.Header().Get("ETag") { + t.Fatalf("%s of a changed page with %s: %d %q %v", method, etag, response.Code, response.Body.String(), response.Header()) + } + } } } + if response := serve(http.MethodGet, "/assets/index-abc.js", nil); response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "public, max-age=31536000, immutable" { + t.Errorf("asset: %d with cache %q", response.Code, response.Header().Get("Cache-Control")) + } + if response := serve(http.MethodGet, "/assets/index-abc.js", map[string]string{"If-Modified-Since": legacyDate}); response.Code != http.StatusNotModified { + t.Errorf("asset revalidation by date: %d", response.Code) + } + if err := os.Remove(index); err != nil { + t.Fatal(err) + } + if response := serve(http.MethodGet, "/", nil); response.Code != http.StatusNotFound { + t.Errorf("missing shell: %d", response.Code) + } } func TestMissingBuildNamesTheFix(t *testing.T) { diff --git a/cli/internal/webui/tailnet.go b/cli/internal/webui/tailnet.go index bfe36cc28..1f0d36ad3 100644 --- a/cli/internal/webui/tailnet.go +++ b/cli/internal/webui/tailnet.go @@ -59,7 +59,7 @@ func certificateCovers(domain, name string) bool { // CurrentTailnet asks the tailscale CLI who this machine is, and reports // false when it is not installed, not running or not signed in. func CurrentTailnet(ctx context.Context) (Tailnet, bool) { - out, err := runTailscale(ctx, "status", "--json", "--peers=false") + out, err := tailscale(ctx, "status", "--json", "--peers=false") if err != nil { return Tailnet{}, false } @@ -107,7 +107,7 @@ func (s Serve) Claim(ctx context.Context) (*url.URL, error) { if root.ours == "" { // tailscale serve exits 0 after printing how to enable HTTPS when // the tailnet has not, so the config read back is the answer. - output, err := runTailscale(ctx, "serve", "--bg", "--https=443", s.target) + output, err := tailscale(ctx, "serve", "--bg", "--https=443", s.target) if err == nil { root, err = s.root(ctx) } @@ -135,12 +135,12 @@ func (s Serve) Release(ctx context.Context) error { if err != nil || root.ours == "" { return err } - _, err = runTailscale(ctx, "serve", "--https=443", "--set-path", "/", "off") + _, err = tailscale(ctx, "serve", "--https=443", "--set-path", "/", "off") return err } func (s Serve) root(ctx context.Context) (serveRoot, error) { - status, err := runTailscale(ctx, "serve", "status", "--json") + status, err := tailscale(ctx, "serve", "status", "--json") if err != nil { return serveRoot{}, err } @@ -194,6 +194,9 @@ func parseServeRoot(status []byte, target string) (serveRoot, error) { return serveRoot{busy: busy}, nil } +// tailscale runs a tailscale command; tests replace it with a fake tailscaled. +var tailscale = runTailscale + // runTailscale runs the tailscale CLI, keeping its own message on failure, // which names the fix (not signed in, https off, no permission). func runTailscale(ctx context.Context, args ...string) (string, error) { diff --git a/cli/internal/webui/tailnet_serve_test.go b/cli/internal/webui/tailnet_serve_test.go index f3e8988af..d12275f1d 100644 --- a/cli/internal/webui/tailnet_serve_test.go +++ b/cli/internal/webui/tailnet_serve_test.go @@ -1,13 +1,19 @@ package webui import ( + "context" + "encoding/json" + "errors" + "fmt" "reflect" + "slices" + "strings" "testing" ) // parseServeRoot decides whether --tailnet-https may take tailscale's https // root, so a misread entry would replace someone else's config or publish -// albedo through Funnel. e2e/web_test.py drives the claim end to end. +// albedo through Funnel. e2e/web_test.py drives the flag end to end. func TestParseServeRoot(t *testing.T) { const ours = `"albedo.example.ts.net:443":{"Handlers":{"/":{"Proxy":"http://127.0.0.1:4317"}}}` for _, test := range []struct { @@ -78,3 +84,81 @@ func TestServeHTTPSNeedsACertificate(t *testing.T) { }) } } + +// fakeTailscaled keeps a serve config the way tailscaled does, answering the +// four commands Claim and Release run. +type fakeTailscaled struct { + serve map[string]any + // flaky loses the status read right after a serve command, as when + // tailscaled restarts under it. + flaky bool + lost bool + calls []string +} + +func (f *fakeTailscaled) run(_ context.Context, args ...string) (string, error) { + f.calls = append(f.calls, strings.Join(args, " ")) + switch { + case slices.Equal(args, []string{"serve", "status", "--json"}): + if f.lost { + f.lost = false + return "", errors.New("tailscaled went away") + } + encoded, _ := json.Marshal(f.serve) + return string(encoded), nil + case len(args) == 4 && slices.Equal(args[:3], []string{"serve", "--bg", "--https=443"}): + f.serve = map[string]any{"TCP": map[string]any{"443": map[string]any{"HTTPS": true}}, "Web": map[string]any{"albedo.example.ts.net:443": map[string]any{"Handlers": map[string]any{"/": map[string]any{"Proxy": args[3]}}}}} + f.lost, f.flaky = f.flaky, false + return "", nil + case slices.Equal(args, []string{"serve", "--https=443", "--set-path", "/", "off"}): + f.serve = map[string]any{} + return "", nil + } + return "", fmt.Errorf("unexpected tailscale %v", args) +} + +func withTailscaled(t *testing.T, fake *fakeTailscaled) { + t.Helper() + previous := tailscale + tailscale = fake.run + t.Cleanup(func() { tailscale = previous }) +} + +// --tailnet-https publishes the root through tailscale serve and --stop takes +// it back; a root Funnel opens to the internet is refused untouched; and a +// handler created but not confirmed is removed before the refusal. +func TestServeClaimsAndReleasesTheRootOnlyWhenItsOwn(t *testing.T) { + serve := NewServe(4317) + fake := &fakeTailscaled{serve: map[string]any{}} + withTailscaled(t, fake) + origin, err := serve.Claim(t.Context()) + if err != nil || origin.String() != "https://albedo.example.ts.net" { + t.Fatalf("claim: %v %v", origin, err) + } + proxy := fake.serve["Web"].(map[string]any)["albedo.example.ts.net:443"].(map[string]any)["Handlers"].(map[string]any)["/"].(map[string]any)["Proxy"] + if proxy != "http://127.0.0.1:4317" { + t.Fatalf("published %v", proxy) + } + if err := serve.Release(t.Context()); err != nil || len(fake.serve) != 0 { + t.Fatalf("release left %v: %v", fake.serve, err) + } + + funnel := map[string]any{"Web": map[string]any{"albedo.example.ts.net:443": map[string]any{"Handlers": map[string]any{"/": map[string]any{"Proxy": "http://127.0.0.1:4317"}}}}, "AllowFunnel": map[string]any{"albedo.example.ts.net:443": true}} + fake = &fakeTailscaled{serve: funnel} + withTailscaled(t, fake) + if _, err := serve.Claim(t.Context()); err == nil || !strings.Contains(err.Error(), "AllowFunnel") { + t.Fatalf("a Funnel root was claimed: %v", err) + } + if len(fake.calls) != 1 { + t.Fatalf("a refused claim changed tailscale: %v", fake.calls) + } + + fake = &fakeTailscaled{serve: map[string]any{}, flaky: true} + withTailscaled(t, fake) + if _, err := serve.Claim(t.Context()); err == nil || !strings.Contains(err.Error(), "tailscaled went away") { + t.Fatalf("an unconfirmed handler was kept: %v", err) + } + if len(fake.serve) != 0 { + t.Fatalf("the unconfirmed handler stayed: %v", fake.serve) + } +} diff --git a/e2e/web_test.py b/e2e/web_test.py index 17834ae9e..6dfdc54f4 100644 --- a/e2e/web_test.py +++ b/e2e/web_test.py @@ -1,9 +1,13 @@ -"""Web lifecycle, sign-in, and cross-release HTML caching through the real CLI/daemon.""" +"""Web lifecycle, sign-in, and the tailnet flag through the real CLI and daemon. + +The shell's revalidation, the tailscale serve claim, and the origin and +network rules are Go tests in cli/internal/webui; these scenarios keep the +background process, its manifest, and the flags reaching them. +""" import http.cookiejar import json import os -import random import re import socket import subprocess @@ -25,27 +29,21 @@ path = os.path.join(root, "state.json") with open(path) as file: state = json.load(file) args = sys.argv[1:] -lost = False with open(os.path.join(root, "calls"), "a") as file: file.write(" ".join(args) + "\\n") if args[:2] == ["status", "--json"]: print(json.dumps({"BackendState": "Running", "Self": {"DNSName": "albedo.example.ts.net."}, "CertDomains": state["certs"]})) elif args == ["serve", "status", "--json"]: - lost = state.pop("lose_status", False) - if not lost: - print(json.dumps(state["serve"])) + print(json.dumps(state["serve"])) elif args[:3] == ["serve", "--bg", "--https=443"]: root = {"Handlers": {"/": {"Proxy": args[3]}}} state["serve"] = {"TCP": {"443": {"HTTPS": True}}, "Web": {"albedo.example.ts.net:443": root}} - state["lose_status"] = state.pop("flaky", False) elif args == ["serve", "--https=443", "--set-path", "/", "off"]: state["serve"] = {} else: sys.exit("unexpected tailscale " + " ".join(args)) with open(path, "w") as file: json.dump(state, file) -if lost: - sys.exit("tailscaled went away") """ @@ -65,10 +63,10 @@ class WebTest(unittest.TestCase): assert match is not None return match[0] - def tailnet(self, serve=None, certs=("albedo.example.ts.net",), **flags): + def tailnet(self): root = Path(tempfile.mkdtemp(dir=self.app.root)) (root / "state.json").write_text( - json.dumps({"serve": serve or {}, "certs": certs, **flags}) + json.dumps({"serve": {}, "certs": ["albedo.example.ts.net"]}) ) script = root / "tailscale" script.write_text(f"#!{sys.executable}\n{FAKE_TAILSCALE}") @@ -77,14 +75,6 @@ class WebTest(unittest.TestCase): self.app.env["PATH"] = f"{root}{os.pathsep}{os.environ['PATH']}" return root - def refused(self, *args): - command = self.app.daemon.start_cli( - "web", "--no-open", *args, stdout=subprocess.PIPE, stderr=subprocess.PIPE - ) - out, err = command.communicate(timeout=60) - self.assertNotEqual(command.returncode, 0, out) - return err.decode() - def browser(self, link): jar = http.cookiejar.CookieJar() client = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar)) @@ -137,87 +127,6 @@ class WebTest(unittest.TestCase): with self.assertRaises(ProcessLookupError, msg="--stop left a busy server"): os.kill(pid, 0) - def test_html_revalidation_tracks_content_not_packaged_mtime(self): - index = self.app.workspace / "index.html" - first = b"

web fixture one

" - second = b"

web fixture two

" - legacy_date = "Thu, 01 Jan 1970 00:00:01 GMT" - index.write_bytes(first) - os.utime(index, (1, 1)) - assets = self.app.workspace / "assets" - assets.mkdir() - asset = assets / "index-abc.js" - asset.write_text("console.log('fixture')") - os.utime(asset, (1, 1)) - link = self.web("--port", "0") - client = self.browser(link) - base = link.split("/?")[0] - - def fetch(path="/", headers=None, method="GET"): - request = urllib.request.Request( - base + path, headers=headers or {}, method=method - ) - try: - response = client.open(request, timeout=3) - except urllib.error.HTTPError as error: - response = error - with response: - return response.status, response.headers, response.read() - - status, before, body = fetch() - self.assertEqual((status, body), (200, first)) - # Nix gives different builds the same timestamp and these pages also - # have equal sizes. Neither is a valid cross-release HTML validator. - index.write_bytes(second) - os.utime(index, (1, 1)) - status, after, body = fetch(headers={"If-Modified-Since": legacy_date}) - self.assertEqual((status, body), (200, second)) - self.assertEqual(after["Cache-Control"], "no-cache") - self.assertNotIn("Last-Modified", after) - self.assertIsNotNone(before["ETag"]) - self.assertIsNotNone(after["ETag"]) - self.assertNotEqual(before["ETag"], after["ETag"]) - - for method, expected in [("GET", second), ("HEAD", b"")]: - with self.subTest(stale_etag=method): - status, headers, body = fetch( - headers={ - "If-None-Match": before["ETag"], - "If-Modified-Since": legacy_date, - }, - method=method, - ) - self.assertEqual((status, body), (200, expected)) - self.assertEqual(headers["ETag"], after["ETag"]) - self.assertEqual(int(headers["Content-Length"]), len(second)) - - for etag in [after["ETag"], "W/" + after["ETag"]]: - with self.subTest(current_etag=etag): - status, headers, body = fetch( - headers={"If-None-Match": etag, "If-Modified-Since": legacy_date} - ) - self.assertEqual((status, body), (304, b"")) - self.assertEqual(headers["Cache-Control"], "no-cache") - - status, headers, body = fetch("/index.html") - self.assertEqual((status, body), (200, second)) - self.assertEqual(headers["ETag"], after["ETag"]) - status, headers, _ = fetch("/assets/index-abc.js") - self.assertEqual(status, 200) - self.assertEqual( - headers["Cache-Control"], "public, max-age=31536000, immutable" - ) - status, _, body = fetch( - "/assets/index-abc.js", {"If-Modified-Since": legacy_date} - ) - self.assertEqual((status, body), (304, b"")) - status, _, body = fetch("/api/server") - self.assertEqual(status, 200) - self.assertEqual(json.loads(body)["state"], "ready") - index.unlink() - status, _, _ = fetch() - self.assertEqual(status, 404) - def test_busy_port_explains_startup_failure_without_waiting(self): with socket.socket() as listener: listener.bind(("127.0.0.1", 0)) @@ -252,51 +161,3 @@ class WebTest(unittest.TestCase): self.assertEqual(proxy, f"http://127.0.0.1:{port}") self.app.cli("web", "--stop") self.assertEqual(json.loads((root / "state.json").read_text())["serve"], {}) - - def test_tailnet_https_refuses_without_changing_tailscale(self): - with self.subTest("no certificate, as on Headscale"): - root = self.tailnet(certs=None) - self.assertIn( - "issues no certificate", self.refused("--tailnet-https", "--port", "0") - ) - self.assertNotIn("serve", (root / "calls").read_text()) - port = free_port_below_ephemeral() - with self.subTest("our root opened to the internet by Funnel"): - funnel = { - "Web": { - "albedo.example.ts.net:443": { - "Handlers": {"/": {"Proxy": f"http://127.0.0.1:{port}"}} - } - }, - "AllowFunnel": {"albedo.example.ts.net:443": True}, - } - root = self.tailnet(serve=funnel) - self.assertIn( - "AllowFunnel", self.refused("--tailnet-https", "--port", str(port)) - ) - self.assertEqual( - json.loads((root / "state.json").read_text())["serve"], funnel - ) - with self.subTest("a handler created but not confirmed"): - root = self.tailnet(flaky=True) - self.assertIn( - "tailscaled went away", - self.refused("--tailnet-https", "--port", str(port)), - ) - self.assertEqual(json.loads((root / "state.json").read_text())["serve"], {}) - self.assertFalse((self.app.home / "web.json").exists()) - - -def free_port_below_ephemeral(): - """A free loopback port below the OS's ephemeral range, so no daemon on - port 0 or outgoing connection takes it between the probe and the CLI's - listen.""" - for _ in range(50): - port = random.randrange(20_000, 30_000) - with socket.socket() as probe: - try: - probe.bind(("127.0.0.1", port)) - except OSError: - continue - return port - raise AssertionError("no free port below the ephemeral range")