| 1 | package agentaccess |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "strings" |
| 10 | "sync" |
| 11 | "testing" |
| 12 | |
| 13 | "github.com/modelcontextprotocol/go-sdk/mcp" |
| 14 | ) |
| 15 | |
| 16 | // permissiveNote has no additionalProperties:false, so a stray key reaches |
| 17 | // the routing code instead of being refused by the schema. |
| 18 | func permissiveNote() Operation { |
| 19 | return Operation{Name: "notes_create", Description: "Create a note", Scope: "notes:write", |
| 20 | Input: json.RawMessage(`{"type":"object","properties":{"team":{"type":"string"},"title":{"type":"string"}},"required":["title"]}`), |
| 21 | Output: json.RawMessage(`{"type":"object"}`)} |
| 22 | } |
| 23 | |
| 24 | // teamArgFixture is a real Gateway in front of one TLS app per routed team. |
| 25 | type teamArgFixture struct { |
| 26 | gateway *Registry |
| 27 | credentials *testCredentials |
| 28 | mu sync.Mutex |
| 29 | hits []string |
| 30 | bodies []string |
| 31 | } |
| 32 | |
| 33 | func (f *teamArgFixture) reached() []string { |
| 34 | f.mu.Lock() |
| 35 | defer f.mu.Unlock() |
| 36 | return append([]string{}, f.hits...) |
| 37 | } |
| 38 | |
| 39 | func newTeamArgFixture(t *testing.T, teams ...string) *teamArgFixture { |
| 40 | t.Helper() |
| 41 | f := &teamArgFixture{credentials: &testCredentials{}} |
| 42 | mux := http.NewServeMux() |
| 43 | s := httptest.NewTLSServer(mux) |
| 44 | t.Cleanup(s.Close) |
| 45 | routes := []Route{} |
| 46 | for _, team := range teams { |
| 47 | routes = append(routes, Route{Team: team, Resource: "https://" + team + ".test/api/v1", Operations: []Operation{permissiveNote()}}) |
| 48 | mux.HandleFunc("POST /"+team+"/api/v1/operations/notes_create", func(w http.ResponseWriter, r *http.Request) { |
| 49 | body, _ := io.ReadAll(r.Body) |
| 50 | f.mu.Lock() |
| 51 | f.hits, f.bodies = append(f.hits, team), append(f.bodies, string(body)) |
| 52 | f.mu.Unlock() |
| 53 | w.Header().Set("Content-Type", "application/json") |
| 54 | _, _ = w.Write([]byte(`{}`)) |
| 55 | }) |
| 56 | } |
| 57 | base := s.Client().Transport |
| 58 | rewrite := roundTripFunc(func(r *http.Request) (*http.Response, error) { |
| 59 | out := r.Clone(r.Context()) |
| 60 | team := strings.TrimSuffix(r.URL.Hostname(), ".test") |
| 61 | out.URL.Scheme, out.URL.Host = "https", strings.TrimPrefix(s.URL, "https://") |
| 62 | out.URL.Path = "/" + team + r.URL.Path |
| 63 | return base.RoundTrip(out) |
| 64 | }) |
| 65 | gateway, err := Gateway(routes, f.credentials, rewrite) |
| 66 | if err != nil { |
| 67 | t.Fatal(err) |
| 68 | } |
| 69 | f.gateway = gateway |
| 70 | return f |
| 71 | } |
| 72 | |
| 73 | type roundTripFunc func(*http.Request) (*http.Response, error) |
| 74 | |
| 75 | func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| 76 | |
| 77 | func teamArgPrincipal(teams ...string) Principal { |
| 78 | return Principal{Subject: "person", Client: "client", Grant: "grant", Teams: teams, Scopes: []string{"notes:write"}} |
| 79 | } |
| 80 | |
| 81 | // Every spelling encoding/json would fold onto "team", in both orders, with |
| 82 | // the same value and with another team's. |
| 83 | var ambiguousTeamInputs = []string{ |
| 84 | `{"team":"acme","TEAM":"other","title":"x"}`, |
| 85 | `{"TEAM":"other","team":"acme","title":"x"}`, |
| 86 | `{"team":"other","TEAM":"acme","title":"x"}`, |
| 87 | `{"team":"acme","Team":"other","title":"x"}`, |
| 88 | `{"team":"acme","tEAM":"other","title":"x"}`, |
| 89 | `{"team":"acme","teaM":"other","title":"x"}`, |
| 90 | `{"team":"acme","TEAM":"acme","title":"x"}`, |
| 91 | `{"TEAM":"acme","title":"x"}`, |
| 92 | `{"team":"acme","team":"other","title":"x"}`, |
| 93 | } |
| 94 | |
| 95 | func TestAmbiguousTeamIsRefusedBeforeAnyApp(t *testing.T) { |
| 96 | for _, raw := range ambiguousTeamInputs { |
| 97 | t.Run(raw, func(t *testing.T) { |
| 98 | f := newTeamArgFixture(t, "acme", "other") |
| 99 | _, err := f.gateway.Call(t.Context(), teamArgPrincipal("acme", "other"), "notes_create", json.RawMessage(raw)) |
| 100 | if err == nil || SafeFailure(err).Code != "invalid" { |
| 101 | t.Fatalf("want invalid, got %v", err) |
| 102 | } |
| 103 | if f.credentials.calls != 0 || len(f.reached()) != 0 { |
| 104 | t.Fatalf("reached minting (%d) or an app (%v)", f.credentials.calls, f.reached()) |
| 105 | } |
| 106 | }) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | func TestAmbiguousTeamIsRefusedOverHTTPAndMCP(t *testing.T) { |
| 111 | const raw = `{"team":"acme","TEAM":"other","title":"x"}` |
| 112 | f := newTeamArgFixture(t, "acme", "other") |
| 113 | verify := VerifyFunc(func(context.Context, string) (Principal, error) { return teamArgPrincipal("acme", "other"), nil }) |
| 114 | |
| 115 | api := httptest.NewServer(f.gateway.HTTPGuarded(verify, verify, f.gateway.ScheduleResponseGuard)) |
| 116 | defer api.Close() |
| 117 | req, _ := http.NewRequest("POST", api.URL+"/api/v1/operations/notes_create", strings.NewReader(raw)) |
| 118 | req.Header.Set("Authorization", "Bearer test") |
| 119 | req.Header.Set("Content-Type", "application/json") |
| 120 | resp, err := api.Client().Do(req) |
| 121 | if err != nil { |
| 122 | t.Fatal(err) |
| 123 | } |
| 124 | resp.Body.Close() |
| 125 | if resp.StatusCode != 422 { |
| 126 | t.Fatalf("HTTP status %d", resp.StatusCode) |
| 127 | } |
| 128 | |
| 129 | server := httptest.NewServer(f.gateway.MCP(verify)) |
| 130 | defer server.Close() |
| 131 | client := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "1"}, nil) |
| 132 | session, err := client.Connect(t.Context(), &mcp.StreamableClientTransport{Endpoint: server.URL, HTTPClient: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { |
| 133 | out := r.Clone(r.Context()) |
| 134 | out.Header.Set("Authorization", "Bearer test") |
| 135 | return http.DefaultTransport.RoundTrip(out) |
| 136 | })}}, nil) |
| 137 | if err != nil { |
| 138 | t.Fatal(err) |
| 139 | } |
| 140 | defer session.Close() |
| 141 | result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "notes_create", Arguments: json.RawMessage(raw)}) |
| 142 | if err == nil && !result.IsError { |
| 143 | t.Fatal("MCP accepted an ambiguous team") |
| 144 | } |
| 145 | if f.credentials.calls != 0 || len(f.reached()) != 0 { |
| 146 | t.Fatalf("reached minting (%d) or an app (%v)", f.credentials.calls, f.reached()) |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | // Only one team has routes, as in production today. |
| 151 | func TestSingleRoutedTeamCannotBeCrossed(t *testing.T) { |
| 152 | for _, tc := range []struct { |
| 153 | raw string |
| 154 | teams []string |
| 155 | }{ |
| 156 | {`{"team":"Uk","TEAM":"Xy","title":"x"}`, []string{"Uk"}}, |
| 157 | {`{"team":"Xy","TEAM":"Uk","title":"x"}`, []string{"Uk"}}, |
| 158 | {`{"team":"Xy","TEAM":"Uk","title":"x"}`, []string{"Uk", "Xy"}}, |
| 159 | {`{"team":"Uk","TEAM":"Xy","title":"x"}`, []string{"Uk", "Xy"}}, |
| 160 | } { |
| 161 | t.Run(tc.raw, func(t *testing.T) { |
| 162 | f := newTeamArgFixture(t, "Uk") |
| 163 | if _, err := f.gateway.Call(t.Context(), teamArgPrincipal(tc.teams...), "notes_create", json.RawMessage(tc.raw)); err == nil { |
| 164 | t.Fatal("accepted") |
| 165 | } |
| 166 | if len(f.reached()) != 0 { |
| 167 | t.Fatalf("reached %v", f.reached()) |
| 168 | } |
| 169 | }) |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | // What must keep working: the named team, unrelated fields, and a nested key |
| 174 | // that happens to be spelled TEAM. |
| 175 | func TestUnambiguousCallsRouteToTheNamedTeam(t *testing.T) { |
| 176 | for _, raw := range []string{ |
| 177 | `{"team":"other","title":"x"}`, |
| 178 | `{"team":"other","title":"x","teammate":"y"}`, |
| 179 | `{"team":"other","title":"x","meta":{"TEAM":"acme"}}`, |
| 180 | } { |
| 181 | t.Run(raw, func(t *testing.T) { |
| 182 | f := newTeamArgFixture(t, "acme", "other") |
| 183 | if _, err := f.gateway.Call(t.Context(), teamArgPrincipal("acme", "other"), "notes_create", json.RawMessage(raw)); err != nil { |
| 184 | t.Fatal(err) |
| 185 | } |
| 186 | if got := f.reached(); len(got) != 1 || got[0] != "other" || f.credentials.team != "other" { |
| 187 | t.Fatalf("routed to %v, minted for %q", got, f.credentials.team) |
| 188 | } |
| 189 | if f.bodies[0] != raw { |
| 190 | t.Fatalf("body changed: %s", f.bodies[0]) |
| 191 | } |
| 192 | }) |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | func TestOperationTeamIsTheExactKey(t *testing.T) { |
| 197 | for _, tc := range []struct { |
| 198 | raw, team string |
| 199 | bad bool |
| 200 | }{ |
| 201 | {raw: `{"team":"acme"}`, team: "acme"}, |
| 202 | {raw: `{"title":"x"}`}, |
| 203 | {raw: `{"team":7}`}, |
| 204 | {raw: `{"team":"acme","meta":{"TEAM":"other"}}`, team: "acme"}, |
| 205 | {raw: `{"team":"acme","TEAM":"other"}`, bad: true}, |
| 206 | {raw: `{"Team":"acme"}`, bad: true}, |
| 207 | {raw: `{"team":"acme","team":"other"}`, bad: true}, |
| 208 | {raw: `[]`, bad: true}, |
| 209 | {raw: `null`, bad: true}, |
| 210 | } { |
| 211 | team, err := operationTeam(json.RawMessage(tc.raw)) |
| 212 | if (err != nil) != tc.bad || team != tc.team { |
| 213 | t.Errorf("%s: team %q, err %v", tc.raw, team, err) |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | // The scheduler's response check reads the team the same way. |
| 219 | func TestScheduleGuardRefusesAnAmbiguousTeam(t *testing.T) { |
| 220 | r, err := NewRegistry() |
| 221 | if err != nil { |
| 222 | t.Fatal(err) |
| 223 | } |
| 224 | err = r.ScheduleResponseGuard(t.Context(), teamArgPrincipal("acme"), "calls_schedule", json.RawMessage(`{"team":"acme","TEAM":"other"}`), map[string]any{}) |
| 225 | if f := SafeFailure(err); f.Code != "unavailable" || !strings.Contains(f.Message, "provenance") { |
| 226 | t.Fatalf("got %v", err) |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | // Invoke holds the same line on its own, whatever reaches it. |
| 231 | func TestInvokeRefusesAnAmbiguousTeam(t *testing.T) { |
| 232 | f := newTeamArgFixture(t, "acme", "other") |
| 233 | invoke := f.gateway.operations["notes_create"].op.Invoke |
| 234 | _, err := invoke(t.Context(), teamArgPrincipal("acme", "other"), json.RawMessage(`{"team":"acme","TEAM":"other","title":"x"}`)) |
| 235 | if err == nil || SafeFailure(err).Code != "invalid" || f.credentials.calls != 0 || len(f.reached()) != 0 { |
| 236 | t.Fatalf("got %v, minted %d, reached %v", err, f.credentials.calls, f.reached()) |
| 237 | } |
| 238 | } |
| 239 | |