| 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 | |
| 13 | "github.com/modelcontextprotocol/go-sdk/mcp" |
| 14 | ) |
| 15 | |
| 16 | func testRegistry(t *testing.T, count *atomic.Int32) *Registry { |
| 17 | t.Helper() |
| 18 | r, err := NewRegistry(Operation{Name: "notes_create", Description: "Create a note", Scope: "notes:write", Input: json.RawMessage(`{"type":"object","properties":{"team":{"type":"string"},"title":{"type":"string","minLength":1}},"required":["team","title"],"additionalProperties":false}`), Output: json.RawMessage(`{"type":"object","properties":{"id":{"type":"integer"}},"required":["id"],"additionalProperties":false}`), Invoke: func(context.Context, Principal, json.RawMessage) (any, error) { |
| 19 | count.Add(1) |
| 20 | return map[string]int{"id": 42}, nil |
| 21 | }}) |
| 22 | if err != nil { |
| 23 | t.Fatal(err) |
| 24 | } |
| 25 | return r |
| 26 | } |
| 27 | func principal() Principal { |
| 28 | return Principal{Subject: "person", Client: "client", Grant: "grant", Teams: []string{"acme"}, Scopes: []string{"notes:write"}} |
| 29 | } |
| 30 | func TestAuthorizationAndValidationPrecedeMutation(t *testing.T) { |
| 31 | var count atomic.Int32 |
| 32 | r := testRegistry(t, &count) |
| 33 | cases := []struct { |
| 34 | name string |
| 35 | p Principal |
| 36 | raw string |
| 37 | code string |
| 38 | }{ |
| 39 | {"anonymous", Principal{}, `{"team":"acme","title":"x"}`, "unauthenticated"}, |
| 40 | {"other team", principal(), `{"team":"elsewhere","title":"x"}`, "forbidden"}, |
| 41 | {"read only", Principal{Subject: "person", Teams: []string{"acme"}, Scopes: []string{"notes:read"}}, `{"team":"acme","title":"x"}`, "forbidden"}, |
| 42 | {"unknown input", principal(), `{"team":"acme","title":"x","subject":"someone"}`, "invalid"}, |
| 43 | {"duplicate team", principal(), `{"team":"elsewhere","team":"acme","title":"x"}`, "invalid"}, |
| 44 | {"empty title", principal(), `{"team":"acme","title":""}`, "invalid"}, |
| 45 | } |
| 46 | for _, tc := range cases { |
| 47 | t.Run(tc.name, func(t *testing.T) { |
| 48 | _, err := r.Call(context.Background(), tc.p, "notes_create", []byte(tc.raw)) |
| 49 | if err == nil || SafeFailure(err).Code != tc.code { |
| 50 | t.Fatalf("got %v", err) |
| 51 | } |
| 52 | if count.Load() != 0 { |
| 53 | t.Fatal("unauthorized mutation") |
| 54 | } |
| 55 | }) |
| 56 | } |
| 57 | _, err := r.Call(context.Background(), principal(), "notes_create", []byte(`{"team":"acme","title":"x"}`)) |
| 58 | if err != nil || count.Load() != 1 { |
| 59 | t.Fatalf("valid call: %v, %d", err, count.Load()) |
| 60 | } |
| 61 | } |
| 62 | func TestHTTPAndMCPUseSameOperationAndRecheckRevocation(t *testing.T) { |
| 63 | var count atomic.Int32 |
| 64 | var revoked atomic.Bool |
| 65 | r := testRegistry(t, &count) |
| 66 | verify := VerifyFunc(func(_ context.Context, token string) (Principal, error) { |
| 67 | if token != "test" || revoked.Load() { |
| 68 | return Principal{}, Fail("unauthenticated", "Connection revoked.") |
| 69 | } |
| 70 | return principal(), nil |
| 71 | }) |
| 72 | mux := http.NewServeMux() |
| 73 | mux.Handle("/api/", r.HTTP(verify)) |
| 74 | mux.Handle("/mcp", r.MCP(verify)) |
| 75 | server := httptest.NewServer(mux) |
| 76 | defer server.Close() |
| 77 | doHTTP := func() int { |
| 78 | req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/notes_create", strings.NewReader(`{"team":"acme","title":"x"}`)) |
| 79 | req.Header.Set("Authorization", "Bearer test") |
| 80 | req.Header.Set("Content-Type", "application/json") |
| 81 | resp, err := server.Client().Do(req) |
| 82 | if err != nil { |
| 83 | t.Fatal(err) |
| 84 | } |
| 85 | defer resp.Body.Close() |
| 86 | io.Copy(io.Discard, resp.Body) |
| 87 | return resp.StatusCode |
| 88 | } |
| 89 | if code := doHTTP(); code != 200 { |
| 90 | t.Fatalf("HTTP %d", code) |
| 91 | } |
| 92 | client := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "1"}, nil) |
| 93 | session, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{Endpoint: server.URL + "/mcp", HTTPClient: &http.Client{Transport: headerTransport{base: http.DefaultTransport}}}, nil) |
| 94 | if err != nil { |
| 95 | t.Fatal(err) |
| 96 | } |
| 97 | defer session.Close() |
| 98 | tools, err := session.ListTools(context.Background(), nil) |
| 99 | if err != nil || len(tools.Tools) != 2 { |
| 100 | t.Fatalf("tools %v %v", tools, err) |
| 101 | } |
| 102 | result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: "notes_create", Arguments: map[string]any{"team": "acme", "title": "x"}}) |
| 103 | if err != nil || result.IsError { |
| 104 | t.Fatalf("MCP call: %v %v", result, err) |
| 105 | } |
| 106 | if count.Load() != 2 { |
| 107 | t.Fatalf("calls %d", count.Load()) |
| 108 | } |
| 109 | revoked.Store(true) |
| 110 | if code := doHTTP(); code != 401 { |
| 111 | t.Fatalf("revoked HTTP %d", code) |
| 112 | } |
| 113 | _, err = session.CallTool(context.Background(), &mcp.CallToolParams{Name: "notes_create", Arguments: map[string]any{"team": "acme", "title": "x"}}) |
| 114 | if err == nil { |
| 115 | t.Fatal("revoked MCP accepted") |
| 116 | } |
| 117 | if count.Load() != 2 { |
| 118 | t.Fatal("revoked call mutated") |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | type headerTransport struct{ base http.RoundTripper } |
| 123 | |
| 124 | func (h headerTransport) RoundTrip(req *http.Request) (*http.Response, error) { |
| 125 | r := req.Clone(req.Context()) |
| 126 | r.Header.Set("Authorization", "Bearer test") |
| 127 | return h.base.RoundTrip(r) |
| 128 | } |
| 129 | func TestUniqueJSON(t *testing.T) { |
| 130 | for _, raw := range []string{`{"x":{"a":1,"a":2}}`, `{"x":1} {}`, `[1,`, strings.Repeat("[", 66) + "0" + strings.Repeat("]", 66)} { |
| 131 | if UniqueJSON([]byte(raw)) == nil { |
| 132 | t.Fatalf("accepted %s", raw) |
| 133 | } |
| 134 | } |
| 135 | if err := UniqueJSON([]byte(`{"x":[1,{"a":2}]}`)); err != nil { |
| 136 | t.Fatal(err) |
| 137 | } |
| 138 | } |
| 139 | |