| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | access "amadan.net/oficina/agent-access.git" |
| 5 | "amadan.net/oficina/memoria/internal/memoria/seal" |
| 6 | "amadan.net/oficina/memoria/internal/memoria/sibling" |
| 7 | "amadan.net/oficina/suite" |
| 8 | "context" |
| 9 | "errors" |
| 10 | "gorm.io/gorm" |
| 11 | "io" |
| 12 | "net/http" |
| 13 | "net/http/httptest" |
| 14 | "strings" |
| 15 | "sync/atomic" |
| 16 | "testing" |
| 17 | ) |
| 18 | |
| 19 | type responseCustody struct { |
| 20 | *fixedCustody |
| 21 | rule func([]sibling.Candidate) []sibling.Disposition |
| 22 | } |
| 23 | |
| 24 | func (c *responseCustody) Rule(_ context.Context, _ suite.Subject, items []sibling.Candidate) []sibling.Disposition { |
| 25 | return c.rule(items) |
| 26 | } |
| 27 | |
| 28 | type agentStreamWriter struct { |
| 29 | http.ResponseWriter |
| 30 | after func() |
| 31 | } |
| 32 | |
| 33 | func (w agentStreamWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| 34 | func (w agentStreamWriter) Write(b []byte) (int, error) { |
| 35 | n, e := w.ResponseWriter.Write(b) |
| 36 | w.after() |
| 37 | return n, e |
| 38 | } |
| 39 | func memoriaLiveCall(t *testing.T, h http.Handler, name, raw string) (int, []byte, error) { |
| 40 | t.Helper() |
| 41 | server := httptest.NewServer(h) |
| 42 | defer server.Close() |
| 43 | req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/"+name, strings.NewReader(raw)) |
| 44 | req.Header.Set("Authorization", "Bearer test-token") |
| 45 | req.Header.Set("Content-Type", "application/json") |
| 46 | resp, e := server.Client().Do(req) |
| 47 | if e != nil { |
| 48 | t.Fatal(e) |
| 49 | } |
| 50 | defer resp.Body.Close() |
| 51 | body, e := io.ReadAll(resp.Body) |
| 52 | return resp.StatusCode, body, e |
| 53 | } |
| 54 | func TestAgentResponseFrozenPassageCustody(t *testing.T) { |
| 55 | for _, kind := range []string{"unlink", "chunk", "revision", "item-id", "new-revision-only", "missing-disposition", "withheld", "removed-source", "during-custody-chunk", "during-custody-revision", "during-custody-unlink", "storage"} { |
| 56 | t.Run(kind, func(t *testing.T) { |
| 57 | f, p := linkedAgentFixture(t) |
| 58 | active := true |
| 59 | mountAgentFixture(t, f, &p, &active) |
| 60 | var changed atomic.Bool |
| 61 | var documentID int64 |
| 62 | custody := &responseCustody{fixedCustody: &fixedCustody{apps: docsRoster(), give: suite.VISIBLE}} |
| 63 | custody.rule = func(items []sibling.Candidate) []sibling.Disposition { |
| 64 | if changed.Load() { |
| 65 | var err error |
| 66 | switch kind { |
| 67 | case "during-custody-chunk": |
| 68 | err = f.app.db.G.Exec("DELETE FROM chunks WHERE document_id=?", documentID).Error |
| 69 | case "during-custody-revision": |
| 70 | err = f.app.db.G.Exec("UPDATE documents SET sibling_revision=2 WHERE id=?", documentID).Error |
| 71 | case "during-custody-unlink": |
| 72 | err = f.app.db.G.Exec("DELETE FROM home_identity_links").Error |
| 73 | } |
| 74 | if err != nil { |
| 75 | t.Error(err) |
| 76 | } |
| 77 | } |
| 78 | if changed.Load() && kind == "missing-disposition" { |
| 79 | return nil |
| 80 | } |
| 81 | out := make([]sibling.Disposition, len(items)) |
| 82 | for i, item := range items { |
| 83 | out[i] = sibling.Render |
| 84 | if changed.Load() && (kind == "withheld" || kind == "new-revision-only" && item.Item.Revision == 1) { |
| 85 | out[i] = sibling.Withhold |
| 86 | } |
| 87 | } |
| 88 | return out |
| 89 | } |
| 90 | f.app.store.custody = custody |
| 91 | id, e := f.app.store.Ingest(t.Context(), IngestSpec{Source: "Docs", Key: "response-sibling", Title: "Nebula private title", Body: "nebula private sibling text", ItemID: "frozen-item", SiblingRevision: 1}) |
| 92 | if e != nil { |
| 93 | t.Fatal(e) |
| 94 | } |
| 95 | if kind == "storage" { |
| 96 | if e := f.app.db.G.Callback().Query().Before("gorm:query").Register("response-storage-fault", func(tx *gorm.DB) { |
| 97 | if changed.Load() && tx.Statement.Table == "documents" { |
| 98 | tx.AddError(errors.New("private storage diagnostic")) |
| 99 | } |
| 100 | }); e != nil { |
| 101 | t.Fatal(e) |
| 102 | } |
| 103 | } |
| 104 | documentID = id |
| 105 | var checks atomic.Int32 |
| 106 | v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| 107 | if checks.Add(1) == 2 { |
| 108 | changed.Store(true) |
| 109 | var e error |
| 110 | switch kind { |
| 111 | case "unlink": |
| 112 | e = f.app.db.G.Exec("DELETE FROM home_identity_links").Error |
| 113 | case "chunk": |
| 114 | e = f.app.db.G.Exec("DELETE FROM chunks WHERE document_id=?", id).Error |
| 115 | case "revision", "new-revision-only": |
| 116 | e = f.app.db.G.Exec("UPDATE documents SET sibling_revision=2 WHERE id=?", id).Error |
| 117 | case "item-id": |
| 118 | sealed, err := f.app.store.sealer.Seal(seal.PurposeItemID, []byte("different-item")) |
| 119 | if err != nil { |
| 120 | return access.Principal{}, err |
| 121 | } |
| 122 | e = f.app.db.G.Exec("UPDATE documents SET sibling_item_id=? WHERE id=?", sealed, id).Error |
| 123 | case "removed-source": |
| 124 | delete(custody.apps, "Docs") |
| 125 | } |
| 126 | if e != nil { |
| 127 | return access.Principal{}, e |
| 128 | } |
| 129 | } |
| 130 | return p, nil |
| 131 | }) |
| 132 | mux := http.NewServeMux() |
| 133 | if e := f.app.mountAgentAccess(mux, f.app.agentIssuer, "acme", v); e != nil { |
| 134 | t.Fatal(e) |
| 135 | } |
| 136 | if strings.HasPrefix(kind, "during-custody-") { |
| 137 | // Exercise one complete app callback directly: the first chunk's |
| 138 | // second check must not mask ordering within the preheader check. |
| 139 | state := &agentRequest{} |
| 140 | ctx := context.WithValue(t.Context(), agentBoundaryKey{}, state) |
| 141 | registry, err := access.NewRegistry(f.app.agentOperations("acme")...) |
| 142 | if err != nil { |
| 143 | t.Fatal(err) |
| 144 | } |
| 145 | raw := []byte(`{"team":"acme","query":"nebula"}`) |
| 146 | result, err := registry.Call(ctx, p, "notes_search", raw) |
| 147 | if err != nil { |
| 148 | t.Fatal(err) |
| 149 | } |
| 150 | changed.Store(true) |
| 151 | if err = f.app.agentResponse(ctx, p, "notes_search", raw, result); err == nil { |
| 152 | t.Fatal("custody-time change escaped the same response check") |
| 153 | } |
| 154 | return |
| 155 | } |
| 156 | status, body, e := memoriaLiveCall(t, mux, "notes_search", `{"team":"acme","query":"nebula"}`) |
| 157 | if kind == "storage" && status != 503 { |
| 158 | t.Fatalf("storage failure masked: %d %s", status, body) |
| 159 | } |
| 160 | if e != nil || status == 200 || strings.Contains(string(body), "private") { |
| 161 | t.Fatalf("%d %s %v", status, body, e) |
| 162 | } |
| 163 | }) |
| 164 | } |
| 165 | } |
| 166 | func TestAgentResponseStreamRechecksLivePassage(t *testing.T) { |
| 167 | f, p := linkedAgentFixture(t) |
| 168 | active := true |
| 169 | h := mountAgentFixture(t, f, &p, &active) |
| 170 | id, e := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "large-title", Title: strings.Repeat("private title ", 10000), Body: "nebula passage"}) |
| 171 | if e != nil { |
| 172 | t.Fatal(e) |
| 173 | } |
| 174 | var writes atomic.Int32 |
| 175 | wrapped := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 176 | h.ServeHTTP(agentStreamWriter{w, func() { |
| 177 | if writes.Add(1) == 1 { |
| 178 | if e := f.app.db.G.Exec("DELETE FROM chunks WHERE document_id=?", id).Error; e != nil { |
| 179 | t.Error(e) |
| 180 | } |
| 181 | } |
| 182 | }}, r) |
| 183 | }) |
| 184 | status, body, e := memoriaLiveCall(t, wrapped, "notes_search", `{"team":"acme","query":"nebula"}`) |
| 185 | if status != 200 || e == nil || len(body) != 64<<10 { |
| 186 | t.Fatalf("%d %d %v", status, len(body), e) |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | func TestAgentRetryFinalGuardWithoutResponseMask(t *testing.T) { |
| 191 | f, p := linkedAgentFixture(t) |
| 192 | active := true |
| 193 | h := mountAgentFixture(t, f, &p, &active) |
| 194 | if w := agentCall(h, "notes_create", agentNoteInput); w.Code != 200 { |
| 195 | t.Fatal(w.Code) |
| 196 | } |
| 197 | var checks int |
| 198 | state := &agentRequest{verify: func(context.Context, access.Principal, string) error { |
| 199 | checks++ |
| 200 | if checks == 2 { |
| 201 | return access.Fail("unauthenticated", "Revoked.") |
| 202 | } |
| 203 | return nil |
| 204 | }} |
| 205 | ctx := context.WithValue(t.Context(), agentBoundaryKey{}, state) |
| 206 | address, err := f.app.agentAddress(ctx, p, "acme") |
| 207 | if err != nil { |
| 208 | t.Fatal(err) |
| 209 | } |
| 210 | _, err = f.app.agentCreate(ctx, p, []byte(agentNoteInput), address) |
| 211 | if err == nil || access.SafeFailure(err).Code != "unauthenticated" || checks != 2 { |
| 212 | t.Fatalf("retry final guard: %v checks=%d", err, checks) |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | func TestAgentCreateResponseReceiptAndStorage(t *testing.T) { |
| 217 | for _, kind := range []string{"storage", "receipt", "external"} { |
| 218 | t.Run(kind, func(t *testing.T) { |
| 219 | f, p := linkedAgentFixture(t) |
| 220 | var checks atomic.Int32 |
| 221 | v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| 222 | if checks.Add(1) == 4 { |
| 223 | if kind == "storage" { |
| 224 | if err := f.app.db.G.Callback().Query().Before("gorm:query").Register("response-receipt-fault", func(tx *gorm.DB) { |
| 225 | if tx.Statement.Table == "documents" { |
| 226 | tx.AddError(errors.New("private storage diagnostic")) |
| 227 | } |
| 228 | }); err != nil { |
| 229 | return access.Principal{}, err |
| 230 | } |
| 231 | } else { |
| 232 | query := "UPDATE memoria_agent_notes SET coordinate='changed'" |
| 233 | if kind == "external" { |
| 234 | query = "UPDATE documents SET external_id='changed'" |
| 235 | } |
| 236 | if err := f.app.db.G.Exec(query).Error; err != nil { |
| 237 | return access.Principal{}, err |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | return p, nil |
| 242 | }) |
| 243 | mux := http.NewServeMux() |
| 244 | if err := f.app.mountAgentAccess(mux, "https://connect.example.test", "acme", v); err != nil { |
| 245 | t.Fatal(err) |
| 246 | } |
| 247 | status, body, err := memoriaLiveCall(t, mux, "notes_create", agentNoteInput) |
| 248 | want := 404 |
| 249 | if kind == "storage" { |
| 250 | want = 503 |
| 251 | } |
| 252 | if err != nil || status != want || strings.Contains(string(body), "private") { |
| 253 | t.Fatalf("%d %s %v", status, body, err) |
| 254 | } |
| 255 | var count int64 |
| 256 | if err := f.app.db.G.Raw("SELECT count(*) FROM memoria_agent_notes WHERE document_id IS NOT NULL").Scan(&count).Error; err != nil || count != 1 { |
| 257 | t.Fatalf("response failure replayed or rolled back committed create: %d %v", count, err) |
| 258 | } |
| 259 | }) |
| 260 | } |
| 261 | } |
| 262 | |