| new file mode 100644 |
| index 0000000..bfd087f |
| --- /dev/null |
| +++ b/http_guarded_test.go |
| @@ -0,0 +1,316 @@ |
| +package agentaccess |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| +) |
| + |
| +type guardedWriter struct { |
| + http.ResponseWriter |
| + after func() |
| + deadline func(time.Time) error |
| +} |
| + |
| +func (w guardedWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| +func (w guardedWriter) Write(b []byte) (int, error) { |
| + n, e := w.ResponseWriter.Write(b) |
| + if w.after != nil { |
| + w.after() |
| + } |
| + return n, e |
| +} |
| +func (w guardedWriter) SetWriteDeadline(d time.Time) error { |
| + if w.deadline != nil { |
| + return w.deadline(d) |
| + } |
| + return http.NewResponseController(w.ResponseWriter).SetWriteDeadline(d) |
| +} |
| + |
| +func TestGuardedHTTPResponseBoundaries(t *testing.T) { |
| + for _, phase := range []string{"success", "preheader", "chunk", "chunk-verifier", "unrelated", "identity", "client", "grant", "scope", "team", "expired"} { |
| + t.Run(phase, func(t *testing.T) { |
| + var invokes, initialCalls, checks, guards atomic.Int32 |
| + var written atomic.Bool |
| + 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) { |
| + invokes.Add(1) |
| + return map[string]string{"body": strings.Repeat("private", 24000)}, nil |
| + }}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + p := principal() |
| + p.Scopes = []string{"notes:read"} |
| + if phase == "unrelated" { |
| + p.Scopes = append(p.Scopes, "extra:read") |
| + p.Teams = append(p.Teams, "extra") |
| + } |
| + initial := VerifyFunc(func(context.Context, string) (Principal, error) { initialCalls.Add(1); return p, nil }) |
| + recheck := VerifyFunc(func(ctx context.Context, token string) (Principal, error) { |
| + checks.Add(1) |
| + if token != "original" { |
| + t.Error("credential changed") |
| + } |
| + fresh := p |
| + if phase == "chunk-verifier" && written.Load() { |
| + return Principal{}, Fail("unauthenticated", "Revoked.") |
| + } |
| + if phase == "unrelated" { |
| + fresh.Scopes = fresh.Scopes[:1] |
| + fresh.Teams = fresh.Teams[:1] |
| + } |
| + switch phase { |
| + case "identity": |
| + fresh.Subject = "other" |
| + case "client": |
| + fresh.Client = "other" |
| + case "grant": |
| + fresh.Grant = "other" |
| + case "scope": |
| + fresh.Scopes = nil |
| + case "team": |
| + fresh.Teams = nil |
| + } |
| + return fresh, nil |
| + }) |
| + guard := func(ctx context.Context, original Principal, name string, raw json.RawMessage, result any) error { |
| + 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"}` { |
| + t.Error("lost original coordinates") |
| + } |
| + value, ok := result.(map[string]any) |
| + if !ok || value["body"] != strings.Repeat("private", 24000) { |
| + t.Error("lost result") |
| + } |
| + guards.Add(1) |
| + if name != "notes_read" { |
| + t.Error("lost operation") |
| + } |
| + if phase == "preheader" || phase == "chunk" && written.Load() { |
| + return Fail("forbidden", "Access changed.") |
| + } |
| + if phase == "expired" { |
| + <-ctx.Done() |
| + return nil |
| + } |
| + return nil |
| + } |
| + h := r.HTTPGuarded(initial, recheck, guard) |
| + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| + if phase == "expired" { |
| + ctx, cancel := context.WithTimeout(req.Context(), 20*time.Millisecond) |
| + defer cancel() |
| + req = req.WithContext(ctx) |
| + } |
| + // Ignore the elapsed network deadline only in the expiry test, so the safe |
| + // failure can be inspected even though the callback consumed its budget. |
| + var deadline func(time.Time) error |
| + if phase == "expired" { |
| + deadline = func(time.Time) error { return nil } |
| + } |
| + h.ServeHTTP(guardedWriter{w, func() { written.Store(true) }, deadline}, req) |
| + })) |
| + defer server.Close() |
| + req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/notes_read", strings.NewReader(`{"team":"acme"}`)) |
| + req.Header.Set("Authorization", "Bearer original") |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, e := server.Client().Do(req) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer resp.Body.Close() |
| + body, e := io.ReadAll(resp.Body) |
| + if invokes.Load() != 1 || initialCalls.Load() != 1 { |
| + t.Fatalf("invokes=%d initial=%d", invokes.Load(), initialCalls.Load()) |
| + } |
| + switch phase { |
| + case "success", "unrelated": |
| + if checks.Load() != 4 || guards.Load() != 4 { |
| + t.Fatalf("checks=%d guards=%d", checks.Load(), guards.Load()) |
| + } |
| + if e != nil || resp.StatusCode != 200 || len(body) < 130000 { |
| + t.Fatalf("%d %d %v", resp.StatusCode, len(body), e) |
| + } |
| + case "chunk", "chunk-verifier": |
| + wantGuards := int32(3) |
| + if phase == "chunk-verifier" { |
| + wantGuards = 2 |
| + } |
| + if checks.Load() != 3 || guards.Load() != wantGuards { |
| + t.Fatalf("checks=%d guards=%d", checks.Load(), guards.Load()) |
| + } |
| + if resp.StatusCode != 200 || e == nil || len(body) != 64<<10 { |
| + t.Fatalf("chunk %d %d %v", resp.StatusCode, len(body), e) |
| + } |
| + default: |
| + if resp.StatusCode == 200 || strings.Contains(string(body), "private") { |
| + t.Fatalf("leaked %d %d %v", resp.StatusCode, len(body), e) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestGuardedDiscoveryRetainsDisclosedAuthority(t *testing.T) { |
| + for _, path := range []string{"connection", "operations"} { |
| + for _, lost := range []string{"scope", "team"} { |
| + t.Run(path+lost, func(t *testing.T) { |
| + var count atomic.Int32 |
| + r := testRegistry(t, &count) |
| + p := principal() |
| + p.Scopes = append(p.Scopes, "unrelated:read") |
| + p.Teams = append(p.Teams, "other") |
| + initial := VerifyFunc(func(context.Context, string) (Principal, error) { return p, nil }) |
| + fresh := p |
| + if lost == "scope" { |
| + fresh.Scopes = fresh.Scopes[:1] |
| + } else { |
| + fresh.Teams = fresh.Teams[:1] |
| + } |
| + recheck := VerifyFunc(func(context.Context, string) (Principal, error) { return fresh, nil }) |
| + server := httptest.NewServer(r.HTTPGuarded(initial, recheck, func(context.Context, Principal, string, json.RawMessage, any) error { return nil })) |
| + defer server.Close() |
| + req, _ := http.NewRequest("GET", server.URL+"/api/v1/"+path, nil) |
| + req.Header.Set("Authorization", "Bearer token") |
| + resp, e := server.Client().Do(req) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer resp.Body.Close() |
| + b, _ := io.ReadAll(resp.Body) |
| + if resp.StatusCode != 403 || strings.Contains(string(b), "unrelated") || count.Load() != 0 { |
| + t.Fatalf("%d %s invokes %d", resp.StatusCode, b, count.Load()) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| +func TestGuardedTransportAndCallbacksRequired(t *testing.T) { |
| + var calls atomic.Int32 |
| + r := testRegistry(t, &calls) |
| + v := VerifyFunc(func(context.Context, string) (Principal, error) { return principal(), nil }) |
| + guard := func(context.Context, Principal, string, json.RawMessage, any) error { return nil } |
| + for _, f := range []func(){func() { r.HTTPGuarded(nil, v, guard) }, func() { r.HTTPGuarded(v, nil, guard) }, func() { r.HTTPGuarded(v, v, nil) }} { |
| + func() { |
| + defer func() { |
| + if recover() == nil { |
| + t.Error("missing callback accepted") |
| + } |
| + }() |
| + f() |
| + }() |
| + } |
| + req := httptest.NewRequest("GET", "/api/v1/connection", nil) |
| + req.Header.Set("Authorization", "Bearer t") |
| + w := httptest.NewRecorder() |
| + r.HTTPGuarded(v, v, guard).ServeHTTP(w, req) |
| + if w.Code != 503 || strings.Contains(w.Body.String(), "acme") { |
| + t.Fatalf("unsupported writer: %d %s", w.Code, w.Body.String()) |
| + } |
| +} |
| + |
| +func TestGuardedAvailableUsesCapturedDiscovery(t *testing.T) { |
| + for _, path := range []string{"operations", "operations/notes_create"} { |
| + t.Run(path, func(t *testing.T) { |
| + var count atomic.Int32 |
| + r := testRegistry(t, &count) |
| + entry := r.operations["notes_create"] |
| + var available atomic.Int32 |
| + // The first evaluation selects the operation; all later checks revoke it. |
| + entry.op.Available = func(Principal) bool { return available.Add(1) == 1 } |
| + r.operations["notes_create"] = entry |
| + v := VerifyFunc(func(context.Context, string) (Principal, error) { return principal(), nil }) |
| + server := httptest.NewServer(r.HTTPGuarded(v, v, func(context.Context, Principal, string, json.RawMessage, any) error { return nil })) |
| + defer server.Close() |
| + method := "GET" |
| + var body io.Reader |
| + if strings.Contains(path, "/") { |
| + method = "POST" |
| + body = strings.NewReader(`{"team":"acme","title":"x"}`) |
| + } |
| + req, _ := http.NewRequest(method, server.URL+"/api/v1/"+path, body) |
| + req.Header.Set("Authorization", "Bearer t") |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, e := server.Client().Do(req) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer resp.Body.Close() |
| + data, _ := io.ReadAll(resp.Body) |
| + if resp.StatusCode != 403 || strings.Contains(string(data), "notes_create") { |
| + t.Fatalf("stale operation: %d %s", resp.StatusCode, data) |
| + } |
| + }) |
| + } |
| +} |
| +func TestGuardedDiscoveryCallsAppGuard(t *testing.T) { |
| + var count, guards atomic.Int32 |
| + r := testRegistry(t, &count) |
| + v := VerifyFunc(func(context.Context, string) (Principal, error) { return principal(), nil }) |
| + h := r.HTTPGuarded(v, v, func(_ context.Context, p Principal, name string, raw json.RawMessage, result any) error { |
| + guards.Add(1) |
| + if p.Subject != principal().Subject || name != "" || raw != nil || result == nil { |
| + t.Error("discovery coordinates") |
| + } |
| + return Fail("forbidden", "Local identity revoked.") |
| + }) |
| + server := httptest.NewServer(h) |
| + defer server.Close() |
| + for _, path := range []string{"connection", "operations"} { |
| + req, _ := http.NewRequest("GET", server.URL+"/api/v1/"+path, nil) |
| + req.Header.Set("Authorization", "Bearer t") |
| + resp, e := server.Client().Do(req) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + io.Copy(io.Discard, resp.Body) |
| + resp.Body.Close() |
| + if resp.StatusCode != 403 { |
| + t.Fatal(resp.StatusCode) |
| + } |
| + } |
| + if guards.Load() != 2 || count.Load() != 0 { |
| + t.Fatal(guards.Load(), count.Load()) |
| + } |
| +} |
| +func TestGuardedExpiredVerifierCannotReachAppGuard(t *testing.T) { |
| + var count, guards atomic.Int32 |
| + r := testRegistry(t, &count) |
| + v := VerifyFunc(func(context.Context, string) (Principal, error) { return principal(), nil }) |
| + recheck := VerifyFunc(func(ctx context.Context, _ string) (Principal, error) { <-ctx.Done(); return principal(), nil }) |
| + h := r.HTTPGuarded(v, recheck, func(context.Context, Principal, string, json.RawMessage, any) error { guards.Add(1); return nil }) |
| + req := httptest.NewRequest("GET", "/api/v1/connection", nil) |
| + req.Header.Set("Authorization", "Bearer t") |
| + ctx, cancel := context.WithTimeout(req.Context(), 10*time.Millisecond) |
| + defer cancel() |
| + w := httptest.NewRecorder() |
| + h.ServeHTTP(guardedWriter{w, nil, func(time.Time) error { return nil }}, req.WithContext(ctx)) |
| + if w.Code == 200 || guards.Load() != 0 { |
| + t.Fatalf("%d guards=%d", w.Code, guards.Load()) |
| + } |
| +} |
| + |
| +func TestGuardedDiscoveryPayloadBound(t *testing.T) { |
| + var count atomic.Int32 |
| + r := testRegistry(t, &count) |
| + p := principal() |
| + p.Teams = []string{strings.Repeat("private-canary", MaxPayload/10)} |
| + v := VerifyFunc(func(context.Context, string) (Principal, error) { return p, nil }) |
| + server := httptest.NewServer(r.HTTPGuarded(v, v, func(context.Context, Principal, string, json.RawMessage, any) error { return nil })) |
| + defer server.Close() |
| + req, _ := http.NewRequest("GET", server.URL+"/api/v1/connection", nil) |
| + req.Header.Set("Authorization", "Bearer t") |
| + resp, e := server.Client().Do(req) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer resp.Body.Close() |
| + b, _ := io.ReadAll(resp.Body) |
| + if resp.StatusCode != 413 || strings.Contains(string(b), "private-canary") { |
| + t.Fatalf("%d %d", resp.StatusCode, len(b)) |
| + } |
| +} |