| 1 | package calendar |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net/http/httptest" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "slices" |
| 11 | "strings" |
| 12 | "sync" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | access "amadan.net/oficina/agent-access.git" |
| 17 | ) |
| 18 | |
| 19 | func linkedCalendarAgent(t *testing.T) (*homeRouterFixture, *access.Principal, Person, int64) { |
| 20 | t.Helper() |
| 21 | f := newHomeRouterFixture(t) |
| 22 | f.local(t) |
| 23 | if w := f.do("GET", "/day/2026-09-10", ""); w.Code != 200 { |
| 24 | t.Fatal(w.Code) |
| 25 | } |
| 26 | if w := f.do("GET", "/account/home", ""); w.Code != 200 { |
| 27 | t.Fatal(w.Code) |
| 28 | } |
| 29 | start := homeRedirect(t, f.do("POST", "/account/home", "")) |
| 30 | if homeRedirect(t, f.exchange(t, start, "opaque-agent-alice")) != "/account/home/confirm" { |
| 31 | t.Fatal("link confirmation missing") |
| 32 | } |
| 33 | homeRedirect(t, f.do("POST", "/account/home/confirm", "")) |
| 34 | p := &access.Principal{Subject: "opaque-agent-alice", Client: "agent-one", Grant: "grant-one", Teams: []string{"acme"}, Scopes: []string{"calendar:read", "calendar:write"}} |
| 35 | if err := f.app.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return *p, nil }), "https://connect.example.test", "acme"); err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | person, err := f.app.agentPerson(t.Context(), *p, "acme") |
| 39 | if err != nil { |
| 40 | t.Fatal(err) |
| 41 | } |
| 42 | cal, err := f.app.store.DefaultCalendarID(t.Context(), person.ID) |
| 43 | if err != nil || cal == 0 { |
| 44 | t.Fatal(cal, err) |
| 45 | } |
| 46 | return f, p, person, cal |
| 47 | } |
| 48 | func calendarAgentCall(a *App, name string, input any) *httptest.ResponseRecorder { |
| 49 | raw, _ := json.Marshal(input) |
| 50 | r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/"+name, strings.NewReader(string(raw))) |
| 51 | r.Header.Set("Content-Type", "application/json") |
| 52 | r.Header.Set("Authorization", "Bearer fixture") |
| 53 | w := httptest.NewRecorder() |
| 54 | a.agent.ServeHTTP(responseRecorder{w}, r) |
| 55 | return w |
| 56 | } |
| 57 | func eventAgentInput(cal int64) map[string]any { |
| 58 | start := time.Now().UTC().Add(48 * time.Hour).Truncate(time.Minute) |
| 59 | return map[string]any{"team": "acme", "calendar_id": cal, "client_id": "44fca936-6f81-4132-9184-f22c61b7a478", "title": "agent_title_52503a8dbf90435a", "location": "agent_location_cf2759ea1ee54b60", "notes": "agent_notes_40b3d60d9d284695", "start_local": start.Format(LayoutLocal), "end_local": start.Add(time.Hour).Format(LayoutLocal), "tz": "UTC"} |
| 60 | } |
| 61 | func TestAgentEventRetryPermissionsAndSealing(t *testing.T) { |
| 62 | f, p, person, cal := linkedCalendarAgent(t) |
| 63 | input := eventAgentInput(cal) |
| 64 | first := calendarAgentCall(f.app, "calendar_create_event", input) |
| 65 | if first.Code != 200 { |
| 66 | t.Fatal(first.Code, first.Body.String()) |
| 67 | } |
| 68 | var receipt struct { |
| 69 | ID int64 `json:"id"` |
| 70 | URL string `json:"url"` |
| 71 | Sent bool `json:"invitations_sent"` |
| 72 | } |
| 73 | if json.Unmarshal(first.Body.Bytes(), &receipt) != nil || receipt.ID == 0 || receipt.Sent || receipt.URL != homeTestOrigin+fmt.Sprintf("/events/%d", receipt.ID) { |
| 74 | t.Fatal("bad receipt") |
| 75 | } |
| 76 | var group sync.WaitGroup |
| 77 | for range 5 { |
| 78 | group.Go(func() { |
| 79 | w := calendarAgentCall(f.app, "calendar_create_event", input) |
| 80 | if w.Code != 200 || w.Body.String() != first.Body.String() { |
| 81 | t.Errorf("retry %d", w.Code) |
| 82 | } |
| 83 | }) |
| 84 | } |
| 85 | group.Wait() |
| 86 | input["title"] = "changed" |
| 87 | if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 409 { |
| 88 | t.Fatal("changed retry", w.Code) |
| 89 | } |
| 90 | input["title"] = "agent_title_52503a8dbf90435a" |
| 91 | var count int64 |
| 92 | if err := f.app.db.G.Model(&Event{}).Count(&count).Error; err != nil || count != 1 { |
| 93 | t.Fatal("duplicate event", count, err) |
| 94 | } |
| 95 | if err := f.app.db.G.Model(&Reminder{}).Count(&count).Error; err != nil || count != 1 { |
| 96 | t.Fatal("default reminder not atomic/idempotent", count, err) |
| 97 | } |
| 98 | if err := f.app.db.G.Model(&ReminderQueue{}).Count(&count).Error; err != nil || count != 1 { |
| 99 | t.Fatal("reminder queue", count, err) |
| 100 | } |
| 101 | read := calendarAgentCall(f.app, "calendar_get_event", map[string]any{"team": "acme", "id": receipt.ID}) |
| 102 | if read.Code != 200 || !strings.Contains(read.Body.String(), input["title"].(string)) { |
| 103 | t.Fatal("read created event", read.Code) |
| 104 | } |
| 105 | for _, column := range []string{"title", "location", "notes"} { |
| 106 | if found, _ := f.app.GrepDatabaseForTest(t, input[column].(string)); found { |
| 107 | t.Fatal("plaintext event content", column) |
| 108 | } |
| 109 | } |
| 110 | if _, err := f.app.db.Writer().Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil { |
| 111 | t.Fatal(err) |
| 112 | } |
| 113 | for _, column := range []string{"title", "location", "notes"} { |
| 114 | if found, _ := f.app.GrepDatabaseForTest(t, input[column].(string)); found { |
| 115 | t.Fatal("plaintext checkpointed content", column) |
| 116 | } |
| 117 | } |
| 118 | coordinate, _ := json.Marshal([]string{f.app.cfg.Home.Issuer, f.app.agentIssuer, p.Subject, p.Client, "acme", input["client_id"].(string)}) |
| 119 | expected, err := f.app.store.seal.Fingerprint("agent.event.coordinate.v1", string(coordinate)) |
| 120 | if err != nil { |
| 121 | t.Fatal(err) |
| 122 | } |
| 123 | var saved string |
| 124 | if err = f.app.db.Writer().QueryRow("SELECT coordinate FROM calendar_agent_events WHERE event_id=?", receipt.ID).Scan(&saved); err != nil || saved != expected { |
| 125 | t.Fatal("receipt identity binding", err) |
| 126 | } |
| 127 | rows, err := f.app.db.Writer().Query("SELECT name FROM pragma_table_info('calendar_agent_events') ORDER BY cid") |
| 128 | if err != nil { |
| 129 | t.Fatal(err) |
| 130 | } |
| 131 | var columns []string |
| 132 | for rows.Next() { |
| 133 | var name string |
| 134 | if err = rows.Scan(&name); err != nil { |
| 135 | t.Fatal(err) |
| 136 | } |
| 137 | columns = append(columns, name) |
| 138 | } |
| 139 | err = rows.Err() |
| 140 | rows.Close() |
| 141 | if err != nil || !slices.Equal(columns, []string{"coordinate", "content", "event_id"}) { |
| 142 | t.Fatal("extra receipt retention", columns, err) |
| 143 | } |
| 144 | // Existing access must be rechecked even for an otherwise valid retry. |
| 145 | if err = f.app.db.G.Model(&Grant{}).Where("person_id=? AND calendar_id=?", person.ID, cal).Update("role", RoleViewer).Error; err != nil { |
| 146 | t.Fatal(err) |
| 147 | } |
| 148 | if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 403 { |
| 149 | t.Fatal("read-only retry", w.Code) |
| 150 | } |
| 151 | if err = f.app.db.G.Where("person_id=? AND calendar_id=?", person.ID, cal).Delete(&Grant{}).Error; err != nil { |
| 152 | t.Fatal(err) |
| 153 | } |
| 154 | for _, op := range []string{"calendar_create_event", "calendar_get_event"} { |
| 155 | args := input |
| 156 | if op == "calendar_get_event" { |
| 157 | args = map[string]any{"team": "acme", "id": receipt.ID} |
| 158 | } |
| 159 | if w := calendarAgentCall(f.app, op, args); w.Code != 404 { |
| 160 | t.Fatal("lost grant disclosed event", op, w.Code) |
| 161 | } |
| 162 | } |
| 163 | if err = f.app.store.ensureGrant(t.Context(), cal, person.ID, RoleOwner, person.ID); err != nil { |
| 164 | t.Fatal(err) |
| 165 | } |
| 166 | if err = f.app.store.DeleteEvent(t.Context(), person.ID, receipt.ID); err != nil { |
| 167 | t.Fatal(err) |
| 168 | } |
| 169 | if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 404 { |
| 170 | t.Fatal("deleted event replay", w.Code) |
| 171 | } |
| 172 | if err = f.app.db.G.Model(&Event{}).Count(&count).Error; err != nil || count != 1 { |
| 173 | t.Fatal("deleted event recreated", count, err) |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | func TestAgentIdentityScopeAndCalendarIsolation(t *testing.T) { |
| 178 | f, p, _, cal := linkedCalendarAgent(t) |
| 179 | input := eventAgentInput(cal) |
| 180 | other, err := f.app.store.EnsurePersonSetup(t.Context(), "replacement@example.test") |
| 181 | if err != nil { |
| 182 | t.Fatal(err) |
| 183 | } |
| 184 | otherCal, err := f.app.store.DefaultCalendarID(t.Context(), other.ID) |
| 185 | if err != nil { |
| 186 | t.Fatal(err) |
| 187 | } |
| 188 | input["calendar_id"] = otherCal |
| 189 | if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 404 { |
| 190 | t.Fatal("foreign calendar write", w.Code) |
| 191 | } |
| 192 | input["calendar_id"] = cal |
| 193 | list := calendarAgentCall(f.app, "calendar_list", map[string]any{"team": "acme"}) |
| 194 | if list.Code != 200 { |
| 195 | t.Fatal(list.Code) |
| 196 | } |
| 197 | var result struct { |
| 198 | Calendars []struct { |
| 199 | ID int64 `json:"id"` |
| 200 | } `json:"calendars"` |
| 201 | } |
| 202 | if json.Unmarshal(list.Body.Bytes(), &result) != nil { |
| 203 | t.Fatal("list JSON") |
| 204 | } |
| 205 | for _, c := range result.Calendars { |
| 206 | if c.ID == otherCal { |
| 207 | t.Fatal("foreign calendar listed") |
| 208 | } |
| 209 | } |
| 210 | original := *p |
| 211 | for _, change := range []func(){func() { p.Subject = "unlinked" }, func() { p.Scopes = []string{"calendar:read"} }, func() { p.Teams = []string{"other"} }, func() { p.Client = "" }, func() { delete(f.app.home.admitted.addrs, "alice@example.test") }} { |
| 212 | change() |
| 213 | w := calendarAgentCall(f.app, "calendar_create_event", input) |
| 214 | if w.Code != 403 { |
| 215 | t.Fatal("unauthorized create", w.Code) |
| 216 | } |
| 217 | *p = original |
| 218 | f.app.home.admitted.addrs["alice@example.test"] = struct{}{} |
| 219 | } |
| 220 | var count int64 |
| 221 | if err = f.app.db.G.Model(&Event{}).Count(&count).Error; err != nil || count != 0 { |
| 222 | t.Fatal("denial wrote event", count, err) |
| 223 | } |
| 224 | if err = f.app.db.G.Model(&Person{}).Count(&count).Error; err != nil || count != 2 { |
| 225 | t.Fatal("request provisioned person", count, err) |
| 226 | } |
| 227 | p.Teams = []string{"acme", "other"} |
| 228 | input["team"] = "other" |
| 229 | if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 403 { |
| 230 | t.Fatal("cross instance team", w.Code) |
| 231 | } |
| 232 | r := httptest.NewRequest("GET", homeTestOrigin+"/api/v1/operations", nil) |
| 233 | for _, c := range f.cookies { |
| 234 | r.AddCookie(c) |
| 235 | } |
| 236 | w := httptest.NewRecorder() |
| 237 | f.app.agent.ServeHTTP(responseRecorder{w}, r) |
| 238 | if w.Code != 401 { |
| 239 | t.Fatal("cookie authorized API", w.Code) |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | func TestAgentTimesAndFreeBusyFailClosed(t *testing.T) { |
| 244 | for _, tc := range []struct { |
| 245 | local, zone string |
| 246 | want bool |
| 247 | }{{"2026-10-25T01:30", "Europe/Dublin", false}, {"2026-03-29T01:30", "Europe/Dublin", false}, {"2026-04-05T01:45", "Australia/Lord_Howe", false}, {"2026-10-25T03:30", "Europe/Dublin", true}, {"2026-10-25T01:30", "UTC", true}} { |
| 248 | if got := agentUnambiguous(tc.local, tc.zone); got != tc.want { |
| 249 | t.Fatal(tc, got) |
| 250 | } |
| 251 | } |
| 252 | f, _, person, cal := linkedCalendarAgent(t) |
| 253 | input := eventAgentInput(cal) |
| 254 | if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 200 { |
| 255 | t.Fatal(w.Code, w.Body.String()) |
| 256 | } |
| 257 | start, _ := ToUTC(input["start_local"].(string), "UTC", false) |
| 258 | rangeInput := map[string]any{"team": "acme", "start": time.Unix(start-60, 0).UTC().Format(time.RFC3339), "end": time.Unix(start+7200, 0).UTC().Format(time.RFC3339)} |
| 259 | busy := calendarAgentCall(f.app, "calendar_free_busy", rangeInput) |
| 260 | if busy.Code != 200 || !strings.Contains(busy.Body.String(), time.Unix(start, 0).UTC().Format(time.RFC3339)) { |
| 261 | t.Fatal("missing busy event", busy.Code, busy.Body.String()) |
| 262 | } |
| 263 | // An imported recurrence outside the supported subset cannot imply free time. |
| 264 | event, err := f.app.store.CreateEvent(t.Context(), person.ID, EventInput{CalendarID: cal, Title: "unsupported recurrence", StartLocal: input["start_local"].(string), EndLocal: input["end_local"].(string), TZ: "UTC", RRule: "FREQ=HOURLY"}) |
| 265 | if err != nil { |
| 266 | t.Fatal(err) |
| 267 | } |
| 268 | if err = f.app.db.G.Model(&Event{}).Where("id=?", event.ID).Update("rrule_foreign", true).Error; err != nil { |
| 269 | t.Fatal(err) |
| 270 | } |
| 271 | if w := calendarAgentCall(f.app, "calendar_free_busy", rangeInput); w.Code != 503 { |
| 272 | t.Fatal("incomplete recurrence reported free", w.Code) |
| 273 | } |
| 274 | input["start_local"] = "2026-10-25T01:30" |
| 275 | input["end_local"] = "2026-10-25T02:30" |
| 276 | input["tz"] = "Europe/Dublin" |
| 277 | input["client_id"] = "7c27948d-9082-42f8-bc12-e3c39bb7479e" |
| 278 | if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 422 { |
| 279 | t.Fatal("ambiguous create", w.Code) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | func TestAgentConfigurationRefusesBeforeStorage(t *testing.T) { |
| 284 | for _, cfg := range []Config{{AgentTeam: "acme"}, {AgentIssuer: "https://connect.example.test"}, {AgentTeam: "acme", AgentIssuer: "http://insecure.test"}} { |
| 285 | cfg.Env = "development" |
| 286 | cfg.Origin = homeTestOrigin |
| 287 | cfg.DBPath = filepath.Join(t.TempDir(), "refused.db") |
| 288 | app, err := New(cfg) |
| 289 | if err == nil { |
| 290 | app.Close() |
| 291 | t.Fatal("accepted incomplete agent config") |
| 292 | } |
| 293 | if _, err = os.Stat(cfg.DBPath); !os.IsNotExist(err) { |
| 294 | t.Fatal("opened storage before refusing") |
| 295 | } |
| 296 | } |
| 297 | } |
| 298 | |