fix: foundation hardening from review pass 🛡️
- chunk.Split returns ([]Chunk, error); stop conflating read errors with EOF (latent now, would silently corrupt snapshots once streaming) + manifest propagates - watch: stop+drain timer before Reset — kills the classic race where a buffered tick leaks a premature pre-debounce signal (would sync half-written files) - config.SaveDaemon + identity.Save now atomic (temp+rename) — no truncated config - secret guard blocks a regular file literally named 'secrets' (dir-pattern slip) - identity.Load validates PEM block type; devbox status surfaces config read errors
This commit is contained in:
parent
9788442f32
commit
1522004e48
9 changed files with 93 additions and 31 deletions
|
|
@ -91,7 +91,10 @@ func statusCmd() *cobra.Command {
|
||||||
fmt.Fprintln(out, "not joined yet — run: devbox join <hub> <token>")
|
fmt.Fprintln(out, "not joined yet — run: devbox join <hub> <token>")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
d, _ := config.LoadDaemon(dir)
|
d, err := config.LoadDaemon(dir)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("reading config: %w", err)
|
||||||
|
}
|
||||||
fmt.Fprintf(out, "device: %s\n", id.Fingerprint())
|
fmt.Fprintf(out, "device: %s\n", id.Fingerprint())
|
||||||
fmt.Fprintf(out, "hub: %s\n", orNone(d.Hub))
|
fmt.Fprintf(out, "hub: %s\n", orNone(d.Hub))
|
||||||
fmt.Fprintf(out, "mounts: %d\n", len(d.Mounts))
|
fmt.Fprintf(out, "mounts: %d\n", len(d.Mounts))
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,8 @@ package chunk
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
|
||||||
fastcdc "github.com/jotfs/fastcdc-go"
|
fastcdc "github.com/jotfs/fastcdc-go"
|
||||||
"github.com/zeebo/blake3"
|
"github.com/zeebo/blake3"
|
||||||
|
|
@ -33,14 +35,16 @@ type Chunk struct {
|
||||||
// each chunk starts where the previous ended, and the sizes sum to len(data).
|
// 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
|
// Inputs smaller than MinSize yield a single chunk. Empty input yields zero
|
||||||
// chunks.
|
// chunks. A genuine read error is returned (never silently truncated) — this
|
||||||
|
// matters once Split streams from an io.Reader, where a mid-input error would
|
||||||
|
// otherwise produce a short, valid-looking chunk list with the wrong hash.
|
||||||
//
|
//
|
||||||
// ponytail: Split is in-memory — it takes the whole []byte and the underlying
|
// 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
|
// chunker reads from a bytes.Reader over it. Streaming large inputs from an
|
||||||
// io.Reader without buffering the entire payload is the upgrade path.
|
// io.Reader without buffering the entire payload is the upgrade path.
|
||||||
func Split(data []byte) []Chunk {
|
func Split(data []byte) ([]Chunk, error) {
|
||||||
if len(data) == 0 {
|
if len(data) == 0 {
|
||||||
return nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
chunker, err := fastcdc.NewChunker(bytes.NewReader(data), fastcdc.Options{
|
chunker, err := fastcdc.NewChunker(bytes.NewReader(data), fastcdc.Options{
|
||||||
|
|
@ -49,27 +53,25 @@ func Split(data []byte) []Chunk {
|
||||||
MaxSize: MaxSize,
|
MaxSize: MaxSize,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Options are compile-time constants that satisfy the library's
|
return nil, err
|
||||||
// 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
|
var chunks []Chunk
|
||||||
for {
|
for {
|
||||||
c, err := chunker.Next()
|
c, err := chunker.Next()
|
||||||
if err != nil {
|
if errors.Is(err, io.EOF) {
|
||||||
// io.EOF (or any error) ends iteration; on a bytes.Reader the only
|
|
||||||
// terminal condition is EOF after the final chunk.
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
chunks = append(chunks, Chunk{
|
chunks = append(chunks, Chunk{
|
||||||
Hash: Hash(c.Data),
|
Hash: Hash(c.Data),
|
||||||
Offset: int64(c.Offset),
|
Offset: int64(c.Offset),
|
||||||
Size: int64(c.Length),
|
Size: int64(c.Length),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return chunks
|
return chunks, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hash returns the BLAKE3-256 digest of b as a lowercase hex string.
|
// Hash returns the BLAKE3-256 digest of b as a lowercase hex string.
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,15 @@ func seededBlob(seed int64, n int) []byte {
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func mustSplit(t *testing.T, data []byte) []Chunk {
|
||||||
|
t.Helper()
|
||||||
|
c, err := Split(data)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Split error: %v", err)
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
func TestHashKnownVector(t *testing.T) {
|
func TestHashKnownVector(t *testing.T) {
|
||||||
// BLAKE3-256 of the empty input.
|
// BLAKE3-256 of the empty input.
|
||||||
const want = "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"
|
const want = "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"
|
||||||
|
|
@ -54,8 +63,8 @@ func TestSplitDeterministic(t *testing.T) {
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
a := Split(tt.data)
|
a := mustSplit(t, tt.data)
|
||||||
b := Split(tt.data)
|
b := mustSplit(t, tt.data)
|
||||||
if len(a) != len(b) {
|
if len(a) != len(b) {
|
||||||
t.Fatalf("chunk count differs: %d vs %d", len(a), len(b))
|
t.Fatalf("chunk count differs: %d vs %d", len(a), len(b))
|
||||||
}
|
}
|
||||||
|
|
@ -81,7 +90,7 @@ func TestSplitReassembly(t *testing.T) {
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
chunks := Split(tt.data)
|
chunks := mustSplit(t, tt.data)
|
||||||
|
|
||||||
// Offsets contiguous starting at 0; sizes sum to len(data).
|
// Offsets contiguous starting at 0; sizes sum to len(data).
|
||||||
var want int64
|
var want int64
|
||||||
|
|
@ -114,17 +123,17 @@ func TestSplitReassembly(t *testing.T) {
|
||||||
|
|
||||||
func TestSplitEmpty(t *testing.T) {
|
func TestSplitEmpty(t *testing.T) {
|
||||||
// Chosen behavior: empty input => zero chunks.
|
// Chosen behavior: empty input => zero chunks.
|
||||||
if got := Split(nil); len(got) != 0 {
|
if got := mustSplit(t, nil); len(got) != 0 {
|
||||||
t.Fatalf("Split(nil) = %d chunks, want 0", len(got))
|
t.Fatalf("Split(nil) = %d chunks, want 0", len(got))
|
||||||
}
|
}
|
||||||
if got := Split([]byte{}); len(got) != 0 {
|
if got := mustSplit(t, []byte{}); len(got) != 0 {
|
||||||
t.Fatalf("Split([]byte{}) = %d chunks, want 0", len(got))
|
t.Fatalf("Split([]byte{}) = %d chunks, want 0", len(got))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSplitSubMinSingleChunk(t *testing.T) {
|
func TestSplitSubMinSingleChunk(t *testing.T) {
|
||||||
data := seededBlob(99, MinSize-1)
|
data := seededBlob(99, MinSize-1)
|
||||||
chunks := Split(data)
|
chunks := mustSplit(t, data)
|
||||||
if len(chunks) != 1 {
|
if len(chunks) != 1 {
|
||||||
t.Fatalf("sub-min input produced %d chunks, want 1", len(chunks))
|
t.Fatalf("sub-min input produced %d chunks, want 1", len(chunks))
|
||||||
}
|
}
|
||||||
|
|
@ -144,8 +153,8 @@ func TestSplitDedupLocalizesEdit(t *testing.T) {
|
||||||
mutated[mid+i] ^= 0xAB // flip bits; deterministic mutation
|
mutated[mid+i] ^= 0xAB // flip bits; deterministic mutation
|
||||||
}
|
}
|
||||||
|
|
||||||
origChunks := Split(orig)
|
origChunks := mustSplit(t, orig)
|
||||||
mutChunks := Split(mutated)
|
mutChunks := mustSplit(t, mutated)
|
||||||
|
|
||||||
if len(origChunks) < 4 {
|
if len(origChunks) < 4 {
|
||||||
t.Fatalf("expected several chunks for a 1 MiB blob, got %d", len(origChunks))
|
t.Fatalf("expected several chunks for a 1 MiB blob, got %d", len(origChunks))
|
||||||
|
|
|
||||||
|
|
@ -61,15 +61,25 @@ func LoadDaemon(dir string) (Daemon, error) {
|
||||||
return d, toml.Unmarshal(b, &d)
|
return d, toml.Unmarshal(b, &d)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SaveDaemon writes daemon.toml under dir (creating dir 0700).
|
// SaveDaemon writes daemon.toml under dir atomically (temp file + rename), so a
|
||||||
|
// crash or encode error never leaves a truncated config that forgets the device's
|
||||||
|
// hub and mounts. os.Rename replaces the target atomically on POSIX and Windows.
|
||||||
func SaveDaemon(dir string, d Daemon) error {
|
func SaveDaemon(dir string, d Daemon) error {
|
||||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
f, err := os.Create(daemonPath(dir))
|
f, err := os.CreateTemp(dir, ".daemon-*.tmp")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer f.Close()
|
tmp := f.Name()
|
||||||
return toml.NewEncoder(f).Encode(d)
|
defer os.Remove(tmp) // no-op once renamed
|
||||||
|
if err := toml.NewEncoder(f).Encode(d); err != nil {
|
||||||
|
f.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := f.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Rename(tmp, daemonPath(dir))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -39,17 +39,39 @@ func (id Identity) Fingerprint() string {
|
||||||
return hex.EncodeToString(sum[:8]) // 16 hex chars
|
return hex.EncodeToString(sum[:8]) // 16 hex chars
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save writes the keypair under dir (private key 0600, dir 0700).
|
// Save writes the keypair under dir atomically (private key 0600, dir 0700).
|
||||||
func (id Identity) Save(dir string) error {
|
func (id Identity) Save(dir string) error {
|
||||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
priv := pem.EncodeToMemory(&pem.Block{Type: "DEVBOX PRIVATE KEY", Bytes: id.Priv})
|
priv := pem.EncodeToMemory(&pem.Block{Type: "DEVBOX PRIVATE KEY", Bytes: id.Priv})
|
||||||
if err := os.WriteFile(filepath.Join(dir, privName), priv, 0o600); err != nil {
|
if err := writeFileAtomic(filepath.Join(dir, privName), priv, 0o600); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
pub := pem.EncodeToMemory(&pem.Block{Type: "DEVBOX PUBLIC KEY", Bytes: id.Pub})
|
pub := pem.EncodeToMemory(&pem.Block{Type: "DEVBOX PUBLIC KEY", Bytes: id.Pub})
|
||||||
return os.WriteFile(filepath.Join(dir, pubName), pub, 0o644)
|
return writeFileAtomic(filepath.Join(dir, pubName), pub, 0o644)
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeFileAtomic writes data to path via a temp file + rename. CreateTemp makes
|
||||||
|
// the temp 0600, so the private key is never briefly world-readable.
|
||||||
|
func writeFileAtomic(path string, data []byte, perm os.FileMode) error {
|
||||||
|
f, err := os.CreateTemp(filepath.Dir(path), ".tmp-*")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tmp := f.Name()
|
||||||
|
defer os.Remove(tmp)
|
||||||
|
if _, err := f.Write(data); err != nil {
|
||||||
|
f.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := f.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.Chmod(tmp, perm); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Rename(tmp, path)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load reads a keypair previously written by Save.
|
// Load reads a keypair previously written by Save.
|
||||||
|
|
@ -59,7 +81,7 @@ func Load(dir string) (Identity, error) {
|
||||||
return Identity{}, err
|
return Identity{}, err
|
||||||
}
|
}
|
||||||
block, _ := pem.Decode(raw)
|
block, _ := pem.Decode(raw)
|
||||||
if block == nil {
|
if block == nil || block.Type != "DEVBOX PRIVATE KEY" {
|
||||||
return Identity{}, fmt.Errorf("identity: bad private key PEM in %s", dir)
|
return Identity{}, fmt.Errorf("identity: bad private key PEM in %s", dir)
|
||||||
}
|
}
|
||||||
priv := ed25519.PrivateKey(block.Bytes)
|
priv := ed25519.PrivateKey(block.Bytes)
|
||||||
|
|
|
||||||
|
|
@ -73,8 +73,12 @@ func Build(root string, ig *ignore.Matcher, guard *secret.Guard) (Manifest, []st
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
cs, err := chunk.Split(data)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("chunk %s: %w", rel, err)
|
||||||
|
}
|
||||||
var hashes []string
|
var hashes []string
|
||||||
for _, c := range chunk.Split(data) {
|
for _, c := range cs {
|
||||||
hashes = append(hashes, c.Hash)
|
hashes = append(hashes, c.Hash)
|
||||||
}
|
}
|
||||||
entries = append(entries, Entry{
|
entries = append(entries, Entry{
|
||||||
|
|
|
||||||
|
|
@ -43,7 +43,9 @@ func New(extra []string) (*Guard, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Blocked reports whether path (forward-slash, relative to the share root) is a
|
// Blocked reports whether path (forward-slash, relative to the share root) is a
|
||||||
// secret that must not be uploaded.
|
// secret that must not be uploaded. It checks the path as both a file and a
|
||||||
|
// directory name so a dir-only pattern like "secrets/" also blocks a regular
|
||||||
|
// file literally named "secrets" — the secret guarantee should never slip.
|
||||||
func (g *Guard) Blocked(path string) bool {
|
func (g *Guard) Blocked(path string) bool {
|
||||||
return g.m.Match(path, false)
|
return g.m.Match(path, false) || g.m.Match(path, true)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ func TestDefaultGuard(t *testing.T) {
|
||||||
"key.pem", "server.key", "cert.p12", "store.pfx", "vault.kdbx",
|
"key.pem", "server.key", "cert.p12", "store.pfx", "vault.kdbx",
|
||||||
"id_rsa", "id_ed25519", "id_ed25519.pub",
|
"id_rsa", "id_ed25519", "id_ed25519.pub",
|
||||||
"secrets/aws.json", "secrets/sub/token", ".aws/credentials", ".ssh/id_rsa",
|
"secrets/aws.json", "secrets/sub/token", ".aws/credentials", ".ssh/id_rsa",
|
||||||
|
"secrets", // a regular file literally named "secrets" must also be blocked
|
||||||
}
|
}
|
||||||
for _, p := range blocked {
|
for _, p := range blocked {
|
||||||
if !g.Blocked(p) {
|
if !g.Blocked(p) {
|
||||||
|
|
|
||||||
|
|
@ -82,6 +82,15 @@ func (w *Watcher) loop() {
|
||||||
if timer == nil {
|
if timer == nil {
|
||||||
timer = time.NewTimer(w.debounce)
|
timer = time.NewTimer(w.debounce)
|
||||||
} else {
|
} else {
|
||||||
|
// Stop and drain any already-buffered tick before Reset, so a
|
||||||
|
// tick that fired concurrently with this event can't leak through
|
||||||
|
// and trigger a premature (pre-debounce) signal.
|
||||||
|
if !timer.Stop() {
|
||||||
|
select {
|
||||||
|
case <-timer.C:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
timer.Reset(w.debounce)
|
timer.Reset(w.debounce)
|
||||||
}
|
}
|
||||||
timerC = timer.C
|
timerC = timer.C
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue