Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/auth/extauth/oidc_login_test.go

raw symbols SCIP
1 // Copyright 2026 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by the license
3 // that can be found in the LICENSE file.
4
5 package extauth
6
7 import (
8 "context"
9 "fmt"
10 "net/http"
11 "net/url"
12 "strings"
13 "testing"
14
15 "github.com/modelcontextprotocol/go-sdk/auth"
16 "github.com/modelcontextprotocol/go-sdk/internal/oauthtest"
17 "github.com/modelcontextprotocol/go-sdk/oauthex"
18 "golang.org/x/oauth2"
19 )
20
21 const testRedirectURL = "http://localhost:18927/callback"
22
23 func validOIDCLoginConfig(issuerURL string) *OIDCLoginConfig {
24 return &OIDCLoginConfig{
25 IssuerURL: issuerURL,
26 Credentials: &oauthex.ClientCredentials{
27 ClientID: "test-client",
28 ClientSecretAuth: &oauthex.ClientSecretAuth{
29 ClientSecret: "test-secret",
30 },
31 },
32 RedirectURL: testRedirectURL,
33 Scopes: []string{"openid", "profile", "email"},
34 }
35 }
36
37 func TestPerformOIDCLogin(t *testing.T) {
38 idpServer := oauthtest.NewFakeIdPServer(oauthtest.IdPConfig{
39 PreregisteredClients: map[string]oauthtest.ClientInfo{
40 "test-client": {
41 Secret: "test-secret",
42 RedirectURIs: []string{testRedirectURL},
43 },
44 },
45 })
46 idpServer.Start(t)
47
48 config := validOIDCLoginConfig(idpServer.URL())
49
50 // fetchAuthCode visits the authorization URL on the fake IdP server,
51 // follows the redirect, and extracts the authorization code and state.
52 fetchAuthCode := func(ctx context.Context, args *auth.AuthorizationArgs) (*auth.AuthorizationResult, error) {
53 client := &http.Client{
54 CheckRedirect: func(req *http.Request, via []*http.Request) error {
55 return http.ErrUseLastResponse
56 },
57 }
58 resp, err := client.Get(args.URL)
59 if err != nil {
60 return nil, fmt.Errorf("failed to visit auth URL: %w", err)
61 }
62 defer resp.Body.Close()
63 if resp.StatusCode != http.StatusFound {
64 return nil, fmt.Errorf("expected redirect, got status %d", resp.StatusCode)
65 }
66 loc, err := resp.Location()
67 if err != nil {
68 return nil, fmt.Errorf("missing Location header: %w", err)
69 }
70 return &auth.AuthorizationResult{
71 Code: loc.Query().Get("code"),
72 State: loc.Query().Get("state"),
73 }, nil
74 }
75
76 verifyOIDCToken := func(token *oauth2.Token) error {
77 idToken, ok := token.Extra("id_token").(string)
78 if !ok || idToken == "" {
79 return fmt.Errorf("id_token is missing or empty")
80 }
81 parts := strings.Split(idToken, ".")
82 if len(parts) != 3 {
83 return fmt.Errorf("id_token is not a JWT (expected 3 parts, got %d)", len(parts))
84 }
85 if token.AccessToken == "" {
86 return fmt.Errorf("access token is empty")
87 }
88 if token.TokenType != "Bearer" {
89 return fmt.Errorf("token type = %q, want %q", token.TokenType, "Bearer")
90 }
91 return nil
92 }
93
94 t.Run("successful flow", func(t *testing.T) {
95 token, err := PerformOIDCLogin(context.Background(), config, fetchAuthCode)
96 if err != nil {
97 t.Fatalf("PerformOIDCLogin() error = %v", err)
98 }
99 if err := verifyOIDCToken(token); err != nil {
100 t.Errorf("invalid token returned: %v", err)
101 }
102 })
103
104 t.Run("with login_hint", func(t *testing.T) {
105 configWithHint := *config
106 configWithHint.LoginHint = "[email protected]"
107
108 token, err := PerformOIDCLogin(context.Background(), &configWithHint,
109 func(ctx context.Context, args *auth.AuthorizationArgs) (*auth.AuthorizationResult, error) {
110 u, err := url.Parse(args.URL)
111 if err != nil {
112 return nil, fmt.Errorf("invalid authURL: %w", err)
113 }
114 if got := u.Query().Get("login_hint"); got != "[email protected]" {
115 t.Errorf("login_hint = %q, want %q", got, "[email protected]")
116 }
117 return fetchAuthCode(ctx, args)
118 })
119 if err != nil {
120 t.Fatalf("PerformOIDCLogin() error = %v", err)
121 }
122 if err := verifyOIDCToken(token); err != nil {
123 t.Errorf("invalid token returned: %v", err)
124 }
125 })
126
127 t.Run("without login_hint", func(t *testing.T) {
128 token, err := PerformOIDCLogin(context.Background(), config,
129 func(ctx context.Context, args *auth.AuthorizationArgs) (*auth.AuthorizationResult, error) {
130 u, err := url.Parse(args.URL)
131 if err != nil {
132 return nil, fmt.Errorf("invalid authURL: %w", err)
133 }
134 if u.Query().Has("login_hint") {
135 t.Errorf("login_hint should be absent, got %q", u.Query().Get("login_hint"))
136 }
137 return fetchAuthCode(ctx, args)
138 })
139 if err != nil {
140 t.Fatalf("PerformOIDCLogin() error = %v", err)
141 }
142 if err := verifyOIDCToken(token); err != nil {
143 t.Errorf("invalid token returned: %v", err)
144 }
145 })
146
147 t.Run("state mismatch", func(t *testing.T) {
148 _, err := PerformOIDCLogin(context.Background(), config,
149 func(ctx context.Context, args *auth.AuthorizationArgs) (*auth.AuthorizationResult, error) {
150 return &auth.AuthorizationResult{
151 Code: "mock-auth-code",
152 State: "wrong-state",
153 }, nil
154 })
155
156 if err == nil {
157 t.Fatal("expected error for state mismatch, got nil")
158 }
159 if !strings.Contains(err.Error(), "state mismatch") {
160 t.Errorf("error = %v, want error containing %q", err, "state mismatch")
161 }
162 })
163
164 t.Run("fetcher error", func(t *testing.T) {
165 _, err := PerformOIDCLogin(context.Background(), config,
166 func(ctx context.Context, args *auth.AuthorizationArgs) (*auth.AuthorizationResult, error) {
167 return nil, fmt.Errorf("user cancelled")
168 })
169
170 if err == nil {
171 t.Fatal("expected error, got nil")
172 }
173 if !strings.Contains(err.Error(), "user cancelled") {
174 t.Errorf("error = %v, want error containing %q", err, "user cancelled")
175 }
176 })
177 }
178
179 func TestPerformOIDCLogin_ValidationErrors(t *testing.T) {
180 const nonexistentIssuer = "https://idp.example.com"
181
182 noopFetcher := func(ctx context.Context, args *auth.AuthorizationArgs) (*auth.AuthorizationResult, error) {
183 return nil, fmt.Errorf("should not be called")
184 }
185
186 tests := []struct {
187 name string
188 config *OIDCLoginConfig
189 fetcher auth.AuthorizationCodeFetcher
190 wantErr string
191 }{
192 {
193 name: "nil config",
194 config: nil,
195 fetcher: noopFetcher,
196 wantErr: "config is required",
197 },
198 {
199 name: "nil fetcher",
200 config: validOIDCLoginConfig(nonexistentIssuer),
201 fetcher: nil,
202 wantErr: "authCodeFetcher is required",
203 },
204 {
205 name: "missing IssuerURL",
206 config: validOIDCLoginConfig(""),
207 fetcher: noopFetcher,
208 wantErr: "IssuerURL is required",
209 },
210 {
211 name: "missing ClientID",
212 config: func() *OIDCLoginConfig {
213 c := validOIDCLoginConfig(nonexistentIssuer)
214 c.Credentials = &oauthex.ClientCredentials{}
215 return c
216 }(),
217 fetcher: noopFetcher,
218 wantErr: "ClientID is required",
219 },
220 {
221 name: "missing RedirectURL",
222 config: func() *OIDCLoginConfig {
223 c := validOIDCLoginConfig(nonexistentIssuer)
224 c.RedirectURL = ""
225 return c
226 }(),
227 fetcher: noopFetcher,
228 wantErr: "RedirectURL is required",
229 },
230 {
231 name: "missing Scopes",
232 config: func() *OIDCLoginConfig {
233 c := validOIDCLoginConfig(nonexistentIssuer)
234 c.Scopes = nil
235 return c
236 }(),
237 fetcher: noopFetcher,
238 wantErr: "at least one scope is required",
239 },
240 {
241 name: "missing openid scope",
242 config: func() *OIDCLoginConfig {
243 c := validOIDCLoginConfig(nonexistentIssuer)
244 c.Scopes = []string{"profile", "email"}
245 return c
246 }(),
247 fetcher: noopFetcher,
248 wantErr: "openid",
249 },
250 }
251
252 for _, tt := range tests {
253 t.Run(tt.name, func(t *testing.T) {
254 _, err := PerformOIDCLogin(context.Background(), tt.config, tt.fetcher)
255 if err == nil {
256 t.Fatalf("expected error containing %q, got nil", tt.wantErr)
257 }
258 if !strings.Contains(err.Error(), tt.wantErr) {
259 t.Errorf("error = %v, want error containing %q", err, tt.wantErr)
260 }
261 })
262 }
263 }