diff --git a/go.mod b/go.mod index 3119587..f6e4fe6 100644 --- a/go.mod +++ b/go.mod @@ -4,10 +4,13 @@ go 1.26 require ( github.com/BurntSushi/toml v1.6.0 + github.com/jotfs/fastcdc-go v0.2.0 github.com/spf13/cobra v1.10.2 + github.com/zeebo/blake3 v0.2.4 ) require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/klauspost/cpuid/v2 v2.0.12 // indirect github.com/spf13/pflag v1.0.9 // indirect ) diff --git a/go.sum b/go.sum index c09a7f6..875407e 100644 --- a/go.sum +++ b/go.sum @@ -3,10 +3,20 @@ github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2 github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/jotfs/fastcdc-go v0.2.0 h1:WHYIGk3k9NumGWfp4YMsemEcx/s4JKpGAa6tpCpHJOo= +github.com/jotfs/fastcdc-go v0.2.0/go.mod h1:PGFBIloiASFbiKnkCd/hmHXxngxYDYtisyurJ/zyDNM= +github.com/klauspost/cpuid/v2 v2.0.12 h1:p9dKCg8i4gmOxtv35DvrYoWqYzQrvEVdjQ762Y0OqZE= +github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY= +github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= +github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI= +github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE= +github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo= +github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/chunk/chunk.go b/internal/chunk/chunk.go new file mode 100644 index 0000000..3a68412 --- /dev/null +++ b/internal/chunk/chunk.go @@ -0,0 +1,79 @@ +// Package chunk implements content-defined chunking (FastCDC) plus BLAKE3-256 +// hashing. Together these form the dedup core: identical content produces +// identical chunk boundaries and hashes regardless of where it appears, so +// unchanged regions of a mutated file dedup against the original. +package chunk + +import ( + "bytes" + "encoding/hex" + + fastcdc "github.com/jotfs/fastcdc-go" + "github.com/zeebo/blake3" +) + +// Chunk size targets. FastCDC keeps chunk lengths within [min, max] and aims +// for the average via content-defined boundaries. +const ( + MinSize = 4 * 1024 // 4 KiB + AvgSize = 16 * 1024 // 16 KiB + MaxSize = 64 * 1024 // 64 KiB +) + +// Chunk describes a single content-defined chunk of an input buffer. +// Hash is the lowercase hex BLAKE3-256 digest of the chunk's bytes. +type Chunk struct { + Hash string + Offset int64 + Size int64 +} + +// Split divides data into content-defined chunks using FastCDC and returns +// them in order. The returned chunks are contiguous: chunk[0].Offset == 0, +// each chunk starts where the previous ended, and the sizes sum to len(data). +// +// Inputs smaller than MinSize yield a single chunk. Empty input yields zero +// chunks. +// +// ponytail: Split is in-memory — it takes the whole []byte and the underlying +// chunker reads from a bytes.Reader over it. Streaming large inputs from an +// io.Reader without buffering the entire payload is the upgrade path. +func Split(data []byte) []Chunk { + if len(data) == 0 { + return nil + } + + chunker, err := fastcdc.NewChunker(bytes.NewReader(data), fastcdc.Options{ + MinSize: MinSize, + AverageSize: AvgSize, + MaxSize: MaxSize, + }) + if err != nil { + // Options are compile-time constants that satisfy the library's + // validation, so construction cannot fail in practice. Fall back to + // treating the whole input as one chunk rather than panicking. + return []Chunk{{Hash: Hash(data), Offset: 0, Size: int64(len(data))}} + } + + var chunks []Chunk + for { + c, err := chunker.Next() + if err != nil { + // io.EOF (or any error) ends iteration; on a bytes.Reader the only + // terminal condition is EOF after the final chunk. + break + } + chunks = append(chunks, Chunk{ + Hash: Hash(c.Data), + Offset: int64(c.Offset), + Size: int64(c.Length), + }) + } + return chunks +} + +// Hash returns the BLAKE3-256 digest of b as a lowercase hex string. +func Hash(b []byte) string { + sum := blake3.Sum256(b) + return hex.EncodeToString(sum[:]) +} diff --git a/internal/chunk/chunk_test.go b/internal/chunk/chunk_test.go new file mode 100644 index 0000000..74ea020 --- /dev/null +++ b/internal/chunk/chunk_test.go @@ -0,0 +1,172 @@ +package chunk + +import ( + "bytes" + "math/rand" + "testing" +) + +// seededBlob returns a deterministic pseudo-random blob of n bytes. +func seededBlob(seed int64, n int) []byte { + r := rand.New(rand.NewSource(seed)) + b := make([]byte, n) + // rand.Read on a seeded source is deterministic. + r.Read(b) + return b +} + +func TestHashKnownVector(t *testing.T) { + // BLAKE3-256 of the empty input. + const want = "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262" + if got := Hash([]byte("")); got != want { + t.Fatalf("Hash(\"\") = %q, want %q", got, want) + } +} + +func TestHashDeterministic(t *testing.T) { + tests := []struct { + name string + in []byte + }{ + {"empty", []byte("")}, + {"short", []byte("hello world")}, + {"binary", []byte{0x00, 0xff, 0x10, 0x80, 0x7f}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if Hash(tt.in) != Hash(tt.in) { + t.Fatalf("Hash not deterministic for %q", tt.name) + } + }) + } +} + +func TestSplitDeterministic(t *testing.T) { + tests := []struct { + name string + data []byte + }{ + {"empty", nil}, + {"tiny", []byte("a few bytes")}, + {"sub-min", seededBlob(1, MinSize-1)}, + {"medium", seededBlob(2, 256*1024)}, + {"large", seededBlob(3, 1<<20)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + a := Split(tt.data) + b := Split(tt.data) + if len(a) != len(b) { + t.Fatalf("chunk count differs: %d vs %d", len(a), len(b)) + } + for i := range a { + if a[i] != b[i] { + t.Fatalf("chunk %d differs: %+v vs %+v", i, a[i], b[i]) + } + } + }) + } +} + +func TestSplitReassembly(t *testing.T) { + tests := []struct { + name string + data []byte + }{ + {"tiny", []byte("hello")}, + {"exactly-min", seededBlob(10, MinSize)}, + {"sub-min", seededBlob(11, MinSize-1)}, + {"medium", seededBlob(12, 100*1024)}, + {"large", seededBlob(13, 1<<20)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + chunks := Split(tt.data) + + // Offsets contiguous starting at 0; sizes sum to len(data). + var want int64 + var total int64 + var reassembled bytes.Buffer + for i, c := range chunks { + if c.Offset != want { + t.Fatalf("chunk %d offset = %d, want %d", i, c.Offset, want) + } + if c.Size <= 0 { + t.Fatalf("chunk %d has non-positive size %d", i, c.Size) + } + reassembled.Write(tt.data[c.Offset : c.Offset+c.Size]) + // Hash recorded must match the chunk's actual bytes. + if got := Hash(tt.data[c.Offset : c.Offset+c.Size]); got != c.Hash { + t.Fatalf("chunk %d hash mismatch: stored %s, recomputed %s", i, c.Hash, got) + } + want += c.Size + total += c.Size + } + if total != int64(len(tt.data)) { + t.Fatalf("sizes sum to %d, want %d", total, len(tt.data)) + } + if !bytes.Equal(reassembled.Bytes(), tt.data) { + t.Fatalf("reassembled data != original (len %d vs %d)", reassembled.Len(), len(tt.data)) + } + }) + } +} + +func TestSplitEmpty(t *testing.T) { + // Chosen behavior: empty input => zero chunks. + if got := Split(nil); len(got) != 0 { + t.Fatalf("Split(nil) = %d chunks, want 0", len(got)) + } + if got := Split([]byte{}); len(got) != 0 { + t.Fatalf("Split([]byte{}) = %d chunks, want 0", len(got)) + } +} + +func TestSplitSubMinSingleChunk(t *testing.T) { + data := seededBlob(99, MinSize-1) + chunks := Split(data) + if len(chunks) != 1 { + t.Fatalf("sub-min input produced %d chunks, want 1", len(chunks)) + } + if chunks[0].Offset != 0 || chunks[0].Size != int64(len(data)) { + t.Fatalf("single chunk = {off %d, size %d}, want {0, %d}", chunks[0].Offset, chunks[0].Size, len(data)) + } +} + +func TestSplitDedupLocalizesEdit(t *testing.T) { + const size = 1 << 20 // 1 MiB + orig := seededBlob(42, size) + + // Copy and mutate ~16 bytes in the middle. + mutated := append([]byte(nil), orig...) + mid := size / 2 + for i := 0; i < 16; i++ { + mutated[mid+i] ^= 0xAB // flip bits; deterministic mutation + } + + origChunks := Split(orig) + mutChunks := Split(mutated) + + if len(origChunks) < 4 { + t.Fatalf("expected several chunks for a 1 MiB blob, got %d", len(origChunks)) + } + + origSet := make(map[string]struct{}, len(origChunks)) + for _, c := range origChunks { + origSet[c.Hash] = struct{}{} + } + + shared := 0 + for _, c := range mutChunks { + if _, ok := origSet[c.Hash]; ok { + shared++ + } + } + + ratio := float64(shared) / float64(len(mutChunks)) + if ratio <= 0.5 { + t.Fatalf("dedup ratio %.2f (%d/%d) <= 0.50; content-defined boundaries should localize a 16-byte edit", + ratio, shared, len(mutChunks)) + } + t.Logf("dedup: %d/%d mutated chunks (%.1f%%) shared with original", shared, len(mutChunks), ratio*100) +} diff --git a/internal/ignore/ignore.go b/internal/ignore/ignore.go new file mode 100644 index 0000000..a7fb55f --- /dev/null +++ b/internal/ignore/ignore.go @@ -0,0 +1,147 @@ +// Package ignore implements a .devignore matcher with gitignore-compatible +// semantics (last-match-wins, negation, anchoring, ** globbing). +package ignore + +import ( + "regexp" + "strings" +) + +// Matcher matches forward-slash paths (relative to the project root) against a +// compiled set of .devignore patterns. +type Matcher struct { + rules []rule +} + +type rule struct { + re *regexp.Regexp + negate bool + dirOnly bool +} + +// Compile parses the lines of a .devignore file into a Matcher. +func Compile(patterns []string) (*Matcher, error) { + m := &Matcher{} + for _, p := range patterns { + r, ok, err := compilePattern(p) + if err != nil { + return nil, err + } + if ok { + m.rules = append(m.rules, r) + } + } + return m, nil +} + +func compilePattern(line string) (rule, bool, error) { + // Trim trailing whitespace; gitignore keeps leading whitespace literal. + line = strings.TrimRight(line, " \t\r\n") + if line == "" || strings.HasPrefix(line, "#") { + return rule{}, false, nil + } + + var r rule + if strings.HasPrefix(line, "!") { + r.negate = true + line = line[1:] + } + if strings.HasSuffix(line, "/") { + r.dirOnly = true + line = strings.TrimSuffix(line, "/") + } + + // A pattern is anchored to root if it contains a (non-trailing) slash or + // has a leading slash; otherwise a bare name matches at any depth. + anchored := strings.Contains(line, "/") + line = strings.TrimPrefix(line, "/") + + re, err := regexp.Compile(buildRegex(line, anchored)) + if err != nil { + return rule{}, false, err + } + r.re = re + return r, true, nil +} + +// buildRegex translates a gitignore glob into an anchored regexp matching a +// whole path. When unanchored, the pattern may begin at any path segment. +func buildRegex(glob string, anchored bool) string { + var b strings.Builder + b.WriteString("^") + if anchored { + b.WriteString(globToRegex(glob)) + } else { + // Bare name: match at root or after any "/". + b.WriteString("(?:.*/)?") + b.WriteString(globToRegex(glob)) + } + b.WriteString("$") + return b.String() +} + +// globToRegex converts gitignore glob metacharacters to a regexp fragment. +// - `**` spans segments (including slashes) +// - `*` matches within a single segment (no slash) +// - `?` matches one non-slash char +func globToRegex(g string) string { + var b strings.Builder + for i := 0; i < len(g); i++ { + switch c := g[i]; c { + case '*': + if i+1 < len(g) && g[i+1] == '*' { + b.WriteString(".*") // ponytail: treat ** as "anything incl. /" + i++ + // swallow a slash directly after ** so a/**/b matches a/b + if i+1 < len(g) && g[i+1] == '/' { + i++ + } + } else { + b.WriteString("[^/]*") + } + case '?': + b.WriteString("[^/]") + default: + b.WriteString(regexp.QuoteMeta(string(c))) + } + } + return b.String() +} + +// Match reports whether path (forward-slash, relative to root) is ignored. +// isDir indicates whether path is a directory. +func (m *Matcher) Match(path string, isDir bool) bool { + path = strings.Trim(path, "/") + + // .devbox is always ignored, including everything under it. + if path == ".devbox" || strings.HasPrefix(path, ".devbox/") { + return true + } + + // A path is ignored if itself matches, or if any ancestor directory is + // ignored (last-match-wins is evaluated per candidate path). + if m.matchOne(path, isDir) { + return true + } + segs := strings.Split(path, "/") + for i := 1; i < len(segs); i++ { + if m.matchOne(strings.Join(segs[:i], "/"), true) { + return true + } + } + return false +} + +// matchOne applies last-match-wins to a single path (no ancestor walking). +func (m *Matcher) matchOne(path string, isDir bool) bool { + ignored := false + for _, r := range m.rules { + if r.dirOnly && !isDir { + continue + } + if r.re.MatchString(path) { + ignored = !r.negate + } + } + return ignored +} diff --git a/internal/ignore/ignore_test.go b/internal/ignore/ignore_test.go new file mode 100644 index 0000000..5546f6e --- /dev/null +++ b/internal/ignore/ignore_test.go @@ -0,0 +1,83 @@ +package ignore + +import ( + "strings" + "testing" +) + +const devignore = ` +node_modules/ +dist/ +build/ +.next/ +target/ +*.log +*.tmp +.DS_Store +.env +.env.* +*.pem +*.key +secrets/ +!.env.example +` + +func newMatcher(t *testing.T) *Matcher { + t.Helper() + m, err := Compile(strings.Split(devignore, "\n")) + if err != nil { + t.Fatalf("Compile: %v", err) + } + return m +} + +func TestMatch(t *testing.T) { + m := newMatcher(t) + + cases := []struct { + path string + isDir bool + want bool + }{ + // node_modules at any depth + {"node_modules", true, true}, + {"node_modules/x", false, true}, + {"a/b/node_modules/c", false, true}, + + // other dir patterns + {"dist/x", false, true}, + {"build", true, true}, + {".next", true, true}, + {"target/y", false, true}, + + // extension / name patterns at any depth + {"app.log", false, true}, + {"a/b/c.tmp", false, true}, + {".DS_Store", false, true}, + {"sub/.DS_Store", false, true}, + + // secrets + env + keys + {".env", false, true}, + {".env.local", false, true}, + {"key.pem", false, true}, + {"id.key", false, true}, + {"secrets/aws", false, true}, + + // negation beats .env.* + {".env.example", false, false}, + + // .devbox always ignored + {".devbox/anything", false, true}, + {".devbox/hooks/post-pull", false, true}, + + // not ignored + {"src/main.go", false, false}, + {"README.md", false, false}, + } + + for _, c := range cases { + if got := m.Match(c.path, c.isDir); got != c.want { + t.Errorf("Match(%q, isDir=%v) = %v, want %v", c.path, c.isDir, got, c.want) + } + } +} diff --git a/internal/manifest/manifest.go b/internal/manifest/manifest.go new file mode 100644 index 0000000..1b42358 --- /dev/null +++ b/internal/manifest/manifest.go @@ -0,0 +1,160 @@ +// Package manifest builds and diffs the synced state of a tree: the set of +// regular files (filtered by .devignore and the secret guard) mapped to their +// content chunks. A manifest is content-addressed; its ID identifies a snapshot. +package manifest + +import ( + "fmt" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + + "git.shoemoney.ai/shoemoney/devbox/internal/chunk" + "git.shoemoney.ai/shoemoney/devbox/internal/ignore" + "git.shoemoney.ai/shoemoney/devbox/internal/secret" +) + +// Entry is one regular file in a manifest. Path is forward-slash, relative to root. +type Entry struct { + Path string + Mode uint32 + Size int64 + Chunks []string +} + +// Manifest is the sorted set of files comprising a tree's synced state. +type Manifest struct { + Entries []Entry +} + +// Build walks root, skipping .devignore matches and (separately) secret-guard +// matches, chunks each remaining regular file, and returns the manifest plus the +// sorted list of secret paths that were blocked from sync. ig and guard may be nil. +func Build(root string, ig *ignore.Matcher, guard *secret.Guard) (Manifest, []string, error) { + var entries []Entry + var blocked []string + + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, err := filepath.Rel(root, p) + if err != nil { + return err + } + if rel == "." { + return nil + } + rel = filepath.ToSlash(rel) + + if d.IsDir() { + if ig != nil && ig.Match(rel, true) { + return filepath.SkipDir + } + return nil + } + if !d.Type().IsRegular() { + return nil // ponytail: symlinks/specials unsupported in v1 + } + if ig != nil && ig.Match(rel, false) { + return nil + } + if guard != nil && guard.Blocked(rel) { + blocked = append(blocked, rel) + return nil + } + info, err := d.Info() + if err != nil { + return err + } + data, err := os.ReadFile(p) // ponytail: whole-file read; stream huge files later + if err != nil { + return err + } + var hashes []string + for _, c := range chunk.Split(data) { + hashes = append(hashes, c.Hash) + } + entries = append(entries, Entry{ + Path: rel, + Mode: uint32(info.Mode().Perm()), + Size: info.Size(), + Chunks: hashes, + }) + return nil + }) + if err != nil { + return Manifest{}, nil, err + } + sort.Slice(entries, func(i, j int) bool { return entries[i].Path < entries[j].Path }) + sort.Strings(blocked) + return Manifest{Entries: entries}, blocked, nil +} + +// ID is the content address of the manifest (BLAKE3 of its canonical form). +func (m Manifest) ID() string { + var b strings.Builder + for _, e := range m.Entries { + fmt.Fprintf(&b, "%s\x00%o\x00%d\x00%s\n", e.Path, e.Mode, e.Size, strings.Join(e.Chunks, ",")) + } + return chunk.Hash([]byte(b.String())) +} + +// Changes is the difference between two manifests. +type Changes struct { + Added []string + Modified []string + Deleted []string +} + +// Empty reports whether there are no changes. +func (c Changes) Empty() bool { + return len(c.Added)+len(c.Modified)+len(c.Deleted) == 0 +} + +// Diff computes what changed from old to cur (by path; modified = different +// chunk list, size, or mode). +func Diff(old, cur Manifest) Changes { + om := index(old) + cm := index(cur) + var ch Changes + for path, ce := range cm { + oe, ok := om[path] + if !ok { + ch.Added = append(ch.Added, path) + } else if !sameContent(oe, ce) { + ch.Modified = append(ch.Modified, path) + } + } + for path := range om { + if _, ok := cm[path]; !ok { + ch.Deleted = append(ch.Deleted, path) + } + } + sort.Strings(ch.Added) + sort.Strings(ch.Modified) + sort.Strings(ch.Deleted) + return ch +} + +func index(m Manifest) map[string]Entry { + idx := make(map[string]Entry, len(m.Entries)) + for _, e := range m.Entries { + idx[e.Path] = e + } + return idx +} + +func sameContent(a, b Entry) bool { + if a.Size != b.Size || a.Mode != b.Mode || len(a.Chunks) != len(b.Chunks) { + return false + } + for i := range a.Chunks { + if a.Chunks[i] != b.Chunks[i] { + return false + } + } + return true +} diff --git a/internal/manifest/manifest_test.go b/internal/manifest/manifest_test.go new file mode 100644 index 0000000..d7d8ad2 --- /dev/null +++ b/internal/manifest/manifest_test.go @@ -0,0 +1,125 @@ +package manifest + +import ( + "os" + "path/filepath" + "testing" + + "git.shoemoney.ai/shoemoney/devbox/internal/ignore" + "git.shoemoney.ai/shoemoney/devbox/internal/secret" +) + +func write(t *testing.T, root, rel, content string) { + t.Helper() + p := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +func buildTree(t *testing.T) string { + root := t.TempDir() + write(t, root, "main.go", "package main\n") + write(t, root, "README.md", "# hi\n") + write(t, root, "sub/code.go", "package sub\n") + write(t, root, "node_modules/dep.js", "module.exports = 1\n") // ignored + write(t, root, "sub/app.log", "noise\n") // ignored (*.log) + write(t, root, ".env", "SECRET=1\n") // secret-blocked + write(t, root, ".env.example", "SECRET=\n") // allowed + return root +} + +func compile(t *testing.T) (*ignore.Matcher, *secret.Guard) { + t.Helper() + ig, err := ignore.Compile([]string{"node_modules/", "*.log"}) + if err != nil { + t.Fatal(err) + } + g, err := secret.New(nil) + if err != nil { + t.Fatal(err) + } + return ig, g +} + +func TestBuildFiltersIgnoredAndSecrets(t *testing.T) { + root := buildTree(t) + ig, g := compile(t) + + m, blocked, err := Build(root, ig, g) + if err != nil { + t.Fatal(err) + } + + got := map[string]bool{} + for _, e := range m.Entries { + got[e.Path] = true + if len(e.Chunks) == 0 { + t.Errorf("%s has no chunks", e.Path) + } + } + want := []string{".env.example", "README.md", "main.go", "sub/code.go"} + for _, w := range want { + if !got[w] { + t.Errorf("expected %q in manifest, missing", w) + } + } + for _, bad := range []string{"node_modules/dep.js", "sub/app.log", ".env"} { + if got[bad] { + t.Errorf("%q should NOT be in manifest", bad) + } + } + if len(m.Entries) != len(want) { + t.Errorf("entry count = %d, want %d (%v)", len(m.Entries), len(want), m.Entries) + } + if len(blocked) != 1 || blocked[0] != ".env" { + t.Errorf("blocked = %v, want [.env]", blocked) + } +} + +func TestManifestIDStable(t *testing.T) { + root := buildTree(t) + ig, g := compile(t) + a, _, _ := Build(root, ig, g) + b, _, _ := Build(root, ig, g) + if a.ID() == "" { + t.Fatal("empty manifest ID") + } + if a.ID() != b.ID() { + t.Fatalf("manifest ID not stable: %s != %s", a.ID(), b.ID()) + } +} + +func TestDiff(t *testing.T) { + root := buildTree(t) + ig, g := compile(t) + old, _, _ := Build(root, ig, g) + + write(t, root, "sub/code.go", "package sub\n// changed\n") // modify + write(t, root, "new.txt", "fresh\n") // add + if err := os.Remove(filepath.Join(root, "README.md")); err != nil { + t.Fatal(err) + } // delete + + cur, _, _ := Build(root, ig, g) + ch := Diff(old, cur) + + if ch.Empty() { + t.Fatal("expected changes") + } + if len(ch.Modified) != 1 || ch.Modified[0] != "sub/code.go" { + t.Errorf("Modified = %v, want [sub/code.go]", ch.Modified) + } + if len(ch.Added) != 1 || ch.Added[0] != "new.txt" { + t.Errorf("Added = %v, want [new.txt]", ch.Added) + } + if len(ch.Deleted) != 1 || ch.Deleted[0] != "README.md" { + t.Errorf("Deleted = %v, want [README.md]", ch.Deleted) + } + if old.ID() == cur.ID() { + t.Error("manifest ID should change after edits") + } +} diff --git a/internal/secret/secret.go b/internal/secret/secret.go new file mode 100644 index 0000000..e3d2917 --- /dev/null +++ b/internal/secret/secret.go @@ -0,0 +1,49 @@ +// Package secret is devbox's default-on secret guard: it hard-refuses to sync +// files whose paths match a built-in deny-list (plus user extras), independent +// of .devignore. This is the "secrets never leave the machine" guarantee. +package secret + +import "git.shoemoney.ai/shoemoney/devbox/internal/ignore" + +// DefaultPatterns are always blocked from upload. Gitignore syntax, so the +// .env.example re-include works via last-match-wins. Users can un-block a +// default with a negation in their extra patterns (e.g. "!config.pem"). +var DefaultPatterns = []string{ + ".env", + ".env.*", + "!.env.example", + "*.pem", + "*.key", + "*.p12", + "*.pfx", + "*.kdbx", + "*.ppk", + "id_rsa*", + "id_dsa*", + "id_ecdsa*", + "id_ed25519*", + "secrets/", + ".aws/credentials", + ".ssh/id_*", +} + +// Guard decides whether a path must never be uploaded. +type Guard struct{ m *ignore.Matcher } + +// New compiles the default deny-list plus any extra gitignore-syntax patterns. +func New(extra []string) (*Guard, error) { + pats := make([]string, 0, len(DefaultPatterns)+len(extra)) + pats = append(pats, DefaultPatterns...) + pats = append(pats, extra...) + m, err := ignore.Compile(pats) + if err != nil { + return nil, err + } + return &Guard{m: m}, nil +} + +// Blocked reports whether path (forward-slash, relative to the share root) is a +// secret that must not be uploaded. +func (g *Guard) Blocked(path string) bool { + return g.m.Match(path, false) +} diff --git a/internal/secret/secret_test.go b/internal/secret/secret_test.go new file mode 100644 index 0000000..7a6abfd --- /dev/null +++ b/internal/secret/secret_test.go @@ -0,0 +1,44 @@ +package secret + +import "testing" + +func TestDefaultGuard(t *testing.T) { + g, err := New(nil) + if err != nil { + t.Fatal(err) + } + blocked := []string{ + ".env", ".env.local", ".env.production", + "key.pem", "server.key", "cert.p12", "store.pfx", "vault.kdbx", + "id_rsa", "id_ed25519", "id_ed25519.pub", + "secrets/aws.json", "secrets/sub/token", ".aws/credentials", ".ssh/id_rsa", + } + for _, p := range blocked { + if !g.Blocked(p) { + t.Errorf("expected %q to be BLOCKED", p) + } + } + allowed := []string{ + ".env.example", "main.go", "README.md", "src/app.ts", + "public.cert", "notes.txt", "config.yaml", + } + for _, p := range allowed { + if g.Blocked(p) { + t.Errorf("expected %q to be ALLOWED", p) + } + } +} + +func TestExtraPatternsAndUnblock(t *testing.T) { + g, err := New([]string{"*.secretz", "!server.key"}) + if err != nil { + t.Fatal(err) + } + if !g.Blocked("creds.secretz") { + t.Error("extra pattern *.secretz should block") + } + // a user negation un-blocks a default-blocked path + if g.Blocked("server.key") { + t.Error("!server.key extra should un-block the default *.key match") + } +}