package edge import ( "bytes" "context" "crypto/ed25519" "errors" "io" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "sync" "testing" "time" "github.com/carlosframework/platform/internal/apperr" "github.com/carlosframework/platform/internal/registry" "github.com/carlosframework/platform/internal/release" ) // getPath GETs base+path with an explicit Host header (getHost, but with a // request path — static trees are about more URLs than "/"). func getPath(t *testing.T, base, host, path string) (int, string) { t.Helper() req, err := http.NewRequest("GET", base+path, nil) if err != nil { t.Fatalf("new request: %v", err) } req.Host = host resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("GET %s%s (host %s): %v", base, path, host, err) } defer resp.Body.Close() b, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("read body: %v", err) } return resp.StatusCode, string(b) } // getPathResp is getPath's sibling for tests that need the response headers // rather than the body — X-Carlos-Version lives there, not in the tree. func getPathResp(t *testing.T, base, host, path string) *http.Response { t.Helper() req, err := http.NewRequest("GET", base+path, nil) if err != nil { t.Fatalf("new request: %v", err) } req.Host = host resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("GET %s%s (host %s): %v", base, path, host, err) } defer resp.Body.Close() io.Copy(io.Discard, resp.Body) return resp } func testKeys(t *testing.T) (ed25519.PrivateKey, ed25519.PublicKey) { t.Helper() seedB64, pubB64, err := release.GenerateKey() if err != nil { t.Fatalf("generate key: %v", err) } priv, err := release.ParseSigningKey(seedB64, "test") if err != nil { t.Fatalf("parse signing key: %v", err) } pub, err := release.ParsePublicKey(pubB64, "test") if err != nil { t.Fatalf("parse public key: %v", err) } return priv, pub } // writeTree materialises files (rel path -> body) under a fresh temp dir. func writeTree(t *testing.T, files map[string]string) string { t.Helper() dir := t.TempDir() for name, body := range files { p := filepath.Join(dir, filepath.FromSlash(name)) if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { t.Fatalf("mkdir for %s: %v", name, err) } if err := os.WriteFile(p, []byte(body), 0o644); err != nil { t.Fatalf("write %s: %v", name, err) } } return dir } // shipSite packs a tree and ships it as a static release of app@version. func shipSite(t *testing.T, store release.Store, app, version string, files map[string]string) { t.Helper() tarball, err := PackDir(writeTree(t, files)) if err != nil { t.Fatalf("PackDir: %v", err) } m := release.Manifest{ Schema: 1, App: app, Version: version, Kind: "static", Artifacts: map[string]release.Artifact{siteArtifactFile: {}}, } if err := release.Ship(context.Background(), store, release.OpsAccount, m, map[string][]byte{siteArtifactFile: tarball}); err != nil { t.Fatalf("Ship %s %s: %v", app, version, err) } } // staticFixture is a shipped+promoted site behind a fresh static handler // whose pointer cache is disabled (recheck 0: every request re-resolves). func staticFixture(t *testing.T) (release.Store, string, ed25519.PrivateKey, *httptest.Server) { t.Helper() storeRoot := filepath.Join(t.TempDir(), "store") store := release.NewDirStore(storeRoot) priv, pub := testKeys(t) shipSite(t, store, "site", "v1", map[string]string{ "index.html": "home v1", "docs/page.html": "docs v1", "style.css": "body{}", }) if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "canary/x", "v1"); err != nil { t.Fatalf("Promote v1: %v", err) } rt := registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"} h := newStaticHandler(rt, store, pub, filepath.Join(t.TempDir(), "cache")) h.(*staticSite).recheck = 0 // re-check the pointer on every request srv := httptest.NewServer(h) t.Cleanup(srv.Close) return store, storeRoot, priv, srv } func TestServesShippedTree(t *testing.T) { _, _, _, srv := staticFixture(t) for path, want := range map[string]string{ "/": "home v1", // directory -> index.html fallback "/docs/page.html": "docs v1", "/style.css": "body{}", } { code, body := getPath(t, srv.URL, "site.example.com", path) if code != http.StatusOK || body != want { t.Fatalf("GET %s = %d %q, want 200 %q", path, code, body, want) } } if code, _ := getPath(t, srv.URL, "site.example.com", "/missing.html"); code != http.StatusNotFound { t.Fatalf("GET /missing.html = %d, want 404", code) } // A directory with no index.html is a clean 404, never a listing. if code, body := getPath(t, srv.URL, "site.example.com", "/docs/"); code != http.StatusNotFound { t.Fatalf("GET /docs/ = %d %q, want 404 (no index.html, no listing)", code, body) } } func TestChannelAdvanceSwapsContent(t *testing.T) { store, _, priv, srv := staticFixture(t) if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != 200 || body != "home v1" { t.Fatalf("pre-advance GET / = %d %q, want 200 %q", code, body, "home v1") } shipSite(t, store, "site", "v2", map[string]string{"index.html": "home v2"}) if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "canary/x", "v2"); err != nil { t.Fatalf("Promote v2: %v", err) } // recheck is 0, so the very next request re-reads the pointer and swaps. if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != 200 || body != "home v2" { t.Fatalf("post-advance GET / = %d %q, want 200 %q", code, body, "home v2") } // v2's tree has no docs/ — the old version's files must not bleed through. if code, _ := getPath(t, srv.URL, "site.example.com", "/docs/page.html"); code != http.StatusNotFound { t.Fatalf("GET /docs/page.html after advance = %d, want 404", code) } } func TestTamperedTarRejected(t *testing.T) { _, storeRoot, _, srv := staticFixture(t) // Corrupt the stored artifact bytes underneath the store (an attacker or // bit-rot on the bucket): flip one byte in the middle of the tar. artPath := filepath.Join(storeRoot, filepath.FromSlash(release.ArtifactKey(release.OpsAccount, "site", "v1", siteArtifactFile))) raw, err := os.ReadFile(artPath) if err != nil { t.Fatalf("read stored artifact: %v", err) } raw[len(raw)/2] ^= 0xff if err := os.WriteFile(artPath, raw, 0o644); err != nil { t.Fatalf("corrupt stored artifact: %v", err) } code, body := getPath(t, srv.URL, "site.example.com", "/") if code < 500 || code > 599 { t.Fatalf("GET / over tampered tar = %d %q, want 5xx", code, body) } if bytes.Contains([]byte(body), []byte("home v1")) { t.Fatalf("tampered tar was served: %q", body) } } func TestPackDirDeterministic(t *testing.T) { files := map[string]string{ "index.html": "same tree", "b/two.txt": "2", "a/one.txt": "1", } // Two independent checkouts of the same tree must pack byte-identically, // so re-shipping an unchanged site is Ship's idempotent no-op. p1, err := PackDir(writeTree(t, files)) if err != nil { t.Fatalf("PackDir 1: %v", err) } p2, err := PackDir(writeTree(t, files)) if err != nil { t.Fatalf("PackDir 2: %v", err) } if !bytes.Equal(p1, p2) { t.Fatalf("PackDir is not deterministic: %d vs %d bytes differ", len(p1), len(p2)) } } func TestEdgeServesStaticRouteWhenEnabled(t *testing.T) { storeRoot := filepath.Join(t.TempDir(), "store") store := release.NewDirStore(storeRoot) priv, pub := testKeys(t) shipSite(t, store, "site", "v1", map[string]string{"index.html": "via the edge"}) if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "canary/x", "v1"); err != nil { t.Fatalf("Promote: %v", err) } reg := openReg(t) if err := reg.Upsert(registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"}); err != nil { t.Fatalf("upsert: %v", err) } e, err := New(reg, nil) if err != nil { t.Fatalf("New: %v", err) } srv := httptest.NewServer(e) defer srv.Close() // Before EnableStatic the route exists but answers 404 (cert-first shape). if code, _ := getHost(t, srv.URL, "site.example.com"); code != http.StatusNotFound { t.Fatalf("pre-enable GET = %d, want 404", code) } e.EnableStatic(store, pub, filepath.Join(t.TempDir(), "cache")) if err := e.Reload(); err != nil { t.Fatalf("Reload: %v", err) } code, body := getHost(t, srv.URL, "site.example.com") if code != 200 || body != "via the edge" { t.Fatalf("post-enable GET = %d %q, want 200 %q", code, body, "via the edge") } } // --- X-Carlos-Version for static routes (issue #112) -------------------- // // A static route is never adopted, so registry.Route.Version is always empty // and edge.go's versionHeader wrapper never applies. The handler stamps its // own — the version whose tree answered the request. // TestStaticStampsTheVersionItServes: every response out of the site tree // carries the version that tree is, including the tree's own 404s, and the // stamp follows a pointer advance. func TestStaticStampsTheVersionItServes(t *testing.T) { store, _, priv, srv := staticFixture(t) resp := getPathResp(t, srv.URL, "site.example.com", "/") if resp.StatusCode != http.StatusOK { t.Fatalf("GET / = %d, want 200", resp.StatusCode) } if got := resp.Header.Get("X-Carlos-Version"); got != "v1" { t.Fatalf("X-Carlos-Version = %q, want %q", got, "v1") } // A 404 from inside the tree is still an answer from a version — the // deploy watch polls "/" and a site whose root is a 404 must still be // diagnosable as "serving v1, but HTTP 404" rather than as an old edge. resp = getPathResp(t, srv.URL, "site.example.com", "/missing.html") if resp.StatusCode != http.StatusNotFound { t.Fatalf("GET /missing.html = %d, want 404", resp.StatusCode) } if got := resp.Header.Get("X-Carlos-Version"); got != "v1" { t.Fatalf("404 X-Carlos-Version = %q, want %q", got, "v1") } shipSite(t, store, "site", "v2", map[string]string{"index.html": "home v2"}) if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "canary/x", "v2"); err != nil { t.Fatalf("Promote v2: %v", err) } resp = getPathResp(t, srv.URL, "site.example.com", "/") if got := resp.Header.Get("X-Carlos-Version"); got != "v2" { t.Fatalf("post-advance X-Carlos-Version = %q, want %q", got, "v2") } } // brokenStore reads through to a real store until breakNow, then fails every // read — the shape that drives staticSite down its degraded path (an // unreadable channel pointer) after it has already resolved and extracted. type brokenStore struct { release.Store mu sync.Mutex broken bool } func (b *brokenStore) breakNow() { b.mu.Lock() defer b.mu.Unlock() b.broken = true } func (b *brokenStore) failing() bool { b.mu.Lock() defer b.mu.Unlock() return b.broken } func (b *brokenStore) Get(ctx context.Context, key string) ([]byte, string, error) { if b.failing() { return nil, "", errors.New("store unreachable") } return b.Store.Get(ctx, key) } func (b *brokenStore) List(ctx context.Context, prefix string) ([]string, error) { if b.failing() { return nil, errors.New("store unreachable") } return b.Store.List(ctx, prefix) } // TestStaticDegradedStampsTheCachedVersion: when the pointer goes unreadable // the handler keeps serving the version it already verified — and must stamp // THAT, never the head it could not reach. A watch that saw the new version // on a response whose bytes are the old one would be exactly the false // "verified" this header exists to prevent. func TestStaticDegradedStampsTheCachedVersion(t *testing.T) { ctx := context.Background() dir := release.NewDirStore(filepath.Join(t.TempDir(), "store")) priv, pub := testKeys(t) shipSite(t, dir, "site", "v1", map[string]string{"index.html": "home v1"}) if err := release.Promote(ctx, dir, priv, release.OpsAccount, "site", "canary/x", "v1"); err != nil { t.Fatalf("Promote v1: %v", err) } bs := &brokenStore{Store: dir} rt := registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"} h := newStaticHandler(rt, bs, pub, filepath.Join(t.TempDir(), "cache")) h.(*staticSite).recheck = 0 // re-check the pointer on every request srv := httptest.NewServer(h) defer srv.Close() if got := getPathResp(t, srv.URL, "site.example.com", "/").Header.Get("X-Carlos-Version"); got != "v1" { t.Fatalf("pre-break X-Carlos-Version = %q, want %q", got, "v1") } // The pointer advances to v2 and the store goes away in the same breath: // the head is v2, the bytes on disk are v1. shipSite(t, dir, "site", "v2", map[string]string{"index.html": "home v2"}) if err := release.Promote(ctx, dir, priv, release.OpsAccount, "site", "canary/x", "v2"); err != nil { t.Fatalf("Promote v2: %v", err) } bs.breakNow() code, body := getPath(t, srv.URL, "site.example.com", "/") if code != http.StatusOK || body != "home v1" { t.Fatalf("degraded GET / = %d %q, want 200 %q", code, body, "home v1") } if got := getPathResp(t, srv.URL, "site.example.com", "/").Header.Get("X-Carlos-Version"); got != "v1" { t.Fatalf("degraded X-Carlos-Version = %q, want %q (the CACHED version, not the unreachable head)", got, "v1") } } // TestStaticCacheWindowStampsTheCachedVersion: inside the trust window the // handler answers from the version it last resolved WITHOUT re-reading the // pointer, and the stamp has to name that version rather than the head the // pointer has since advanced to. This is the window the deploy watch waits // out, and the reason it can only converge once the recheck lapses. func TestStaticCacheWindowStampsTheCachedVersion(t *testing.T) { ctx := context.Background() dir := release.NewDirStore(filepath.Join(t.TempDir(), "store")) priv, pub := testKeys(t) shipSite(t, dir, "site", "v1", map[string]string{"index.html": "home v1"}) if err := release.Promote(ctx, dir, priv, release.OpsAccount, "site", "canary/x", "v1"); err != nil { t.Fatalf("Promote v1: %v", err) } rt := registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"} h := newStaticHandler(rt, dir, pub, filepath.Join(t.TempDir(), "cache")) h.(*staticSite).recheck = time.Hour // a window no test run can outlive srv := httptest.NewServer(h) defer srv.Close() if got := getPathResp(t, srv.URL, "site.example.com", "/").Header.Get("X-Carlos-Version"); got != "v1" { t.Fatalf("first request X-Carlos-Version = %q, want %q", got, "v1") } shipSite(t, dir, "site", "v2", map[string]string{"index.html": "home v2"}) if err := release.Promote(ctx, dir, priv, release.OpsAccount, "site", "canary/x", "v2"); err != nil { t.Fatalf("Promote v2: %v", err) } code, body := getPath(t, srv.URL, "site.example.com", "/") if code != http.StatusOK || body != "home v1" { t.Fatalf("in-window GET / = %d %q, want 200 %q (the window has not lapsed)", code, body, "home v1") } if got := getPathResp(t, srv.URL, "site.example.com", "/").Header.Get("X-Carlos-Version"); got != "v1" { t.Fatalf("in-window X-Carlos-Version = %q, want %q — the header must name the bytes, not the pointer", got, "v1") } } // TestStaticNeverResolvedHasNoVersionHeader: a handler that has never // resolved anything answers 502, and there is no version to name — stamping // one would be inventing a build out of an empty bucket. func TestStaticNeverResolvedHasNoVersionHeader(t *testing.T) { _, pub := testKeys(t) empty := release.NewDirStore(filepath.Join(t.TempDir(), "store")) // no pointer, no release rt := registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"} h := newStaticHandler(rt, empty, pub, filepath.Join(t.TempDir(), "cache")) h.(*staticSite).recheck = 0 srv := httptest.NewServer(h) defer srv.Close() resp := getPathResp(t, srv.URL, "site.example.com", "/") if resp.StatusCode != http.StatusBadGateway { t.Fatalf("never-resolved GET / = %d, want 502", resp.StatusCode) } if got, ok := resp.Header["X-Carlos-Version"]; ok { t.Fatalf("X-Carlos-Version present (%v) on a handler that has never served a version", got) } // The 502 is the edge's own, and says so: Availability files it as // "the static site could not be read", not as the app answering. req, out := withOutcome(httptest.NewRequest("GET", "http://site.example.com/", nil)) h.ServeHTTP(httptest.NewRecorder(), req) if out.cause != apperr.CauseStatic { t.Fatalf("static 502 cause = %q, want %q", out.cause, apperr.CauseStatic) } } // TestStaticUnconfiguredHasNoVersionHeader: the pre-EnableStatic 404 is not a // version — the route exists (so its cert can be minted) before any bytes can // flow, and there is nothing to name. func TestStaticUnconfiguredHasNoVersionHeader(t *testing.T) { reg := openReg(t) if err := reg.Upsert(registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"}); err != nil { t.Fatalf("upsert: %v", err) } e, err := New(reg, nil) if err != nil { t.Fatalf("New: %v", err) } srv := httptest.NewServer(e) defer srv.Close() resp := getHostHeader(t, srv.URL, "site.example.com") if resp.StatusCode != http.StatusNotFound { t.Fatalf("unconfigured GET = %d, want 404", resp.StatusCode) } if got, ok := resp.Header["X-Carlos-Version"]; ok { t.Fatalf("X-Carlos-Version present (%v) on the unconfigured 404 — no version exists there", got) } } // legacyTripwire fails the test if the edge asks the store for anything under // one app's LEGACY unqualified prefix. The release package has its own; the // edge needs one of its own too, because a tripwire only guards the paths a // test actually routes through it — and the static extract is where a // fallback would put unmigrated bytes in front of real traffic. type legacyTripwire struct { release.Store t *testing.T app string } func (l *legacyTripwire) trip(what, key string) { l.t.Helper() if strings.HasPrefix(key, release.LegacyAppPrefix(l.app)) { l.t.Errorf("the edge %s a legacy key: %s — the read-fallback is retired", what, key) } } func (l *legacyTripwire) Get(ctx context.Context, key string) ([]byte, string, error) { l.trip("read", key) return l.Store.Get(ctx, key) } func (l *legacyTripwire) List(ctx context.Context, prefix string) ([]string, error) { l.trip("listed", prefix) return l.Store.List(ctx, prefix) } // The static extract never falls back to a legacy artifact. The fixture is // the half-migrated shape that makes the read observable: pointer and // manifest qualified (so the handler resolves and gets as far as wanting the // tar), the tar itself only at the legacy key. A fallback reintroduced in // ensureExtracted would serve those bytes; qualified-only serves an error. // // Without this, a fallback in ensureExtracted passes the whole suite. func TestStaticExtractNeverReadsALegacyArtifact(t *testing.T) { ctx := context.Background() dir := release.NewDirStore(filepath.Join(t.TempDir(), "store")) priv, pub := testKeys(t) scratch := release.NewDirStore(filepath.Join(t.TempDir(), "scratch")) shipSite(t, scratch, "site", "v1", map[string]string{"index.html": "legacy bytes"}) if err := release.Promote(ctx, scratch, priv, release.OpsAccount, "site", "canary/x", "v1"); err != nil { t.Fatalf("Promote: %v", err) } keys, err := scratch.List(ctx, release.AppPrefix(release.OpsAccount, "site")) if err != nil { t.Fatal(err) } for _, k := range keys { body, _, err := scratch.Get(ctx, k) if err != nil { t.Fatal(err) } dst := k if strings.HasSuffix(k, siteArtifactFile) { dst = release.LegacyAppPrefix("site") + strings.TrimPrefix(k, release.AppPrefix(release.OpsAccount, "site")) } if _, err := dir.Put(ctx, dst, body, ""); err != nil { t.Fatal(err) } } s := &legacyTripwire{Store: dir, t: t, app: "site"} rt := registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"} h := newStaticHandler(rt, s, pub, filepath.Join(t.TempDir(), "cache")) h.(*staticSite).recheck = 0 srv := httptest.NewServer(h) defer srv.Close() if code, body := getPath(t, srv.URL, "site.example.com", "/"); code == 200 { t.Errorf("GET / = %d %q — the edge served an artifact that only exists at the legacy key", code, body) } }