|
| 1 | +package ghmcp |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/github/github-mcp-server/internal/oauth" |
| 9 | + "github.com/github/github-mcp-server/pkg/inventory" |
| 10 | + "github.com/google/jsonschema-go/jsonschema" |
| 11 | + "github.com/modelcontextprotocol/go-sdk/jsonrpc" |
| 12 | + "github.com/modelcontextprotocol/go-sdk/mcp" |
| 13 | + "github.com/stretchr/testify/assert" |
| 14 | + "github.com/stretchr/testify/require" |
| 15 | +) |
| 16 | + |
| 17 | +type oauthProbeOutput struct { |
| 18 | + Status string `json:"status"` |
| 19 | +} |
| 20 | + |
| 21 | +func oauthRegisteredSession( |
| 22 | + t *testing.T, |
| 23 | + typed bool, |
| 24 | + fake oauthAuthenticator, |
| 25 | + protocol string, |
| 26 | + options *mcp.ClientOptions, |
| 27 | + toolCalls *int, |
| 28 | + captures ...chan json.RawMessage, |
| 29 | +) *mcp.ClientSession { |
| 30 | + t.Helper() |
| 31 | + server := mcp.NewServer(&mcp.Implementation{Name: "oauth-test", Version: "test"}, nil) |
| 32 | + middleware := createOAuthToolMiddleware(fake, discardLogger()) |
| 33 | + if typed { |
| 34 | + tool := inventory.NewServerToolWithContextHandler( |
| 35 | + mcp.Tool{Name: probeToolName}, |
| 36 | + inventory.ToolsetMetadata{ID: "test"}, |
| 37 | + func(context.Context, *mcp.CallToolRequest, struct{}) (*mcp.CallToolResult, oauthProbeOutput, error) { |
| 38 | + (*toolCalls)++ |
| 39 | + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "tool-ran"}}}, |
| 40 | + oauthProbeOutput{Status: "tool-ran"}, nil |
| 41 | + }, |
| 42 | + ) |
| 43 | + tool.RegisterFunc(server, nil, middleware) |
| 44 | + } else { |
| 45 | + server.AddTool(&mcp.Tool{Name: probeToolName, InputSchema: &jsonschema.Schema{Type: "object"}}, |
| 46 | + middleware(func(context.Context, *mcp.CallToolRequest) (*mcp.CallToolResult, error) { |
| 47 | + (*toolCalls)++ |
| 48 | + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "tool-ran"}}}, nil |
| 49 | + })) |
| 50 | + } |
| 51 | + return connectOAuthRegisteredServer(t, server, protocol, options, captures...) |
| 52 | +} |
| 53 | + |
| 54 | +func connectOAuthRegisteredServer(t *testing.T, server *mcp.Server, protocol string, options *mcp.ClientOptions, captures ...chan json.RawMessage) *mcp.ClientSession { |
| 55 | + t.Helper() |
| 56 | + st, ct := mcp.NewInMemoryTransports() |
| 57 | + ss, err := server.Connect(context.Background(), st, nil) |
| 58 | + require.NoError(t, err) |
| 59 | + t.Cleanup(func() { _ = ss.Close() }) |
| 60 | + client := mcp.NewClient(&mcp.Implementation{Name: "oauth-client", Version: "test"}, options) |
| 61 | + var transport mcp.Transport = ct |
| 62 | + if len(captures) > 0 { |
| 63 | + transport = oauthCaptureTransport{Transport: ct, responses: captures[0]} |
| 64 | + } |
| 65 | + cs, err := client.Connect(context.Background(), transport, &mcp.ClientSessionOptions{ProtocolVersion: protocol}) |
| 66 | + require.NoError(t, err) |
| 67 | + t.Cleanup(func() { _ = cs.Close() }) |
| 68 | + return cs |
| 69 | +} |
| 70 | + |
| 71 | +type oauthCaptureTransport struct { |
| 72 | + mcp.Transport |
| 73 | + responses chan json.RawMessage |
| 74 | +} |
| 75 | + |
| 76 | +func (t oauthCaptureTransport) Connect(ctx context.Context) (mcp.Connection, error) { |
| 77 | + connection, err := t.Transport.Connect(ctx) |
| 78 | + if err != nil { |
| 79 | + return nil, err |
| 80 | + } |
| 81 | + return oauthCaptureConnection{Connection: connection, responses: t.responses}, nil |
| 82 | +} |
| 83 | + |
| 84 | +type oauthCaptureConnection struct { |
| 85 | + mcp.Connection |
| 86 | + responses chan json.RawMessage |
| 87 | +} |
| 88 | + |
| 89 | +func (c oauthCaptureConnection) Read(ctx context.Context) (jsonrpc.Message, error) { |
| 90 | + message, err := c.Connection.Read(ctx) |
| 91 | + if err == nil { |
| 92 | + if response, ok := message.(*jsonrpc.Response); ok && response.Result != nil { |
| 93 | + c.responses <- append(json.RawMessage(nil), response.Result...) |
| 94 | + } |
| 95 | + } |
| 96 | + return message, err |
| 97 | +} |
| 98 | + |
| 99 | +func oauthPendingAuthenticator() *fakeAuthenticator { |
| 100 | + return &fakeAuthenticator{ |
| 101 | + outcome: &oauth.Outcome{ |
| 102 | + UserAction: &oauth.UserAction{URL: "https://example.com/auth", Message: "Authorize, then retry."}, |
| 103 | + FlowID: "flow-1", |
| 104 | + }, |
| 105 | + tokenAfterAwait: true, |
| 106 | + cancelResult: true, |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +func TestOAuthTypedRegistration(t *testing.T) { |
| 111 | + for _, typed := range []bool{false, true} { |
| 112 | + name := "untyped-control" |
| 113 | + if typed { |
| 114 | + name = "typed" |
| 115 | + } |
| 116 | + t.Run(name, func(t *testing.T) { |
| 117 | + urlCaps := &mcp.ClientCapabilities{Elicitation: &mcp.ElicitationCapabilities{URL: &mcp.URLElicitationCapabilities{}}} |
| 118 | + t.Run("wire-input-required", func(t *testing.T) { |
| 119 | + fake := oauthPendingAuthenticator() |
| 120 | + calls := 0 |
| 121 | + captures := make(chan json.RawMessage, 8) |
| 122 | + session := oauthRegisteredSession(t, typed, fake, "", &mcp.ClientOptions{ |
| 123 | + Capabilities: urlCaps, MultiRoundTrip: &mcp.MultiRoundTripOptions{Disabled: true}, |
| 124 | + }, &calls, captures) |
| 125 | + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: probeToolName}) |
| 126 | + require.NoError(t, err) |
| 127 | + <-captures // initialize |
| 128 | + wire := <-captures |
| 129 | + var fields map[string]json.RawMessage |
| 130 | + require.NoError(t, json.Unmarshal(wire, &fields)) |
| 131 | + assert.JSONEq(t, `"input_required"`, string(fields["resultType"]), "wire: %s", wire) |
| 132 | + assert.True(t, result.NeedsInput()) |
| 133 | + assert.Contains(t, result.InputRequests, oauthElicitIDPrefix+"flow-1") |
| 134 | + assert.Nil(t, result.StructuredContent) |
| 135 | + assert.Zero(t, calls) |
| 136 | + t.Logf("raw tools/call response: %s", wire) |
| 137 | + }) |
| 138 | + for _, action := range []string{"accept", "decline"} { |
| 139 | + t.Run(action, func(t *testing.T) { |
| 140 | + fake := oauthPendingAuthenticator() |
| 141 | + calls, prompts := 0, 0 |
| 142 | + session := oauthRegisteredSession(t, typed, fake, "", &mcp.ClientOptions{ |
| 143 | + Capabilities: urlCaps, |
| 144 | + ElicitationHandler: func(_ context.Context, req *mcp.ElicitRequest) (*mcp.ElicitResult, error) { |
| 145 | + prompts++ |
| 146 | + assert.Equal(t, "url", req.Params.Mode) |
| 147 | + assert.Equal(t, "https://example.com/auth", req.Params.URL) |
| 148 | + return &mcp.ElicitResult{Action: action}, nil |
| 149 | + }, |
| 150 | + }, &calls) |
| 151 | + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: probeToolName}) |
| 152 | + require.NoError(t, err) |
| 153 | + assert.Equal(t, 1, prompts) |
| 154 | + require.Len(t, result.Content, 1) |
| 155 | + assert.False(t, result.NeedsInput()) |
| 156 | + wire, err := json.Marshal(result) |
| 157 | + require.NoError(t, err) |
| 158 | + assert.Contains(t, string(wire), `"resultType":"complete"`) |
| 159 | + if action == "accept" { |
| 160 | + assert.Equal(t, 1, calls) |
| 161 | + assert.Equal(t, 1, fake.awaitCalls) |
| 162 | + assert.Equal(t, "flow-1", fake.lastAwaitFlowID) |
| 163 | + assert.Zero(t, fake.cancelCalls) |
| 164 | + if typed { |
| 165 | + output, err := json.Marshal(result.StructuredContent) |
| 166 | + require.NoError(t, err) |
| 167 | + assert.JSONEq(t, `{"status":"tool-ran"}`, string(output)) |
| 168 | + } |
| 169 | + } else { |
| 170 | + assert.Zero(t, calls) |
| 171 | + assert.Zero(t, fake.awaitCalls) |
| 172 | + assert.Equal(t, 1, fake.cancelCalls) |
| 173 | + assert.Contains(t, result.Content[0].(*mcp.TextContent).Text, "declined") |
| 174 | + assert.Nil(t, result.StructuredContent) |
| 175 | + } |
| 176 | + }) |
| 177 | + } |
| 178 | + for _, protocol := range []string{"", "2025-11-25"} { |
| 179 | + t.Run("manual-fallback/"+protocol, func(t *testing.T) { |
| 180 | + fake := oauthPendingAuthenticator() |
| 181 | + calls := 0 |
| 182 | + session := oauthRegisteredSession(t, typed, fake, protocol, &mcp.ClientOptions{ |
| 183 | + Capabilities: &mcp.ClientCapabilities{}, |
| 184 | + }, &calls) |
| 185 | + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: probeToolName}) |
| 186 | + require.NoError(t, err) |
| 187 | + require.Len(t, result.Content, 1) |
| 188 | + assert.Equal(t, "Authorize, then retry.", result.Content[0].(*mcp.TextContent).Text) |
| 189 | + assert.False(t, result.NeedsInput()) |
| 190 | + assert.Nil(t, result.StructuredContent) |
| 191 | + assert.Zero(t, calls) |
| 192 | + assert.Zero(t, fake.awaitCalls) |
| 193 | + assert.Zero(t, fake.cancelCalls) |
| 194 | + assert.Equal(t, protocol != "", fake.lastPrompter != nil) |
| 195 | + }) |
| 196 | + } |
| 197 | + }) |
| 198 | + } |
| 199 | +} |
| 200 | + |
| 201 | +type legacyPromptAuthenticator struct { |
| 202 | + fakeAuthenticator |
| 203 | +} |
| 204 | + |
| 205 | +func (f *legacyPromptAuthenticator) Authenticate(ctx context.Context, prompter oauth.Prompter) (*oauth.Outcome, error) { |
| 206 | + f.authCalls++ |
| 207 | + f.lastPrompter = prompter |
| 208 | + if err := prompter.PromptURL(ctx, oauth.Prompt{URL: "https://example.com/auth", Message: "Authorize"}); err != nil { |
| 209 | + return nil, err |
| 210 | + } |
| 211 | + f.hasToken = true |
| 212 | + return nil, nil |
| 213 | +} |
| 214 | + |
| 215 | +func TestOAuthTypedRegistrationLegacyElicitation(t *testing.T) { |
| 216 | + for _, typed := range []bool{false, true} { |
| 217 | + t.Run(map[bool]string{false: "untyped-control", true: "typed"}[typed], func(t *testing.T) { |
| 218 | + fake := &legacyPromptAuthenticator{} |
| 219 | + calls, prompts := 0, 0 |
| 220 | + session := oauthRegisteredSession(t, typed, fake, "2025-11-25", &mcp.ClientOptions{ |
| 221 | + Capabilities: &mcp.ClientCapabilities{Elicitation: &mcp.ElicitationCapabilities{URL: &mcp.URLElicitationCapabilities{}}}, |
| 222 | + ElicitationHandler: func(context.Context, *mcp.ElicitRequest) (*mcp.ElicitResult, error) { |
| 223 | + prompts++ |
| 224 | + return &mcp.ElicitResult{Action: "accept"}, nil |
| 225 | + }, |
| 226 | + }, &calls) |
| 227 | + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: probeToolName}) |
| 228 | + require.NoError(t, err) |
| 229 | + assert.Equal(t, 1, prompts) |
| 230 | + assert.Equal(t, 1, calls) |
| 231 | + assert.Equal(t, 1, fake.authCalls) |
| 232 | + assert.False(t, result.NeedsInput()) |
| 233 | + assert.Nil(t, result.StructuredContent) |
| 234 | + require.Len(t, result.Content, 1) |
| 235 | + assert.Equal(t, "tool-ran", result.Content[0].(*mcp.TextContent).Text) |
| 236 | + }) |
| 237 | + } |
| 238 | +} |
| 239 | + |
| 240 | +func TestOAuthTypedRegistrationGuardsInvalidArguments(t *testing.T) { |
| 241 | + type input struct { |
| 242 | + Mode string `json:"mode"` |
| 243 | + } |
| 244 | + for _, raw := range []string{ |
| 245 | + `{}`, `{"mode":"invalid"}`, `{"mode":42}`, `[]`, `null`, `"not an object"`, |
| 246 | + } { |
| 247 | + t.Run(raw, func(t *testing.T) { |
| 248 | + arguments := json.RawMessage(raw) |
| 249 | + fake := oauthPendingAuthenticator() |
| 250 | + handlerCalls, preflightCalls, normalizerCalls := 0, 0, 0 |
| 251 | + tool := inventory.NewServerToolWithContextHandlerAndSchemaOptions( |
| 252 | + mcp.Tool{ |
| 253 | + Name: probeToolName, |
| 254 | + InputSchema: &jsonschema.Schema{ |
| 255 | + Type: "object", |
| 256 | + Properties: map[string]*jsonschema.Schema{"mode": {Type: "string", Enum: []any{"valid"}}}, |
| 257 | + Required: []string{"mode"}, |
| 258 | + }, |
| 259 | + }, |
| 260 | + inventory.ToolsetMetadata{ID: "test"}, |
| 261 | + func(context.Context, *mcp.CallToolRequest, input) (*mcp.CallToolResult, oauthProbeOutput, error) { |
| 262 | + handlerCalls++ |
| 263 | + return nil, oauthProbeOutput{Status: "unexpected"}, nil |
| 264 | + }, |
| 265 | + inventory.TypedSchemaOptions{ |
| 266 | + Preflight: func(ctx context.Context, _ *mcp.CallToolRequest) (context.Context, *mcp.CallToolResult, error) { |
| 267 | + preflightCalls++ |
| 268 | + return ctx, nil, nil |
| 269 | + }, |
| 270 | + }, |
| 271 | + func(raw json.RawMessage) (json.RawMessage, error) { |
| 272 | + normalizerCalls++ |
| 273 | + return raw, nil |
| 274 | + }, |
| 275 | + ) |
| 276 | + server := mcp.NewServer(&mcp.Implementation{Name: "test", Version: "test"}, nil) |
| 277 | + tool.RegisterFunc(server, nil, createOAuthToolMiddleware(fake, discardLogger())) |
| 278 | + session := connectOAuthRegisteredServer(t, server, "", &mcp.ClientOptions{ |
| 279 | + Capabilities: &mcp.ClientCapabilities{Elicitation: &mcp.ElicitationCapabilities{URL: &mcp.URLElicitationCapabilities{}}}, |
| 280 | + MultiRoundTrip: &mcp.MultiRoundTripOptions{Disabled: true}, |
| 281 | + }) |
| 282 | + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: probeToolName, Arguments: arguments}) |
| 283 | + require.NoError(t, err) |
| 284 | + assert.True(t, result.NeedsInput(), "auth must win over invalid arguments") |
| 285 | + assert.Zero(t, handlerCalls) |
| 286 | + assert.Zero(t, preflightCalls) |
| 287 | + assert.Zero(t, normalizerCalls) |
| 288 | + result, err = session.CallTool(context.Background(), &mcp.CallToolParams{ |
| 289 | + Name: probeToolName, Arguments: arguments, |
| 290 | + InputResponses: mcp.InputResponseMap{oauthElicitIDPrefix + "flow-1": &mcp.ElicitResult{Action: "accept"}}, |
| 291 | + }) |
| 292 | + require.NoError(t, err) |
| 293 | + assert.True(t, result.IsError, "authorized retries must enforce original input schema") |
| 294 | + assert.False(t, result.NeedsInput()) |
| 295 | + assert.Zero(t, handlerCalls) |
| 296 | + assert.Equal(t, 1, preflightCalls) |
| 297 | + assert.Equal(t, 1, normalizerCalls) |
| 298 | + assert.Equal(t, 1, fake.awaitCalls) |
| 299 | + list, err := session.ListTools(context.Background(), nil) |
| 300 | + require.NoError(t, err) |
| 301 | + require.Len(t, list.Tools, 1) |
| 302 | + encoded, err := json.Marshal(list.Tools[0].InputSchema) |
| 303 | + require.NoError(t, err) |
| 304 | + assert.Contains(t, string(encoded), `"required":["mode"]`) |
| 305 | + assert.Contains(t, string(encoded), `"enum":["valid"]`) |
| 306 | + }) |
| 307 | + } |
| 308 | +} |
0 commit comments