carlos / platform Public

edge: bound the expanded size of a static release at extraction

Only the compressed artifact was bounded (256 MiB at ship), so a small
release could unpack into gigabytes or millions of files on the shared
disk of every box serving it (hunt H5-M6). extractSiteTar now refuses a
tree over 1 GiB in all (the free plan's disk), any file over 256 MiB
(the ship cap) or over 100,000 entries, checked from each tar header
before the entry is written. A refused tree is remembered per handler so
a site that never served does not re-extract on every request.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 149a3b842e89e318e7ae692f583b5c0c412d4e0c parent cb292cf
2 files changed, +259 −1
  • internal/edge/hunt_H5-M6_test.go +192 −0
  • internal/edge/static.go +67 −1
diff --git a/internal/edge/hunt_H5-M6_test.go b/internal/edge/hunt_H5-M6_test.go
new file mode 100644
index 000000000..a82e78a28
--- /dev/null
+++ b/internal/edge/hunt_H5-M6_test.go
@@ -0,0 +1,192 @@
+package edge
+
+// Hunt H5-M6 (verifier: opus). A static release's site.tar.gz is bounded only
+// in its COMPRESSED size (console handleAPIShip / apiShipMaxBytes). The edge's
+// ensureExtracted verifies the compressed artifact's sha256 and length, then
+// extractSiteTar copies every entry with an unbounded io.Copy and no
+// aggregate-byte or entry-count budget. So a tenant can ship a small,
+// well-formed release that expands into a large shared-disk write on every
+// box that serves it.
+//
+// Production wiring: release.Ship + release.Promote write a real, signature-
+// verified static release whose artifact is a hand-built gzip tar of
+// highly compressible data; the real newStaticHandler serves it, which runs
+// ensureExtracted -> extractSiteTar on the first request. The secure
+// assertion: the extracted tree stays within a sane budget (or the request
+// is refused). It FAILS on current code, which writes the whole bomb.
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "context"
+ "errors"
+ "io/fs"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func buildBombTarGz(t *testing.T, entries, perEntry int) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ zw := gzip.NewWriter(&buf)
+ tw := tar.NewWriter(zw)
+ zeros := make([]byte, perEntry) // all zero: compresses to almost nothing
+ for i := 0; i < entries; i++ {
+ name := "f" + string(rune('a'+i%26)) + string(rune('0'+i/26))
+ if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o644, Size: int64(perEntry), Typeflag: tar.TypeReg}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tw.Write(zeros); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := tw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if err := zw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+func dirBytes(t *testing.T, root string) int64 {
+ t.Helper()
+ var total int64
+ _ = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
+ if err != nil || d.IsDir() {
+ return nil
+ }
+ if info, e := d.Info(); e == nil {
+ total += info.Size()
+ }
+ return nil
+ })
+ return total
+}
+
+func TestHunt_H5_M6_StaticTarExpandsUnbounded(t *testing.T) {
+ const entries, perEntry = 24, 1 << 20 // 24 MiB expanded
+ bomb := buildBombTarGz(t, entries, perEntry)
+ // The production budget is 1 GiB (siteMaxBytes); lowered to the
+ // assertion's own budget so the proof writes megabytes, not a gigabyte.
+ const budget = 8 << 20
+ old := siteMaxBytes
+ siteMaxBytes = budget
+ t.Cleanup(func() { siteMaxBytes = old })
+ if len(bomb) > 256<<10 {
+ t.Fatalf("test bug: the bomb compressed to %d bytes, want it small", len(bomb))
+ }
+
+ store := release.NewDirStore(t.TempDir())
+ priv, pub := testKeys(t)
+ m := release.Manifest{Schema: 1, App: "site", Version: "v1", Kind: "static",
+ Artifacts: map[string]release.Artifact{siteArtifactFile: {}}}
+ if err := release.Ship(context.Background(), store, release.OpsAccount, m, map[string][]byte{siteArtifactFile: bomb}); err != nil {
+ t.Fatal(err)
+ }
+ if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "canary/x", "v1"); err != nil {
+ t.Fatal(err)
+ }
+
+ cacheDir := t.TempDir()
+ rt := registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"}
+ h := newStaticHandler(rt, store, pub, cacheDir)
+ h.(*staticSite).recheck = 0
+ req, _ := http.NewRequest("GET", "http://site.example.com/f a", nil)
+ req.Host = "site.example.com"
+ h.ServeHTTP(httptest.NewRecorder(), req)
+
+ got := dirBytes(t, cacheDir)
+ if got > budget {
+ t.Fatalf("H5-M6: a %d-byte compressed static release expanded to %d MiB on disk (%d entries x %d MiB) "+
+ "with no aggregate-byte or entry-count bound; want extraction refused past ~%d MiB",
+ len(bomb), got>>20, entries, perEntry>>20, budget>>20)
+ }
+}
+
+// Each limit refuses on its own, before the entry is written, and a site
+// refused for size is not downloaded and extracted again on the next
+// request.
+func TestSiteTarLimits(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ entries, perFile int
+ set func()
+ }{
+ {"aggregate", 4, 1 << 20, func() { siteMaxBytes = 3 << 20 }},
+ {"one file", 1, 2 << 20, func() { siteMaxFileBytes = 1 << 20 }},
+ {"entries", 11, 1, func() { siteMaxEntries = 10 }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ b, f, n := siteMaxBytes, siteMaxFileBytes, siteMaxEntries
+ t.Cleanup(func() { siteMaxBytes, siteMaxFileBytes, siteMaxEntries = b, f, n })
+ tc.set()
+ dst := t.TempDir()
+ err := ExtractSite(buildBombTarGz(t, tc.entries, tc.perFile), dst)
+ if !errors.Is(err, errSiteTooLarge) {
+ t.Fatalf("ExtractSite = %v, want errSiteTooLarge", err)
+ }
+ if got := dirBytes(t, dst); got > siteMaxBytes || got > int64(tc.entries-1)*int64(tc.perFile) {
+ t.Fatalf("wrote %d bytes before refusing; want the refused entry unwritten", got)
+ }
+ })
+ }
+ t.Run("under every limit", func(t *testing.T) {
+ if err := ExtractSite(buildBombTarGz(t, 3, 1<<20), t.TempDir()); err != nil {
+ t.Fatalf("a 3 MiB tree: %v", err)
+ }
+ })
+}
+
+func TestOversizedSiteIsNotExtractedTwice(t *testing.T) {
+ old := siteMaxBytes
+ siteMaxBytes = 1 << 20
+ t.Cleanup(func() { siteMaxBytes = old })
+
+ bucket := t.TempDir()
+ store := release.NewDirStore(bucket)
+ priv, pub := testKeys(t)
+ m := release.Manifest{Schema: 1, App: "site", Version: "v1", Kind: "static",
+ Artifacts: map[string]release.Artifact{siteArtifactFile: {}}}
+ if err := release.Ship(context.Background(), store, release.OpsAccount, m, map[string][]byte{siteArtifactFile: buildBombTarGz(t, 2, 1<<20)}); err != nil {
+ t.Fatal(err)
+ }
+ if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "canary/x", "v1"); err != nil {
+ t.Fatal(err)
+ }
+ rt := registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"}
+ h := newStaticHandler(rt, store, pub, t.TempDir()).(*staticSite)
+ h.recheck = 0
+ for i := 0; i < 2; i++ {
+ req, _ := http.NewRequest("GET", "http://site.example.com/", nil)
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+ if w.Code != http.StatusBadGateway {
+ t.Fatalf("request %d: %d, want 502 for a site that never served", i, w.Code)
+ }
+ if i == 0 {
+ // The artifact goes; the pointer and manifest stay. A second
+ // extraction would now fail on the download with another
+ // error, so the size refusal can only come from memory.
+ key := release.ArtifactKey(h.acct, "site", "v1", siteArtifactFile)
+ if err := os.Remove(filepath.Join(bucket, filepath.FromSlash(key))); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ h.mu.Lock()
+ h.checkedAt = time.Time{}
+ _, err := h.resolveLocked(context.Background())
+ h.mu.Unlock()
+ if !errors.Is(err, errSiteTooLarge) {
+ t.Fatalf("a third resolve: %v; want the remembered size refusal, not a download", err)
+ }
+}
diff --git a/internal/edge/static.go b/internal/edge/static.go
index 997e835ca..ef18fb6b0 100644
--- a/internal/edge/static.go
+++ b/internal/edge/static.go
@@ -159,6 +159,15 @@ type staticSite struct {
// while this handler chooses a tree there. nil records nothing.
trees *staticTrees
serving atomic.Pointer[string]
+
+ // oversized is the tree name (siteDirName) whose extraction was last
+ // refused for size (errSiteTooLarge), with that refusal. The release is
+ // immutable under its digest, so a retry would refuse again, after
+ // downloading the artifact and writing up to the budget a second time:
+ // a site that never served would otherwise pay that on every request.
+ // Under mu.
+ oversized string
+ oversizedErr error
}
// newStaticHandler builds the serving handler for one static route. The
@@ -432,6 +441,9 @@ func (s *staticSite) ensureExtracted(ctx context.Context, version, want string)
if _, err := os.Stat(dst); err == nil {
return name, digest, nil // extracted by an earlier check or a sibling handler
}
+ if name == s.oversized {
+ return "", "", s.oversizedErr
+ }
if m.Kind != "static" {
return "", "", fmt.Errorf("release %s/%s is kind %q, not static", s.app, version, m.Kind)
}
@@ -507,6 +519,9 @@ func (s *staticSite) ensureExtracted(ctx context.Context, version, want string)
}
defer os.RemoveAll(tmp)
if err := extractSiteTar(artifact, tmp); err != nil {
+ if errors.Is(err, errSiteTooLarge) {
+ s.oversized, s.oversizedErr = name, err
+ }
return "", "", err
}
if err := os.Rename(tmp, dst); err != nil {
@@ -545,10 +560,43 @@ func (s *staticSite) pointCurrent(name string) error {
// refusals.
func ExtractSite(data []byte, dst string) error { return extractSiteTar(bytes.NewReader(data), dst) }
+// The expanded size of a site tree, bounded at extraction (hunt H5-M6). The
+// ship cap (the console's apiShipMaxBytes, 256 MiB; the devbox's
+// MaxFolderBytes, 200 MiB) bounds only the COMPRESSED artifact, and gzip
+// expands highly repetitive input about a thousandfold, so a small release
+// could unpack into gigabytes on the shared disk of every box that serves
+// it, or into enough empty files to run the disk out of inodes. Each limit
+// is checked against the tar header before the entry is written, so a
+// refused tree has written at most the budget, and that into a temp dir
+// that is removed.
+//
+// - siteMaxBytes, 1 GiB in all: the smallest plan's disk for one running
+// thing (the free plan's disk_bytes in deploy/billing's catalog), and
+// four times the ship cap, which
+// covers a tree of text and markup that gzip shrank to a quarter.
+// Images, fonts and video, the bulk of a big site, barely compress, so
+// a real site that fits the ship cap expands to little more.
+// - siteMaxFileBytes, 256 MiB for any one file: the ship cap. A static
+// site has no business serving one file bigger than a whole release.
+// - siteMaxEntries, 100,000 entries (files and directories): an inode
+// budget, many times the largest generated docs site.
+//
+// Vars, not consts, so a test can lower them.
+var (
+ siteMaxBytes int64 = 1 << 30
+ siteMaxFileBytes int64 = 256 << 20
+ siteMaxEntries = 100_000
+)
+
+// errSiteTooLarge is the refusal of a tree over one of the limits above.
+var errSiteTooLarge = errors.New("site tar: over the expanded size limit")
+
// extractSiteTar unpacks a verified site tar into dst, rejecting anything
// that would write outside it: absolute names, ".." traversal, and non-file
// entry types (a symlink in a site tar could alias the extraction outside
-// the cache — PackDir never emits one, so none is ever legitimate).
+// the cache — PackDir never emits one, so none is ever legitimate). A tree
+// over siteMaxBytes, siteMaxFileBytes or siteMaxEntries is refused with
+// errSiteTooLarge; the caller removes what was written.
func extractSiteTar(src io.Reader, dst string) error {
gz, err := gzip.NewReader(src)
if err != nil {
@@ -556,6 +604,8 @@ func extractSiteTar(src io.Reader, dst string) error {
}
defer gz.Close()
tr := tar.NewReader(gz)
+ var total int64
+ entries := 0
for {
hdr, err := tr.Next()
if err == io.EOF {
@@ -568,6 +618,22 @@ func extractSiteTar(src io.Reader, dst string) error {
if !filepath.IsLocal(name) {
return fmt.Errorf("site tar: entry %q escapes the extraction dir", hdr.Name)
}
+ // hdr.Size is what a read of the entry yields (archive/tar stops
+ // there, and expands a sparse entry to it), so checking it here
+ // bounds what the copy below can write.
+ if hdr.Typeflag != tar.TypeXGlobalHeader {
+ if entries++; entries > siteMaxEntries {
+ return fmt.Errorf("%w: more than %d entries", errSiteTooLarge, siteMaxEntries)
+ }
+ }
+ if hdr.Typeflag == tar.TypeReg {
+ if hdr.Size > siteMaxFileBytes {
+ return fmt.Errorf("%w: %q is %d bytes, over %d", errSiteTooLarge, hdr.Name, hdr.Size, siteMaxFileBytes)
+ }
+ if total += hdr.Size; total > siteMaxBytes {
+ return fmt.Errorf("%w: more than %d bytes in all", errSiteTooLarge, siteMaxBytes)
+ }
+ }
switch hdr.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(filepath.Join(dst, name), 0o755); err != nil {