oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "io"
9 "net/http"
10 "net/http/httptest"
11 "os"
12 "strings"
13 "sync"
14 "sync/atomic"
15 "testing"
16 "time"
17
18 access "amadan.net/oficina/agent-access.git"
19 "amadan.net/oficina/home/handoff/seal"
20 "github.com/google/uuid"
21 "gorm.io/gorm"
22)
23
24type docAgentFixture struct {
25 a *documentAgent
26 app *App
27 p access.Principal
28 handler http.Handler
29 revoked atomic.Bool
30 checks atomic.Int64
31 revokeAt atomic.Int64
32 verified chan struct{}
33}
34
35func TestAgentDocumentRevokedWriterNeverCommits(t *testing.T) {
36 for _, phase := range []string{"waiting", "before-commit"} {
37 t.Run(phase, func(t *testing.T) {
38 f := newDocAgentFixture(t)
39 if phase == "waiting" {
40 held, release := make(chan struct{}), make(chan struct{})
41 txDone := make(chan error, 1)
42 go func() {
43 txDone <- f.a.store.db.Transaction(func(tx *gorm.DB) error { close(held); <-release; return nil })
44 }()
45 <-held
46 f.verified = make(chan struct{})
47 result := make(chan *httptest.ResponseRecorder, 1)
48 go func() { result <- f.call(t, "docs_create", initialAgentInput()) }()
49 select {
50 case <-f.verified:
51 case <-time.After(5 * time.Second):
52 close(release)
53 t.Fatal("request never verified")
54 }
55 f.revoked.Store(true)
56 close(release)
57 if err := <-txDone; err != nil {
58 t.Fatal(err)
59 }
60 if rec := <-result; rec.Code != 401 {
61 t.Error("waiting revoked create", rec.Code, rec.Body.String())
62 }
63 } else {
64 // Initial verification, reserved writer, then final in-transaction check.
65 f.revokeAt.Store(3)
66 if rec := f.call(t, "docs_create", initialAgentInput()); rec.Code != 401 {
67 t.Error("final revoked create", rec.Code, rec.Body.String())
68 }
69 }
70 for _, model := range []any{&Document{}, &DocUpdate{}, &agentReceipt{}, &agentAttribution{}} {
71 var count int64
72 if e := f.a.store.db.Model(model).Count(&count).Error; e != nil || count != 0 {
73 t.Fatal("revoked create persisted", count, e)
74 }
75 }
76 })
77 }
78}
79
80type docAgentCredentials struct{}
81
82func (docAgentCredentials) Downstream(context.Context, access.Principal, string, string, []string) (string, error) {
83 return "test-token", nil
84}
85
86func TestAgentDocumentTeamContractsComposeAndWrongInstanceRefuses(t *testing.T) {
87 f := newDocAgentFixture(t)
88 other := *f.a
89 other.team = "green"
90 f.p.Teams = []string{"blue", "green"}
91 first, e := f.a.registry()
92 if e != nil {
93 t.Fatal(e)
94 }
95 second, e := other.registry()
96 if e != nil {
97 t.Fatal(e)
98 }
99 gateway, e := access.Gateway([]access.Route{{Team: "blue", Resource: bridgeOrigin + "/api/v1", Operations: first.List(f.p)}, {Team: "green", Resource: "https://green.docs.oficina.works/api/v1", Operations: second.List(f.p)}}, docAgentCredentials{}, nil)
100 if e != nil || len(gateway.List(f.p)) != 4 {
101 t.Fatal("contracts cannot compose", e)
102 }
103 in := initialAgentInput()
104 in.Team = "green"
105 if rec := f.call(t, "docs_create", in); rec.Code != 403 {
106 t.Fatal("multi-team credential crossed instance", rec.Code)
107 }
108}
109
110func TestAgentDocumentRejectsLossyJSONAndKeepsLargeCreateRetryable(t *testing.T) {
111 f := newDocAgentFixture(t)
112 for _, text := range []string{string([]byte{0xff}), `\ud800`, `\udfff`} {
113 raw := `{"team":"blue","client_id":"` + uuid.NewString() + `","title":"title","blocks":[{"type":"paragraph","text":"` + text + `"}]}`
114 req := httptest.NewRequest("POST", bridgeOrigin+"/api/v1/operations/docs_create", strings.NewReader(raw))
115 req.Header.Set("Authorization", "Bearer test-token")
116 req.Header.Set("Content-Type", "application/json")
117 w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
118 f.handler.ServeHTTP(w, req)
119 if w.Code != 422 {
120 t.Fatal("lossy JSON accepted", w.Code, w.Body.String())
121 }
122 }
123 var count int64
124 f.a.store.db.Model(&Document{}).Count(&count)
125 if count != 0 {
126 t.Fatal("malformed input wrote documents")
127 }
128 in := initialAgentInput()
129 in.Blocks = []agentBlock{{Type: "paragraph", Text: strings.Repeat("<", 128<<10)}}
130 body := decodeAgentBody(t, f.call(t, "docs_create", in))
131 retry := decodeAgentBody(t, f.call(t, "docs_create", in))
132 if body.ID != retry.ID || body.Revision != retry.Revision {
133 t.Fatal("large create retry changed result")
134 }
135 if rec := f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID}); rec.Code != 413 {
136 t.Fatal("oversized read was not refused", rec.Code)
137 }
138 var doc Document
139 if e := f.a.store.db.Where("sqid=?", body.ID).First(&doc).Error; e != nil {
140 t.Fatal(e)
141 }
142 var attribution agentAttribution
143 if e := f.a.store.db.First(&attribution, doc.ID).Error; e != nil {
144 t.Fatal(e)
145 }
146 sealer, e := seal.New(f.a.key, "oficina/docs")
147 if e != nil {
148 t.Fatal(e)
149 }
150 client, e := sealer.Open("agent-client/"+doc.GUID, attribution.ClientSealed)
151 if e != nil || string(client) != f.p.Client || bytes.Contains(attribution.ClientSealed, []byte(f.p.Client)) {
152 t.Fatal("client attribution not recoverable and sealed", e)
153 }
154}
155
156func TestAgentDocumentPagesUseCurrentPermissionAndExactCursor(t *testing.T) {
157 f := newDocAgentFixture(t)
158 for i := 0; i < 3; i++ {
159 decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
160 }
161 // Tie timestamps so the stable ID tiebreaker is necessary.
162 if e := f.a.store.db.Model(&Document{}).Where("id > 0").Update("updated_at", time.Date(2026, 10, 25, 0, 0, 0, 0, time.UTC)).Error; e != nil {
163 t.Fatal(e)
164 }
165 cursor := ""
166 seen := map[string]bool{}
167 for i := 0; i < 3; i++ {
168 rec := f.call(t, "docs_list", map[string]any{"team": "blue", "limit": 1, "cursor": cursor})
169 if rec.Code != 200 {
170 t.Fatal(rec.Code, rec.Body.String())
171 }
172 var page struct {
173 Documents []agentDocument `json:"documents"`
174 Next string `json:"next_cursor"`
175 }
176 if e := json.Unmarshal(rec.Body.Bytes(), &page); e != nil {
177 t.Fatal(e)
178 }
179 if len(page.Documents) != 1 || seen[page.Documents[0].ID] {
180 t.Fatal("pagination duplicated or skipped", page)
181 }
182 seen[page.Documents[0].ID] = true
183 cursor = page.Next
184 }
185 if cursor != "" {
186 t.Fatal("last page has cursor")
187 }
188 if rec := f.call(t, "docs_list", map[string]any{"team": "blue", "cursor": "not-a-cursor"}); rec.Code != 422 {
189 t.Fatal("malformed cursor accepted", rec.Code)
190 }
191 other, e := f.a.store.EnsurePerson(t.Context(), "foreign@example.com")
192 if e != nil {
193 t.Fatal(e)
194 }
195 // Private said out loud: a new document is on the team rung (Docs spec
196 // §8.2.1), and this test is about a document the caller may not read.
197 doc, e := f.a.store.createDocument(t.Context(), other, "Private foreign title", "", VisibilityPrivate)
198 if e != nil {
199 t.Fatal(e)
200 }
201 if rec := f.call(t, "docs_get", map[string]any{"team": "blue", "id": doc.Sqid}); rec.Code != 404 {
202 t.Fatal("foreign document disclosed", rec.Code)
203 }
204 rec := f.call(t, "docs_list", map[string]any{"team": "blue"})
205 if rec.Code != 200 || strings.Contains(rec.Body.String(), doc.Title) {
206 t.Fatal("foreign title in list", rec.Code)
207 }
208}
209
210func newDocAgentFixture(t *testing.T, issuers ...string) *docAgentFixture {
211 t.Helper()
212 return newDocAgentFixtureWithStorage(t, true, issuers...)
213}
214func newDocAgentFixtureWithStorage(t *testing.T, activate bool, issuers ...string) *docAgentFixture {
215 t.Helper()
216 f := newBridgeFixture(t)
217 person, err := f.app.store.EnsurePerson(t.Context(), "owner@example.com")
218 if err != nil {
219 t.Fatal(err)
220 }
221 tx, err := f.app.db.Writer().BeginTx(t.Context(), nil)
222 if err != nil {
223 t.Fatal(err)
224 }
225 if err = f.h.bridge.Adopt(t.Context(), tx, bridgeIssuer, "opaque-owner", person); err != nil {
226 tx.Rollback()
227 t.Fatal(err)
228 }
229 if err = tx.Commit(); err != nil {
230 t.Fatal(err)
231 }
232 cipher, err := newContentCipher("", "development")
233 if err != nil {
234 t.Fatal(err)
235 }
236 if activate {
237 if err = convertContent(t.Context(), f.app.store.db, cipher); err != nil {
238 t.Fatal(err)
239 }
240 f.app.store.content = cipher
241 }
242 a := &documentAgent{store: f.app.store, resolver: f.h.resolver, list: allowlist{addrs: map[string]struct{}{"owner@example.com": {}}}, origin: bridgeOrigin, issuer: "https://connect.oficina.works", identityIssuer: bridgeIssuer, team: "blue", key: bytes.Repeat([]byte{41}, 32)}
243 if len(issuers) > 0 {
244 a.issuer = issuers[0]
245 }
246 a.list.granted = func(address string) (bool, error) { return a.store.HasGrant(t.Context(), address) }
247 if err = a.store.db.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); err != nil {
248 t.Fatal(err)
249 }
250 out := &docAgentFixture{a: a, app: f.app, p: access.Principal{Subject: "opaque-owner", Client: "test-client", Grant: "grant-one", Teams: []string{"blue"}, Scopes: []string{"docs:read", "docs:write"}}}
251 out.handler, err = a.httpHandler(access.VerifyFunc(func(ctx context.Context, token string) (access.Principal, error) {
252 n := out.checks.Add(1)
253 if n == 1 && out.verified != nil {
254 close(out.verified)
255 }
256 if at := out.revokeAt.Load(); at > 0 && n >= at {
257 out.revoked.Store(true)
258 }
259 if token != "test-token" || out.revoked.Load() {
260 return access.Principal{}, access.Fail("unauthenticated", "Connection expired.")
261 }
262 return out.p, nil
263 }))
264 if err != nil {
265 t.Fatal(err)
266 }
267 return out
268}
269func (f *docAgentFixture) call(t *testing.T, name string, input any) *httptest.ResponseRecorder {
270 t.Helper()
271 body, err := json.Marshal(input)
272 if err != nil {
273 t.Fatal(err)
274 }
275 r := httptest.NewRequest("POST", bridgeOrigin+"/api/v1/operations/"+name, bytes.NewReader(body))
276 r.Header.Set("Authorization", "Bearer test-token")
277 r.Header.Set("Content-Type", "application/json")
278 w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
279 f.handler.ServeHTTP(w, r)
280 return w.ResponseRecorder
281}
282func initialAgentInput() agentCreateInput {
283 return agentCreateInput{Team: "blue", ClientID: uuid.NewString(), Title: "API document", Blocks: []agentBlock{{Type: "heading", Text: "Meeting", Level: 2}, {Type: "paragraph", Text: "PRIVATE_INITIAL_BODY_7f39 <script> literal ✓"}}}
284}
285func decodeAgentBody(t *testing.T, w *httptest.ResponseRecorder) agentBody {
286 t.Helper()
287 if w.Code != 200 {
288 t.Fatalf("operation failed: %d %s", w.Code, w.Body.String())
289 }
290 var body agentBody
291 if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
292 t.Fatal(err)
293 }
294 return body
295}
296func TestAgentDocumentCreatesRealSealedContentAndRetries(t *testing.T) {
297 f := newDocAgentFixture(t)
298 in := initialAgentInput()
299 body := decodeAgentBody(t, f.call(t, "docs_create", in))
300 body = decodeAgentBody(t, f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID}))
301 if body.ID == "" || body.Revision != "1" || !strings.Contains(body.Text, "PRIVATE_INITIAL_BODY_7f39") || !strings.Contains(string(body.Content), `"level":2`) {
302 t.Fatalf("invalid core body: %+v", body)
303 }
304 got := decodeAgentBody(t, f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID}))
305 if got.Text != body.Text || got.Revision != body.Revision {
306 t.Fatal("get mismatch")
307 }
308 var wg sync.WaitGroup
309 results := make(chan *httptest.ResponseRecorder, 4)
310 for i := 0; i < 4; i++ {
311 wg.Add(1)
312 go func() { defer wg.Done(); results <- f.call(t, "docs_create", in) }()
313 }
314 wg.Wait()
315 close(results)
316 for rec := range results {
317 if retry := decodeAgentBody(t, rec); retry.ID != body.ID {
318 t.Fatal("retry duplicated document")
319 }
320 }
321 changed := in
322 changed.Title = "Different"
323 if rec := f.call(t, "docs_create", changed); rec.Code != 409 {
324 t.Fatal("changed retry", rec.Code)
325 }
326 var n int64
327 if err := f.a.store.db.Model(&Document{}).Count(&n).Error; err != nil || n != 1 {
328 t.Fatal(n, err)
329 }
330 var doc Document
331 if err := f.a.store.db.Where("sqid=?", body.ID).First(&doc).Error; err != nil {
332 t.Fatal(err)
333 }
334 // Real browser-compatible update advances the body; retry must not reapply initial content.
335 ctx, id, err := f.a.prepare(t.Context(), f.p, true)
336 if err != nil {
337 t.Fatal(err)
338 }
339 if _, err = f.a.store.ApplyUpdate(ctx, &doc, id.Actor, validUpdate(t)); err != nil {
340 t.Fatal(err)
341 }
342 retried := decodeAgentBody(t, f.call(t, "docs_create", in))
343 if retried.ID != body.ID || retried.Revision != "2" {
344 t.Fatal("retry reset body revision", retried.Revision)
345 }
346 for _, suffix := range []string{"", "-wal"} {
347 raw, e := os.ReadFile(f.app.cfg.DBPath + suffix)
348 if e != nil && !os.IsNotExist(e) {
349 t.Fatal(e)
350 }
351 if bytes.Contains(raw, []byte("PRIVATE_INITIAL_BODY_7f39")) {
352 t.Fatal("plaintext body in storage", suffix)
353 }
354 }
355 if err = f.a.store.db.Model(&doc).Update("deleted_at", time.Now()).Error; err != nil {
356 t.Fatal(err)
357 }
358 if rec := f.call(t, "docs_create", in); rec.Code != 404 {
359 t.Fatal("deleted retry recreated", rec.Code)
360 }
361}
362func TestAgentDocumentAtomicRollbackAndAuthorityBinding(t *testing.T) {
363 f := newDocAgentFixture(t)
364 in := initialAgentInput()
365 for _, table := range []string{"doc_updates", "docs_agent_receipts", "docs_agent_attribution"} {
366 if err := f.a.store.db.Exec("CREATE TRIGGER agent_failure BEFORE INSERT ON " + table + " BEGIN SELECT RAISE(ABORT,'injected failure'); END").Error; err != nil {
367 t.Fatal(err)
368 }
369 if rec := f.call(t, "docs_create", in); rec.Code != 503 {
370 t.Fatal("write failure not surfaced", rec.Code)
371 }
372 for _, model := range []any{&Document{}, &DocUpdate{}, &agentReceipt{}, &agentAttribution{}} {
373 var count int64
374 if e := f.a.store.db.Model(model).Count(&count).Error; e != nil || count != 0 {
375 t.Fatal("partial creation", count, e)
376 }
377 }
378 if err := f.a.store.db.Exec("DROP TRIGGER agent_failure").Error; err != nil {
379 t.Fatal(err)
380 }
381 }
382 body := decodeAgentBody(t, f.call(t, "docs_create", in))
383 for _, change := range []func(*documentAgent){func(a *documentAgent) { a.key = bytes.Repeat([]byte{42}, 32) }, func(a *documentAgent) { a.identityIssuer = "https://another-home.example" }, func(a *documentAgent) { a.issuer = "https://another-connect.example" }, func(a *documentAgent) { a.team = "other" }} {
384 copy := *f.a
385 change(&copy)
386 if err := copy.store.db.Transaction(func(tx *gorm.DB) error { return copy.bind(tx) }); err == nil {
387 t.Fatal("authority/key change accepted")
388 }
389 }
390 copy := *f.a
391
392 reopened, err := New(f.app.cfg)
393 if err != nil {
394 t.Fatal(err)
395 }
396 defer reopened.Close()
397 copy.store = reopened.store
398 if err := copy.store.db.Transaction(func(tx *gorm.DB) error { return copy.bind(tx) }); err != nil {
399 t.Fatal("same authority restart refused", err)
400 }
401 if retry := decodeAgentBody(t, f.call(t, "docs_create", in)); retry.ID != body.ID {
402 t.Fatal("same authority retry changed ID")
403 }
404 f.a.store.content = nil
405 if rec := f.call(t, "docs_create", initialAgentInput()); rec.Code != 503 {
406 t.Fatal("legacy storage write", rec.Code)
407 }
408}
409
410func TestAgentDocumentIdentityLostBeforeCommitRollsBack(t *testing.T) {
411 f := newDocAgentFixture(t)
412 if e := f.a.store.db.Exec("CREATE TRIGGER agent_unlink AFTER INSERT ON docs_agent_receipts BEGIN DELETE FROM home_identity_links; END").Error; e != nil {
413 t.Fatal(e)
414 }
415 rec := f.call(t, "docs_create", initialAgentInput())
416 for _, model := range []any{&Document{}, &DocUpdate{}, &agentReceipt{}, &agentAttribution{}} {
417 var count int64
418 if e := f.a.store.db.Model(model).Count(&count).Error; e != nil || count != 0 {
419 t.Fatal("lost identity committed creation", count, e)
420 }
421 }
422 if rec.Code != 403 {
423 t.Fatal("lost identity refusal", rec.Code)
424 }
425 var links int
426 f.a.store.db.Raw("SELECT COUNT(*) FROM home_identity_links").Scan(&links)
427 if links != 1 {
428 t.Fatal("identity deletion was not rolled back")
429 }
430}
431func TestAgentDocumentScopeIdentityAndFinalRevocation(t *testing.T) {
432 f := newDocAgentFixture(t)
433 body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
434 in := map[string]any{"team": "blue", "id": body.ID}
435 saved := f.p
436 f.p.Subject = "never-linked"
437 if rec := f.call(t, "docs_get", in); rec.Code != 403 {
438 t.Fatal("unlinked", rec.Code)
439 }
440 f.p = saved
441 f.p.Scopes = []string{"docs:write"}
442 if rec := f.call(t, "docs_get", in); rec.Code != 403 {
443 t.Fatal("wrong scope", rec.Code)
444 }
445 f.p = saved
446 in["team"] = "foreign"
447 if rec := f.call(t, "docs_get", in); rec.Code != 403 {
448 t.Fatal("wrong team", rec.Code)
449 }
450 in["team"] = "blue"
451 f.revoked.Store(true)
452 if rec := f.call(t, "docs_get", in); rec.Code != 401 {
453 t.Fatal("revoked", rec.Code)
454 }
455 f.revoked.Store(false)
456 if err := f.a.store.db.Exec("DELETE FROM home_identity_links WHERE subject=?", f.p.Subject).Error; err != nil {
457 t.Fatal(err)
458 }
459 if rec := f.call(t, "docs_get", in); rec.Code != 403 {
460 t.Fatal("unlinked existing credential", rec.Code)
461 }
462 var count int64
463 f.a.store.db.Model(&Person{}).Count(&count)
464 if count != 1 {
465 t.Fatal("agent provisioned identity")
466 }
467}
468func TestAgentDocumentHTTPAbortsRevocationDuringEmission(t *testing.T) {
469 f := newDocAgentFixture(t)
470 in := initialAgentInput()
471 in.Blocks = []agentBlock{{Type: "paragraph", Text: strings.Repeat("x", 100<<10)}}
472 body := decodeAgentBody(t, f.call(t, "docs_create", in))
473 raw, _ := json.Marshal(map[string]any{"team": "blue", "id": body.ID})
474 r := httptest.NewRequest("POST", bridgeOrigin+"/api/v1/operations/docs_get", bytes.NewReader(raw))
475 r.Header.Set("Content-Type", "application/json")
476 r.Header.Set("Authorization", "Bearer test-token")
477 w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder(), afterWrite: func() { f.revoked.Store(true) }}
478 aborted := false
479 func() {
480 defer func() {
481 if e := recover(); e != nil {
482 if e != http.ErrAbortHandler {
483 panic(e)
484 }
485 aborted = true
486 }
487 }()
488 f.handler.ServeHTTP(w, r)
489 }()
490 if !aborted || w.Body.Len() != 64<<10 {
491 t.Fatal("revocation emitted a successful partial body", aborted, w.Body.Len())
492 }
493}
494func TestAgentDocumentHTTPWorksWithoutBrowserSession(t *testing.T) {
495 f := newDocAgentFixture(t)
496 server := httptest.NewServer(f.handler)
497 defer server.Close()
498 raw, _ := json.Marshal(initialAgentInput())
499 req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/docs_create", bytes.NewReader(raw))
500 req.Header.Set("Content-Type", "application/json")
501 req.Header.Set("Authorization", "Bearer test-token")
502 response, err := server.Client().Do(req)
503 if err != nil {
504 t.Fatal(err)
505 }
506 defer response.Body.Close()
507 body, err := io.ReadAll(response.Body)
508 if err != nil || response.StatusCode != 200 {
509 t.Fatal(response.StatusCode, string(body), err)
510 }
511}
512func TestAgentDocumentConfigRefusesPartialAndWrongIdentityNamespace(t *testing.T) {
513 home := &homeSettings{issuer: bridgeIssuer}
514 for _, cfg := range []Config{{AgentTeam: "blue"}, {AgentIssuer: "https://connect.oficina.works"}, {AgentIssuer: bridgeIssuer, AgentTeam: "blue"}, {AgentIssuer: "http://connect.oficina.works", AgentTeam: "blue"}} {
515 cfg.Origin = bridgeOrigin
516 if _, err := validatedAgentConfig(cfg, home, nil); !errors.Is(err, errAgentConfig) {
517 t.Fatal("invalid configuration accepted")
518 }
519 }
520 if _, err := validatedAgentConfig(Config{AgentIssuer: "https://connect.oficina.works", AgentTeam: "blue", Origin: bridgeOrigin}, nil, nil); err == nil {
521 t.Fatal("Home required")
522 }
523}
524
525func TestAgentDocumentTeamEpochIsCheckedDuringActualEmission(t *testing.T) {
526 for _, mode := range []string{"late", "partial", "explicit-grant"} {
527 t.Run(mode, func(t *testing.T) {
528 f := newDocAgentFixture(t)
529 in := initialAgentInput()
530 in.Blocks = []agentBlock{{Type: "paragraph", Text: strings.Repeat("z", 100<<10)}}
531 body := decodeAgentBody(t, f.call(t, "docs_create", in))
532 var doc Document
533 if e := f.a.store.db.Where("sqid=?", body.ID).First(&doc).Error; e != nil {
534 t.Fatal(e)
535 }
536 if mode == "explicit-grant" {
537 other, e := f.a.store.EnsurePerson(t.Context(), "other@example.com")
538 if e != nil {
539 t.Fatal(e)
540 }
541 if e = f.a.store.db.Model(&doc).Update("owner_id", other).Error; e != nil {
542 t.Fatal(e)
543 }
544 doc.OwnerID = other
545 if e := f.a.store.Grant(t.Context(), doc.OwnerID, doc.Sqid, "owner@example.com", RoleReader); e != nil {
546 t.Fatal(e)
547 }
548 }
549 rt, clock := configureDocAgentTestTeam(t, f)
550 calls := 0
551 handler, e := f.a.httpHandler(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
552 calls++
553 if mode == "late" && calls == 2 {
554 clock.step(60 * time.Second)
555 }
556 return f.p, nil
557 }))
558 if e != nil {
559 t.Fatal(e)
560 }
561 if mode == "explicit-grant" {
562 clock.step(60 * time.Second)
563 }
564 raw, _ := json.Marshal(map[string]any{"team": rt.bindings.Team, "id": doc.Sqid})
565 req := httptest.NewRequest("POST", bridgeOrigin+"/api/v1/operations/docs_get", bytes.NewReader(raw))
566 req.Header.Set("Content-Type", "application/json")
567 req.Header.Set("Authorization", "Bearer token")
568 w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
569 if mode == "partial" {
570 w.afterWrite = func() { clock.step(60 * time.Second) }
571 }
572 aborted := false
573 func() {
574 defer func() {
575 if e := recover(); e != nil {
576 if e != http.ErrAbortHandler {
577 panic(e)
578 }
579 aborted = true
580 }
581 }()
582 handler.ServeHTTP(w, req)
583 }()
584 switch mode {
585 case "late":
586 if aborted || w.Code != 503 || strings.Contains(w.Body.String(), strings.Repeat("z", 64)) {
587 t.Fatal("late epoch leaked body", w.Code, aborted)
588 }
589 case "partial":
590 if !aborted || w.Body.Len() != 64<<10 {
591 t.Fatal("expired epoch did not abort", aborted, w.Body.Len())
592 }
593 case "explicit-grant":
594 if aborted || w.Code != 200 || !strings.Contains(w.Body.String(), strings.Repeat("z", 64)) {
595 t.Fatal("explicit grant lost independent authority", w.Code, aborted)
596 }
597 }
598 })
599 }
600}
601
602func TestAgentDocumentLegacyStorageRefusesBeforeWrite(t *testing.T) {
603 f := newDocAgentFixtureWithStorage(t, false)
604 rec := f.call(t, "docs_create", initialAgentInput())
605 var count int64
606 f.a.store.db.Model(&Document{}).Count(&count)
607 if rec.Code != 503 || count != 0 {
608 t.Fatal("legacy storage accepted agent write", rec.Code, count)
609 }
610}
611