| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "log/slog" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | "amadan.net/rastrillo/rastrillo/db" |
| 16 | "gorm.io/gorm" |
| 17 | ) |
| 18 | |
| 19 | // meteredRig is a store with one metered connection of owner's, a |
| 20 | // connecting one waiting for its model, and an authority whose roster |
| 21 | // check can fail between authentication and the write (removed). |
| 22 | type meteredRig struct { |
| 23 | t *testing.T |
| 24 | s *Store |
| 25 | removed bool |
| 26 | audits []string |
| 27 | } |
| 28 | |
| 29 | func newMeteredRig(t *testing.T) *meteredRig { |
| 30 | src, err := hkTemplatePath() |
| 31 | if err != nil { |
| 32 | t.Fatal(err) |
| 33 | } |
| 34 | raw, err := os.ReadFile(src) |
| 35 | if err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | path := filepath.Join(t.TempDir(), "m.db") |
| 39 | if err := os.WriteFile(path, raw, 0o600); err != nil { |
| 40 | t.Fatal(err) |
| 41 | } |
| 42 | d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 43 | if err != nil { |
| 44 | t.Fatal(err) |
| 45 | } |
| 46 | t.Cleanup(func() { _ = d.Close() }) |
| 47 | r := &meteredRig{t: t} |
| 48 | r.s = NewStore(d, Authority{ |
| 49 | CurrentPerson: func(context.Context, *gorm.DB) error { |
| 50 | if r.removed { |
| 51 | return ErrForbidden |
| 52 | } |
| 53 | return nil |
| 54 | }, |
| 55 | Me: func(*gorm.DB, string) (wire.Me, error) { return wire.Me{Role: "owner"}, nil }, |
| 56 | PrimaryRunner: func(*gorm.DB, string) (string, error) { return "RUNNER1", nil }, |
| 57 | Copy: func(k string) string { return k }, |
| 58 | Audit: func(_ *gorm.DB, actor, kind, record string) error { |
| 59 | r.audits = append(r.audits, actor+" "+kind+" "+record) |
| 60 | return nil |
| 61 | }, |
| 62 | }, nil) |
| 63 | now := time.Date(2026, 11, 12, 12, 0, 0, 0, time.UTC) |
| 64 | r.s.now = func() time.Time { return now } |
| 65 | for _, c := range []connectionRecord{ |
| 66 | {ID: "cn_made", Person: "owner@example.com", RunnerID: "RUNNER1", LocalID: "tensorx-abc", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Billing: wire.BillingMetered, Budget: `{"day":1000000,"month":10000000,"currency":"USD","revision":1}`, BudgetApplied: 1, Spend: `{"day":0,"month":0,"currency":"USD","unknown":true,"pause_revision":3,"running":false}`, Revision: 1, CreatedAt: now, UpdatedAt: now}, |
| 67 | {ID: "cn_new", Person: "owner@example.com", RunnerID: "RUNNER1", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnConnecting, Prompt: `{"kind":"model","url":"","code":"","models":["z-ai/glm-5.3"]}`, Revision: 1, CreatedAt: now, UpdatedAt: now}, |
| 68 | } { |
| 69 | if err := d.G.Create(&c).Error; err != nil { |
| 70 | t.Fatal(err) |
| 71 | } |
| 72 | } |
| 73 | return r |
| 74 | } |
| 75 | |
| 76 | // unchanged checks no command was queued and no record moved. |
| 77 | func (r *meteredRig) unchanged(what string) { |
| 78 | r.t.Helper() |
| 79 | var commands, revisions int64 |
| 80 | r.s.db.G.Model(&commandRecord{}).Count(&commands) |
| 81 | r.s.db.G.Raw("SELECT sum(revision) FROM chat_connections").Scan(&revisions) |
| 82 | if commands != 0 || revisions != 2 || len(r.audits) != 0 { |
| 83 | r.t.Fatalf("%s changed something: %d commands, revisions %d, audits %v", what, commands, revisions, r.audits) |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | // TestMeteredWritesCheckPersonAndRoster (security round, findings 8 and |
| 88 | // 9): another person's model pick, budget change or Resume finds |
| 89 | // nothing; a person removed between authentication and the write |
| 90 | // changes nothing; the owner's budget change and Resume each append a |
| 91 | // credential-free audit event in their transaction. |
| 92 | func TestMeteredWritesCheckPersonAndRoster(t *testing.T) { |
| 93 | ctx := context.Background() |
| 94 | r := newMeteredRig(t) |
| 95 | writes := map[string]func(person string) error{ |
| 96 | "model": func(p string) error { |
| 97 | _, err := r.s.ChooseModel(ctx, p, "cn_new", wire.ChooseModel{Model: "z-ai/glm-5.3"}) |
| 98 | return err |
| 99 | }, |
| 100 | "budget": func(p string) error { |
| 101 | _, err := r.s.SetBudget(ctx, p, "cn_made", wire.SetBudget{Day: 2_000_000, Month: 10_000_000, Revision: 1}) |
| 102 | return err |
| 103 | }, |
| 104 | "resume": func(p string) error { return r.s.ResumeSpend(ctx, p, "cn_made", wire.ResumeSpend{PauseRevision: 3}) }, |
| 105 | } |
| 106 | for name, write := range writes { |
| 107 | if err := write("member@example.com"); !errors.Is(err, ErrNotFound) { |
| 108 | t.Fatalf("another person's %s: %v", name, err) |
| 109 | } |
| 110 | r.unchanged("another person's " + name) |
| 111 | r.removed = true |
| 112 | if err := write("owner@example.com"); !errors.Is(err, ErrForbidden) { |
| 113 | t.Fatalf("a removed person's %s: %v", name, err) |
| 114 | } |
| 115 | r.unchanged("a removed person's " + name) |
| 116 | r.removed = false |
| 117 | } |
| 118 | for _, name := range []string{"budget", "resume"} { |
| 119 | if err := writes[name]("owner@example.com"); err != nil { |
| 120 | t.Fatalf("%s: %v", name, err) |
| 121 | } |
| 122 | } |
| 123 | want := []string{"owner@example.com connection.budget cn_made@2", "owner@example.com connection.resume cn_made@3"} |
| 124 | if strings.Join(r.audits, "|") != strings.Join(want, "|") { |
| 125 | t.Fatalf("audits %v", r.audits) |
| 126 | } |
| 127 | } |
| 128 | |