oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package plan3test
2
3import (
4 "amadan.net/oficina/equipo/internal/equipo/notifications"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "gorm.io/gorm"
9 "net/http"
10 "net/http/httptest"
11 "net/url"
12 "reflect"
13 "strings"
14 "testing"
15 "time"
16
17 "amadan.net/oficina/equipo/internal/equipo"
18 "amadan.net/oficina/equipo/internal/equipo/personapi"
19)
20
21func notificationSubscription(t *testing.T, f *fixture, d personapi.PersonCredential) equipo.NotificationSubscription {
22 t.Helper()
23 w := deviceRequest(t, f, d.Token, "POST", "/api/v1/notification-subscriptions", fmt.Sprintf(`{"device_id":%q}`, d.ID), "subscribe", "")
24 expectHTTP(t, w, 200)
25 s := apiValue[equipo.NotificationSubscription](t, w)
26 if s.DeviceID != d.ID || s.Cursor == "" || !s.Active || s.Revision != 1 {
27 t.Fatal("invalid subscription", s)
28 }
29 return s
30}
31func notificationFeed(t *testing.T, f *fixture, d personapi.PersonCredential, cursor string) personapi.Page[equipo.Notification] {
32 t.Helper()
33 w := deviceRequest(t, f, d.Token, "GET", "/api/v1/notifications?cursor="+url.QueryEscape(cursor), "", "", "")
34 expectHTTP(t, w, 200)
35 if w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("ETag") == "" {
36 t.Fatal("private feed cache headers")
37 }
38 return apiValue[personapi.Page[equipo.Notification]](t, w)
39}
40func notificationAck(t *testing.T, f *fixture, d personapi.PersonCredential, s equipo.NotificationSubscription, n, key, rev string) {
41 t.Helper()
42 w := deviceRequest(t, f, d.Token, "POST", "/api/v1/notification-subscriptions/"+s.ID+"/ack", fmt.Sprintf(`{"notification_id":%q}`, n), key, rev)
43 expectHTTP(t, w, 200)
44}
45func TestNotificationOutboxAtomic(t *testing.T) {
46 f, x, p, c := claimTools(t)
47 args := map[string]any{"message_id": c.Turn.MessageID, "question": "Private question text", "options": []any{}}
48 q := toolCall(t, x, p, c, "q", "ask_person", args)
49 if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND recipient=? AND kind='question'", q.ResourceID, owner.Address) != 1 {
50 t.Fatal("question/card/outbox not committed together")
51 }
52 var eventID string
53 must(t, f.DB.Writer().QueryRow("SELECT id FROM notification_outbox WHERE resource_id=?", q.ResourceID).Scan(&eventID))
54 f.exec(t, "UPDATE coordinator_questions SET state=state WHERE id=?", q.ResourceID)
55 var replayID string
56 must(t, f.DB.Writer().QueryRow("SELECT id FROM notification_outbox WHERE resource_id=?", q.ResourceID).Scan(&replayID))
57 if replayID != eventID {
58 t.Fatal("duplicate effect changed notification ID")
59 }
60 before := f.count(t, "SELECT count(*) FROM notification_outbox")
61 toolCall(t, x, p, c, "q", "ask_person", args)
62 if f.count(t, "SELECT count(*) FROM notification_outbox") != before {
63 t.Fatal("replay duplicated outbox")
64 }
65 f.exec(t, "CREATE TRIGGER fail_notification BEFORE INSERT ON notification_outbox BEGIN SELECT RAISE(ABORT,'fixture'); END")
66 args["question"] = "A different question"
67 raw, _ := json.Marshal(args)
68 // A different tool request must roll back both its question and card.
69 call := notificationToolCall("rollback", raw)
70 if _, err := x.CallCoordinatorTool(ctx, p, c, call); err == nil {
71 t.Fatal("outbox failure did not roll back effect")
72 }
73 if f.count(t, "SELECT count(*) FROM coordinator_questions") != 1 || f.count(t, "SELECT count(*) FROM notification_outbox") != before {
74 t.Fatal("rollback left notification or question")
75 }
76 f.exec(t, "DROP TRIGGER fail_notification")
77 f.exec(t, "CREATE TRIGGER fail_notification_audit BEFORE INSERT ON audit_events BEGIN SELECT RAISE(ABORT,'fixture'); END")
78 if _, err := x.CallCoordinatorTool(ctx, p, c, call); err == nil {
79 t.Fatal("audit failure ignored")
80 }
81 if f.count(t, "SELECT count(*) FROM notification_outbox") != before {
82 t.Fatal("rollback emitted notification")
83 }
84 f.exec(t, "DROP TRIGGER fail_notification_audit")
85 f = newFixture(t)
86 plan := proposed(t, f)
87 notificationPlanWait(t, f, plan.TaskID)
88 if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND kind='task_ready'", plan.TaskID) != 1 {
89 t.Fatal("plan card notification missing")
90 }
91 plan.Steps[0].Instructions = "changed"
92 _, err := f.Store.EditPlan(ctx, owner, plan, equipo.Mutation{RequestID: "edit", Revision: 1})
93 must(t, err)
94 notificationPlanWait(t, f, plan.TaskID)
95 if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND resource_revision=2", plan.TaskID) != 1 {
96 t.Fatal("plan revision notification missing")
97 }
98 if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND resource_revision=1 AND state='superseded'", plan.TaskID) != 1 {
99 t.Fatal("old plan notification retained")
100 }
101}
102func TestNotificationRecipientIsolation(t *testing.T) {
103 f := newFixture(t)
104 d := approvedDevice(t, f)
105 s := notificationSubscription(t, f, d)
106 p := proposed(t, f)
107 notificationPlanWait(t, f, p.TaskID)
108 own := notificationFeed(t, f, d, s.Cursor)
109 if len(own.Items) != 1 || own.Items[0].ResourceID != p.TaskID {
110 t.Fatal("missing own notification", own)
111 }
112 other, err := f.Store.Notifications(ctx, peer, "", 50)
113 must(t, err)
114 if len(other.Items) != 0 {
115 t.Fatal("recipient scope leaked", other)
116 }
117 if _, err = f.Store.Notifications(ctx, peer, s.Cursor, 50); err == nil {
118 t.Fatal("foreign cursor accepted")
119 }
120 if err = f.Store.AcknowledgeNotification(ctx, peer, s.ID, own.Items[0].ID, equipo.Mutation{RequestID: "foreign", Revision: 1}); err == nil {
121 t.Fatal("foreign acknowledgement accepted")
122 }
123 if f.Store.AllowNotificationSubscription(ctx, peer, s.ID) {
124 t.Fatal("foreign live allowed")
125 }
126 if !f.Store.AllowNotificationSubscription(ctx, owner, s.ID) {
127 t.Fatal("own live denied")
128 }
129 f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address)
130 if _, err = f.Store.Notifications(ctx, owner, s.Cursor, 50); !errors.Is(err, equipo.ErrForbidden) {
131 t.Fatal("removed member read", err)
132 }
133 if f.Store.AllowNotificationSubscription(ctx, owner, s.ID) {
134 t.Fatal("stale live allowed removed member")
135 }
136 if err = f.Store.AcknowledgeNotification(ctx, owner, s.ID, own.Items[0].ID, equipo.Mutation{RequestID: "removed", Revision: 1}); err == nil {
137 t.Fatal("removed member ACK accepted")
138 }
139 if f.count(t, "SELECT count(*) FROM notification_subscriptions WHERE id=? AND active=1", s.ID) != 0 {
140 t.Fatal("roster removal did not disable subscription")
141 }
142}
143func TestNotificationReconnect(t *testing.T) {
144 f := newFixture(t)
145 a := approvedDevice(t, f)
146 b := approvedDevice(t, f)
147 sa := notificationSubscription(t, f, a)
148 sb := notificationSubscription(t, f, b)
149 f.task(t, owner, "first")
150 f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='first'")
151 f.task(t, owner, "second")
152 f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='second'")
153 // No delivery on B means no acknowledgement authority, even for the same person.
154 pa := notificationFeed(t, f, a, sa.Cursor)
155 if len(pa.Items) != 2 {
156 t.Fatal("expected two events", pa)
157 }
158 body := fmt.Sprintf(`{"notification_id":%q}`, pa.Items[0].ID)
159 expectHTTP(t, deviceRequest(t, f, b.Token, "POST", "/api/v1/notification-subscriptions/"+sb.ID+"/ack", body, "undelivered", `"1"`), 404)
160 expectHTTP(t, deviceRequest(t, f, b.Token, "GET", "/api/v1/notifications?cursor="+url.QueryEscape(sa.Cursor), "", "", ""), 404)
161 _ = notificationFeed(t, f, b, sb.Cursor)
162 notificationAck(t, f, a, sa, pa.Items[1].ID, "second", `"1"`)
163 if f.count(t, "SELECT ack_sequence FROM notification_subscriptions WHERE id=?", sa.ID) != 0 {
164 t.Fatal("out-of-order ACK skipped earlier event")
165 }
166 notificationAck(t, f, a, sa, pa.Items[1].ID, "second", `"1"`)
167 if f.count(t, "SELECT revision FROM notification_subscriptions WHERE id=?", sa.ID) != 2 {
168 t.Fatal("lost ACK replay changed revision")
169 }
170 notificationAck(t, f, a, sa, pa.Items[0].ID, "first", `"2"`)
171 if f.count(t, "SELECT ack_sequence FROM notification_subscriptions WHERE id=?", sa.ID) == 0 {
172 t.Fatal("contiguous ACK did not advance")
173 }
174 pb := notificationFeed(t, f, b, sb.Cursor)
175 if len(pb.Items) != 2 || pb.Items[0].State != "unread" || pb.Items[1].State != "unread" {
176 t.Fatal("another device lost unread state", pb)
177 }
178 replay := notificationFeed(t, f, a, sa.Cursor)
179 if len(replay.Items) != 2 || replay.Items[0].ID != pa.Items[0].ID || replay.Items[0].State != "acknowledged" {
180 t.Fatal("reconnect did not preserve delivery IDs", replay)
181 }
182}
183func TestNotificationStaleAnswer(t *testing.T) {
184 f, x, p, c := claimTools(t)
185 notificationRouter(t, f, f.Store)
186 q := toolCall(t, x, p, c, "q", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Secret question", "options": []map[string]string{{"id": "one", "label": "Secret option"}}})
187 feed, err := f.Store.Notifications(ctx, owner, "", 50)
188 must(t, err)
189 if len(feed.Items) != 1 {
190 t.Fatal("missing question event", feed)
191 }
192 n := feed.Items[0]
193 raw, _ := json.Marshal(n)
194 for _, secret := range []string{"Secret question", "Secret option", "permission", "answer", "token", "recipient"} {
195 if strings.Contains(string(raw), secret) {
196 t.Fatal("notification contains authority/content", string(raw))
197 }
198 }
199 f.exec(t, "UPDATE coordinator_turns SET state='delivered' WHERE id=?", c.Turn.ID)
200 get := apiRequest(t, f, owner, "GET", "/api/v1/questions/"+q.ResourceID, "", "", "")
201 expectHTTP(t, get, 200)
202 expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/questions/"+q.ResourceID+"/answer", `{"kind":"clarification","option_id":"one","text":""}`, "missing", ""), 428)
203 // Supersede before the answer arrives: the notification's old revision cannot answer.
204 f.exec(t, "UPDATE coordinator_questions SET state='superseded',revision=revision+1 WHERE id=?", q.ResourceID)
205 expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/questions/"+q.ResourceID+"/answer", `{"kind":"clarification","option_id":"one","text":""}`, "stale", get.Header().Get("ETag")), 409)
206 feed, err = f.Store.Notifications(ctx, owner, "", 50)
207 must(t, err)
208 if len(feed.Items) != 1 || feed.Items[0].State != "superseded" {
209 t.Fatal("stale question remains actionable", feed)
210 }
211}
212
213type notificationClock struct{ at time.Time }
214
215func (c *notificationClock) Now() time.Time { return c.at }
216func TestNotificationSubscriptionExpiry(t *testing.T) {
217 f := newFixture(t)
218 d := approvedDevice(t, f)
219 clock := &notificationClock{time.Now().UTC()}
220 s := equipo.NewStore(f.DB, equipo.WithRunnerClock(clock))
221 // The router initializes the instance key; fixture credentials remain offline.
222 notificationRouter(t, f, s)
223 sub := notificationSubscription(t, f, d)
224 if !sub.ExpiresAt.Equal(d.ExpiresAt) {
225 t.Fatal("subscription exceeds credential expiry", sub.ExpiresAt, d.ExpiresAt)
226 }
227 f.task(t, owner, "pending")
228 f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='pending'")
229 page := notificationFeed(t, f, d, sub.Cursor)
230 if len(page.Items) != 1 {
231 t.Fatal("pending work absent")
232 }
233 clock.at = sub.ExpiresAt
234 if f.Store.AllowNotificationSubscription(ctx, owner, sub.ID) {
235 t.Fatal("live allowed at deadline")
236 }
237 if _, err := f.Store.Notifications(ctx, owner, sub.Cursor, 50); err == nil {
238 t.Fatal("feed allowed at deadline")
239 }
240 if err := f.Store.AcknowledgeNotification(ctx, owner, sub.ID, page.Items[0].ID, equipo.Mutation{RequestID: "late", Revision: 1}); err == nil {
241 t.Fatal("ACK allowed at deadline")
242 }
243 // A fresh credential is required once the device itself expires.
244 fresh := approvedDevice(t, f)
245 replacement := notificationSubscription(t, f, fresh)
246 unread := notificationFeed(t, f, fresh, replacement.Cursor)
247 if len(unread.Items) != 1 || unread.Items[0].ID != page.Items[0].ID || unread.Items[0].State != "unread" {
248 t.Fatal("replacement lost unread work", unread)
249 }
250 must(t, f.Store.RevokePersonDevice(ctx, owner, fresh.ID, equipo.Mutation{RequestID: "revoke", Revision: 3}))
251 if f.count(t, "SELECT count(*) FROM notification_subscriptions WHERE device_id=? AND active=1", fresh.ID) != 0 {
252 t.Fatal("device revocation not atomic")
253 }
254 expectHTTP(t, deviceRequest(t, f, fresh.Token, "GET", "/api/v1/me", "", "", ""), 401)
255 // Even a stale active flag cannot outlive its revoked credential.
256 f.exec(t, "UPDATE notification_subscriptions SET active=1 WHERE id=?", replacement.ID)
257 if f.Store.AllowNotificationSubscription(ctx, owner, replacement.ID) {
258 t.Fatal("revoked live allowed")
259 }
260 if _, err := f.Store.Notifications(ctx, owner, replacement.Cursor, 50); err == nil {
261 t.Fatal("revoked feed allowed")
262 }
263}
264func TestNotificationNoExternalDelivery(t *testing.T) {
265 f := newFixture(t)
266 d := approvedDevice(t, f)
267 for _, extra := range []string{`"recipient":"other@example.com"`, `"callback_url":"https://example.com/push"`, `"provider_token":"secret"`, `"answer":"allow"`} {
268 expectHTTP(t, deviceRequest(t, f, d.Token, "POST", "/api/v1/notification-subscriptions", fmt.Sprintf(`{"device_id":%q,%s}`, d.ID, extra), "invalid", ""), 422)
269 }
270 for _, table := range []string{"notification_outbox", "notification_subscriptions", "notification_deliveries"} {
271 var names []string
272 must(t, f.DB.G.Raw("SELECT name FROM pragma_table_info(?)", table).Scan(&names).Error)
273 if len(names) == 0 {
274 t.Fatal("missing notification table", table)
275 }
276 for _, name := range names {
277 if strings.Contains(name, "token") || strings.Contains(name, "secret") || strings.Contains(name, "callback") {
278 t.Fatal("external delivery field", name)
279 }
280 }
281 }
282 sub := notificationSubscription(t, f, d)
283 raw, _ := json.Marshal(sub)
284 var keys map[string]any
285 must(t, json.Unmarshal(raw, &keys))
286 expected := []string{"id", "device_id", "cursor", "revision", "active", "expires_at"}
287 if len(keys) != len(expected) {
288 t.Fatal("unexpected subscription payload", string(raw))
289 }
290 for _, key := range expected {
291 if _, ok := keys[key]; !ok {
292 t.Fatal("missing safe field", key)
293 }
294 }
295 // Store methods return explicit values, not records or credential capabilities.
296 if reflect.TypeOf(sub).Kind() != reflect.Struct {
297 t.Fatal("subscription is not a projection")
298 }
299}
300
301func TestNotificationLiveRechecks(t *testing.T) {
302 f := newFixture(t)
303 d := approvedDevice(t, f)
304 sub := notificationSubscription(t, f, d)
305 topic := notifications.Topic(f.TeamID, owner.Address, sub.ID)
306 allowed := func(r *http.Request, key string) bool { return f.Store.AllowNotificationTopic(r.Context(), owner, key) }
307 writes := 0
308 next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
309 if _, err := w.Write([]byte("before")); err != nil {
310 t.Fatal(err)
311 }
312 writes++
313 must(t, f.Store.RevokePersonDevice(ctx, owner, d.ID, equipo.Mutation{RequestID: "live-revoke", Revision: 3}))
314 if _, err := w.Write([]byte("after")); err == nil {
315 t.Fatal("stale stream wrote after revocation")
316 }
317 writes++
318 })
319 w := httptest.NewRecorder()
320 notifications.GuardLive(next, allowed).ServeHTTP(w, httptest.NewRequest("GET", "/live?t="+url.QueryEscape(topic+"@0"), nil))
321 if writes != 2 || w.Body.String() != "before" {
322 t.Fatal("live guard leaked invalidation", w.Body.String())
323 }
324}
325
326func TestNotificationRetentionAndCursor(t *testing.T) {
327 f := newFixture(t)
328 d := approvedDevice(t, f)
329 sub := notificationSubscription(t, f, d)
330 clock := &notificationClock{time.Now().UTC()}
331 s := equipo.NewStore(f.DB, equipo.WithRunnerClock(clock))
332 notificationRouter(t, f, s)
333 f.task(t, owner, "retained")
334 f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='retained'")
335 page := notificationFeed(t, f, d, sub.Cursor)
336 notificationAck(t, f, d, sub, page.Items[0].ID, "ack", `"1"`)
337 // Cursor remains cryptographically fresh; the retained-history boundary changed.
338 f.exec(t, "UPDATE notification_outbox SET acknowledged_at=?", clock.at.Add(-30*24*time.Hour-time.Second))
339 // Do not renew the device/subscription while pruning.
340 expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/notifications?cursor="+url.QueryEscape(page.NextCursor), "", "", ""), 410)
341 fresh, err := f.Store.Notifications(ctx, owner, "", 50)
342 must(t, err)
343 if len(fresh.Items) != 0 || f.count(t, "SELECT count(*) FROM notification_outbox") != 0 {
344 t.Fatal("old acknowledged history retained")
345 }
346 // A modified or other-route token is never an accepted continuation.
347 expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/notifications?cursor="+url.QueryEscape(fresh.NextCursor+"x"), "", "", ""), 410)
348 expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/people?cursor="+url.QueryEscape(fresh.NextCursor), "", "", ""), 410)
349 clock.at = clock.at.Add(24 * time.Hour)
350 if _, err = f.Store.Notifications(ctx, owner, fresh.NextCursor, 50); !errors.Is(err, equipo.ErrCursorExpired) {
351 t.Fatal("expired cursor accepted", err)
352 }
353}
354
355func TestNotificationNativeAndReady(t *testing.T) {
356 f, x, principal, request, q := nativeConversationFixture(t)
357 feed, err := f.Store.Notifications(ctx, owner, "", 100)
358 must(t, err)
359 var found bool
360 for _, n := range feed.Items {
361 if n.ResourceID == q.ID {
362 found = true
363 if n.State != "unread" {
364 t.Fatal("current native question superseded", n)
365 }
366 }
367 }
368 if !found {
369 t.Fatal("native question event missing")
370 }
371 device := approvedDevice(t, f)
372 sub := notificationSubscription(t, f, device)
373 delivered := notificationFeed(t, f, device, sub.Cursor)
374 for _, n := range delivered.Items {
375 if n.ResourceID == q.ID {
376 notificationAck(t, f, device, sub, n.ID, "question-ack", `"1"`)
377 }
378 }
379 needs := apiRequest(t, f, owner, "GET", "/api/v1/needs-you", "", "", "")
380 expectHTTP(t, needs, 200)
381 tasks := apiValue[personapi.Page[personapi.Task]](t, needs)
382 pending := false
383 for _, task := range tasks.Items {
384 if task.ID == q.TaskID {
385 pending = true
386 }
387 }
388 if !pending {
389 t.Fatal("acknowledgement hid pending question from Needs you")
390 }
391 before := f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=?", q.ID)
392 request.Question = &q
393 _, err = x.Mutate(ctx, principal, "questions", request)
394 must(t, err)
395 if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=?", q.ID) != before {
396 t.Fatal("native replay duplicated notification")
397 }
398 f.exec(t, "UPDATE questions SET state='invalid' WHERE id=?", q.ID)
399 feed, err = f.Store.Notifications(ctx, owner, "", 100)
400 must(t, err)
401 for _, n := range feed.Items {
402 if n.ResourceID == q.ID && n.State != "superseded" {
403 t.Fatal("invalid native event remains current")
404 }
405 }
406 // Core completion notifies the requester and an explicit decision owner atomically.
407 var task equipo.Task
408 must(t, f.DB.G.First(&task, "id=?", q.TaskID).Error)
409 f.exec(t, "UPDATE decision_owners SET address=? WHERE project_id=? AND decision='merge'", peer.Address, task.ProjectID)
410 must(t, x.Write(ctx, func(tx *gorm.DB) error {
411 return tx.Exec("UPDATE jobs SET state='succeeded',revision=revision+1 WHERE id=?", task.JobID).Error
412 }))
413 for _, recipient := range []string{owner.Address, peer.Address} {
414 if f.count(t, "SELECT count(*) FROM notification_outbox WHERE event='task_ready.complete' AND resource_id=? AND recipient=?", task.ID, recipient) != 1 {
415 t.Fatal("completion recipient missing", recipient)
416 }
417 }
418}
419