| 1 | package agentaccess |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "github.com/google/uuid" |
| 8 | "github.com/modelcontextprotocol/go-sdk/mcp" |
| 9 | "io" |
| 10 | "net/http" |
| 11 | "net/http/httptest" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "testing" |
| 15 | ) |
| 16 | |
| 17 | type scheduleCredentials struct { |
| 18 | mu sync.Mutex |
| 19 | revoked bool |
| 20 | denied string |
| 21 | } |
| 22 | |
| 23 | func (c *scheduleCredentials) Downstream(_ context.Context, p Principal, resource, team string, scopes []string) (string, error) { |
| 24 | c.mu.Lock() |
| 25 | defer c.mu.Unlock() |
| 26 | if c.revoked { |
| 27 | return "", Fail("unauthenticated", "Revoked") |
| 28 | } |
| 29 | for _, s := range scopes { |
| 30 | if s == c.denied { |
| 31 | return "", Fail("forbidden", "Scope removed") |
| 32 | } |
| 33 | } |
| 34 | return "test", nil |
| 35 | } |
| 36 | |
| 37 | type scheduleHarness struct { |
| 38 | server *httptest.Server |
| 39 | credentials *scheduleCredentials |
| 40 | routes []Route |
| 41 | p Principal |
| 42 | mu sync.Mutex |
| 43 | receipts map[string]string |
| 44 | objects map[string]map[string]any |
| 45 | effects map[string]int |
| 46 | drop, fail, foreign, revokeAfter string |
| 47 | denyAfter string |
| 48 | reads int |
| 49 | } |
| 50 | |
| 51 | func schedulePrincipal() Principal { |
| 52 | return Principal{Subject: "person", Client: "client", Grant: "grant", Teams: []string{"acme"}, Scopes: []string{"calls:read", "calls:write", "calendar:read", "calendar:write", "docs:read", "docs:write"}} |
| 53 | } |
| 54 | func newScheduleHarness(t *testing.T) *scheduleHarness { |
| 55 | t.Helper() |
| 56 | h := &scheduleHarness{credentials: &scheduleCredentials{}, p: schedulePrincipal(), receipts: map[string]string{}, objects: map[string]map[string]any{}, effects: map[string]int{}} |
| 57 | h.server = httptest.NewTLSServer(http.HandlerFunc(h.serve)) |
| 58 | t.Cleanup(h.server.Close) |
| 59 | for _, name := range []string{"calls_reserve_schedule", "calls_create_meeting", "calls_get_meeting", "calendar_create_event", "calendar_get_event", "docs_create", "docs_get"} { |
| 60 | scope := strings.Split(name, "_")[0] + ":write" |
| 61 | if strings.Contains(name, "get") { |
| 62 | scope = strings.Split(name, "_")[0] + ":read" |
| 63 | } |
| 64 | op := Operation{Name: name, Description: name, Scope: scope, Input: json.RawMessage(`{"type":"object"}`), Output: json.RawMessage(`{"type":"object"}`)} |
| 65 | h.routes = append(h.routes, Route{Team: "acme", Resource: h.server.URL + "/api/v1", Operations: []Operation{op}}) |
| 66 | } |
| 67 | return h |
| 68 | } |
| 69 | func (h *scheduleHarness) serve(w http.ResponseWriter, r *http.Request) { |
| 70 | h.mu.Lock() |
| 71 | defer h.mu.Unlock() |
| 72 | name := strings.TrimPrefix(r.URL.Path, "/api/v1/operations/") |
| 73 | var in map[string]any |
| 74 | raw, _ := io.ReadAll(r.Body) |
| 75 | if DecodeJSON(raw, &in) != nil { |
| 76 | w.WriteHeader(422) |
| 77 | return |
| 78 | } |
| 79 | if name == h.fail { |
| 80 | w.WriteHeader(503) |
| 81 | return |
| 82 | } |
| 83 | if strings.Contains(name, "get") { |
| 84 | h.reads++ |
| 85 | id := in["id"] |
| 86 | if name == "calls_get_meeting" { |
| 87 | id = in["sqid"] |
| 88 | } |
| 89 | for _, v := range h.objects { |
| 90 | if v["id"] == id || v["sqid"] == id { |
| 91 | writeJSON(w, 200, v) |
| 92 | return |
| 93 | } |
| 94 | } |
| 95 | w.WriteHeader(404) |
| 96 | return |
| 97 | } |
| 98 | key := name + "/" + in["client_id"].(string) |
| 99 | canonical, _ := json.Marshal(in) |
| 100 | if old, ok := h.receipts[key]; ok && old != string(canonical) { |
| 101 | w.WriteHeader(409) |
| 102 | return |
| 103 | } |
| 104 | if name == "calls_reserve_schedule" { |
| 105 | h.receipts[key] = string(canonical) |
| 106 | writeJSON(w, 200, map[string]any{"reserved": true}) |
| 107 | return |
| 108 | } |
| 109 | out := h.objects[key] |
| 110 | if out == nil { |
| 111 | h.effects[name]++ |
| 112 | path, id := "/m/", "abcdef2345" |
| 113 | field := "sqid" |
| 114 | var value any = id |
| 115 | if name == "docs_create" { |
| 116 | path, id, field = "/d/", "ghjkmnpqrs", "id" |
| 117 | value = id |
| 118 | } |
| 119 | if name == "calendar_create_event" { |
| 120 | path, id, field = "/events/", "1", "id" |
| 121 | value = json.Number("1") |
| 122 | } |
| 123 | out = map[string]any{field: value, "url": h.server.URL + path + id} |
| 124 | h.objects[key] = out |
| 125 | h.receipts[key] = string(canonical) |
| 126 | } |
| 127 | if name == h.foreign { |
| 128 | out = map[string]any{"id": "ghjkmnpqrs", "url": "https://foreign.test/d/ghjkmnpqrs"} |
| 129 | } |
| 130 | if name == h.revokeAfter { |
| 131 | h.credentials.mu.Lock() |
| 132 | h.credentials.revoked = true |
| 133 | h.credentials.mu.Unlock() |
| 134 | } |
| 135 | if name == h.denyAfter { |
| 136 | h.credentials.mu.Lock() |
| 137 | h.credentials.denied = "docs:read" |
| 138 | h.credentials.mu.Unlock() |
| 139 | } |
| 140 | writeJSON(w, 200, out) |
| 141 | } |
| 142 | |
| 143 | type scheduleDropTransport struct{ h *scheduleHarness } |
| 144 | |
| 145 | func (d scheduleDropTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| 146 | resp, err := d.h.server.Client().Transport.RoundTrip(r) |
| 147 | d.h.mu.Lock() |
| 148 | defer d.h.mu.Unlock() |
| 149 | if err == nil && strings.HasSuffix(r.URL.Path, "/"+d.h.drop) && d.h.drop != "" { |
| 150 | d.h.drop = "" |
| 151 | resp.Body.Close() |
| 152 | return nil, errors.New("response lost after commit") |
| 153 | } |
| 154 | return resp, err |
| 155 | } |
| 156 | func (h *scheduleHarness) gateway(t *testing.T) *Registry { |
| 157 | t.Helper() |
| 158 | r, err := Gateway(h.routes, h.credentials, scheduleDropTransport{h}) |
| 159 | if err != nil { |
| 160 | t.Fatal(err) |
| 161 | } |
| 162 | return r |
| 163 | } |
| 164 | func scheduleArgs() map[string]any { |
| 165 | return map[string]any{"team": "acme", "client_id": "3395dd82-455b-46ae-a758-a7fb1484f3e6", "title": "Review", "calendar_id": 1, "start": "2026-11-02T10:00:00Z", "end": "2026-11-02T11:00:00Z", "tz": "Europe/Dublin", "notes": "Bring notes", "agenda": map[string]any{"title": "Agenda", "blocks": []any{map[string]any{"type": "paragraph", "text": "Review changes"}}}} |
| 166 | } |
| 167 | func scheduleCall(t *testing.T, r *Registry, p Principal, in map[string]any) (scheduleResult, error) { |
| 168 | t.Helper() |
| 169 | b, _ := json.Marshal(in) |
| 170 | out, err := r.Call(t.Context(), p, "calls_schedule", b) |
| 171 | var result scheduleResult |
| 172 | if err == nil { |
| 173 | b, _ = json.Marshal(out) |
| 174 | if err = json.Unmarshal(b, &result); err != nil { |
| 175 | t.Fatal(err) |
| 176 | } |
| 177 | } |
| 178 | return result, err |
| 179 | } |
| 180 | func TestScheduleResumeLostResponsesAndGatewayRestart(t *testing.T) { |
| 181 | for _, drop := range []string{"docs_create", "calls_create_meeting", "calendar_create_event"} { |
| 182 | t.Run(drop, func(t *testing.T) { |
| 183 | h := newScheduleHarness(t) |
| 184 | h.drop = drop |
| 185 | first, err := scheduleCall(t, h.gateway(t), h.p, scheduleArgs()) |
| 186 | if err != nil || first.Status != "partial" || first.Failure.Code != "unavailable" { |
| 187 | t.Fatal(first, err) |
| 188 | } |
| 189 | second, err := scheduleCall(t, h.gateway(t), h.p, scheduleArgs()) |
| 190 | if err != nil || second.Status != "complete" || second.InvitationsSent { |
| 191 | t.Fatal(second, err) |
| 192 | } |
| 193 | for _, name := range []string{"docs_create", "calls_create_meeting", "calendar_create_event"} { |
| 194 | if h.effects[name] != 1 { |
| 195 | t.Fatal("duplicate effect", name, h.effects) |
| 196 | } |
| 197 | } |
| 198 | before := h.reads |
| 199 | r := h.gateway(t) |
| 200 | raw, _ := json.Marshal(scheduleArgs()) |
| 201 | if err = r.ScheduleResponseGuard(t.Context(), h.p, "calls_schedule", raw, second); err != nil || h.reads != before+3 { |
| 202 | t.Fatal("guard not pure reads", err, h.reads) |
| 203 | } |
| 204 | changed := scheduleArgs() |
| 205 | changed["notes"] = "changed" |
| 206 | if _, err = scheduleCall(t, r, h.p, changed); SafeFailure(err).Code != "conflict" { |
| 207 | t.Fatal("changed workflow accepted", err) |
| 208 | } |
| 209 | }) |
| 210 | } |
| 211 | } |
| 212 | func TestScheduleAuthorityAndProvenance(t *testing.T) { |
| 213 | for _, mode := range []string{"missing-scope", "scope-revoked", "revoked-after-agenda", "foreign-url", "missing-after-completion"} { |
| 214 | t.Run(mode, func(t *testing.T) { |
| 215 | h := newScheduleHarness(t) |
| 216 | switch mode { |
| 217 | case "missing-scope": |
| 218 | h.p.Scopes = []string{"calls:write", "calendar:write"} |
| 219 | case "scope-revoked": |
| 220 | h.credentials.denied = "calendar:read" |
| 221 | case "revoked-after-agenda": |
| 222 | h.revokeAfter = "docs_create" |
| 223 | case "foreign-url": |
| 224 | h.foreign = "docs_create" |
| 225 | } |
| 226 | r := h.gateway(t) |
| 227 | out, err := scheduleCall(t, r, h.p, scheduleArgs()) |
| 228 | if mode == "foreign-url" { |
| 229 | if err != nil || out.Status != "partial" || out.Steps[0].Resource != nil || h.effects["calls_create_meeting"] != 0 { |
| 230 | t.Fatal(out, err) |
| 231 | } |
| 232 | return |
| 233 | } |
| 234 | if mode == "missing-after-completion" { |
| 235 | if err != nil { |
| 236 | t.Fatal(err) |
| 237 | } |
| 238 | h.objects = map[string]map[string]any{} |
| 239 | raw, _ := json.Marshal(scheduleArgs()) |
| 240 | if err = r.ScheduleResponseGuard(t.Context(), h.p, "calls_schedule", raw, out); SafeFailure(err).Code != "not_found" { |
| 241 | t.Fatal("deleted resource emitted", err) |
| 242 | } |
| 243 | return |
| 244 | } |
| 245 | if err == nil { |
| 246 | t.Fatal("unauthorized workflow returned", out) |
| 247 | } |
| 248 | if h.effects["calls_create_meeting"] != 0 { |
| 249 | t.Fatal("effect after authority failure") |
| 250 | } |
| 251 | }) |
| 252 | } |
| 253 | } |
| 254 | func TestScheduleTimesAndIdentifiers(t *testing.T) { |
| 255 | for _, v := range []struct { |
| 256 | start, end, tz string |
| 257 | valid bool |
| 258 | }{{"2026-11-02T10:00:00Z", "2026-11-02T11:00:00Z", "Europe/Dublin", true}, {"2026-10-25T01:30:00+01:00", "2026-10-25T02:30:00Z", "Europe/Dublin", false}, {"2026-03-29T01:30:00Z", "2026-03-29T02:30:00+01:00", "Europe/Dublin", false}, {"2026-11-02T10:00:01Z", "2026-11-02T11:00:00Z", "UTC", false}, {"2026-11-02T11:00:00Z", "2026-11-02T10:00:00Z", "UTC", false}} { |
| 259 | _, _, err := scheduleTimes(scheduleInput{Start: v.start, End: v.end, TZ: v.tz}) |
| 260 | if (err == nil) != v.valid { |
| 261 | t.Fatal(v, err) |
| 262 | } |
| 263 | } |
| 264 | a, b := scheduleID("root", "agenda"), scheduleID("root", "meeting") |
| 265 | if a == b || a != scheduleID("root", "agenda") || uuid.MustParse(a).Version() != 5 { |
| 266 | t.Fatal(a, b) |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | func TestScheduleMalformedUnicodeNoEffects(t *testing.T) { |
| 271 | for _, bad := range []string{`\ud800`, string([]byte{255})} { |
| 272 | h := newScheduleHarness(t) |
| 273 | args := scheduleArgs() |
| 274 | args["title"] = "REPLACE" |
| 275 | raw, _ := json.Marshal(args) |
| 276 | raw = []byte(strings.Replace(string(raw), "REPLACE", bad, 1)) |
| 277 | if _, err := h.gateway(t).Call(t.Context(), h.p, "calls_schedule", raw); SafeFailure(err).Code != "invalid" { |
| 278 | t.Fatal(err) |
| 279 | } |
| 280 | if len(h.receipts) != 0 { |
| 281 | t.Fatal("invalid Unicode reserved workflow") |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | func TestScheduleMCPFinalResponseGuard(t *testing.T) { |
| 286 | h := newScheduleHarness(t) |
| 287 | r := h.gateway(t) |
| 288 | entry := r.operations["calls_schedule"] |
| 289 | invoke := entry.op.Invoke |
| 290 | entry.op.Invoke = func(ctx context.Context, p Principal, raw json.RawMessage) (any, error) { |
| 291 | out, err := invoke(ctx, p, raw) |
| 292 | h.credentials.mu.Lock() |
| 293 | h.credentials.revoked = true |
| 294 | h.credentials.mu.Unlock() |
| 295 | return out, err |
| 296 | } |
| 297 | r.operations["calls_schedule"] = entry |
| 298 | server := httptest.NewServer(r.MCP(VerifyFunc(func(context.Context, string) (Principal, error) { return h.p, nil }))) |
| 299 | defer server.Close() |
| 300 | client := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "1"}, nil) |
| 301 | session, err := client.Connect(t.Context(), &mcp.StreamableClientTransport{Endpoint: server.URL, HTTPClient: &http.Client{Transport: headerTransport{base: http.DefaultTransport}}}, nil) |
| 302 | if err != nil { |
| 303 | t.Fatal(err) |
| 304 | } |
| 305 | defer session.Close() |
| 306 | out, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "calls_schedule", Arguments: scheduleArgs()}) |
| 307 | if err != nil || !out.IsError || out.StructuredContent != nil { |
| 308 | t.Fatal("MCP emitted revoked result", out, err) |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | func TestScheduleFinalAndCompositeAuthority(t *testing.T) { |
| 313 | for _, mode := range []string{"final-revoke", "completed-scope-revoked", "missing-confirmed"} { |
| 314 | t.Run(mode, func(t *testing.T) { |
| 315 | h := newScheduleHarness(t) |
| 316 | switch mode { |
| 317 | case "final-revoke": |
| 318 | h.revokeAfter = "calendar_create_event" |
| 319 | case "completed-scope-revoked": |
| 320 | h.denyAfter = "docs_create" |
| 321 | case "missing-confirmed": |
| 322 | h.fail = "docs_get" |
| 323 | } |
| 324 | if _, err := scheduleCall(t, h.gateway(t), h.p, scheduleArgs()); err == nil { |
| 325 | t.Fatal("unverified result returned") |
| 326 | } |
| 327 | if mode == "completed-scope-revoked" && h.effects["calls_create_meeting"] != 0 { |
| 328 | t.Fatal("later write after completed app scope removed") |
| 329 | } |
| 330 | }) |
| 331 | } |
| 332 | } |
| 333 | func TestScheduleReferencesCannotEscapeMemberRoutes(t *testing.T) { |
| 334 | h := newScheduleHarness(t) |
| 335 | r := h.gateway(t) |
| 336 | for _, id := range []string{"..", ".", "x%2fy", "/evil", "abcdef2345?", ""} { |
| 337 | if _, err := r.schedule.reference("acme", "agenda", map[string]any{"id": id, "url": h.server.URL + "/d/" + id}); err == nil { |
| 338 | t.Fatal("invalid member id", id) |
| 339 | } |
| 340 | } |
| 341 | out, err := scheduleCall(t, r, h.p, scheduleArgs()) |
| 342 | if err != nil { |
| 343 | t.Fatal(err) |
| 344 | } |
| 345 | out.Steps[0].Resource.URL = "https://foreign.test/d/ghjkmnpqrs" |
| 346 | raw, _ := json.Marshal(scheduleArgs()) |
| 347 | if err = r.ScheduleResponseGuard(t.Context(), h.p, "calls_schedule", raw, out); err == nil { |
| 348 | t.Fatal("guard accepted substituted URL") |
| 349 | } |
| 350 | } |
| 351 | |