| 1 | package mcpdiag |
| 2 | |
| 3 | import "testing" |
| 4 | |
| 5 | func TestDiagnoseAuthRequiredFromFailure(t *testing.T) { |
| 6 | got := DiagnoseAuth("http", "failed", "connect: 401 unauthorized", "https://mcp.example.com/mcp", false) |
| 7 | if got.Status != AuthRequired { |
| 8 | t.Fatalf("status = %q, want %q", got.Status, AuthRequired) |
| 9 | } |
| 10 | if got.URL != "https://mcp.example.com/mcp" { |
| 11 | t.Fatalf("url = %q", got.URL) |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | func TestDiagnoseAuthPossibleForDeferredRemoteWithoutAuthConfig(t *testing.T) { |
| 16 | got := DiagnoseAuth("sse", "deferred", "", "https://mcp.example.com/sse", false) |
| 17 | if got.Status != AuthPossible { |
| 18 | t.Fatalf("status = %q, want %q", got.Status, AuthPossible) |
| 19 | } |
| 20 | if got.URL == "" { |
| 21 | t.Fatal("possible remote auth should keep the server URL") |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | func TestDiagnoseAuthSkipsRemoteWithStaticAuth(t *testing.T) { |
| 26 | got := DiagnoseAuth("http", "deferred", "", "https://mcp.example.com/mcp", true) |
| 27 | if got.Status != AuthNone { |
| 28 | t.Fatalf("status = %q, want %q", got.Status, AuthNone) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | func TestHasAuthConfig(t *testing.T) { |
| 33 | if !HasAuthConfig(map[string]string{"Authorization": "Bearer ${TOKEN}"}, nil, "") { |
| 34 | t.Fatal("authorization header should count as auth config") |
| 35 | } |
| 36 | if !HasAuthConfig(nil, map[string]string{"DIDA_TOKEN": "${DIDA_TOKEN}"}, "") { |
| 37 | t.Fatal("auth-like env key should count as auth config") |
| 38 | } |
| 39 | if HasAuthConfig(nil, map[string]string{"DEBUG": "1"}, "https://mcp.example.com/mcp") { |
| 40 | t.Fatal("unrelated env should not count as auth config") |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | func TestClearAuthConfigRemovesOnlyAuthMaterial(t *testing.T) { |
| 45 | headers, env, rawURL, changed := ClearAuthConfig( |
| 46 | map[string]string{ |
| 47 | "Authorization": "Bearer ${TOKEN}", |
| 48 | "X-Org": "team", |
| 49 | }, |
| 50 | map[string]string{ |
| 51 | "DIDA_TOKEN": "${DIDA_TOKEN}", |
| 52 | "DEBUG": "1", |
| 53 | }, |
| 54 | "https://mcp.example.com/mcp?access_token=abc&workspace=main", |
| 55 | ) |
| 56 | if !changed { |
| 57 | t.Fatal("ClearAuthConfig should report changed") |
| 58 | } |
| 59 | if _, ok := headers["Authorization"]; ok { |
| 60 | t.Fatalf("auth header should be removed: %v", headers) |
| 61 | } |
| 62 | if headers["X-Org"] != "team" { |
| 63 | t.Fatalf("ordinary header should be preserved: %v", headers) |
| 64 | } |
| 65 | if _, ok := env["DIDA_TOKEN"]; ok { |
| 66 | t.Fatalf("auth env should be removed: %v", env) |
| 67 | } |
| 68 | if env["DEBUG"] != "1" { |
| 69 | t.Fatalf("ordinary env should be preserved: %v", env) |
| 70 | } |
| 71 | if rawURL != "https://mcp.example.com/mcp?workspace=main" { |
| 72 | t.Fatalf("url = %q", rawURL) |
| 73 | } |
| 74 | } |
| 75 |