| 1 | package calendar |
| 2 | |
| 3 | import ( |
| 4 | access "amadan.net/oficina/agent-access.git" |
| 5 | "amadan.net/oficina/calendar/internal/calendar/seal" |
| 6 | "bytes" |
| 7 | "context" |
| 8 | "encoding/json" |
| 9 | "io" |
| 10 | "net/http" |
| 11 | "net/http/httptest" |
| 12 | "strings" |
| 13 | "sync/atomic" |
| 14 | "testing" |
| 15 | "time" |
| 16 | ) |
| 17 | |
| 18 | type agentStreamWriter struct { |
| 19 | http.ResponseWriter |
| 20 | after func() |
| 21 | } |
| 22 | |
| 23 | func (w agentStreamWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| 24 | func (w agentStreamWriter) Write(b []byte) (int, error) { |
| 25 | n, e := w.ResponseWriter.Write(b) |
| 26 | w.after() |
| 27 | return n, e |
| 28 | } |
| 29 | func calendarLiveCall(t *testing.T, h http.Handler, name string, input any) (int, []byte, error) { |
| 30 | t.Helper() |
| 31 | server := httptest.NewServer(h) |
| 32 | defer server.Close() |
| 33 | raw, _ := json.Marshal(input) |
| 34 | req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/"+name, bytes.NewReader(raw)) |
| 35 | req.Header.Set("Authorization", "Bearer fixture") |
| 36 | req.Header.Set("Content-Type", "application/json") |
| 37 | resp, e := server.Client().Do(req) |
| 38 | if e != nil { |
| 39 | t.Fatal(e) |
| 40 | } |
| 41 | defer resp.Body.Close() |
| 42 | body, e := io.ReadAll(resp.Body) |
| 43 | return resp.StatusCode, body, e |
| 44 | } |
| 45 | func TestAgentResponseCurrentEventAndIdentity(t *testing.T) { |
| 46 | for _, kind := range []string{"unlink", "calendar", "delete", "move", "archive"} { |
| 47 | t.Run(kind, func(t *testing.T) { |
| 48 | f, p, person, cal := linkedCalendarAgent(t) |
| 49 | w := calendarAgentCall(f.app, "calendar_create_event", eventAgentInput(cal)) |
| 50 | if w.Code != 200 { |
| 51 | t.Fatal(w.Code, w.Body.String()) |
| 52 | } |
| 53 | var created struct{ ID int64 } |
| 54 | json.Unmarshal(w.Body.Bytes(), &created) |
| 55 | var checks atomic.Int32 |
| 56 | v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| 57 | if checks.Add(1) == 2 { |
| 58 | var e error |
| 59 | switch kind { |
| 60 | case "unlink": |
| 61 | e = f.app.db.G.Exec("DELETE FROM home_identity_links").Error |
| 62 | case "calendar": |
| 63 | e = f.app.db.G.Exec("DELETE FROM grants WHERE calendar_id=? AND person_id=?", cal, person.ID).Error |
| 64 | case "delete": |
| 65 | e = f.app.db.G.Exec("UPDATE events SET deleted_at=? WHERE id=?", time.Now(), created.ID).Error |
| 66 | case "move": |
| 67 | cals, err := f.app.store.Calendars(t.Context(), person.ID) |
| 68 | if err != nil { |
| 69 | return access.Principal{}, err |
| 70 | } |
| 71 | for _, c := range cals { |
| 72 | if c.ID != cal { |
| 73 | e = f.app.db.G.Exec("UPDATE events SET calendar_id=? WHERE id=?", c.ID, created.ID).Error |
| 74 | break |
| 75 | } |
| 76 | } |
| 77 | case "archive": |
| 78 | e = f.app.db.G.Exec("UPDATE calendars SET archived_at=? WHERE id=?", time.Now(), cal).Error |
| 79 | } |
| 80 | if e != nil { |
| 81 | return access.Principal{}, e |
| 82 | } |
| 83 | } |
| 84 | return *p, nil |
| 85 | }) |
| 86 | if e := f.app.mountAgent(v, f.app.agentIssuer, "acme"); e != nil { |
| 87 | t.Fatal(e) |
| 88 | } |
| 89 | status, body, e := calendarLiveCall(t, f.app.agent, "calendar_get_event", map[string]any{"team": "acme", "id": created.ID}) |
| 90 | if e != nil || status == 200 || strings.Contains(string(body), "agent_title_") { |
| 91 | t.Fatalf("%s: %d %s %v", kind, status, body, e) |
| 92 | } |
| 93 | }) |
| 94 | } |
| 95 | } |
| 96 | func TestAgentBusyKeepsEveryContributingCalendar(t *testing.T) { |
| 97 | f, p, person, _ := linkedCalendarAgent(t) |
| 98 | cals, e := f.app.store.Calendars(t.Context(), person.ID) |
| 99 | if e != nil || len(cals) < 2 { |
| 100 | t.Fatal(len(cals), e) |
| 101 | } |
| 102 | var input map[string]any |
| 103 | for i, c := range cals[:2] { |
| 104 | input = eventAgentInput(c.ID) |
| 105 | if i == 1 { |
| 106 | input["client_id"] = "55fca936-6f81-4132-9184-f22c61b7a478" |
| 107 | } |
| 108 | if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 200 { |
| 109 | t.Fatal(w.Code, w.Body.String()) |
| 110 | } |
| 111 | } |
| 112 | start, _ := time.Parse(LayoutLocal, input["start_local"].(string)) |
| 113 | busy := map[string]any{"team": "acme", "start": start.Add(-time.Hour).Format(time.RFC3339), "end": start.Add(2 * time.Hour).Format(time.RFC3339)} |
| 114 | if w := calendarAgentCall(f.app, "calendar_free_busy", busy); w.Code != 200 || !strings.Contains(w.Body.String(), "start") { |
| 115 | t.Fatal(w.Code, w.Body.String()) |
| 116 | } |
| 117 | var checks atomic.Int32 |
| 118 | v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| 119 | if checks.Add(1) == 2 { |
| 120 | if e := f.app.db.G.Exec("DELETE FROM grants WHERE calendar_id=? AND person_id=?", cals[1].ID, person.ID).Error; e != nil { |
| 121 | return access.Principal{}, e |
| 122 | } |
| 123 | } |
| 124 | return *p, nil |
| 125 | }) |
| 126 | if e := f.app.mountAgent(v, f.app.agentIssuer, "acme"); e != nil { |
| 127 | t.Fatal(e) |
| 128 | } |
| 129 | status, body, e := calendarLiveCall(t, f.app.agent, "calendar_free_busy", busy) |
| 130 | if e != nil || status == 200 || strings.Contains(string(body), "busy") { |
| 131 | t.Fatalf("%d %s %v", status, body, e) |
| 132 | } |
| 133 | } |
| 134 | func TestAgentResponseStreamAbortsOnPermissionLoss(t *testing.T) { |
| 135 | f, _, person, cal := linkedCalendarAgent(t) |
| 136 | var base Calendar |
| 137 | if e := f.app.db.G.First(&base, cal).Error; e != nil { |
| 138 | t.Fatal(e) |
| 139 | } |
| 140 | name, e := f.app.store.seal.SealString(seal.PurposeCalendarName, strings.Repeat("private ", 160)) |
| 141 | if e != nil { |
| 142 | t.Fatal(e) |
| 143 | } |
| 144 | for i := 0; i < 80; i++ { |
| 145 | clone := base |
| 146 | clone.ID = 0 |
| 147 | clone.Kind = "personal" |
| 148 | clone.NameSealed = name |
| 149 | if e := f.app.db.G.Create(&clone).Error; e != nil { |
| 150 | t.Fatal(e) |
| 151 | } |
| 152 | if e := f.app.db.G.Create(&Grant{CalendarID: clone.ID, PersonID: person.ID, Role: "owner"}).Error; e != nil { |
| 153 | t.Fatal(e) |
| 154 | } |
| 155 | } |
| 156 | var writes atomic.Int32 |
| 157 | h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 158 | f.app.agent.ServeHTTP(agentStreamWriter{w, func() { |
| 159 | if writes.Add(1) == 1 { |
| 160 | if e := f.app.db.G.Exec("DELETE FROM grants WHERE calendar_id=? AND person_id=?", cal, person.ID).Error; e != nil { |
| 161 | t.Error(e) |
| 162 | } |
| 163 | } |
| 164 | }}, r) |
| 165 | }) |
| 166 | status, body, e := calendarLiveCall(t, h, "calendar_list", map[string]any{"team": "acme"}) |
| 167 | if status != 200 || e == nil || len(body) != 64<<10 { |
| 168 | t.Fatalf("%d %d %v", status, len(body), e) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | func TestAgentRetryFinalGuardWithoutResponseMask(t *testing.T) { |
| 173 | f, p, person, cal := linkedCalendarAgent(t) |
| 174 | input := eventAgentInput(cal) |
| 175 | if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 200 { |
| 176 | t.Fatal(w.Code) |
| 177 | } |
| 178 | var checks int |
| 179 | ctx := context.WithValue(t.Context(), agentBoundaryKey{}, agentRecheck(func(context.Context, access.Principal) error { |
| 180 | checks++ |
| 181 | if checks == 2 { |
| 182 | return access.Fail("unauthenticated", "Revoked.") |
| 183 | } |
| 184 | return nil |
| 185 | })) |
| 186 | raw, _ := json.Marshal(input) |
| 187 | _, err := f.app.agentCreateEvent(ctx, *p, person, raw) |
| 188 | if err == nil || access.SafeFailure(err).Code != "unauthenticated" || checks != 2 { |
| 189 | t.Fatalf("retry final guard: %v checks=%d", err, checks) |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | func TestAgentDiscoveryRechecksLocalIdentity(t *testing.T) { |
| 194 | for _, path := range []string{"connection", "operations"} { |
| 195 | t.Run(path, func(t *testing.T) { |
| 196 | f, p, _, _ := linkedCalendarAgent(t) |
| 197 | var checks atomic.Int32 |
| 198 | v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| 199 | if checks.Add(1) == 2 { |
| 200 | if err := f.app.db.G.Exec("DELETE FROM home_identity_links").Error; err != nil { |
| 201 | return access.Principal{}, err |
| 202 | } |
| 203 | } |
| 204 | return *p, nil |
| 205 | }) |
| 206 | if err := f.app.mountAgent(v, f.app.agentIssuer, "acme"); err != nil { |
| 207 | t.Fatal(err) |
| 208 | } |
| 209 | server := httptest.NewServer(f.app.agent) |
| 210 | defer server.Close() |
| 211 | req, _ := http.NewRequest("GET", server.URL+"/api/v1/"+path, nil) |
| 212 | req.Header.Set("Authorization", "Bearer fixture") |
| 213 | resp, err := server.Client().Do(req) |
| 214 | if err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | defer resp.Body.Close() |
| 218 | body, _ := io.ReadAll(resp.Body) |
| 219 | if resp.StatusCode != 403 || strings.Contains(string(body), "acme") || strings.Contains(string(body), "operations") { |
| 220 | t.Fatalf("%d %s", resp.StatusCode, body) |
| 221 | } |
| 222 | }) |
| 223 | } |
| 224 | } |
| 225 | |