package thin import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/attach" "amadan.net/oficina/equipo/internal/wire" "amadan.net/oficina/equipo/internal/wire/wiretest" "github.com/coder/websocket" ) func chunkFrames(t *testing.T, person, id, name string, data []byte, first int) ([][]byte, wire.AttachmentRef) { t.Helper() sum := sha256.Sum256(data) ref := wire.AttachmentRef{ID: id, Kind: wire.AttachmentFile, Name: name, MediaType: attach.Text, Size: int64(len(data)), SHA256: hex.EncodeToString(sum[:])} count := attach.Chunks(ref.Size) var out [][]byte for i := 0; i < count; i++ { end := min(len(data), (i+1)*attach.ChunkBytes) f, _ := wire.NewFrame("c"+itoa(int64(first+i)), wire.FrameAttachment, wire.AttachmentChunk{Person: person, AttachmentRef: ref, Index: i, Count: count, Data: data[i*attach.ChunkBytes : end]}) raw, _ := json.Marshal(f) out = append(out, raw) } return out, ref } // handshake answers a fresh connection: hello in, welcome out, sync in. func handshake(t *testing.T, c *websocket.Conn) { t.Helper() read(t, c, wire.FrameHello) write(t, c, wiretest.Fixture("frames/welcome.json")) read(t, c, wire.FrameSync) } func ackOf(t *testing.T, c *websocket.Conn) string { t.Helper() f, _ := read(t, c, wire.FrameAck) var a wire.Ack json.Unmarshal(f.Data, &a) return a.ID } // TestRunnerAttachmentExactlyOnce: chunks are written and acked one by // one; the stream drops after two; on reconnect the instance resends what // it has not seen acked (and, as a resend can, one it has); the file is // assembled once, checked against its SHA-256, moved read-only into the // desk, and the turn that names it runs once with it. func TestRunnerAttachmentExactlyOnce(t *testing.T) { inst := newFakeInstance(t) coord := &stubCoordinator{} link, state, _, _ := startLink(t, inst.url, coord) c := <-inst.conns handshake(t, c) data := []byte(strings.Repeat("a line of the log\n", 20000)) // 360,000 bytes: 3 chunks frames, ref := chunkFrames(t, "owner@example.com", "at_0001notes", "build.log", data, 10) for _, raw := range frames[:2] { write(t, c, raw) ackOf(t, c) } c.Close(websocket.StatusGoingAway, "dropped") c = <-inst.conns handshake(t, c) for _, raw := range frames { write(t, c, raw) ackOf(t, c) } msg, _ := wire.NewFrame("c13", wire.FrameMessage, wire.MessageCommand{Person: "owner@example.com", TurnID: "t_0001", Attempt: 1, Text: "what broke?", PersonText: []string{"what broke?"}, Tail: []wire.TailMessage{}, Attachments: []wire.AttachmentRef{ref}}) rawMsg, _ := json.Marshal(msg) write(t, c, rawMsg) if id := ackOf(t, c); id != "c13" { t.Fatalf("ack %s", id) } read(t, c, wire.FrameReply) // Resent again after the turn (an ack the instance lost): no-ops. write(t, c, frames[2]) ackOf(t, c) write(t, c, rawMsg) ackOf(t, c) time.Sleep(100 * time.Millisecond) coord.mu.Lock() turns := append([]TurnInput(nil), coord.turns...) coord.mu.Unlock() if len(turns) != 1 || len(turns[0].Attachments) != 1 || turns[0].Attachments[0] != ref { t.Fatalf("turns %+v", turns) } desk, err := OpenDesk(link.Files.SessionRoot, "owner@example.com") if err != nil { t.Fatal(err) } held, err := heldFiles(desk, turns[0].Attachments) if err != nil || len(held) != 1 || held[0].Path != "/workspace/attachments/at_0001notes/build.log" { t.Fatalf("held %+v %v", held, err) } info, err := os.Stat(held[0].Host) if err != nil || info.Mode().Perm() != 0400 { t.Fatalf("delivered file %v %v", info, err) } if parts, _ := filepath.Glob(filepath.Join(filepath.Dir(desk.Dir), "incoming", "*")); len(parts) != 0 { t.Fatalf("leftover parts %v", parts) } var left int state.db.QueryRow("SELECT count(*) FROM file_chunks").Scan(&left) if left != 0 { t.Fatalf("%d chunk rows left", left) } } // TestAttachmentIntegrity: a file whose bytes do not match its SHA-256 is // discarded, not delivered; a chunk that is not valid is refused; and a // turn's files are checked again before it starts. func TestAttachmentIntegrity(t *testing.T) { ctx := context.Background() state, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer state.Close() root := filepath.Join(t.TempDir(), "sessions") os.MkdirAll(root, 0700) files := &Files{State: state, SessionRoot: root} data := []byte("the real notes\n") sum := sha256.Sum256([]byte("other bytes entirely")) ref := wire.AttachmentRef{ID: "at_0002forged", Kind: wire.AttachmentFile, Name: "notes.txt", MediaType: attach.Text, Size: int64(len(data)), SHA256: hex.EncodeToString(sum[:])} if err := files.Accept(ctx, "c1", wire.AttachmentChunk{Person: "p@example.com", AttachmentRef: ref, Index: 0, Count: 1, Data: data}); err != nil { t.Fatal(err) } desk, _ := OpenDesk(root, "p@example.com") if _, err := os.Stat(filepath.Join(desk.Dir, "attachments", ref.ID, ref.Name)); !os.IsNotExist(err) { t.Fatal("a file that does not match its hash was delivered") } if _, err := heldFiles(desk, []wire.AttachmentRef{ref}); err != errMissingFile { t.Fatalf("held a missing file: %v", err) } // Not valid: a path in the name, a short chunk, an unknown type. good := sha256.Sum256(data) ref.SHA256 = hex.EncodeToString(good[:]) for i, bad := range []wire.AttachmentChunk{ {Person: "p@example.com", AttachmentRef: wire.AttachmentRef{ID: ref.ID, Kind: ref.Kind, Name: "../escape.txt", MediaType: ref.MediaType, Size: ref.Size, SHA256: ref.SHA256}, Count: 1, Data: data}, {Person: "p@example.com", AttachmentRef: ref, Count: 1, Data: data[:3]}, {Person: "p@example.com", AttachmentRef: wire.AttachmentRef{ID: ref.ID, Kind: ref.Kind, Name: ref.Name, MediaType: "application/x-sh", Size: ref.Size, SHA256: ref.SHA256}, Count: 1, Data: data}, {Person: "p@example.com", AttachmentRef: ref, Index: 1, Count: 2, Data: data}, } { if validChunk(bad) || files.Accept(ctx, "bad"+itoa(int64(i)), bad) != nil { t.Fatalf("chunk %d was taken", i) } } if entries, _ := os.ReadDir(filepath.Join(desk.Dir, "attachments")); len(entries) != 0 { t.Fatal("a refused chunk left a file on the desk") } // Whole and matching: delivered; then changed on disk: refused again. if err := files.Accept(ctx, "c2", wire.AttachmentChunk{Person: "p@example.com", AttachmentRef: ref, Index: 0, Count: 1, Data: data}); err != nil { t.Fatal(err) } held, err := heldFiles(desk, []wire.AttachmentRef{ref}) if err != nil { t.Fatal(err) } os.Chmod(held[0].Host, 0600) os.WriteFile(held[0].Host, []byte("the real notez\n"), 0600) if _, err := heldFiles(desk, []wire.AttachmentRef{ref}); err != errMissingFile { t.Fatal("a changed file was used") } } func filesRig(t *testing.T) (*Files, context.Context) { t.Helper() ctx := context.Background() state, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } t.Cleanup(func() { state.Close() }) root := filepath.Join(t.TempDir(), "sessions") os.MkdirAll(root, 0700) return &Files{State: state, SessionRoot: root}, ctx } func chunksOf(person, id, name string, data []byte) ([]wire.AttachmentChunk, wire.AttachmentRef) { sum := sha256.Sum256(data) ref := wire.AttachmentRef{ID: id, Kind: wire.AttachmentFile, Name: name, MediaType: attach.Text, Size: int64(len(data)), SHA256: hex.EncodeToString(sum[:])} n := attach.Chunks(ref.Size) var out []wire.AttachmentChunk for i := 0; i < n; i++ { out = append(out, wire.AttachmentChunk{Person: person, AttachmentRef: ref, Index: i, Count: n, Data: data[i*attach.ChunkBytes : min(len(data), (i+1)*attach.ChunkBytes)]}) } return out, ref } // Astra round 1: a filesystem failure while finishing deleted the chunks // and let the frame be acked, so the file could never be rebuilt; a crash // between chmod and rename left a part replay could not write. At each // step of finishing, a failure returns an error (the frame is not acked) // and keeps every chunk; replaying the frame delivers the file whole. func TestAttachmentFinishCrashes(t *testing.T) { data := []byte(strings.Repeat("crash at each step\n", 16000)) // 3 chunks for _, step := range []string{"verify", "ready", "chmod", "mkdir", "rename", "forget"} { t.Run(step, func(t *testing.T) { t.Parallel() f, ctx := filesRig(t) chunks, ref := chunksOf("p@example.com", "at_crash"+step, "build.log", data) for i, c := range chunks[:len(chunks)-1] { if err := f.Accept(ctx, "c"+itoa(int64(i)), c); err != nil { t.Fatal(err) } } f.fault = func(s string) error { if s == step { return errors.New("disk said no at " + s) } return nil } last := chunks[len(chunks)-1] if err := f.Accept(ctx, "c-last", last); err == nil { t.Fatal("a failure while finishing was acked") } var rows int f.State.db.QueryRow("SELECT count(*) FROM file_chunks WHERE attachment_id=?", ref.ID).Scan(&rows) if step != "forget" && rows != len(chunks) { t.Fatalf("%d of %d chunk records kept", rows, len(chunks)) } f.fault = nil if err := f.Accept(ctx, "c-last", last); err != nil { t.Fatalf("replay: %v", err) } desk, _ := OpenDesk(f.SessionRoot, "p@example.com") held, err := heldFiles(desk, []wire.AttachmentRef{ref}) if err != nil { t.Fatalf("not delivered after replay: %v", err) } if info, _ := os.Stat(held[0].Host); info.Mode().Perm() != 0400 { t.Fatalf("mode %v", info.Mode()) } left, _ := filepath.Glob(filepath.Join(filepath.Dir(desk.Dir), "incoming", "*")) f.State.db.QueryRow("SELECT count(*) FROM file_chunks").Scan(&rows) if len(left) != 0 || rows != 0 { t.Fatalf("left %v and %d records", left, rows) } }) } } // Astra round 1: retention had no aggregate bound and ran only when a // file arrived. Sweep removes stale parts with their records, records with // no file, files past retention, and, over a person's or the runner's // quota, the oldest delivered files first; never one a running turn names // (b3, the newest, stays only because the quota is met without it). func TestAttachmentSweep(t *testing.T) { f, ctx := filesRig(t) deliver := func(person, id string, age time.Duration) wire.AttachmentRef { t.Helper() chunks, ref := chunksOf(person, id, "n.txt", []byte(strings.Repeat("x", 100))) if err := f.Accept(ctx, "f-"+id, chunks[0]); err != nil { t.Fatal(err) } desk, _ := OpenDesk(f.SessionRoot, person) at := time.Now().Add(-age) if err := os.Chtimes(filepath.Join(desk.Dir, attachmentsDir, id), at, at); err != nil { t.Fatal(err) } return ref } exists := func(person, id string) bool { desk, _ := OpenDesk(f.SessionRoot, person) _, err := os.Stat(filepath.Join(desk.Dir, attachmentsDir, id)) return err == nil } const a, b = "a@example.com", "b@example.com" // a1, the oldest, is named by a running turn; so is b1, past retention. ref := func(id string) wire.AttachmentRef { _, r := chunksOf("", id, "n.txt", []byte(strings.Repeat("x", 100))) return r } if err := f.State.Accept(ctx, "m1", wire.MessageCommand{Person: a, TurnID: "t_1", Attempt: 1, Text: "x", PersonText: []string{"x"}, Tail: []wire.TailMessage{}, Attachments: []wire.AttachmentRef{ref("at_a1aaaaaaaa"), ref("at_b1bbbbbbbb")}}); err != nil { t.Fatal(err) } deliver(a, "at_a1aaaaaaaa", 5*time.Hour) deliver(a, "at_a2aaaaaaaa", 4*time.Hour) deliver(a, "at_a3aaaaaaaa", 3*time.Hour) deliver(a, "at_a4aaaaaaaa", 2*time.Hour) deliver(b, "at_b1bbbbbbbb", 15*24*time.Hour) deliver(b, "at_b2bbbbbbbb", 6*time.Hour) deliver(b, "at_b3bbbbbbbb", 30*time.Minute) // A stale part with its records, and records with no file at all. desk, _ := OpenDesk(f.SessionRoot, b) incoming := filepath.Join(filepath.Dir(desk.Dir), "incoming") os.MkdirAll(incoming, 0700) stale := filepath.Join(incoming, "at_stale0000.part") os.WriteFile(stale, []byte("half"), 0600) then := time.Now().Add(-3 * 24 * time.Hour) os.Chtimes(stale, then, then) fresh := filepath.Join(incoming, "at_fresh0000.part") os.WriteFile(fresh, []byte("half"), 0600) for _, id := range []string{"at_stale0000", "at_orphan000", "at_fresh0000"} { f.State.db.Exec("INSERT INTO file_chunks(attachment_id, idx) VALUES(?,0)", id) } // Their messages came and went (the admissions are done); then the // quota shrinks below what is held. f.State.db.Exec("DELETE FROM file_admits") f.Quota = Quota{PersonBytes: 250, PersonFiles: 100, TotalBytes: 1 << 30, TotalFiles: 4} f.Sweep(ctx) // Person a: 400 bytes over 250; a1 is protected, so a2 and a3 go. for id, want := range map[string]bool{"at_a1aaaaaaaa": true, "at_a2aaaaaaaa": false, "at_a3aaaaaaaa": false, "at_a4aaaaaaaa": true} { if exists(a, id) != want { t.Fatalf("%s kept=%v, want %v", id, !want, want) } } // The runner: at most 4 files; b1 is protected though past retention. for id, want := range map[string]bool{"at_b1bbbbbbbb": true, "at_b2bbbbbbbb": false, "at_b3bbbbbbbb": true} { if exists(b, id) != want { t.Fatalf("%s kept=%v, want %v", id, !want, want) } } if _, err := os.Stat(stale); !os.IsNotExist(err) { t.Fatal("a stale part stayed") } var ids []string rows, _ := f.State.db.Query("SELECT attachment_id FROM file_chunks ORDER BY 1") for rows.Next() { var id string rows.Scan(&id) ids = append(ids, id) } rows.Close() if strings.Join(ids, ",") != "at_fresh0000" { t.Fatalf("chunk records left %v, want only the fresh part's", ids) } } // held is what delivered and arriving attachments hold on disk: bytes and // files under every desk's attachments and every incoming directory. func held(t *testing.T, root string) (int64, int) { t.Helper() var bytes int64 files := 0 for _, pattern := range []string{"*/desk/attachments/*/*", "*/incoming/*"} { paths, _ := filepath.Glob(filepath.Join(root, pattern)) for _, p := range paths { if info, err := os.Stat(p); err == nil && info.Mode().IsRegular() { bytes += info.Size() files++ } } } return bytes, files } // Astra round 2: the quota exempted every file delivered in the last hour // and left partial files out, so a 1-file, 1-byte quota held three files. // Admission counts arriving files by their declared size; room is made from // the oldest unprotected delivered files; failing that the file is refused // (runner_storage_full) and its chunks acked unwritten. Never a protected // file removed. func TestAttachmentQuotaAdmission(t *testing.T) { ctx := context.Background() t.Run("one file one byte", func(t *testing.T) { t.Parallel() f, _ := filesRig(t) f.Quota = Quota{PersonBytes: 1, PersonFiles: 1, TotalBytes: 1, TotalFiles: 1} for i, id := range []string{"at_q1aaaaaaaa", "at_q2aaaaaaaa", "at_q3aaaaaaaa"} { chunks, ref := chunksOf("p@example.com", id, "n.txt", []byte("ten bytes!")) if err := f.Accept(ctx, "q"+itoa(int64(i)), chunks[0]); err != nil { t.Fatal(err) } if b, n := held(t, f.SessionRoot); b > 1 || n > 1 { t.Fatalf("after %s the runner holds %d bytes in %d files", id, b, n) } if !f.State.anyRefused(ctx, []wire.AttachmentRef{ref}) { t.Fatalf("%s was not refused", id) } } }) t.Run("room from the oldest unprotected, never the protected", func(t *testing.T) { t.Parallel() f, _ := filesRig(t) f.Quota = Quota{PersonBytes: 100, PersonFiles: 1, TotalBytes: 100, TotalFiles: 1} ten := []byte("ten bytes!") c1, r1 := chunksOf("p@example.com", "at_r1aaaaaaaa", "a.txt", ten) if err := f.Accept(ctx, "r1", c1[0]); err != nil { t.Fatal(err) } // Its message names it: a running turn now protects it. if err := f.State.Accept(ctx, "m1", wire.MessageCommand{Person: "p@example.com", TurnID: "t_1", Attempt: 1, Text: "x", PersonText: []string{"x"}, Tail: []wire.TailMessage{}, Attachments: []wire.AttachmentRef{r1}}); err != nil { t.Fatal(err) } c2, r2 := chunksOf("p@example.com", "at_r2aaaaaaaa", "b.txt", ten) if err := f.Accept(ctx, "r2", c2[0]); err != nil { t.Fatal(err) } desk, _ := OpenDesk(f.SessionRoot, "p@example.com") if _, err := heldFiles(desk, []wire.AttachmentRef{r1}); err != nil || !f.State.anyRefused(ctx, []wire.AttachmentRef{r2}) { t.Fatalf("the protected file went or the new one was taken in: %v", err) } // The turn ends: r1 is no longer protected, and makes room for r3. f.State.db.Exec("UPDATE runs SET state='done'") c3, r3 := chunksOf("p@example.com", "at_r3aaaaaaaa", "c.txt", ten) if err := f.Accept(ctx, "r3", c3[0]); err != nil { t.Fatal(err) } if _, err := heldFiles(desk, []wire.AttachmentRef{r3}); err != nil { t.Fatalf("r3 not delivered: %v", err) } if _, err := heldFiles(desk, []wire.AttachmentRef{r1}); err == nil { t.Fatal("r1 kept beyond the quota") } // An arriving file counts: its first chunk holds the one file, so a // file behind it is refused while it is still arriving. f.State.db.Exec("DELETE FROM file_admits") os.RemoveAll(filepath.Join(desk.Dir, attachmentsDir)) big := []byte(strings.Repeat("y", attach.ChunkBytes+10)) f.Quota = Quota{PersonBytes: 1 << 20, PersonFiles: 1, TotalBytes: 1 << 20, TotalFiles: 1} c4, _ := chunksOf("p@example.com", "at_r4aaaaaaaa", "d.txt", big) if err := f.Accept(ctx, "r4", c4[0]); err != nil { t.Fatal(err) } c5, r5 := chunksOf("p@example.com", "at_r5aaaaaaaa", "e.txt", ten) if err := f.Accept(ctx, "r5", c5[0]); err != nil { t.Fatal(err) } if !f.State.anyRefused(ctx, []wire.AttachmentRef{r5}) { t.Fatal("an arriving file did not count against the quota") } }) } // Astra round 2: a failed protection lookup read as "nothing protected", // so a cancelled sweep removed a running turn's file. A sweep whose // lookup fails (cancelled, a query error, a record that does not decode) // removes nothing. func TestAttachmentSweepAbortsOnLookupFailure(t *testing.T) { for _, tc := range []string{"cancelled", "query", "decode"} { t.Run(tc, func(t *testing.T) { t.Parallel() f, ctx := filesRig(t) var refs []wire.AttachmentRef for _, id := range []string{"at_s1aaaaaaaa", "at_s2aaaaaaaa", "at_s3aaaaaaaa"} { chunks, ref := chunksOf("p@example.com", id, "n.txt", []byte("ten bytes!")) if err := f.Accept(ctx, "f-"+id, chunks[0]); err != nil { t.Fatal(err) } refs = append(refs, ref) } if err := f.State.Accept(ctx, "m1", wire.MessageCommand{Person: "p@example.com", TurnID: "t_1", Attempt: 1, Text: "x", PersonText: []string{"x"}, Tail: []wire.TailMessage{}, Attachments: refs[:1]}); err != nil { t.Fatal(err) } f.State.db.Exec("DELETE FROM file_admits") f.Quota = Quota{PersonBytes: 1, PersonFiles: 1, TotalBytes: 1, TotalFiles: 1} sweep := ctx switch tc { case "cancelled": c, cancel := context.WithCancel(ctx) cancel() sweep = c case "query": f.State.fault = func(op string) error { if op == "running_attachments" { return errors.New("disk I/O error") } return nil } case "decode": f.State.db.Exec("INSERT INTO runs(turn_id, person, attempt, state, text, tail, kind, person_text, attachments, created_at) VALUES('t_bad','p@example.com',1,?, 'x','[]','','[]','{not json',?)", runRunning, now()) } _, before := held(t, f.SessionRoot) f.Sweep(sweep) if _, after := held(t, f.SessionRoot); after != before { t.Fatalf("a sweep whose lookup failed removed %d files", before-after) } // A healthy sweep removes the unprotected, keeps the protected. f.State.fault = nil f.State.db.Exec("DELETE FROM runs WHERE turn_id='t_bad'") f.Sweep(ctx) desk, _ := OpenDesk(f.SessionRoot, "p@example.com") if _, err := heldFiles(desk, refs[:1]); err != nil { t.Fatal("the protected file went") } if _, after := held(t, f.SessionRoot); after != 1 { t.Fatalf("a healthy sweep left %d files", after) } }) } }