| 1 | package agentaccess |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "net/http/httptest" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | func TestPublicMCPOriginGuardBeforeVerification(t *testing.T) { |
| 11 | registry, err := NewRegistry() |
| 12 | if err != nil { |
| 13 | t.Fatal(err) |
| 14 | } |
| 15 | calls := 0 |
| 16 | h, err := registry.MCPAtOrigin(VerifyFunc(func(context.Context, string) (Principal, error) { calls++; return principal(), nil }), "https://connect.example.test") |
| 17 | if err != nil { |
| 18 | t.Fatal(err) |
| 19 | } |
| 20 | for _, tc := range []struct { |
| 21 | host, origin string |
| 22 | duplicate bool |
| 23 | status int |
| 24 | }{{"evil.test", "", false, 403}, {"connect.example.test", "https://evil.test", false, 403}, {"connect.example.test", "null", false, 403}, {"connect.example.test", "https://connect.example.test", true, 403}, {"connect.example.test", "", false, 200}, {"connect.example.test", "https://connect.example.test", false, 200}} { |
| 25 | r := httptest.NewRequest("POST", "https://"+tc.host+"/mcp", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}`)) |
| 26 | r.Header.Set("Content-Type", "application/json") |
| 27 | r.Header.Set("Accept", "application/json, text/event-stream") |
| 28 | r.Header.Set("Authorization", "Bearer test") |
| 29 | if tc.origin != "" { |
| 30 | r.Header.Add("Origin", tc.origin) |
| 31 | } |
| 32 | if tc.duplicate { |
| 33 | r.Header.Add("Origin", tc.origin) |
| 34 | } |
| 35 | before := calls |
| 36 | w := httptest.NewRecorder() |
| 37 | h.ServeHTTP(w, r) |
| 38 | if w.Code != tc.status { |
| 39 | t.Fatal(tc, w.Code, w.Body.String()) |
| 40 | } |
| 41 | if tc.status == 403 && calls != before { |
| 42 | t.Fatal("untrusted origin reached verifier") |
| 43 | } |
| 44 | } |
| 45 | if calls != 2 { |
| 46 | t.Fatal("valid requests failed", calls) |
| 47 | } |
| 48 | } |
| 49 | |