| 1 | package agentaccess |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "strings" |
| 10 | "sync/atomic" |
| 11 | "testing" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | type guardedWriter struct { |
| 16 | http.ResponseWriter |
| 17 | after func() |
| 18 | deadline func(time.Time) error |
| 19 | } |
| 20 | |
| 21 | func (w guardedWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| 22 | func (w guardedWriter) Write(b []byte) (int, error) { |
| 23 | n, e := w.ResponseWriter.Write(b) |
| 24 | if w.after != nil { |
| 25 | w.after() |
| 26 | } |
| 27 | return n, e |
| 28 | } |
| 29 | func (w guardedWriter) SetWriteDeadline(d time.Time) error { |
| 30 | if w.deadline != nil { |
| 31 | return w.deadline(d) |
| 32 | } |
| 33 | return http.NewResponseController(w.ResponseWriter).SetWriteDeadline(d) |
| 34 | } |
| 35 | |
| 36 | func TestGuardedHTTPResponseBoundaries(t *testing.T) { |
| 37 | for _, phase := range []string{"success", "preheader", "chunk", "chunk-verifier", "unrelated", "identity", "client", "grant", "scope", "team", "expired"} { |
| 38 | t.Run(phase, func(t *testing.T) { |
| 39 | var invokes, initialCalls, checks, guards atomic.Int32 |
| 40 | var written atomic.Bool |
| 41 | r, e := NewRegistry(Operation{Name: "notes_read", Description: "Read", Scope: "notes:read", Input: json.RawMessage(`{"type":"object","properties":{"team":{"type":"string"}},"required":["team"]}`), Output: json.RawMessage(`{"type":"object"}`), Invoke: func(context.Context, Principal, json.RawMessage) (any, error) { |
| 42 | invokes.Add(1) |
| 43 | return map[string]string{"body": strings.Repeat("private", 24000)}, nil |
| 44 | }}) |
| 45 | if e != nil { |
| 46 | t.Fatal(e) |
| 47 | } |
| 48 | p := principal() |
| 49 | p.Scopes = []string{"notes:read"} |
| 50 | if phase == "unrelated" { |
| 51 | p.Scopes = append(p.Scopes, "extra:read") |
| 52 | p.Teams = append(p.Teams, "extra") |
| 53 | } |
| 54 | initial := VerifyFunc(func(context.Context, string) (Principal, error) { initialCalls.Add(1); return p, nil }) |
| 55 | recheck := VerifyFunc(func(ctx context.Context, token string) (Principal, error) { |
| 56 | checks.Add(1) |
| 57 | if token != "original" { |
| 58 | t.Error("credential changed") |
| 59 | } |
| 60 | fresh := p |
| 61 | if phase == "chunk-verifier" && written.Load() { |
| 62 | return Principal{}, Fail("unauthenticated", "Revoked.") |
| 63 | } |
| 64 | if phase == "unrelated" { |
| 65 | fresh.Scopes = fresh.Scopes[:1] |
| 66 | fresh.Teams = fresh.Teams[:1] |
| 67 | } |
| 68 | switch phase { |
| 69 | case "identity": |
| 70 | fresh.Subject = "other" |
| 71 | case "client": |
| 72 | fresh.Client = "other" |
| 73 | case "grant": |
| 74 | fresh.Grant = "other" |
| 75 | case "scope": |
| 76 | fresh.Scopes = nil |
| 77 | case "team": |
| 78 | fresh.Teams = nil |
| 79 | } |
| 80 | return fresh, nil |
| 81 | }) |
| 82 | guard := func(ctx context.Context, original Principal, name string, raw json.RawMessage, result any) error { |
| 83 | if strings.Join(original.Teams, ",") != strings.Join(p.Teams, ",") || strings.Join(original.Scopes, ",") != strings.Join(p.Scopes, ",") || original.Subject != p.Subject || original.Client != p.Client || original.Grant != p.Grant || string(raw) != `{"team":"acme"}` { |
| 84 | t.Error("lost original coordinates") |
| 85 | } |
| 86 | value, ok := result.(map[string]any) |
| 87 | if !ok || value["body"] != strings.Repeat("private", 24000) { |
| 88 | t.Error("lost result") |
| 89 | } |
| 90 | guards.Add(1) |
| 91 | if name != "notes_read" { |
| 92 | t.Error("lost operation") |
| 93 | } |
| 94 | if phase == "preheader" || phase == "chunk" && written.Load() { |
| 95 | return Fail("forbidden", "Access changed.") |
| 96 | } |
| 97 | if phase == "expired" { |
| 98 | <-ctx.Done() |
| 99 | return nil |
| 100 | } |
| 101 | return nil |
| 102 | } |
| 103 | h := r.HTTPGuarded(initial, recheck, guard) |
| 104 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 105 | if phase == "expired" { |
| 106 | ctx, cancel := context.WithTimeout(req.Context(), 20*time.Millisecond) |
| 107 | defer cancel() |
| 108 | req = req.WithContext(ctx) |
| 109 | } |
| 110 | // Ignore the elapsed network deadline only in the expiry test, so the safe |
| 111 | // failure can be inspected even though the callback consumed its budget. |
| 112 | var deadline func(time.Time) error |
| 113 | if phase == "expired" { |
| 114 | deadline = func(time.Time) error { return nil } |
| 115 | } |
| 116 | h.ServeHTTP(guardedWriter{w, func() { written.Store(true) }, deadline}, req) |
| 117 | })) |
| 118 | defer server.Close() |
| 119 | req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/notes_read", strings.NewReader(`{"team":"acme"}`)) |
| 120 | req.Header.Set("Authorization", "Bearer original") |
| 121 | req.Header.Set("Content-Type", "application/json") |
| 122 | resp, e := server.Client().Do(req) |
| 123 | if e != nil { |
| 124 | t.Fatal(e) |
| 125 | } |
| 126 | defer resp.Body.Close() |
| 127 | body, e := io.ReadAll(resp.Body) |
| 128 | if invokes.Load() != 1 || initialCalls.Load() != 1 { |
| 129 | t.Fatalf("invokes=%d initial=%d", invokes.Load(), initialCalls.Load()) |
| 130 | } |
| 131 | switch phase { |
| 132 | case "success", "unrelated": |
| 133 | if checks.Load() != 4 || guards.Load() != 4 { |
| 134 | t.Fatalf("checks=%d guards=%d", checks.Load(), guards.Load()) |
| 135 | } |
| 136 | if e != nil || resp.StatusCode != 200 || len(body) < 130000 { |
| 137 | t.Fatalf("%d %d %v", resp.StatusCode, len(body), e) |
| 138 | } |
| 139 | case "chunk", "chunk-verifier": |
| 140 | wantGuards := int32(3) |
| 141 | if phase == "chunk-verifier" { |
| 142 | wantGuards = 2 |
| 143 | } |
| 144 | if checks.Load() != 3 || guards.Load() != wantGuards { |
| 145 | t.Fatalf("checks=%d guards=%d", checks.Load(), guards.Load()) |
| 146 | } |
| 147 | if resp.StatusCode != 200 || e == nil || len(body) != 64<<10 { |
| 148 | t.Fatalf("chunk %d %d %v", resp.StatusCode, len(body), e) |
| 149 | } |
| 150 | default: |
| 151 | if resp.StatusCode == 200 || strings.Contains(string(body), "private") { |
| 152 | t.Fatalf("leaked %d %d %v", resp.StatusCode, len(body), e) |
| 153 | } |
| 154 | } |
| 155 | }) |
| 156 | } |
| 157 | } |
| 158 | func TestGuardedDiscoveryRetainsDisclosedAuthority(t *testing.T) { |
| 159 | for _, path := range []string{"connection", "operations"} { |
| 160 | for _, lost := range []string{"scope", "team"} { |
| 161 | t.Run(path+lost, func(t *testing.T) { |
| 162 | var count atomic.Int32 |
| 163 | r := testRegistry(t, &count) |
| 164 | p := principal() |
| 165 | p.Scopes = append(p.Scopes, "unrelated:read") |
| 166 | p.Teams = append(p.Teams, "other") |
| 167 | initial := VerifyFunc(func(context.Context, string) (Principal, error) { return p, nil }) |
| 168 | fresh := p |
| 169 | if lost == "scope" { |
| 170 | fresh.Scopes = fresh.Scopes[:1] |
| 171 | } else { |
| 172 | fresh.Teams = fresh.Teams[:1] |
| 173 | } |
| 174 | recheck := VerifyFunc(func(context.Context, string) (Principal, error) { return fresh, nil }) |
| 175 | server := httptest.NewServer(r.HTTPGuarded(initial, recheck, func(context.Context, Principal, string, json.RawMessage, any) error { return nil })) |
| 176 | defer server.Close() |
| 177 | req, _ := http.NewRequest("GET", server.URL+"/api/v1/"+path, nil) |
| 178 | req.Header.Set("Authorization", "Bearer token") |
| 179 | resp, e := server.Client().Do(req) |
| 180 | if e != nil { |
| 181 | t.Fatal(e) |
| 182 | } |
| 183 | defer resp.Body.Close() |
| 184 | b, _ := io.ReadAll(resp.Body) |
| 185 | if resp.StatusCode != 403 || strings.Contains(string(b), "unrelated") || count.Load() != 0 { |
| 186 | t.Fatalf("%d %s invokes %d", resp.StatusCode, b, count.Load()) |
| 187 | } |
| 188 | }) |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | func TestGuardedTransportAndCallbacksRequired(t *testing.T) { |
| 193 | var calls atomic.Int32 |
| 194 | r := testRegistry(t, &calls) |
| 195 | v := VerifyFunc(func(context.Context, string) (Principal, error) { return principal(), nil }) |
| 196 | guard := func(context.Context, Principal, string, json.RawMessage, any) error { return nil } |
| 197 | for _, f := range []func(){func() { r.HTTPGuarded(nil, v, guard) }, func() { r.HTTPGuarded(v, nil, guard) }, func() { r.HTTPGuarded(v, v, nil) }} { |
| 198 | func() { |
| 199 | defer func() { |
| 200 | if recover() == nil { |
| 201 | t.Error("missing callback accepted") |
| 202 | } |
| 203 | }() |
| 204 | f() |
| 205 | }() |
| 206 | } |
| 207 | req := httptest.NewRequest("GET", "/api/v1/connection", nil) |
| 208 | req.Header.Set("Authorization", "Bearer t") |
| 209 | w := httptest.NewRecorder() |
| 210 | r.HTTPGuarded(v, v, guard).ServeHTTP(w, req) |
| 211 | if w.Code != 503 || strings.Contains(w.Body.String(), "acme") { |
| 212 | t.Fatalf("unsupported writer: %d %s", w.Code, w.Body.String()) |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | func TestGuardedAvailableUsesCapturedDiscovery(t *testing.T) { |
| 217 | for _, path := range []string{"operations", "operations/notes_create"} { |
| 218 | t.Run(path, func(t *testing.T) { |
| 219 | var count atomic.Int32 |
| 220 | r := testRegistry(t, &count) |
| 221 | entry := r.operations["notes_create"] |
| 222 | var available atomic.Int32 |
| 223 | // The first evaluation selects the operation; all later checks revoke it. |
| 224 | entry.op.Available = func(Principal) bool { return available.Add(1) == 1 } |
| 225 | r.operations["notes_create"] = entry |
| 226 | v := VerifyFunc(func(context.Context, string) (Principal, error) { return principal(), nil }) |
| 227 | server := httptest.NewServer(r.HTTPGuarded(v, v, func(context.Context, Principal, string, json.RawMessage, any) error { return nil })) |
| 228 | defer server.Close() |
| 229 | method := "GET" |
| 230 | var body io.Reader |
| 231 | if strings.Contains(path, "/") { |
| 232 | method = "POST" |
| 233 | body = strings.NewReader(`{"team":"acme","title":"x"}`) |
| 234 | } |
| 235 | req, _ := http.NewRequest(method, server.URL+"/api/v1/"+path, body) |
| 236 | req.Header.Set("Authorization", "Bearer t") |
| 237 | req.Header.Set("Content-Type", "application/json") |
| 238 | resp, e := server.Client().Do(req) |
| 239 | if e != nil { |
| 240 | t.Fatal(e) |
| 241 | } |
| 242 | defer resp.Body.Close() |
| 243 | data, _ := io.ReadAll(resp.Body) |
| 244 | if resp.StatusCode != 403 || strings.Contains(string(data), "notes_create") { |
| 245 | t.Fatalf("stale operation: %d %s", resp.StatusCode, data) |
| 246 | } |
| 247 | }) |
| 248 | } |
| 249 | } |
| 250 | func TestGuardedDiscoveryCallsAppGuard(t *testing.T) { |
| 251 | var count, guards atomic.Int32 |
| 252 | r := testRegistry(t, &count) |
| 253 | v := VerifyFunc(func(context.Context, string) (Principal, error) { return principal(), nil }) |
| 254 | h := r.HTTPGuarded(v, v, func(_ context.Context, p Principal, name string, raw json.RawMessage, result any) error { |
| 255 | guards.Add(1) |
| 256 | if p.Subject != principal().Subject || name != "" || raw != nil || result == nil { |
| 257 | t.Error("discovery coordinates") |
| 258 | } |
| 259 | return Fail("forbidden", "Local identity revoked.") |
| 260 | }) |
| 261 | server := httptest.NewServer(h) |
| 262 | defer server.Close() |
| 263 | for _, path := range []string{"connection", "operations"} { |
| 264 | req, _ := http.NewRequest("GET", server.URL+"/api/v1/"+path, nil) |
| 265 | req.Header.Set("Authorization", "Bearer t") |
| 266 | resp, e := server.Client().Do(req) |
| 267 | if e != nil { |
| 268 | t.Fatal(e) |
| 269 | } |
| 270 | io.Copy(io.Discard, resp.Body) |
| 271 | resp.Body.Close() |
| 272 | if resp.StatusCode != 403 { |
| 273 | t.Fatal(resp.StatusCode) |
| 274 | } |
| 275 | } |
| 276 | if guards.Load() != 2 || count.Load() != 0 { |
| 277 | t.Fatal(guards.Load(), count.Load()) |
| 278 | } |
| 279 | } |
| 280 | func TestGuardedExpiredVerifierCannotReachAppGuard(t *testing.T) { |
| 281 | var count, guards atomic.Int32 |
| 282 | r := testRegistry(t, &count) |
| 283 | v := VerifyFunc(func(context.Context, string) (Principal, error) { return principal(), nil }) |
| 284 | recheck := VerifyFunc(func(ctx context.Context, _ string) (Principal, error) { <-ctx.Done(); return principal(), nil }) |
| 285 | h := r.HTTPGuarded(v, recheck, func(context.Context, Principal, string, json.RawMessage, any) error { guards.Add(1); return nil }) |
| 286 | req := httptest.NewRequest("GET", "/api/v1/connection", nil) |
| 287 | req.Header.Set("Authorization", "Bearer t") |
| 288 | ctx, cancel := context.WithTimeout(req.Context(), 10*time.Millisecond) |
| 289 | defer cancel() |
| 290 | w := httptest.NewRecorder() |
| 291 | h.ServeHTTP(guardedWriter{w, nil, func(time.Time) error { return nil }}, req.WithContext(ctx)) |
| 292 | if w.Code == 200 || guards.Load() != 0 { |
| 293 | t.Fatalf("%d guards=%d", w.Code, guards.Load()) |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | func TestGuardedDiscoveryPayloadBound(t *testing.T) { |
| 298 | var count atomic.Int32 |
| 299 | r := testRegistry(t, &count) |
| 300 | p := principal() |
| 301 | p.Teams = []string{strings.Repeat("private-canary", MaxPayload/10)} |
| 302 | v := VerifyFunc(func(context.Context, string) (Principal, error) { return p, nil }) |
| 303 | server := httptest.NewServer(r.HTTPGuarded(v, v, func(context.Context, Principal, string, json.RawMessage, any) error { return nil })) |
| 304 | defer server.Close() |
| 305 | req, _ := http.NewRequest("GET", server.URL+"/api/v1/connection", nil) |
| 306 | req.Header.Set("Authorization", "Bearer t") |
| 307 | resp, e := server.Client().Do(req) |
| 308 | if e != nil { |
| 309 | t.Fatal(e) |
| 310 | } |
| 311 | defer resp.Body.Close() |
| 312 | b, _ := io.ReadAll(resp.Body) |
| 313 | if resp.StatusCode != 413 || strings.Contains(string(b), "private-canary") { |
| 314 | t.Fatalf("%d %d", resp.StatusCode, len(b)) |
| 315 | } |
| 316 | } |
| 317 | |