Revalidate Memoria passages and custody during delegated response emission
10 files changed,
+430
−9
docs/superpowers/specs/2026-10-25-agent-response-authorization.md+13 −0go.mod+1 −1go.sum+2 −0internal/memoria/agent_access.go+9 −2internal/memoria/agent_access_test.go+6 −4internal/memoria/agent_boundary.go+7 −2internal/memoria/agent_create.go+7 −0internal/memoria/agent_recorder_test.go+12 −0internal/memoria/agent_response.go+112 −0internal/memoria/agent_response_test.go+261 −0
CI passed — run details
diff --git a/docs/superpowers/specs/2026-10-25-agent-response-authorization.md b/docs/superpowers/specs/2026-10-25-agent-response-authorization.md| new file mode 100644 |
| index 0000000..2b0364f |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-10-25-agent-response-authorization.md |
| @@ -0,0 +1,13 @@ |
| +# Guarded app HTTP responses |
| + |
| +Status: bounded design approved by GPT-6 Astra with the explicit continuity and fail-closed requirements below; implementation/evidence review pending. Follow-up to close the legacy adapters' response-emission gap. Docs, Sheets and Slides already have app-owned guarded emission; Calendar, Calls and Memoria still use direct Registry.HTTP output. |
| + |
| +Add a separate Registry.HTTPGuarded(initial Verifier, recheck Verifier, guard ResponseGuard) entry point. Existing HTTP behavior stays for the connection gateway and compatibility. A nonnil app guard is mandatory. Initial verification may include local admission and one rate-limit charge. Rechecks use the original underlying credential verifier, never the rate-limiting wrapper. Preserve the exact bearer and Subject/Client/Grant; require the original operation's scope and input team on each check. Discovery must retain the originally disclosed team/scope set (revoked facts cannot be emitted). Registry.Call and schemas remain the single invocation path, executed exactly once. |
| + |
| +Before serializing success, bound it to MaxPayload. The app callback receives the request context, original principal, operation name, input and result, and revalidates current local identity plus permissions for every returned resource. It must not execute a write, refresh a token or replay the operation. Call original-verifier plus app guard immediately before headers and each at-most-64-KiB write with a five-second context/write deadline (shortened to caller deadline). Fail safely before headers; abort partial HTTP bodies with ErrAbortHandler and exact Content-Length. Do not silently tolerate a transport without write-deadline support. Failure bodies contain no app result. Check the elapsed context deadline after every verifier and guard callback, including callbacks that return nil. |
| + |
| +Adapter state is per request, captured before domain execution, and retains stable local person ID/address plus the returned resource set. Calendar rechecks current calendar readability and archive state; event reads/creation capture the event and calendar IDs, then re-read the live event and reject deletion or any change to its captured calendar coordinate, and free/busy must carry calendar provenance from the same range expansion that produced its spans. Calls rechecks local membership and meeting existence; invitation responses additionally require the exact originally returned invitation to remain live and its meeting unended. Memoria checks current Home/local admission, exact live chunk/document pairs, and current sibling custody for the returned revisions. Sibling checks use the existing custody interface without replaying search or recording duplicate breaker statistics. Locally owned created notes require the same current document/receipt identity. Missing or incomplete resource provenance fails closed. Memoria freezes the original sibling item/revision coordinates; current coordinates must still match, and every original candidate must receive an explicit VISIBLE/renderable custody disposition. Missing, short, or non-renderable dispositions fail closed. Never filter a selected response midway through emission. No second model call and no repeated mutation. |
| + |
| +Tests use actual HTTP transport to prove revocation/permission loss after the first chunk truncates the body, plus preheader rejection, successful-principal continuity, metadata revocation, deadline failure/timeout, single domain invocation, and one Calls rate charge. App tests distinguish loss of local identity, item permission, invitation revocation, missing/stale chunks and changed sibling visibility. Writer-boundary regression tests must remain discriminating now that a later response guard could mask a missing transaction guard. Effective mutants omit preheader versus chunk checks independently and each app's resource guard. Run full shared and affected app CI/race checks, independent source/evidence review, then exact module pins. |
| + |
| +Consumer pins shared module 4b94ff9. Design approval: GPT-6 Astra. App implementation/evidence review is recorded in the existing agent-access branch discussion. Source and tests are additive to the already reviewed create/retry authority boundary; direct completed-retry tests prevent later HTTP checks masking missing transaction checks. |
diff --git a/go.mod b/go.mod| index 6b151b7..3236d86 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -5,7 +5,7 @@ go 1.26 |
| toolchain go1.26.5 |
| require ( |
| - amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000 |
| + amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d |
| amadan.net/oficina/estilo.git v0.0.0-20261001093750-530cb932e768 |
| amadan.net/oficina/home/connect v0.0.0-20261025004522-7430dd23a847 |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 |
diff --git a/go.sum b/go.sum| index 1d92687..f4739ce 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -1,5 +1,7 @@ |
| amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000 h1:L07nc+dmLI7c1PBkSkbnrjOK5f8p6OBbA/yTxznxCAw= |
| amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA= |
| +amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d h1:bSsf1NXVhXTfLLB9J7a5v9CqzdKj8CALHZ6W3H7A/4M= |
| +amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA= |
| amadan.net/oficina/estilo.git v0.0.0-20261001093750-530cb932e768 h1:bVscoa9fH5LdLDjlyecZhrX7JzWPT0blb57MH0FIm2U= |
| amadan.net/oficina/estilo.git v0.0.0-20261001093750-530cb932e768/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| amadan.net/oficina/home/connect v0.0.0-20261001093757-2bec942ddd0c h1:3yxO2D8BxDLMGfFV2o6Sp9Z91yLnjDCIuRKHVWORa8A= |
diff --git a/internal/memoria/agent_access.go b/internal/memoria/agent_access.go| index 56c77f2..e483565 100644 |
| --- a/internal/memoria/agent_access.go |
| +++ b/internal/memoria/agent_access.go |
| @@ -57,7 +57,7 @@ func (a *app) mountAgentAccess(mux *http.ServeMux, issuer, team string, verifier |
| } |
| return p, nil |
| }) |
| - h := a.agentBoundary(verifier, registry.HTTP(checked)) |
| + h := a.agentBoundary(verifier, registry.HTTPGuarded(checked, verifier, a.agentResponse)) |
| mux.Handle("/api/v1/operations", h) |
| mux.Handle("/api/v1/operations/", h) |
| return nil |
| @@ -79,10 +79,11 @@ func (a *app) agentAddress(ctx context.Context, p access.Principal, team string) |
| return "", access.Fail("forbidden", "Link an admitted Memoria account to Home first.") |
| } |
| if state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| - if state.personID != 0 && state.personID != person.ID { |
| + if state.personID != 0 && (state.personID != person.ID || state.address != person.Label) { |
| return "", access.Fail("forbidden", "The linked identity changed.") |
| } |
| state.personID = person.ID |
| + state.address = person.Label |
| } |
| return person.Label, nil |
| } |
| @@ -111,6 +112,9 @@ func (a *app) agentOperations(team string) []access.Operation { |
| } |
| return nil, access.Fail("unavailable", "Note storage or authority is unavailable.") |
| } |
| + if state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| + state.selected = true |
| + } |
| return out, nil |
| } |
| } |
| @@ -137,6 +141,9 @@ func (a *app) agentSearch(ctx context.Context, _ access.Principal, raw json.RawM |
| if err != nil { |
| return nil, access.Fail("unavailable", "Search is unavailable. Try again.") |
| } |
| + if state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| + state.passages = append([]Result{}, found.Results...) |
| + } |
| type result struct { |
| ID int64 `json:"id"` |
| DocumentID int64 `json:"document_id"` |
diff --git a/internal/memoria/agent_access_test.go b/internal/memoria/agent_access_test.go| index 0d91bbc..6759bd9 100644 |
| --- a/internal/memoria/agent_access_test.go |
| +++ b/internal/memoria/agent_access_test.go |
| @@ -54,7 +54,7 @@ func agentCall(h http.Handler, name, body string) *httptest.ResponseRecorder { |
| r.Header.Set("Content-Type", "application/json") |
| r.Header.Set("Authorization", "Bearer test-token") |
| w := httptest.NewRecorder() |
| - h.ServeHTTP(w, r) |
| + h.ServeHTTP(responseRecorder{w}, r) |
| return w |
| } |
| @@ -155,7 +155,7 @@ func TestAgentNoteAdmissionScopeAndRetries(t *testing.T) { |
| r.AddCookie(cookie) |
| } |
| w := httptest.NewRecorder() |
| - h.ServeHTTP(w, r) |
| + h.ServeHTTP(responseRecorder{w}, r) |
| if w.Code != 401 { |
| t.Fatal("cookie authorized delegated API", w.Code) |
| } |
| @@ -163,7 +163,7 @@ func TestAgentNoteAdmissionScopeAndRetries(t *testing.T) { |
| r = httptest.NewRequest("GET", homeTestOrigin+"/api/v1/operations", nil) |
| r.Header.Set("Authorization", "Bearer test-token") |
| w = httptest.NewRecorder() |
| - h.ServeHTTP(w, r) |
| + h.ServeHTTP(responseRecorder{w}, r) |
| if w.Code != 403 { |
| t.Fatal("wrong instance team discovered operations", w.Code) |
| } |
| @@ -206,7 +206,9 @@ func TestAgentSearchRechecksSiblingPermission(t *testing.T) { |
| 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") { |
| t.Fatal("sibling refusal not enforced", w.Code, w.Body.String()) |
| } |
| - if custody.calls != 2 { |
| + // First query: search plus preheader and first-chunk checks. The second |
| + // query withholds the sibling before selection and needs no custody replay. |
| + if custody.calls != 4 { |
| t.Fatal("did not ask sibling on each query", custody.calls) |
| } |
| // A grant for two teams still cannot select the other instance's team. |
diff --git a/internal/memoria/agent_boundary.go b/internal/memoria/agent_boundary.go| index 76f39e2..6996918 100644 |
| --- a/internal/memoria/agent_boundary.go |
| +++ b/internal/memoria/agent_boundary.go |
| @@ -15,8 +15,13 @@ import ( |
| type agentBoundaryKey struct{} |
| type agentRequest struct { |
| - verify func(context.Context, access.Principal, string) error |
| - personID int64 |
| + verify func(context.Context, access.Principal, string) error |
| + personID int64 |
| + address string |
| + selected bool |
| + passages []Result |
| + noteID int64 |
| + noteKey, noteExternal string |
| } |
| func (a *app) agentBoundary(verifier access.Verifier, next http.Handler) http.Handler { |
diff --git a/internal/memoria/agent_create.go b/internal/memoria/agent_create.go| index 1a11c67..90a0916 100644 |
| --- a/internal/memoria/agent_create.go |
| +++ b/internal/memoria/agent_create.go |
| @@ -36,8 +36,10 @@ func (a *app) agentCreate(ctx context.Context, p access.Principal, raw json.RawM |
| a.agentNotes.Lock() |
| defer a.agentNotes.Unlock() |
| replayed, indexed := false, false |
| + var noteExternal string |
| guard := &ingestBoundary{ |
| before: func(tx *gormTx, external string) (int64, bool, error) { |
| + noteExternal = external |
| if e := a.bindAgent(tx); e != nil { |
| return 0, false, e |
| } |
| @@ -92,6 +94,11 @@ func (a *app) agentCreate(ctx context.Context, p access.Principal, raw json.RawM |
| if e != nil && !errors.Is(e, ErrIndexLag) { |
| return nil, e |
| } |
| + if state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| + state.noteID = noteID |
| + state.noteKey = key |
| + state.noteExternal = noteExternal |
| + } |
| if replayed { |
| return agentNoteResult{noteID, indexed}, nil |
| } |
diff --git a/internal/memoria/agent_recorder_test.go b/internal/memoria/agent_recorder_test.go| new file mode 100644 |
| index 0000000..f88e6c4 |
| --- /dev/null |
| +++ b/internal/memoria/agent_recorder_test.go |
| @@ -0,0 +1,12 @@ |
| +package memoria |
| + |
| +import ( |
| + "net/http/httptest" |
| + "time" |
| +) |
| + |
| +// Unit request fixtures use an in-memory transport. Real HTTP deadline and |
| +// truncation behavior is exercised separately. |
| +type responseRecorder struct{ *httptest.ResponseRecorder } |
| + |
| +func (responseRecorder) SetWriteDeadline(time.Time) error { return nil } |
diff --git a/internal/memoria/agent_response.go b/internal/memoria/agent_response.go| new file mode 100644 |
| index 0000000..fd05c1f |
| --- /dev/null |
| +++ b/internal/memoria/agent_response.go |
| @@ -0,0 +1,112 @@ |
| +package memoria |
| + |
| +import ( |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/memoria/internal/memoria/seal" |
| + "amadan.net/oficina/memoria/internal/memoria/sibling" |
| + "amadan.net/oficina/suite" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func (a *app) agentResponse(ctx context.Context, p access.Principal, name string, _ json.RawMessage, result any) error { |
| + state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest) |
| + if !ok || state.personID == 0 || name != "" && !state.selected { |
| + return access.Fail("forbidden", "Response authority is unavailable.") |
| + } |
| + address, err := a.agentAddress(ctx, p, a.agentTeam) |
| + if err != nil { |
| + return err |
| + } |
| + if name == "notes_search" { |
| + value, ok := result.(map[string]any) |
| + if !ok { |
| + return access.Fail("forbidden", "Passage provenance is unavailable.") |
| + } |
| + rows, ok := value["results"].([]any) |
| + if !ok || len(rows) != len(state.passages) { |
| + return access.Fail("forbidden", "Passage provenance is unavailable.") |
| + } |
| + if err := a.store.guardAgentPassages(ctx, address, state.passages); err != nil { |
| + return err |
| + } |
| + _, err = a.agentAddress(ctx, p, a.agentTeam) |
| + return err |
| + } |
| + if name == "notes_create" { |
| + if state.noteID <= 0 || state.noteKey == "" || state.noteExternal == "" { |
| + return access.Fail("forbidden", "Note provenance is unavailable.") |
| + } |
| + var count int64 |
| + err := a.db.G.WithContext(ctx).Table("documents").Joins("JOIN memoria_agent_notes ON memoria_agent_notes.document_id=documents.id").Where("documents.id=? AND documents.source='paste' AND documents.external_id=? AND memoria_agent_notes.coordinate=?", state.noteID, state.noteExternal, state.noteKey).Count(&count).Error |
| + if err != nil { |
| + return access.Fail("unavailable", "Note storage is unavailable.") |
| + } |
| + if count != 1 { |
| + return access.Fail("not_found", "This note is unavailable.") |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// guardAgentPassages asks only about the already selected passage coordinates; |
| +// it neither searches again nor changes the original search's breaker counters. |
| +func (s *Store) guardAgentPassages(ctx context.Context, address string, passages []Result) error { |
| + var candidates []sibling.Candidate |
| + for _, r := range passages { |
| + if r.ChunkID <= 0 || r.DocumentID <= 0 { |
| + return access.Fail("forbidden", "Passage provenance is unavailable.") |
| + } |
| + if r.item.Item.ItemID == "" { |
| + continue |
| + } |
| + if s.custody == nil { |
| + return access.Fail("unavailable", "Passage custody is unavailable.") |
| + } |
| + sib, ok := s.custody.Sibling(r.Source) |
| + if !ok { |
| + return access.Fail("forbidden", "Passage custody is unavailable.") |
| + } |
| + candidate := r.item |
| + candidate.Sibling = sib |
| + candidates = append(candidates, candidate) |
| + } |
| + if len(candidates) > 0 { |
| + dispositions := s.custody.Rule(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: address}, candidates) |
| + if len(dispositions) != len(candidates) { |
| + return access.Fail("forbidden", "Passage custody is incomplete.") |
| + } |
| + for _, d := range dispositions { |
| + if !d.Renders() { |
| + return access.Fail("forbidden", "Passage access changed.") |
| + } |
| + } |
| + } |
| + // Custody may take network time; verify local provenance after it returns. |
| + for _, r := range passages { |
| + var d Document |
| + err := s.db.G.WithContext(ctx).Table("documents").Select("documents.*").Joins("JOIN chunks ON chunks.document_id=documents.id").Where("documents.id=? AND chunks.id=?", r.DocumentID, r.ChunkID).Take(&d).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return access.Fail("not_found", "This passage is unavailable.") |
| + } |
| + if err != nil { |
| + return access.Fail("unavailable", "Passage storage is unavailable.") |
| + } |
| + if d.Source != r.Source { |
| + return access.Fail("not_found", "This passage is unavailable.") |
| + } |
| + if r.item.Item.ItemID == "" { |
| + if len(d.SiblingItemID) != 0 || d.SiblingRevision != 0 { |
| + return access.Fail("forbidden", "Passage custody changed.") |
| + } |
| + continue |
| + } |
| + id, err := s.sealer.Open(seal.PurposeItemID, d.SiblingItemID) |
| + if err != nil || string(id) != r.item.Item.ItemID || d.SiblingRevision != r.item.Item.Revision { |
| + return access.Fail("forbidden", "Passage custody changed.") |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/memoria/agent_response_test.go b/internal/memoria/agent_response_test.go| new file mode 100644 |
| index 0000000..efdcfbe |
| --- /dev/null |
| +++ b/internal/memoria/agent_response_test.go |
| @@ -0,0 +1,261 @@ |
| +package memoria |
| + |
| +import ( |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/memoria/internal/memoria/seal" |
| + "amadan.net/oficina/memoria/internal/memoria/sibling" |
| + "amadan.net/oficina/suite" |
| + "context" |
| + "errors" |
| + "gorm.io/gorm" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| +) |
| + |
| +type responseCustody struct { |
| + *fixedCustody |
| + rule func([]sibling.Candidate) []sibling.Disposition |
| +} |
| + |
| +func (c *responseCustody) Rule(_ context.Context, _ suite.Subject, items []sibling.Candidate) []sibling.Disposition { |
| + return c.rule(items) |
| +} |
| + |
| +type agentStreamWriter struct { |
| + http.ResponseWriter |
| + after func() |
| +} |
| + |
| +func (w agentStreamWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| +func (w agentStreamWriter) Write(b []byte) (int, error) { |
| + n, e := w.ResponseWriter.Write(b) |
| + w.after() |
| + return n, e |
| +} |
| +func memoriaLiveCall(t *testing.T, h http.Handler, name, raw string) (int, []byte, error) { |
| + t.Helper() |
| + server := httptest.NewServer(h) |
| + defer server.Close() |
| + req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/"+name, strings.NewReader(raw)) |
| + req.Header.Set("Authorization", "Bearer test-token") |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, e := server.Client().Do(req) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer resp.Body.Close() |
| + body, e := io.ReadAll(resp.Body) |
| + return resp.StatusCode, body, e |
| +} |
| +func TestAgentResponseFrozenPassageCustody(t *testing.T) { |
| + 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"} { |
| + t.Run(kind, func(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + mountAgentFixture(t, f, &p, &active) |
| + var changed atomic.Bool |
| + var documentID int64 |
| + custody := &responseCustody{fixedCustody: &fixedCustody{apps: docsRoster(), give: suite.VISIBLE}} |
| + custody.rule = func(items []sibling.Candidate) []sibling.Disposition { |
| + if changed.Load() { |
| + var err error |
| + switch kind { |
| + case "during-custody-chunk": |
| + err = f.app.db.G.Exec("DELETE FROM chunks WHERE document_id=?", documentID).Error |
| + case "during-custody-revision": |
| + err = f.app.db.G.Exec("UPDATE documents SET sibling_revision=2 WHERE id=?", documentID).Error |
| + case "during-custody-unlink": |
| + err = f.app.db.G.Exec("DELETE FROM home_identity_links").Error |
| + } |
| + if err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + if changed.Load() && kind == "missing-disposition" { |
| + return nil |
| + } |
| + out := make([]sibling.Disposition, len(items)) |
| + for i, item := range items { |
| + out[i] = sibling.Render |
| + if changed.Load() && (kind == "withheld" || kind == "new-revision-only" && item.Item.Revision == 1) { |
| + out[i] = sibling.Withhold |
| + } |
| + } |
| + return out |
| + } |
| + f.app.store.custody = custody |
| + 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}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if kind == "storage" { |
| + if e := f.app.db.G.Callback().Query().Before("gorm:query").Register("response-storage-fault", func(tx *gorm.DB) { |
| + if changed.Load() && tx.Statement.Table == "documents" { |
| + tx.AddError(errors.New("private storage diagnostic")) |
| + } |
| + }); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + documentID = id |
| + var checks atomic.Int32 |
| + v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + if checks.Add(1) == 2 { |
| + changed.Store(true) |
| + var e error |
| + switch kind { |
| + case "unlink": |
| + e = f.app.db.G.Exec("DELETE FROM home_identity_links").Error |
| + case "chunk": |
| + e = f.app.db.G.Exec("DELETE FROM chunks WHERE document_id=?", id).Error |
| + case "revision", "new-revision-only": |
| + e = f.app.db.G.Exec("UPDATE documents SET sibling_revision=2 WHERE id=?", id).Error |
| + case "item-id": |
| + sealed, err := f.app.store.sealer.Seal(seal.PurposeItemID, []byte("different-item")) |
| + if err != nil { |
| + return access.Principal{}, err |
| + } |
| + e = f.app.db.G.Exec("UPDATE documents SET sibling_item_id=? WHERE id=?", sealed, id).Error |
| + case "removed-source": |
| + delete(custody.apps, "Docs") |
| + } |
| + if e != nil { |
| + return access.Principal{}, e |
| + } |
| + } |
| + return p, nil |
| + }) |
| + mux := http.NewServeMux() |
| + if e := f.app.mountAgentAccess(mux, f.app.agentIssuer, "acme", v); e != nil { |
| + t.Fatal(e) |
| + } |
| + if strings.HasPrefix(kind, "during-custody-") { |
| + // Exercise one complete app callback directly: the first chunk's |
| + // second check must not mask ordering within the preheader check. |
| + state := &agentRequest{} |
| + ctx := context.WithValue(t.Context(), agentBoundaryKey{}, state) |
| + registry, err := access.NewRegistry(f.app.agentOperations("acme")...) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw := []byte(`{"team":"acme","query":"nebula"}`) |
| + result, err := registry.Call(ctx, p, "notes_search", raw) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + changed.Store(true) |
| + if err = f.app.agentResponse(ctx, p, "notes_search", raw, result); err == nil { |
| + t.Fatal("custody-time change escaped the same response check") |
| + } |
| + return |
| + } |
| + status, body, e := memoriaLiveCall(t, mux, "notes_search", `{"team":"acme","query":"nebula"}`) |
| + if kind == "storage" && status != 503 { |
| + t.Fatalf("storage failure masked: %d %s", status, body) |
| + } |
| + if e != nil || status == 200 || strings.Contains(string(body), "private") { |
| + t.Fatalf("%d %s %v", status, body, e) |
| + } |
| + }) |
| + } |
| +} |
| +func TestAgentResponseStreamRechecksLivePassage(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + id, e := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "large-title", Title: strings.Repeat("private title ", 10000), Body: "nebula passage"}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + var writes atomic.Int32 |
| + wrapped := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + h.ServeHTTP(agentStreamWriter{w, func() { |
| + if writes.Add(1) == 1 { |
| + if e := f.app.db.G.Exec("DELETE FROM chunks WHERE document_id=?", id).Error; e != nil { |
| + t.Error(e) |
| + } |
| + } |
| + }}, r) |
| + }) |
| + status, body, e := memoriaLiveCall(t, wrapped, "notes_search", `{"team":"acme","query":"nebula"}`) |
| + if status != 200 || e == nil || len(body) != 64<<10 { |
| + t.Fatalf("%d %d %v", status, len(body), e) |
| + } |
| +} |
| + |
| +func TestAgentRetryFinalGuardWithoutResponseMask(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + if w := agentCall(h, "notes_create", agentNoteInput); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + var checks int |
| + state := &agentRequest{verify: func(context.Context, access.Principal, string) error { |
| + checks++ |
| + if checks == 2 { |
| + return access.Fail("unauthenticated", "Revoked.") |
| + } |
| + return nil |
| + }} |
| + ctx := context.WithValue(t.Context(), agentBoundaryKey{}, state) |
| + address, err := f.app.agentAddress(ctx, p, "acme") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err = f.app.agentCreate(ctx, p, []byte(agentNoteInput), address) |
| + if err == nil || access.SafeFailure(err).Code != "unauthenticated" || checks != 2 { |
| + t.Fatalf("retry final guard: %v checks=%d", err, checks) |
| + } |
| +} |
| + |
| +func TestAgentCreateResponseReceiptAndStorage(t *testing.T) { |
| + for _, kind := range []string{"storage", "receipt", "external"} { |
| + t.Run(kind, func(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + var checks atomic.Int32 |
| + v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + if checks.Add(1) == 4 { |
| + if kind == "storage" { |
| + if err := f.app.db.G.Callback().Query().Before("gorm:query").Register("response-receipt-fault", func(tx *gorm.DB) { |
| + if tx.Statement.Table == "documents" { |
| + tx.AddError(errors.New("private storage diagnostic")) |
| + } |
| + }); err != nil { |
| + return access.Principal{}, err |
| + } |
| + } else { |
| + query := "UPDATE memoria_agent_notes SET coordinate='changed'" |
| + if kind == "external" { |
| + query = "UPDATE documents SET external_id='changed'" |
| + } |
| + if err := f.app.db.G.Exec(query).Error; err != nil { |
| + return access.Principal{}, err |
| + } |
| + } |
| + } |
| + return p, nil |
| + }) |
| + mux := http.NewServeMux() |
| + if err := f.app.mountAgentAccess(mux, "https://connect.example.test", "acme", v); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, body, err := memoriaLiveCall(t, mux, "notes_create", agentNoteInput) |
| + want := 404 |
| + if kind == "storage" { |
| + want = 503 |
| + } |
| + if err != nil || status != want || strings.Contains(string(body), "private") { |
| + t.Fatalf("%d %s %v", status, body, err) |
| + } |
| + var count int64 |
| + 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 { |
| + t.Fatalf("response failure replayed or rolled back committed create: %d %v", count, err) |
| + } |
| + }) |
| + } |
| +} |