| new file mode 100644 |
| index 0000000..5c214a0 |
| --- /dev/null |
| +++ b/team_arg_test.go |
| @@ -0,0 +1,238 @@ |
| +package agentaccess |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "github.com/modelcontextprotocol/go-sdk/mcp" |
| +) |
| + |
| +// permissiveNote has no additionalProperties:false, so a stray key reaches |
| +// the routing code instead of being refused by the schema. |
| +func permissiveNote() Operation { |
| + return Operation{Name: "notes_create", Description: "Create a note", Scope: "notes:write", |
| + Input: json.RawMessage(`{"type":"object","properties":{"team":{"type":"string"},"title":{"type":"string"}},"required":["title"]}`), |
| + Output: json.RawMessage(`{"type":"object"}`)} |
| +} |
| + |
| +// teamArgFixture is a real Gateway in front of one TLS app per routed team. |
| +type teamArgFixture struct { |
| + gateway *Registry |
| + credentials *testCredentials |
| + mu sync.Mutex |
| + hits []string |
| + bodies []string |
| +} |
| + |
| +func (f *teamArgFixture) reached() []string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return append([]string{}, f.hits...) |
| +} |
| + |
| +func newTeamArgFixture(t *testing.T, teams ...string) *teamArgFixture { |
| + t.Helper() |
| + f := &teamArgFixture{credentials: &testCredentials{}} |
| + mux := http.NewServeMux() |
| + s := httptest.NewTLSServer(mux) |
| + t.Cleanup(s.Close) |
| + routes := []Route{} |
| + for _, team := range teams { |
| + routes = append(routes, Route{Team: team, Resource: "https://" + team + ".test/api/v1", Operations: []Operation{permissiveNote()}}) |
| + mux.HandleFunc("POST /"+team+"/api/v1/operations/notes_create", func(w http.ResponseWriter, r *http.Request) { |
| + body, _ := io.ReadAll(r.Body) |
| + f.mu.Lock() |
| + f.hits, f.bodies = append(f.hits, team), append(f.bodies, string(body)) |
| + f.mu.Unlock() |
| + w.Header().Set("Content-Type", "application/json") |
| + _, _ = w.Write([]byte(`{}`)) |
| + }) |
| + } |
| + base := s.Client().Transport |
| + rewrite := roundTripFunc(func(r *http.Request) (*http.Response, error) { |
| + out := r.Clone(r.Context()) |
| + team := strings.TrimSuffix(r.URL.Hostname(), ".test") |
| + out.URL.Scheme, out.URL.Host = "https", strings.TrimPrefix(s.URL, "https://") |
| + out.URL.Path = "/" + team + r.URL.Path |
| + return base.RoundTrip(out) |
| + }) |
| + gateway, err := Gateway(routes, f.credentials, rewrite) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.gateway = gateway |
| + return f |
| +} |
| + |
| +type roundTripFunc func(*http.Request) (*http.Response, error) |
| + |
| +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| + |
| +func teamArgPrincipal(teams ...string) Principal { |
| + return Principal{Subject: "person", Client: "client", Grant: "grant", Teams: teams, Scopes: []string{"notes:write"}} |
| +} |
| + |
| +// Every spelling encoding/json would fold onto "team", in both orders, with |
| +// the same value and with another team's. |
| +var ambiguousTeamInputs = []string{ |
| + `{"team":"acme","TEAM":"other","title":"x"}`, |
| + `{"TEAM":"other","team":"acme","title":"x"}`, |
| + `{"team":"other","TEAM":"acme","title":"x"}`, |
| + `{"team":"acme","Team":"other","title":"x"}`, |
| + `{"team":"acme","tEAM":"other","title":"x"}`, |
| + `{"team":"acme","teaM":"other","title":"x"}`, |
| + `{"team":"acme","TEAM":"acme","title":"x"}`, |
| + `{"TEAM":"acme","title":"x"}`, |
| + `{"team":"acme","team":"other","title":"x"}`, |
| +} |
| + |
| +func TestAmbiguousTeamIsRefusedBeforeAnyApp(t *testing.T) { |
| + for _, raw := range ambiguousTeamInputs { |
| + t.Run(raw, func(t *testing.T) { |
| + f := newTeamArgFixture(t, "acme", "other") |
| + _, err := f.gateway.Call(t.Context(), teamArgPrincipal("acme", "other"), "notes_create", json.RawMessage(raw)) |
| + if err == nil || SafeFailure(err).Code != "invalid" { |
| + t.Fatalf("want invalid, got %v", err) |
| + } |
| + if f.credentials.calls != 0 || len(f.reached()) != 0 { |
| + t.Fatalf("reached minting (%d) or an app (%v)", f.credentials.calls, f.reached()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAmbiguousTeamIsRefusedOverHTTPAndMCP(t *testing.T) { |
| + const raw = `{"team":"acme","TEAM":"other","title":"x"}` |
| + f := newTeamArgFixture(t, "acme", "other") |
| + verify := VerifyFunc(func(context.Context, string) (Principal, error) { return teamArgPrincipal("acme", "other"), nil }) |
| + |
| + api := httptest.NewServer(f.gateway.HTTPGuarded(verify, verify, f.gateway.ScheduleResponseGuard)) |
| + defer api.Close() |
| + req, _ := http.NewRequest("POST", api.URL+"/api/v1/operations/notes_create", strings.NewReader(raw)) |
| + req.Header.Set("Authorization", "Bearer test") |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, err := api.Client().Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode != 422 { |
| + t.Fatalf("HTTP status %d", resp.StatusCode) |
| + } |
| + |
| + server := httptest.NewServer(f.gateway.MCP(verify)) |
| + defer server.Close() |
| + client := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "1"}, nil) |
| + session, err := client.Connect(t.Context(), &mcp.StreamableClientTransport{Endpoint: server.URL, HTTPClient: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { |
| + out := r.Clone(r.Context()) |
| + out.Header.Set("Authorization", "Bearer test") |
| + return http.DefaultTransport.RoundTrip(out) |
| + })}}, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer session.Close() |
| + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "notes_create", Arguments: json.RawMessage(raw)}) |
| + if err == nil && !result.IsError { |
| + t.Fatal("MCP accepted an ambiguous team") |
| + } |
| + if f.credentials.calls != 0 || len(f.reached()) != 0 { |
| + t.Fatalf("reached minting (%d) or an app (%v)", f.credentials.calls, f.reached()) |
| + } |
| +} |
| + |
| +// Only one team has routes, as in production today. |
| +func TestSingleRoutedTeamCannotBeCrossed(t *testing.T) { |
| + for _, tc := range []struct { |
| + raw string |
| + teams []string |
| + }{ |
| + {`{"team":"Uk","TEAM":"Xy","title":"x"}`, []string{"Uk"}}, |
| + {`{"team":"Xy","TEAM":"Uk","title":"x"}`, []string{"Uk"}}, |
| + {`{"team":"Xy","TEAM":"Uk","title":"x"}`, []string{"Uk", "Xy"}}, |
| + {`{"team":"Uk","TEAM":"Xy","title":"x"}`, []string{"Uk", "Xy"}}, |
| + } { |
| + t.Run(tc.raw, func(t *testing.T) { |
| + f := newTeamArgFixture(t, "Uk") |
| + if _, err := f.gateway.Call(t.Context(), teamArgPrincipal(tc.teams...), "notes_create", json.RawMessage(tc.raw)); err == nil { |
| + t.Fatal("accepted") |
| + } |
| + if len(f.reached()) != 0 { |
| + t.Fatalf("reached %v", f.reached()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// What must keep working: the named team, unrelated fields, and a nested key |
| +// that happens to be spelled TEAM. |
| +func TestUnambiguousCallsRouteToTheNamedTeam(t *testing.T) { |
| + for _, raw := range []string{ |
| + `{"team":"other","title":"x"}`, |
| + `{"team":"other","title":"x","teammate":"y"}`, |
| + `{"team":"other","title":"x","meta":{"TEAM":"acme"}}`, |
| + } { |
| + t.Run(raw, func(t *testing.T) { |
| + f := newTeamArgFixture(t, "acme", "other") |
| + if _, err := f.gateway.Call(t.Context(), teamArgPrincipal("acme", "other"), "notes_create", json.RawMessage(raw)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := f.reached(); len(got) != 1 || got[0] != "other" || f.credentials.team != "other" { |
| + t.Fatalf("routed to %v, minted for %q", got, f.credentials.team) |
| + } |
| + if f.bodies[0] != raw { |
| + t.Fatalf("body changed: %s", f.bodies[0]) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestOperationTeamIsTheExactKey(t *testing.T) { |
| + for _, tc := range []struct { |
| + raw, team string |
| + bad bool |
| + }{ |
| + {raw: `{"team":"acme"}`, team: "acme"}, |
| + {raw: `{"title":"x"}`}, |
| + {raw: `{"team":7}`}, |
| + {raw: `{"team":"acme","meta":{"TEAM":"other"}}`, team: "acme"}, |
| + {raw: `{"team":"acme","TEAM":"other"}`, bad: true}, |
| + {raw: `{"Team":"acme"}`, bad: true}, |
| + {raw: `{"team":"acme","team":"other"}`, bad: true}, |
| + {raw: `[]`, bad: true}, |
| + {raw: `null`, bad: true}, |
| + } { |
| + team, err := operationTeam(json.RawMessage(tc.raw)) |
| + if (err != nil) != tc.bad || team != tc.team { |
| + t.Errorf("%s: team %q, err %v", tc.raw, team, err) |
| + } |
| + } |
| +} |
| + |
| +// The scheduler's response check reads the team the same way. |
| +func TestScheduleGuardRefusesAnAmbiguousTeam(t *testing.T) { |
| + r, err := NewRegistry() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + err = r.ScheduleResponseGuard(t.Context(), teamArgPrincipal("acme"), "calls_schedule", json.RawMessage(`{"team":"acme","TEAM":"other"}`), map[string]any{}) |
| + if f := SafeFailure(err); f.Code != "unavailable" || !strings.Contains(f.Message, "provenance") { |
| + t.Fatalf("got %v", err) |
| + } |
| +} |
| + |
| +// Invoke holds the same line on its own, whatever reaches it. |
| +func TestInvokeRefusesAnAmbiguousTeam(t *testing.T) { |
| + f := newTeamArgFixture(t, "acme", "other") |
| + invoke := f.gateway.operations["notes_create"].op.Invoke |
| + _, err := invoke(t.Context(), teamArgPrincipal("acme", "other"), json.RawMessage(`{"team":"acme","TEAM":"other","title":"x"}`)) |
| + if err == nil || SafeFailure(err).Code != "invalid" || f.credentials.calls != 0 || len(f.reached()) != 0 { |
| + t.Fatalf("got %v, minted %d, reached %v", err, f.credentials.calls, f.reached()) |
| + } |
| +} |