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 "strconv"
8 "strings"
9 "sync"
10 "testing"
11 "time"
12
13 "amadan.net/oficina/home/handoff/seal"
14 "github.com/carlosframework/docs/internal/core"
15 "github.com/google/uuid"
16)
17
18func editAgentInput(body agentBody) agentUpdateInput {
19 return agentUpdateInput{Team: "blue", ID: body.ID, ClientID: uuid.NewString(), Expected: body.Revision, Edits: []agentEdit{{Index: 1, Delete: 1, Blocks: []agentBlock{{Type: "paragraph", Text: "EDITED_PRIVATE_BODY đŸ˜€ <script>"}}}}}
20}
21func agentEditCounts(t *testing.T, f *docAgentFixture, want int64) {
22 t.Helper()
23 for _, model := range []any{&agentUpdateReceipt{}, &agentUpdateAttribution{}} {
24 var count int64
25 if e := f.a.store.db.Model(model).Count(&count).Error; e != nil || count != want {
26 t.Fatal("edit rows", count, want, e)
27 }
28 }
29}
30func TestAgentUpdateRevisionRetryAndEditorPublication(t *testing.T) {
31 f := newDocAgentFixture(t)
32 body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
33 in := editAgentInput(body)
34 var doc Document
35 if e := f.a.store.db.Where("sqid=?", body.ID).First(&doc).Error; e != nil {
36 t.Fatal(e)
37 }
38 live := newHub()
39 f.a.notify = live.broadcast
40 changes, unsubscribe := live.subscribe(doc.ID)
41 defer unsubscribe()
42 first := f.call(t, "docs_update", in)
43 if first.Code != 200 {
44 t.Fatal(first.Code, first.Body.String())
45 }
46 var ack agentUpdated
47 if e := json.Unmarshal(first.Body.Bytes(), &ack); e != nil || ack.Revision != "2" || ack.ID != body.ID {
48 t.Fatal(ack, e)
49 }
50 select {
51 case seq := <-changes:
52 if seq != 2 {
53 t.Fatal(seq)
54 }
55 default:
56 t.Fatal("editor not notified")
57 }
58 after := decodeAgentBody(t, f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID}))
59 if after.Revision != "2" || !strings.Contains(after.Text, "EDITED_PRIVATE_BODY") {
60 t.Fatal(after)
61 }
62 // An ordinary editor update enters through the existing domain method.
63 copy := doc
64 copy.ClientID = 12345
65 h, _, _, e := f.a.store.replay(t.Context(), &copy)
66 if e != nil {
67 t.Fatal(e)
68 }
69 browser, e := h.EditUpdate(t.Context(), []core.BlockEdit{{Index: 1, Delete: 1, Blocks: []core.InitialBlock{{Text: "BROWSER LATER"}}}})
70 if e != nil {
71 t.Fatal(e)
72 }
73 id, e := f.a.resolver.resolveHome(t.Context(), f.p.Subject)
74 if e != nil {
75 t.Fatal(e)
76 }
77 if _, e = f.a.store.ApplyUpdate(t.Context(), &doc, id.Actor, browser); e != nil {
78 t.Fatal(e)
79 }
80 retried := f.call(t, "docs_update", in)
81 if retried.Code != 200 || !bytes.Equal(first.Body.Bytes(), retried.Body.Bytes()) {
82 t.Fatal("retry changed receipt", retried.Code, retried.Body.String())
83 }
84 select {
85 case <-changes:
86 t.Fatal("retry notified a new effect")
87 default:
88 }
89 after = decodeAgentBody(t, f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID}))
90 if after.Revision != "3" || !strings.Contains(after.Text, "BROWSER LATER") {
91 t.Fatal("retry overwrote browser", after)
92 }
93 stale := in
94 stale.ClientID = uuid.NewString()
95 if w := f.call(t, "docs_update", stale); w.Code != 409 {
96 t.Fatal("stale accepted", w.Code, w.Body.String())
97 }
98 changed := in
99 changed.Expected = "3"
100 if w := f.call(t, "docs_update", changed); w.Code != 409 {
101 t.Fatal("changed payload accepted", w.Code)
102 }
103 agentEditCounts(t, f, 1)
104 var receipt agentUpdateReceipt
105 var attribution agentUpdateAttribution
106 var update DocUpdate
107 if e = f.a.store.db.First(&receipt).Error; e != nil {
108 t.Fatal(e)
109 }
110 if e = f.a.store.db.First(&attribution).Error; e != nil {
111 t.Fatal(e)
112 }
113 if e = f.a.store.db.Where("doc_id=? AND seq=2", doc.ID).First(&update).Error; e != nil {
114 t.Fatal(e)
115 }
116 if bytes.Contains(update.UpdateBin, []byte("EDITED_PRIVATE_BODY")) || bytes.Contains(attribution.ClientSealed, []byte(f.p.Client)) {
117 t.Fatal("plaintext stored")
118 }
119 sealer, e := seal.New(f.a.key, "oficina/docs")
120 if e != nil {
121 t.Fatal(e)
122 }
123 plain, e := sealer.Open("agent-update-client/"+doc.GUID+"/2/"+receipt.Coordinate, attribution.ClientSealed)
124 if e != nil || string(plain) != f.p.Client {
125 t.Fatal("attribution", string(plain), e)
126 }
127 if _, e = sealer.Open("agent-update-client/"+doc.GUID+"/3/"+receipt.Coordinate, attribution.ClientSealed); e == nil {
128 t.Fatal("attribution coordinate not bound")
129 }
130 if e = f.a.store.db.Model(&Document{}).Where("id=?", doc.ID).Update("deleted_at", time.Now()).Error; e != nil {
131 t.Fatal(e)
132 }
133 if w := f.call(t, "docs_update", in); w.Code != 404 {
134 t.Fatal("deleted retry", w.Code)
135 }
136}
137
138func TestAgentUpdateConcurrentAndStaleWrites(t *testing.T) {
139 for _, same := range []bool{true, false} {
140 t.Run(strconv.FormatBool(same), func(t *testing.T) {
141 f := newDocAgentFixture(t)
142 body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
143 in := editAgentInput(body)
144 var wg sync.WaitGroup
145 results := make(chan int, 4)
146 for i := 0; i < 4; i++ {
147 request := in
148 if !same {
149 request.ClientID = uuid.NewString()
150 }
151 wg.Add(1)
152 go func() { defer wg.Done(); results <- f.call(t, "docs_update", request).Code }()
153 }
154 wg.Wait()
155 close(results)
156 success := 0
157 for code := range results {
158 if code == 200 {
159 success++
160 } else if same || code != 409 {
161 t.Fatal(code)
162 }
163 }
164 if same && success != 4 || !same && success != 1 {
165 t.Fatal("successes", success)
166 }
167 agentEditCounts(t, f, 1)
168 after := decodeAgentBody(t, f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID}))
169 if after.Revision != "2" {
170 t.Fatal(after)
171 }
172 })
173 }
174}
175
176func TestAgentUpdateFinalAuthorityAndStorageRollback(t *testing.T) {
177 for _, mode := range []string{"revoke", "binding", "receipt", "attribution", "update"} {
178 t.Run(mode, func(t *testing.T) {
179 f := newDocAgentFixture(t)
180 body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
181 in := editAgentInput(body)
182 want := 503
183 switch mode {
184 case "revoke":
185 f.checks.Store(0)
186 f.revokeAt.Store(3)
187 want = 401
188 case "binding":
189 want = 403
190 if e := f.a.store.db.Exec("CREATE TRIGGER edit_unlink AFTER INSERT ON docs_agent_update_receipts BEGIN UPDATE home_identity_links SET person_binding='corrupt'; END").Error; e != nil {
191 t.Fatal(e)
192 }
193 default:
194 table := map[string]string{"receipt": "docs_agent_update_receipts", "attribution": "docs_agent_update_attribution", "update": "doc_updates"}[mode]
195 if e := f.a.store.db.Exec("CREATE TRIGGER edit_fail BEFORE INSERT ON " + table + " BEGIN SELECT RAISE(ABORT,'test edit storage failure'); END").Error; e != nil {
196 t.Fatal(e)
197 }
198 }
199 if w := f.call(t, "docs_update", in); w.Code != want {
200 t.Fatal(w.Code, w.Body.String())
201 }
202 agentEditCounts(t, f, 0)
203 var count int64
204 if e := f.a.store.db.Model(&DocUpdate{}).Count(&count).Error; e != nil || count != 1 {
205 t.Fatal("body did not roll back", count, e)
206 }
207 })
208 }
209}
210
211func TestAgentUpdateCompletedRetryFinalGuardWithoutHTTP(t *testing.T) {
212 f := newDocAgentFixture(t)
213 body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
214 in := editAgentInput(body)
215 if w := f.call(t, "docs_update", in); w.Code != 200 {
216 t.Fatal(w.Code, w.Body.String())
217 }
218 ctx, id, e := f.a.prepareMode(t.Context(), f.p, true, false)
219 if e != nil {
220 t.Fatal(e)
221 }
222 checks := 0
223 ctx.Value(accessContextKey{}).(*requestAccess).delegationCheck = func(context.Context) error {
224 checks++
225 if checks == 2 {
226 return errIdentityRefused
227 }
228 return nil
229 }
230 if result, e := f.a.update(ctx, f.p, id, in); result != nil || e == nil || checks != 2 {
231 t.Fatal("retry bypassed final authority", result, e, checks)
232 }
233}
234
235func TestAgentUpdateInvalidAndTitleOnlyChange(t *testing.T) {
236 f := newDocAgentFixture(t)
237 body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
238 in := editAgentInput(body)
239 for _, revision := range []string{"", "01", "-1", "1.0", "9223372036854775808"} {
240 bad := in
241 bad.Expected = revision
242 if w := f.call(t, "docs_update", bad); w.Code != 422 {
243 t.Fatal(revision, w.Code)
244 }
245 }
246 for _, edits := range [][]agentEdit{{{Index: 20, Delete: 1}}, {{Index: 0, Delete: 2}}, {{Index: 0, Delete: 0, Blocks: []agentBlock{}}}, {{Index: 1, Delete: 1, Blocks: []agentBlock{{Type: "html", Text: "unsafe"}}}}} {
247 bad := in
248 bad.Edits = edits
249 if w := f.call(t, "docs_update", bad); w.Code != 422 {
250 t.Fatal(edits, w.Code, w.Body.String())
251 }
252 }
253 agentEditCounts(t, f, 0)
254 if e := f.a.store.db.Model(&Document{}).Where("sqid=?", body.ID).Update("title", "Renamed only").Error; e != nil {
255 t.Fatal(e)
256 }
257 if w := f.call(t, "docs_update", in); w.Code != 200 || strings.Contains(w.Body.String(), "Renamed") {
258 t.Fatal(w.Code, w.Body.String())
259 }
260}
261