carlos / platform Public

edge: count implied directories against the site inode budget

The budget counted archive entries, so a few deep names made a great
many parent directories uncounted (O4 R1, H5-M6). Every inode
extraction creates is now charged before it is made: each file, each
directory named or implied. An entry that makes nothing still costs
one, and a name past PATH_MAX is refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 55860e8fe9e8919b4e76b18f25fe0442010a62b6 parent e3a01de
2 files changed, +218 −20
  • internal/edge/hunt_H5-M6_test.go +119 −0
  • internal/edge/static.go +99 −20
diff --git a/internal/edge/hunt_H5-M6_test.go b/internal/edge/hunt_H5-M6_test.go
index a82e78a28..ade48af86 100644
--- a/internal/edge/hunt_H5-M6_test.go
+++ b/internal/edge/hunt_H5-M6_test.go
@@ -21,6 +21,7 @@ import (
"compress/gzip"
"context"
"errors"
+ "fmt"
"io/fs"
"net/http"
"net/http/httptest"
@@ -190,3 +191,121 @@ func TestOversizedSiteIsNotExtractedTwice(t *testing.T) {
t.Fatalf("a third resolve: %v; want the remembered size refusal, not a download", err)
}
}
+
+// buildDeepTarGz writes entries archive entries of type typ, each the only
+// named leaf of its own chain of depth directories, so the archive names
+// entries things and implies entries*depth directories.
+func buildDeepTarGz(t *testing.T, entries, depth int, typ byte) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ zw := gzip.NewWriter(&buf)
+ tw := tar.NewWriter(zw)
+ for i := 0; i < entries; i++ {
+ name := fmt.Sprintf("e%d", i)
+ for j := 0; j < depth; j++ {
+ name += "/d"
+ }
+ hdr := &tar.Header{Name: name, Mode: 0o755, Typeflag: typ}
+ if typ == tar.TypeDir {
+ hdr.Name += "/"
+ }
+ if err := tw.WriteHeader(hdr); 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()
+}
+
+// countInodes is every file and directory under root, root excluded.
+func countInodes(t *testing.T, root string) int {
+ t.Helper()
+ n := -1
+ _ = filepath.WalkDir(root, func(string, fs.DirEntry, error) error { n++; return nil })
+ return n
+}
+
+// The inode budget counts every inode extraction creates, not every archive
+// entry: a directory a file or directory entry implies (its missing
+// parents) is one too (O4 round 1, H5-M6's fault family). Through the
+// production wiring: a shipped, promoted release served by the real static
+// handler, whose first request extracts it into the cache dir.
+func TestSiteTarImpliedDirectoriesCountAgainstTheInodeBudget(t *testing.T) {
+ for _, typ := range []byte{tar.TypeDir, tar.TypeReg} {
+ t.Run(fmt.Sprintf("type %c", typ), func(t *testing.T) {
+ old := siteMaxEntries
+ siteMaxEntries = 50
+ t.Cleanup(func() { siteMaxEntries = old })
+ // 5 entries, under the budget of 50; 100 directories implied.
+ site := buildDeepTarGz(t, 5, 20, typ)
+
+ 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: site}); 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).(*staticSite)
+ h.recheck = 0
+ req, _ := http.NewRequest("GET", "http://site.example.com/", nil)
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+ if w.Code != http.StatusBadGateway {
+ t.Fatalf("serve: %d, want 502 for a site refused at extraction", w.Code)
+ }
+ h.mu.Lock()
+ _, err := h.resolveLocked(context.Background())
+ h.mu.Unlock()
+ if !errors.Is(err, errSiteTooLarge) {
+ t.Fatalf("resolve: %v, want errSiteTooLarge", err)
+ }
+ // The refused tree's temp dir is gone; the app dir itself
+ // (and nothing else of the release) is what is left.
+ if n := countInodes(t, cacheDir); n > 2 {
+ t.Fatalf("%d inodes left in the cache after a refusal", n)
+ }
+ })
+ }
+ t.Run("budget bounds what is created before the refusal", func(t *testing.T) {
+ old := siteMaxEntries
+ siteMaxEntries = 50
+ t.Cleanup(func() { siteMaxEntries = old })
+ dst := t.TempDir()
+ if err := ExtractSite(buildDeepTarGz(t, 5, 20, tar.TypeDir), dst); !errors.Is(err, errSiteTooLarge) {
+ t.Fatalf("ExtractSite = %v, want errSiteTooLarge", err)
+ }
+ if n := countInodes(t, dst); n > siteMaxEntries {
+ t.Fatalf("created %d inodes before refusing; want at most the budget %d", n, siteMaxEntries)
+ }
+ })
+ t.Run("a tree that fits", func(t *testing.T) {
+ old := siteMaxEntries
+ siteMaxEntries = 50
+ t.Cleanup(func() { siteMaxEntries = old })
+ dst := t.TempDir()
+ // 2 chains of 20 directories, the leaf named: 42 inodes.
+ if err := ExtractSite(buildDeepTarGz(t, 2, 20, tar.TypeReg), dst); err != nil {
+ t.Fatalf("ExtractSite: %v", err)
+ }
+ if n := countInodes(t, dst); n != 42 {
+ t.Fatalf("%d inodes, want 42", n)
+ }
+ })
+ t.Run("a name past PATH_MAX", func(t *testing.T) {
+ long := buildDeepTarGz(t, 1, 2100, tar.TypeReg) // "e0" + 2100 x "/d"
+ if err := ExtractSite(long, t.TempDir()); !errors.Is(err, errSiteTooLarge) {
+ t.Fatalf("ExtractSite = %v, want errSiteTooLarge", err)
+ }
+ })
+}
diff --git a/internal/edge/static.go b/internal/edge/static.go
index b04b45775..41a7fde33 100644
--- a/internal/edge/static.go
+++ b/internal/edge/static.go
@@ -578,8 +578,17 @@ func ExtractSite(data []byte, dst string) error { return extractSiteTar(bytes.Ne
// 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.
+// - siteMaxEntries, 100,000 inodes: an inode budget, many times the
+// largest generated docs site. Every inode extraction creates counts,
+// before it is created: each entry's own file or directory, and each
+// directory an entry implies (a missing parent, which extraction makes
+// for it). An entry that makes nothing (a pax global header, a
+// directory already made) still costs one, so none is free to read.
+// Counting archive entries alone let a few deep names make a great
+// many directories (O4 round 1).
+// - siteMaxName, 4,096 bytes for an entry's name: PATH_MAX, past which
+// no file could be made anyway. It bounds the work a name costs, as
+// the inode budget bounds the names.
//
// Vars, not consts, so a test can lower them.
var (
@@ -588,6 +597,8 @@ var (
siteMaxEntries = 100_000
)
+const siteMaxName = 4096
+
// errSiteTooLarge is the refusal of a tree over one of the limits above.
var errSiteTooLarge = errors.New("site tar: over the expanded size limit")
@@ -595,8 +606,9 @@ var errSiteTooLarge = errors.New("site tar: over the expanded size limit")
// 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). A tree
-// over siteMaxBytes, siteMaxFileBytes or siteMaxEntries is refused with
-// errSiteTooLarge; the caller removes what was written.
+// over siteMaxBytes, siteMaxFileBytes or siteMaxEntries, or with a name
+// over siteMaxName, 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 {
@@ -605,7 +617,7 @@ func extractSiteTar(src io.Reader, dst string) error {
defer gz.Close()
tr := tar.NewReader(gz)
var total int64
- entries := 0
+ x := siteDirs{dst: dst, made: map[string]struct{}{}}
for {
hdr, err := tr.Next()
if err == io.EOF {
@@ -614,6 +626,17 @@ func extractSiteTar(src io.Reader, dst string) error {
if err != nil {
return fmt.Errorf("site tar: %v", err)
}
+ if hdr.Typeflag == tar.TypeXGlobalHeader {
+ // pax global header: metadata, nothing to write, but an entry
+ // to read, so it costs one like any other.
+ if err := x.count(); err != nil {
+ return err
+ }
+ continue
+ }
+ if len(hdr.Name) > siteMaxName {
+ return fmt.Errorf("%w: a name of %d bytes, over %d", errSiteTooLarge, len(hdr.Name), siteMaxName)
+ }
name := filepath.FromSlash(path.Clean(hdr.Name))
if !filepath.IsLocal(name) {
return fmt.Errorf("site tar: entry %q escapes the extraction dir", hdr.Name)
@@ -621,30 +644,35 @@ func extractSiteTar(src io.Reader, dst string) error {
// 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)
+ switch hdr.Typeflag {
+ case tar.TypeDir:
+ made, err := x.mkdirs(name)
+ if err != nil {
+ return err
}
- }
- if hdr.Typeflag == tar.TypeReg {
+ // An entry naming a directory already made (or dst itself)
+ // still costs one, so no entry is free to read.
+ if made == 0 {
+ if err := x.count(); err != nil {
+ return err
+ }
+ }
+ case 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 {
+ if _, err := x.mkdirs(filepath.Dir(name)); err != nil {
return err
}
- case tar.TypeReg:
- p := filepath.Join(dst, name)
- if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ // The file's own inode. A name written twice counts twice,
+ // which only errs toward refusing.
+ if err := x.count(); err != nil {
return err
}
- f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
+ f, err := os.OpenFile(filepath.Join(dst, name), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return err
}
@@ -655,14 +683,65 @@ func extractSiteTar(src io.Reader, dst string) error {
if err := f.Close(); err != nil {
return err
}
- case tar.TypeXGlobalHeader:
- // pax global header: metadata, nothing to write
default:
return fmt.Errorf("site tar: entry %q has unsupported type %d", hdr.Name, hdr.Typeflag)
}
}
}
+// siteDirs is extractSiteTar's inode budget and the directories it has
+// made under dst, so each is counted once, when it is made.
+type siteDirs struct {
+ dst string
+ made map[string]struct{}
+ inodes int
+}
+
+// count charges one inode to the budget, refusing past siteMaxEntries.
+func (x *siteDirs) count() error {
+ if x.inodes++; x.inodes > siteMaxEntries {
+ return fmt.Errorf("%w: more than %d files and directories", errSiteTooLarge, siteMaxEntries)
+ }
+ return nil
+}
+
+// mkdirs makes rel (local, cleaned) and each missing parent under x.dst,
+// top down, charging each to the budget before it is made. The walk up
+// stops at the first directory already made, whose parents were made with
+// it, so a directory costs one lookup per entry under it and its making
+// once; the name cap bounds the walk. made holds at most siteMaxEntries
+// keys of at most siteMaxName bytes each. It returns how many it made.
+func (x *siteDirs) mkdirs(rel string) (int, error) {
+ var missing []string
+ for d := rel; d != "."; d = filepath.Dir(d) {
+ if _, ok := x.made[d]; ok {
+ break
+ }
+ missing = append(missing, d)
+ }
+ for i := len(missing) - 1; i >= 0; i-- {
+ if err := x.count(); err != nil {
+ return 0, err
+ }
+ if err := os.Mkdir(filepath.Join(x.dst, missing[i]), 0o755); err != nil && !existingDir(filepath.Join(x.dst, missing[i]), err) {
+ return 0, err
+ }
+ x.made[missing[i]] = struct{}{}
+ }
+ return len(missing), nil
+}
+
+// existingDir reports whether err, from a Mkdir of p, says only that p is
+// already a directory: dst itself may be one ExtractSite's caller made
+// with content, and MkdirAll accepted that before.
+func existingDir(p string, err error) bool {
+ if !errors.Is(err, fs.ErrExist) {
+ return false
+ }
+ fi, serr := os.Lstat(p)
+ return serr == nil && fi.IsDir()
+}
+
// serveTree answers one request from an extracted version dir:
// http.FileServer semantics with index.html for directories and a clean 404
// (never a directory listing) when neither the file nor an index exists —