| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "slices" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "testing" |
| 15 | |
| 16 | access "amadan.net/oficina/agent-access.git" |
| 17 | "amadan.net/oficina/suite" |
| 18 | ) |
| 19 | |
| 20 | // The account link goes through both real browser proofs and confirmation; |
| 21 | // a verifier alone must never provision a Memoria identity. |
| 22 | func linkedAgentFixture(t *testing.T) (*homeRouterFixture, access.Principal) { |
| 23 | t.Helper() |
| 24 | f := newHomeRouterFixture(t) |
| 25 | f.local(t) |
| 26 | if w := f.do("GET", "/account/home", ""); w.Code != 200 { |
| 27 | t.Fatal("link page", w.Code) |
| 28 | } |
| 29 | start := homeRedirect(t, f.do("POST", "/account/home", "")) |
| 30 | if homeRedirect(t, f.exchange(t, start, "opaque-home-alice")) != "/account/home/confirm" { |
| 31 | t.Fatal("wrong link landing") |
| 32 | } |
| 33 | homeRedirect(t, f.do("POST", "/account/home/confirm", "")) |
| 34 | return f, access.Principal{Subject: "opaque-home-alice", Client: "test-agent", Grant: "grant-1", Teams: []string{"acme"}, Scopes: []string{"notes:read", "notes:write"}} |
| 35 | } |
| 36 | |
| 37 | func mountAgentFixture(t *testing.T, f *homeRouterFixture, p *access.Principal, active *bool) http.Handler { |
| 38 | t.Helper() |
| 39 | mux := http.NewServeMux() |
| 40 | err := f.app.mountAgentAccess(mux, "https://connect.example.test", "acme", access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| 41 | if !*active { |
| 42 | return access.Principal{}, access.Fail("unauthenticated", "Revoked.") |
| 43 | } |
| 44 | return *p, nil |
| 45 | })) |
| 46 | if err != nil { |
| 47 | t.Fatal(err) |
| 48 | } |
| 49 | return mux |
| 50 | } |
| 51 | |
| 52 | func agentCall(h http.Handler, name, body string) *httptest.ResponseRecorder { |
| 53 | r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/"+name, strings.NewReader(body)) |
| 54 | r.Header.Set("Content-Type", "application/json") |
| 55 | r.Header.Set("Authorization", "Bearer test-token") |
| 56 | w := httptest.NewRecorder() |
| 57 | h.ServeHTTP(responseRecorder{w}, r) |
| 58 | return w |
| 59 | } |
| 60 | |
| 61 | const agentTitleCanary = "title_canary_7f360f42e2ab4a52b47a" |
| 62 | const agentBodyCanary = "body_canary_358efd1ec48c4db9b01e" |
| 63 | const agentNoteInput = `{"team":"acme","title":"Nebula agent note ` + agentTitleCanary + `","body":"nebula private note passage ` + agentBodyCanary + `","client_id":"a8d99147-249b-40df-a8a6-c311d425e03b"}` |
| 64 | |
| 65 | func TestAgentNoteAdmissionScopeAndRetries(t *testing.T) { |
| 66 | f, p := linkedAgentFixture(t) |
| 67 | active := true |
| 68 | h := mountAgentFixture(t, f, &p, &active) |
| 69 | first := agentCall(h, "notes_create", agentNoteInput) |
| 70 | if first.Code != 200 { |
| 71 | t.Fatal(first.Code, first.Body.String()) |
| 72 | } |
| 73 | var result agentNoteResult |
| 74 | if json.Unmarshal(first.Body.Bytes(), &result) != nil || result.ID <= 0 || !result.Indexed { |
| 75 | t.Fatal("invalid receipt") |
| 76 | } |
| 77 | var wg sync.WaitGroup |
| 78 | for range 5 { |
| 79 | wg.Go(func() { |
| 80 | w := agentCall(h, "notes_create", agentNoteInput) |
| 81 | if w.Code != 200 || w.Body.String() != first.Body.String() { |
| 82 | t.Errorf("retry: %d", w.Code) |
| 83 | } |
| 84 | }) |
| 85 | } |
| 86 | wg.Wait() |
| 87 | if w := agentCall(h, "notes_create", strings.Replace(agentNoteInput, "private note passage", "different passage", 1)); w.Code != 409 { |
| 88 | t.Fatal("mismatched retry", w.Code) |
| 89 | } |
| 90 | if w := agentCall(h, "notes_create", strings.Replace(agentNoteInput, "Nebula agent note", "Different title", 1)); w.Code != 409 { |
| 91 | t.Fatal("title mismatch retry", w.Code) |
| 92 | } |
| 93 | var count int |
| 94 | if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 { |
| 95 | t.Fatal("duplicate created", count, err) |
| 96 | } |
| 97 | var sealedBody []byte |
| 98 | if err := f.app.db.Writer().QueryRow("SELECT sealed_body FROM documents WHERE id=?", result.ID).Scan(&sealedBody); err != nil { |
| 99 | t.Fatal(err) |
| 100 | } |
| 101 | if strings.Contains(string(sealedBody), "private note") { |
| 102 | t.Fatal("body stored unsealed") |
| 103 | } |
| 104 | var coordinate, content string |
| 105 | if err := f.app.db.Writer().QueryRow("SELECT coordinate,content FROM memoria_agent_notes").Scan(&coordinate, &content); err != nil { |
| 106 | t.Fatal(err) |
| 107 | } |
| 108 | if len(coordinate) != 64 || len(content) != 64 || strings.Contains(coordinate+content, p.Subject) { |
| 109 | t.Fatal("receipt is not fingerprinted") |
| 110 | } |
| 111 | |
| 112 | checks := []struct { |
| 113 | name string |
| 114 | change func() |
| 115 | restore func() |
| 116 | }{ |
| 117 | {"read-only grant", func() { p.Scopes = []string{"notes:read"} }, func() { p.Scopes = []string{"notes:read", "notes:write"} }}, |
| 118 | {"wrong instance team", func() { p.Teams = []string{"other"} }, func() { p.Teams = []string{"acme"} }}, |
| 119 | {"unlinked subject", func() { p.Subject = "unlinked-home-bob" }, func() { p.Subject = "opaque-home-alice" }}, |
| 120 | {"local removal", func() { f.app.SetOwners([]string{"bob@example.test"}) }, func() { f.app.SetOwners([]string{"alice@example.test"}) }}, |
| 121 | {"revoked grant", func() { active = false }, func() { active = true }}, |
| 122 | } |
| 123 | for _, tc := range checks { |
| 124 | t.Run(tc.name, func(t *testing.T) { |
| 125 | tc.change() |
| 126 | defer tc.restore() |
| 127 | var identitiesBefore, linksBefore, identitiesAfter, linksAfter int |
| 128 | if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&identitiesBefore); err != nil { |
| 129 | t.Fatal(err) |
| 130 | } |
| 131 | if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM home_identity_links").Scan(&linksBefore); err != nil { |
| 132 | t.Fatal(err) |
| 133 | } |
| 134 | w := agentCall(h, "notes_create", strings.Replace(agentNoteInput, "a8d99147", "b8d99147", 1)) |
| 135 | if w.Code != 401 && w.Code != 403 { |
| 136 | t.Fatal(w.Code, w.Body.String()) |
| 137 | } |
| 138 | if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 { |
| 139 | t.Fatal("denial changed documents", count, err) |
| 140 | } |
| 141 | if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&identitiesAfter); err != nil { |
| 142 | t.Fatal(err) |
| 143 | } |
| 144 | if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM home_identity_links").Scan(&linksAfter); err != nil { |
| 145 | t.Fatal(err) |
| 146 | } |
| 147 | if identitiesBefore != identitiesAfter || linksBefore != linksAfter { |
| 148 | t.Fatal("denial provisioned identity or link") |
| 149 | } |
| 150 | }) |
| 151 | } |
| 152 | // A cookie may authorize the browser UI, but cannot replace a bearer. |
| 153 | r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/notes_create", strings.NewReader(agentNoteInput)) |
| 154 | for _, cookie := range f.cookies { |
| 155 | r.AddCookie(cookie) |
| 156 | } |
| 157 | w := httptest.NewRecorder() |
| 158 | h.ServeHTTP(responseRecorder{w}, r) |
| 159 | if w.Code != 401 { |
| 160 | t.Fatal("cookie authorized delegated API", w.Code) |
| 161 | } |
| 162 | p.Teams = []string{"other"} |
| 163 | r = httptest.NewRequest("GET", homeTestOrigin+"/api/v1/operations", nil) |
| 164 | r.Header.Set("Authorization", "Bearer test-token") |
| 165 | w = httptest.NewRecorder() |
| 166 | h.ServeHTTP(responseRecorder{w}, r) |
| 167 | if w.Code != 403 { |
| 168 | t.Fatal("wrong instance team discovered operations", w.Code) |
| 169 | } |
| 170 | p.Teams = []string{"acme"} |
| 171 | assertAgentContentSealed(t, f) |
| 172 | if err := f.app.store.Delete(t.Context(), result.ID); err != nil { |
| 173 | t.Fatal(err) |
| 174 | } |
| 175 | w = agentCall(h, "notes_create", agentNoteInput) |
| 176 | if w.Code != 404 { |
| 177 | t.Fatal("deleted receipt succeeded", w.Code) |
| 178 | } |
| 179 | if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 0 { |
| 180 | t.Fatal("replay recreated deleted note", count, err) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | func TestAgentSearchRechecksSiblingPermission(t *testing.T) { |
| 185 | f, p := linkedAgentFixture(t) |
| 186 | active := true |
| 187 | h := mountAgentFixture(t, f, &p, &active) |
| 188 | custody := &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| 189 | f.app.store.custody = custody |
| 190 | if w := agentCall(h, "notes_create", agentNoteInput); w.Code != 200 { |
| 191 | t.Fatal(w.Code) |
| 192 | } |
| 193 | if _, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "Docs", Key: "agent-sibling", Title: "Sibling nebula", Body: "nebula sibling secret", ItemID: "docs-one", SiblingRevision: 1}); err != nil { |
| 194 | t.Fatal(err) |
| 195 | } |
| 196 | input := `{"team":"acme","query":"nebula"}` |
| 197 | w := agentCall(h, "notes_search", input) |
| 198 | if w.Code != 200 || !strings.Contains(w.Body.String(), "sibling secret") || !strings.Contains(w.Body.String(), "private note passage") { |
| 199 | t.Fatal("positive search", w.Code, w.Body.String()) |
| 200 | } |
| 201 | if custody.asker.Kind != suite.SubjectAddress || custody.asker.Value != "alice@example.test" { |
| 202 | t.Fatal("wrong sibling asker", custody.asker) |
| 203 | } |
| 204 | custody.give = suite.NOT_VISIBLE |
| 205 | w = agentCall(h, "notes_search", input) |
| 206 | if w.Code != 200 || strings.Contains(w.Body.String(), "sibling secret") || strings.Contains(w.Body.String(), "Sibling nebula") || !strings.Contains(w.Body.String(), "private note passage") { |
| 207 | t.Fatal("sibling refusal not enforced", w.Code, w.Body.String()) |
| 208 | } |
| 209 | // First query: search plus preheader and first-chunk checks. The second |
| 210 | // query withholds the sibling before selection and needs no custody replay. |
| 211 | if custody.calls != 4 { |
| 212 | t.Fatal("did not ask sibling on each query", custody.calls) |
| 213 | } |
| 214 | // A grant for two teams still cannot select the other instance's team. |
| 215 | p.Teams = []string{"acme", "other"} |
| 216 | if w = agentCall(h, "notes_search", `{"team":"other","query":"nebula"}`); w.Code != 403 { |
| 217 | t.Fatal("cross-instance team", w.Code) |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | // Review-selected gate: scanning complete database files catches a newly added |
| 222 | // plaintext column that selected-column assertions would miss. Existing local |
| 223 | // auth sessions predate this API and contain addresses; the new content canaries |
| 224 | // must be absent from every file, including WAL and temporary files. |
| 225 | func assertAgentContentSealed(t *testing.T, f *homeRouterFixture) { |
| 226 | t.Helper() |
| 227 | var dbPath string |
| 228 | if err := f.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&dbPath); err != nil { |
| 229 | t.Fatal(err) |
| 230 | } |
| 231 | scan := func() { |
| 232 | err := filepath.WalkDir(filepath.Dir(dbPath), func(path string, entry os.DirEntry, err error) error { |
| 233 | if err != nil { |
| 234 | return err |
| 235 | } |
| 236 | if entry.IsDir() { |
| 237 | return nil |
| 238 | } |
| 239 | data, err := os.ReadFile(path) |
| 240 | if err != nil { |
| 241 | return err |
| 242 | } |
| 243 | for _, canary := range []string{agentTitleCanary, agentBodyCanary} { |
| 244 | if bytes.Contains(data, []byte(canary)) { |
| 245 | t.Error("readable content persisted in database files") |
| 246 | } |
| 247 | } |
| 248 | return nil |
| 249 | }) |
| 250 | if err != nil { |
| 251 | t.Fatal(err) |
| 252 | } |
| 253 | } |
| 254 | scan() |
| 255 | if _, err := f.app.db.Writer().Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil { |
| 256 | t.Fatal(err) |
| 257 | } |
| 258 | scan() |
| 259 | } |
| 260 | |
| 261 | func TestAgentIdentityStorageFailureIsUnavailable(t *testing.T) { |
| 262 | f, p := linkedAgentFixture(t) |
| 263 | active := true |
| 264 | h := mountAgentFixture(t, f, &p, &active) |
| 265 | f.app.db.Close() |
| 266 | if w := agentCall(h, "notes_create", agentNoteInput); w.Code != 503 { |
| 267 | t.Fatal("storage failure misreported", w.Code) |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | func TestAgentAccessConfigurationFailsClosed(t *testing.T) { |
| 272 | f := newHomeRouterFixture(t) |
| 273 | for _, cfg := range []Config{ |
| 274 | {Origin: homeTestOrigin, AgentTeam: "acme"}, |
| 275 | {Origin: homeTestOrigin, AgentIssuer: "https://connect.example.test"}, |
| 276 | {Origin: homeTestOrigin, AgentTeam: "acme", AgentIssuer: "http://insecure.example.test"}, |
| 277 | } { |
| 278 | if f.app.WireAgentAccess(http.NewServeMux(), cfg) == nil { |
| 279 | t.Fatal("accepted invalid configuration") |
| 280 | } |
| 281 | } |
| 282 | mux := http.NewServeMux() |
| 283 | if err := f.app.WireAgentAccess(mux, Config{}); err != nil { |
| 284 | t.Fatal(err) |
| 285 | } |
| 286 | if w := agentCall(mux, "notes_create", agentNoteInput); w.Code != 404 { |
| 287 | t.Fatal("disabled endpoint mounted", w.Code) |
| 288 | } |
| 289 | f.app.home = nil |
| 290 | if f.app.WireAgentAccess(mux, Config{Origin: homeTestOrigin, AgentTeam: "acme", AgentIssuer: "https://connect.example.test"}) == nil { |
| 291 | t.Fatal("enabled without Home") |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | // Review-selected 2026-10-24: bind every coordinate field and distinguish |
| 296 | // independent clients reusing the same UUID. Deleting any field must go red. |
| 297 | func TestAgentReceiptCoordinateAndSchema(t *testing.T) { |
| 298 | f, p := linkedAgentFixture(t) |
| 299 | active := true |
| 300 | h := mountAgentFixture(t, f, &p, &active) |
| 301 | for _, client := range []string{"first-agent", "second-agent"} { |
| 302 | p.Client = client |
| 303 | w := agentCall(h, "notes_create", agentNoteInput) |
| 304 | if w.Code != 200 { |
| 305 | t.Fatal(w.Code, w.Body.String()) |
| 306 | } |
| 307 | coordinate, _ := json.Marshal([]string{f.app.home.issuer, f.app.agentIssuer, p.Subject, client, "acme", "a8d99147-249b-40df-a8a6-c311d425e03b"}) |
| 308 | expected, err := f.app.store.sealer.Fingerprint("agent.note.coordinate.v1", coordinate) |
| 309 | if err != nil { |
| 310 | t.Fatal(err) |
| 311 | } |
| 312 | var count int |
| 313 | if err = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_agent_notes WHERE coordinate=?", expected).Scan(&count); err != nil || count != 1 { |
| 314 | t.Fatal("coordinate binding", count, err) |
| 315 | } |
| 316 | } |
| 317 | var count int |
| 318 | if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 2 { |
| 319 | t.Fatal("independent client receipts collided", count, err) |
| 320 | } |
| 321 | rows, err := f.app.db.Writer().Query("SELECT name FROM pragma_table_info('memoria_agent_notes') ORDER BY cid") |
| 322 | if err != nil { |
| 323 | t.Fatal(err) |
| 324 | } |
| 325 | defer rows.Close() |
| 326 | var columns []string |
| 327 | for rows.Next() { |
| 328 | var name string |
| 329 | if err = rows.Scan(&name); err != nil { |
| 330 | t.Fatal(err) |
| 331 | } |
| 332 | columns = append(columns, name) |
| 333 | } |
| 334 | if err = rows.Err(); err != nil { |
| 335 | t.Fatal(err) |
| 336 | } |
| 337 | if !slices.Equal(columns, []string{"coordinate", "content", "document_id", "indexed"}) { |
| 338 | t.Fatal("receipt schema retains extra data", columns) |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | func TestAgentRechecksDeletedLocalIdentity(t *testing.T) { |
| 343 | f, p := linkedAgentFixture(t) |
| 344 | active := true |
| 345 | h := mountAgentFixture(t, f, &p, &active) |
| 346 | if w := agentCall(h, "notes_create", agentNoteInput); w.Code != 200 { |
| 347 | t.Fatal(w.Code) |
| 348 | } |
| 349 | if _, err := f.app.db.Writer().Exec("DELETE FROM memoria_home_local_identities"); err != nil { |
| 350 | t.Fatal(err) |
| 351 | } |
| 352 | if w := agentCall(h, "notes_create", strings.Replace(agentNoteInput, "a8d99147", "b8d99147", 1)); w.Code != 403 { |
| 353 | t.Fatal("removed identity authorized", w.Code) |
| 354 | } |
| 355 | var count int |
| 356 | if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&count); err != nil || count != 0 { |
| 357 | t.Fatal("identity recreated", count, err) |
| 358 | } |
| 359 | if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 { |
| 360 | t.Fatal("denial changed documents", count, err) |
| 361 | } |
| 362 | } |
| 363 | |