Repository navigation
Expand file tree
/
Copy pathauth.rs
More file actions
8164 lines (7295 loc) · 306 KB
/
Copy pathauth.rs
File metadata and controls
8164 lines (7295 loc) · 306 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
collections::HashMap,
future::Future,
net::{IpAddr, Ipv4Addr, Ipv6Addr},
pin::Pin,
sync::Arc,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use async_trait::async_trait;
use futures::StreamExt;
use oauth2::{
AsyncHttpClient, AuthType, AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken,
EmptyExtraTokenFields, ExtraTokenFields, HttpRequest, HttpResponse, PkceCodeChallenge,
PkceCodeVerifier, RedirectUrl, RefreshToken, RequestTokenError, Scope, StandardTokenResponse,
TokenResponse, TokenUrl,
basic::{BasicErrorResponseType, BasicTokenType},
};
use reqwest::{
Client as ReqwestClient, IntoUrl, StatusCode, Url,
header::{AUTHORIZATION, CONTENT_TYPE, LOCATION, WWW_AUTHENTICATE},
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
use tokio::sync::{Mutex, RwLock};
use tracing::{debug, warn};
use crate::transport::common::http_header::HEADER_MCP_PROTOCOL_VERSION;
const DEFAULT_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES: usize = 1024 * 1024;
const MAX_OAUTH_DISCOVERY_REDIRECTS: usize = 10;
const CLOUD_METADATA_HOSTS: &[&str] = &[
"metadata",
"metadata.google.internal",
"metadata.azure.internal",
];
/// Redirect handling requested for an outbound OAuth HTTP operation.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum OAuthHttpRedirectPolicy {
/// Follow redirects using the client's normal limits.
#[default]
Follow,
/// Return the redirect response without following its location.
Stop,
}
/// A complete outbound HTTP operation requested by the OAuth implementation.
#[non_exhaustive]
pub struct OAuthHttpRequest {
/// HTTP request with an absolute URI and buffered body.
pub request: HttpRequest,
/// Redirect behavior required by the OAuth operation.
pub redirect_policy: OAuthHttpRedirectPolicy,
/// Suggested maximum duration for the operation, or no SDK-specified timeout.
/// Implementations with their own timeout policy may retain it instead.
pub timeout: Option<Duration>,
}
impl OAuthHttpRequest {
fn new(request: HttpRequest, redirect_policy: OAuthHttpRedirectPolicy) -> Self {
Self {
request,
redirect_policy,
timeout: Some(DEFAULT_HTTP_TIMEOUT),
}
}
}
/// Type-erased error returned by an [`OAuthHttpClient`].
pub type OAuthHttpClientError = Box<dyn std::error::Error + Send + Sync>;
#[derive(Debug, Error)]
enum OAuthHttpError {
#[error("OAuth HTTP response body exceeds {0} bytes")]
ResponseBodyTooLarge(usize),
#[error("unexpected HTTP status {0}")]
UnexpectedStatus(StatusCode),
#[error("OAuth discovery redirect to non-same-origin URL rejected: {0}")]
CrossOriginRedirect(Url),
#[error("OAuth discovery exceeded {0} redirects")]
TooManyRedirects(usize),
}
/// Future returned by [`OAuthHttpClient::execute`].
pub type OAuthHttpClientFuture<'a> =
Pin<Box<dyn Future<Output = Result<HttpResponse, OAuthHttpClientError>> + Send + 'a>>;
/// Executes every outbound HTTP request made by the OAuth state machine.
///
/// Implementations may route requests through a remote execution environment.
/// They must honor the request's redirect policy and return the raw response
/// status, headers, and body.
pub trait OAuthHttpClient: Send + Sync {
/// Execute one OAuth HTTP operation.
fn execute(&self, request: OAuthHttpRequest) -> OAuthHttpClientFuture<'_>;
}
struct ReqwestOAuthHttpClient {
follow_redirects: ReqwestClient,
stop_redirects: ReqwestClient,
}
impl ReqwestOAuthHttpClient {
fn new(follow_redirects: ReqwestClient) -> Result<Self, AuthError> {
let stop_redirects = ReqwestClient::builder()
.timeout(DEFAULT_HTTP_TIMEOUT)
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|error| AuthError::InternalError(error.to_string()))?;
Ok(Self {
follow_redirects,
stop_redirects,
})
}
}
impl OAuthHttpClient for ReqwestOAuthHttpClient {
fn execute(&self, request: OAuthHttpRequest) -> OAuthHttpClientFuture<'_> {
Box::pin(async move {
let OAuthHttpRequest {
request,
redirect_policy,
..
} = request;
let client = match redirect_policy {
OAuthHttpRedirectPolicy::Follow => &self.follow_redirects,
OAuthHttpRedirectPolicy::Stop => &self.stop_redirects,
};
let request = reqwest::Request::try_from(request)
.map_err(|error| Box::new(error) as OAuthHttpClientError)?;
let response = client
.execute(request)
.await
.map_err(|error| Box::new(error) as OAuthHttpClientError)?;
let mut builder = oauth2::http::Response::builder()
.status(response.status())
.version(response.version());
for (name, value) in response.headers() {
builder = builder.header(name, value);
}
let mut body = Vec::new();
let mut body_stream = response.bytes_stream();
while let Some(chunk) = body_stream.next().await {
let chunk = chunk.map_err(|error| Box::new(error) as OAuthHttpClientError)?;
if chunk.len() > MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES - body.len() {
return Err(Box::new(OAuthHttpError::ResponseBodyTooLarge(
MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES,
)) as OAuthHttpClientError);
}
body.extend_from_slice(&chunk);
}
builder
.body(body)
.map_err(|error| Box::new(error) as OAuthHttpClientError)
})
}
}
struct OAuth2HttpClient<'a> {
client: &'a dyn OAuthHttpClient,
redirect_policy: OAuthHttpRedirectPolicy,
}
#[derive(Debug)]
struct OAuth2HttpClientError(OAuthHttpClientError);
impl std::fmt::Display for OAuth2HttpClientError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("OAuth HTTP request failed")
}
}
impl std::error::Error for OAuth2HttpClientError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(self.0.as_ref())
}
}
impl<'c> AsyncHttpClient<'c> for OAuth2HttpClient<'_> {
type Error = OAuth2HttpClientError;
type Future = std::pin::Pin<
Box<dyn std::future::Future<Output = Result<HttpResponse, Self::Error>> + Send + 'c>,
>;
fn call(&'c self, request: HttpRequest) -> Self::Future {
Box::pin(async move {
self.client
.execute(OAuthHttpRequest::new(request, self.redirect_policy))
.await
.map_err(OAuth2HttpClientError)
})
}
}
const DEFAULT_EXCHANGE_URL: &str = "http://localhost";
/// Default OIDC Dynamic Client Registration `application_type` (SEP-837)
const DEFAULT_APPLICATION_TYPE: &str = "native";
/// Stored credentials for OAuth2 authorization
#[derive(Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct StoredCredentials {
pub client_id: String,
pub token_response: Option<OAuthTokenResponse>,
#[serde(default)]
pub granted_scopes: Vec<String>,
#[serde(default)]
pub token_received_at: Option<u64>,
#[serde(default)]
pub issuer: Option<String>,
}
impl std::fmt::Debug for StoredCredentials {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StoredCredentials")
.field("client_id", &self.client_id)
.field(
"token_response",
&self.token_response.as_ref().map(|_| "[REDACTED]"),
)
.field("granted_scopes", &self.granted_scopes)
.field("token_received_at", &self.token_received_at)
.field("issuer", &self.issuer)
.finish()
}
}
impl StoredCredentials {
/// Create a new `StoredCredentials` instance.
pub fn new(
client_id: String,
token_response: Option<OAuthTokenResponse>,
granted_scopes: Vec<String>,
token_received_at: Option<u64>,
) -> Self {
Self {
client_id,
token_response,
granted_scopes,
token_received_at,
issuer: None,
}
}
pub fn with_issuer(mut self, issuer: Option<String>) -> Self {
self.issuer = issuer;
self
}
}
/// Trait for storing and retrieving OAuth2 credentials
///
/// Implementations of this trait can provide custom storage backends
/// for OAuth2 credentials, such as file-based storage, keychain integration,
/// or database storage.
#[async_trait]
pub trait CredentialStore: Send + Sync {
async fn load(&self) -> Result<Option<StoredCredentials>, AuthError>;
async fn save(&self, credentials: StoredCredentials) -> Result<(), AuthError>;
async fn clear(&self) -> Result<(), AuthError>;
}
/// In-memory credential store (default implementation)
///
/// This store keeps credentials in memory only and does not persist them
/// between application restarts. This is the default behavior when no
/// custom credential store is provided.
#[derive(Debug, Default, Clone)]
pub struct InMemoryCredentialStore {
credentials: Arc<RwLock<Option<StoredCredentials>>>,
}
impl InMemoryCredentialStore {
pub fn new() -> Self {
Self {
credentials: Arc::new(RwLock::new(None)),
}
}
}
#[async_trait::async_trait]
impl CredentialStore for InMemoryCredentialStore {
async fn load(&self) -> Result<Option<StoredCredentials>, AuthError> {
Ok(self.credentials.read().await.clone())
}
async fn save(&self, credentials: StoredCredentials) -> Result<(), AuthError> {
*self.credentials.write().await = Some(credentials);
Ok(())
}
async fn clear(&self) -> Result<(), AuthError> {
*self.credentials.write().await = None;
Ok(())
}
}
/// Stored authorization state for OAuth2 PKCE flow
#[derive(Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct StoredAuthorizationState {
pub pkce_verifier: String,
pub csrf_token: String,
#[serde(default)]
pub expected_issuer: Option<String>,
#[serde(default)]
pub require_issuer: bool,
pub created_at: u64,
/// scopes requested in this round, used to resolve the grant when the token response omits
/// `scope` (RFC 6749 §5.1)
#[serde(default)]
pub requested_scopes: Vec<String>,
}
impl std::fmt::Debug for StoredAuthorizationState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StoredAuthorizationState")
.field("pkce_verifier", &"[REDACTED]")
.field("csrf_token", &"[REDACTED]")
.field("expected_issuer", &self.expected_issuer)
.field("require_issuer", &self.require_issuer)
.field("created_at", &self.created_at)
.field("requested_scopes", &self.requested_scopes)
.finish()
}
}
/// A transparent wrapper around a JSON object that captures any extra fields returned by the
/// authorization server during token exchange that are not part of the standard OAuth 2.0 token
/// response.
///
/// OAuth providers may include non-standard fields alongside the
/// standard OAuth fields. Those fields are collected here so callers
/// can inspect them without losing data.
///
/// The inner [`HashMap<String, Value>`] maps field names to their raw JSON values.
///
/// # Accessing extra fields
///
/// Extra fields are available through [`StandardTokenResponse::extra_fields()`], which returns a
/// reference to this struct. Use the inner map (`.0`) to look up individual fields by name:
///
/// ```rust,ignore
/// // Obtain the token response from the AuthorizationManager, then:
/// if let Some(value) = token_response.extra_fields().0.get("vendorSpecificField") {
/// println!("vendorSpecificField = {value}");
/// }
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct VendorExtraTokenFields(pub HashMap<String, Value>);
impl ExtraTokenFields for VendorExtraTokenFields {}
impl StoredAuthorizationState {
pub fn new(pkce_verifier: &PkceCodeVerifier, csrf_token: &CsrfToken) -> Self {
Self::new_with_expected_issuer(pkce_verifier, csrf_token, None, false)
}
pub fn new_with_expected_issuer(
pkce_verifier: &PkceCodeVerifier,
csrf_token: &CsrfToken,
expected_issuer: Option<String>,
require_issuer: bool,
) -> Self {
Self {
pkce_verifier: pkce_verifier.secret().to_string(),
csrf_token: csrf_token.secret().to_string(),
expected_issuer,
require_issuer,
created_at: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
requested_scopes: Vec::new(),
}
}
/// record the scopes requested in this authorization round (SEP-2350)
pub fn with_requested_scopes(mut self, scopes: Vec<String>) -> Self {
self.requested_scopes = scopes;
self
}
pub fn into_pkce_verifier(self) -> PkceCodeVerifier {
PkceCodeVerifier::new(self.pkce_verifier)
}
}
/// Trait for storing and retrieving OAuth2 authorization state
///
/// Implementations of this trait can provide custom storage backends
/// for OAuth2 PKCE flow state, such as Redis or database storage.
///
/// Implementors are responsible for expiring stale states (e.g., abandoned
/// authorization flows). Use [`StoredAuthorizationState::created_at`] for
/// TTL-based expiration.
#[async_trait]
pub trait StateStore: Send + Sync {
async fn save(
&self,
csrf_token: &str,
state: StoredAuthorizationState,
) -> Result<(), AuthError>;
async fn load(&self, csrf_token: &str) -> Result<Option<StoredAuthorizationState>, AuthError>;
async fn delete(&self, csrf_token: &str) -> Result<(), AuthError>;
}
/// In-memory state store (default implementation)
///
/// This store keeps authorization state in memory only and does not persist
/// between application restarts or across multiple server instances.
#[derive(Debug, Default, Clone)]
pub struct InMemoryStateStore {
states: Arc<RwLock<HashMap<String, StoredAuthorizationState>>>,
}
impl InMemoryStateStore {
pub fn new() -> Self {
Self {
states: Arc::new(RwLock::new(HashMap::new())),
}
}
}
#[async_trait]
impl StateStore for InMemoryStateStore {
async fn save(
&self,
csrf_token: &str,
state: StoredAuthorizationState,
) -> Result<(), AuthError> {
self.states
.write()
.await
.insert(csrf_token.to_string(), state);
Ok(())
}
async fn load(&self, csrf_token: &str) -> Result<Option<StoredAuthorizationState>, AuthError> {
Ok(self.states.read().await.get(csrf_token).cloned())
}
async fn delete(&self, csrf_token: &str) -> Result<(), AuthError> {
self.states.write().await.remove(csrf_token);
Ok(())
}
}
/// HTTP client with OAuth 2.0 authorization
#[derive(Clone)]
#[non_exhaustive]
pub struct AuthClient<C> {
pub http_client: C,
pub auth_manager: Arc<Mutex<AuthorizationManager>>,
}
impl<C: std::fmt::Debug> std::fmt::Debug for AuthClient<C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AuthorizedClient")
.field("http_client", &self.http_client)
.field("auth_manager", &"...")
.finish()
}
}
impl<C> AuthClient<C> {
/// Create a new authorized HTTP client
pub fn new(http_client: C, auth_manager: AuthorizationManager) -> Self {
Self {
http_client,
auth_manager: Arc::new(Mutex::new(auth_manager)),
}
}
}
impl<C> AuthClient<C> {
pub fn get_access_token(&self) -> impl Future<Output = Result<String, AuthError>> + Send {
let auth_manager = self.auth_manager.clone();
async move { auth_manager.lock().await.get_access_token().await }
}
}
/// Auth error
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum AuthError {
#[error("OAuth authorization required")]
AuthorizationRequired,
#[error("OAuth authorization failed: {0}")]
AuthorizationFailed(String),
#[error("OAuth token exchange failed: {0}")]
TokenExchangeFailed(String),
/// The refresh attempt failed without a definitive refresh-token rejection.
///
/// Callers may retry this error because it includes transient request and provider failures.
#[error("OAuth token refresh failed: {0}")]
TokenRefreshFailed(String),
/// The authorization server definitively rejected the refresh token.
#[error("OAuth refresh token was rejected: {0}")]
TokenRefreshRejected(String),
#[error("HTTP error: {0}")]
HttpError(#[from] reqwest::Error),
#[error("OAuth error: {0}")]
OAuthError(String),
#[error("Metadata error: {0}")]
MetadataError(String),
#[error("Authorization server does not support the required PKCE code challenge method (S256)")]
PkceUnsupported,
#[error("URL parse error: {0}")]
UrlError(#[from] url::ParseError),
#[error("No authorization support detected")]
NoAuthorizationSupport,
#[error("Internal error: {0}")]
InternalError(String),
#[error("Invalid token type: {0}")]
InvalidTokenType(String),
#[error("Token expired")]
TokenExpired,
#[error("Invalid scope: {0}")]
InvalidScope(String),
#[error("Registration failed: {0}")]
RegistrationFailed(String),
#[error("Insufficient scope: {required_scope}")]
InsufficientScope {
required_scope: String,
upgrade_url: Option<String>,
},
#[error(
"Authorization server issuer mismatch: expected {expected_issuer}, received {received_issuer}"
)]
AuthorizationServerMismatch {
expected_issuer: String,
received_issuer: String,
},
#[error("Authorization server response missing required issuer: expected {expected_issuer}")]
AuthorizationServerMissingIssuer { expected_issuer: String },
#[error("Client credentials error: {0}")]
ClientCredentialsError(String),
#[cfg(feature = "auth-client-credentials-jwt")]
#[error("JWT signing error: {0}")]
JwtSigningError(String),
}
/// oauth2 metadata
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[non_exhaustive]
pub struct AuthorizationMetadata {
pub authorization_endpoint: String,
pub token_endpoint: String,
pub registration_endpoint: Option<String>,
pub issuer: Option<String>,
pub jwks_uri: Option<String>,
pub scopes_supported: Option<Vec<String>>,
pub response_types_supported: Option<Vec<String>>,
pub code_challenge_methods_supported: Option<Vec<String>>,
// allow additional fields
#[serde(flatten)]
pub additional_fields: HashMap<String, serde_json::Value>,
}
/// How [`AuthorizationMetadata`] was obtained during discovery.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthorizationMetadataSource {
/// Discovered through RFC 9728 protected resource metadata.
ProtectedResourceMetadata,
/// Discovered through RFC 8414 / OpenID Connect metadata at the server's
/// base URL.
AuthorizationServerMetadata,
/// Nothing was discovered; the endpoints were synthesized from the base
/// URL (`/authorize`, `/token`, `/register`) for compatibility with the
/// 2025-03-26 MCP spec's default-endpoint fallback. The server gave no
/// evidence that it supports OAuth.
///
/// [Newer MCP revisions] require metadata discovery and do not define an
/// endpoint-synthesis fallback.
///
/// [Newer MCP revisions]: https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/authorization-server-discovery#protected-resource-metadata-discovery-requirements
LegacyEndpointFallback,
}
impl AuthorizationMetadataSource {
/// Whether the metadata was actually published by the server, as opposed
/// to synthesized by the client as a legacy compatibility fallback.
pub fn is_discovered(self) -> bool {
!matches!(self, Self::LegacyEndpointFallback)
}
}
/// [`AuthorizationMetadata`] together with how it was resolved.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AuthorizationMetadataResolution {
pub metadata: AuthorizationMetadata,
pub source: AuthorizationMetadataSource,
}
#[derive(Debug, Clone, Deserialize)]
struct ResourceServerMetadata {
resource: Option<String>,
authorization_server: Option<String>,
authorization_servers: Option<Vec<String>>,
scopes_supported: Option<Vec<String>>,
}
/// Parameters extracted from WWW-Authenticate header
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct WWWAuthenticateParams {
pub resource_metadata_url: Option<Url>,
pub scope: Option<String>,
pub error: Option<String>,
pub error_description: Option<String>,
}
impl WWWAuthenticateParams {
/// Parse a `WWW-Authenticate` header value, resolving a relative
/// `resource_metadata` URL against `base_url`.
pub fn parse(header: &str, base_url: &Url) -> Self {
AuthorizationManager::extract_www_authenticate_params(header, base_url)
}
/// check if this is an insufficient_scope error
pub fn is_insufficient_scope(&self) -> bool {
self.error.as_deref() == Some("insufficient_scope")
}
/// check if this is an invalid_token error (expired/revoked)
pub fn is_invalid_token(&self) -> bool {
self.error.as_deref() == Some("invalid_token")
}
}
/// oauth2 client config
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct OAuthClientConfig {
pub client_id: String,
pub client_secret: Option<String>,
pub scopes: Vec<String>,
pub redirect_uri: String,
pub application_type: Option<String>,
}
impl OAuthClientConfig {
pub fn new(client_id: impl Into<String>, redirect_uri: impl Into<String>) -> Self {
Self {
client_id: client_id.into(),
client_secret: None,
scopes: Vec::new(),
redirect_uri: redirect_uri.into(),
application_type: Some(DEFAULT_APPLICATION_TYPE.to_string()),
}
}
pub fn with_client_secret(mut self, secret: impl Into<String>) -> Self {
self.client_secret = Some(secret.into());
self
}
pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
self.scopes = scopes;
self
}
/// Set the OIDC Dynamic Client Registration `application_type` (SEP-837), e.g. `"native"` or `"web"`
pub fn with_application_type(mut self, application_type: impl Into<String>) -> Self {
self.application_type = Some(application_type.into());
self
}
}
/// Declarative description of the client identity material available for an
/// authorization flow.
///
/// The [MCP authorization specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration)
/// recommends that clients obtain a client ID using the following priority
/// order. [`OAuthState::start_authorization`] and [`AuthorizationSession::new`]
/// apply it internally:
///
/// 1. Pre-registered client information
/// ([`with_preregistered_client`](Self::with_preregistered_client)), when
/// the client already holds a `client_id` issued out of band
/// 2. Client ID Metadata Documents (SEP-991,
/// [`with_client_metadata_url`](Self::with_client_metadata_url)), when the
/// authorization server advertises `client_id_metadata_document_supported`
/// 3. Dynamic Client Registration as a fallback, when the authorization server
/// advertises a `registration_endpoint`
///
/// Provide whichever identity material the client has available; the SDK
/// selects the highest-priority mechanism the server supports.
///
/// ```rust,ignore
/// let request = AuthorizationRequest::new("http://localhost:8080/callback")
/// // Omit `with_scopes` to let the SDK auto-select scopes from server metadata.
/// // Used when the server supports CIMD and no pre-registered client is set.
/// .with_client_metadata_url("https://example.com/client-metadata.json")
/// // used for dynamic client registration as a last resort
/// .with_client_name("My MCP Client");
/// oauth_state.start_authorization(request).await?;
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AuthorizationRequest {
/// Redirect URI for the authorization-code flow.
pub redirect_uri: String,
/// Scopes to request. When empty, the SDK selects scopes from the
/// server's `WWW-Authenticate` challenge, Protected Resource Metadata,
/// or authorization server metadata.
pub scopes: Vec<String>,
/// Human-readable client name, used for Dynamic Client Registration.
pub client_name: Option<String>,
/// Pre-registered client ID obtained from the authorization server out of
/// band. When set, registration is skipped entirely.
pub client_id: Option<String>,
/// Client secret paired with the pre-registered [`client_id`](Self::client_id).
pub client_secret: Option<String>,
/// HTTPS URL of a Client ID Metadata Document (SEP-991). Used when the
/// authorization server advertises `client_id_metadata_document_supported`
/// and no pre-registered client is configured.
pub client_metadata_url: Option<String>,
/// OIDC Dynamic Client Registration `application_type` (SEP-837),
/// e.g. `"native"` or `"web"`.
pub application_type: Option<String>,
/// `WWW-Authenticate` header value from a real request's 401 response.
/// When set, discovery is seeded from the challenge (its
/// `resource_metadata` URL and `scope` hint) instead of probing the
/// server — the reactive discovery path.
pub challenge: Option<String>,
}
impl AuthorizationRequest {
/// Create a request for the given redirect URI. With no further identity
/// material, authorization falls back to Dynamic Client Registration.
pub fn new(redirect_uri: impl Into<String>) -> Self {
Self {
redirect_uri: redirect_uri.into(),
scopes: Vec::new(),
client_name: None,
client_id: None,
client_secret: None,
client_metadata_url: None,
application_type: None,
challenge: None,
}
}
/// Set the scopes to request. When not set, the SDK auto-selects scopes
/// using its normal scope-selection policy.
pub fn with_scopes<I, S>(mut self, scopes: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.scopes = scopes.into_iter().map(Into::into).collect();
self
}
/// Set the client name used for Dynamic Client Registration.
pub fn with_client_name(mut self, client_name: impl Into<String>) -> Self {
self.client_name = Some(client_name.into());
self
}
/// Use a client ID that was pre-registered with the authorization server
/// out of band. This takes priority over every other mechanism.
///
/// Pair with [`with_client_secret`](Self::with_client_secret) for
/// confidential clients.
pub fn with_preregistered_client(mut self, client_id: impl Into<String>) -> Self {
self.client_id = Some(client_id.into());
self
}
/// Set the client secret paired with a pre-registered client ID.
///
/// Must be used together with
/// [`with_preregistered_client`](Self::with_preregistered_client);
/// authorization fails with [`AuthError::RegistrationFailed`] if a secret
/// is provided without a client ID.
pub fn with_client_secret(mut self, client_secret: impl Into<String>) -> Self {
self.client_secret = Some(client_secret.into());
self
}
/// Set the HTTPS URL of a Client ID Metadata Document (SEP-991). Used when
/// the authorization server advertises support and no pre-registered
/// client is configured.
pub fn with_client_metadata_url(mut self, client_metadata_url: impl Into<String>) -> Self {
self.client_metadata_url = Some(client_metadata_url.into());
self
}
/// Set the OIDC Dynamic Client Registration `application_type` (SEP-837),
/// e.g. `"native"` or `"web"`.
pub fn with_application_type(mut self, application_type: impl Into<String>) -> Self {
self.application_type = Some(application_type.into());
self
}
/// Seed discovery from the `WWW-Authenticate` header value of a real
/// request's 401 response instead of probing the server.
pub fn with_challenge(mut self, www_authenticate: impl Into<String>) -> Self {
self.challenge = Some(www_authenticate.into());
self
}
}
// add type aliases for oauth2 types
type OAuthErrorResponse = oauth2::StandardErrorResponse<oauth2::basic::BasicErrorResponseType>;
/// The token response returned by the authorization server after a successful OAuth 2.0 flow.
///
/// This is a [`StandardTokenResponse`] parameterised with [`VendorExtraTokenFields`], which means
/// it carries both the standard OAuth fields and
/// any vendor-specific fields the server may have included in the JSON response body.
///
/// # Accessing vendor-specific fields
///
/// Call [`extra_fields()`][OAuthTokenResponse::extra_fields] to obtain a reference to the
/// [`VendorExtraTokenFields`] wrapper, then index into its inner map.
pub type OAuthTokenResponse = StandardTokenResponse<VendorExtraTokenFields, BasicTokenType>;
type OAuthTokenIntrospection =
oauth2::StandardTokenIntrospectionResponse<EmptyExtraTokenFields, BasicTokenType>;
type OAuthRevocableToken = oauth2::StandardRevocableToken;
type OAuthRevocationError = oauth2::StandardErrorResponse<oauth2::RevocationErrorResponseType>;
type OAuthClient = oauth2::Client<
OAuthErrorResponse,
OAuthTokenResponse,
OAuthTokenIntrospection,
OAuthRevocableToken,
OAuthRevocationError,
oauth2::EndpointSet,
oauth2::EndpointNotSet,
oauth2::EndpointNotSet,
oauth2::EndpointNotSet,
oauth2::EndpointSet,
>;
type Credentials = (String, Option<OAuthTokenResponse>);
/// OAuth 2.0 extension identifier for client credentials flow (SEP-1046)
pub const EXTENSION_OAUTH_CLIENT_CREDENTIALS: &str =
"io.modelcontextprotocol/oauth-client-credentials";
/// JWT signing algorithm for private_key_jwt authentication (SEP-1046)
#[cfg(feature = "auth-client-credentials-jwt")]
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum JwtSigningAlgorithm {
RS256,
RS384,
RS512,
ES256,
ES384,
}
#[cfg(feature = "auth-client-credentials-jwt")]
impl JwtSigningAlgorithm {
fn to_jsonwebtoken_algorithm(self) -> jsonwebtoken::Algorithm {
match self {
JwtSigningAlgorithm::RS256 => jsonwebtoken::Algorithm::RS256,
JwtSigningAlgorithm::RS384 => jsonwebtoken::Algorithm::RS384,
JwtSigningAlgorithm::RS512 => jsonwebtoken::Algorithm::RS512,
JwtSigningAlgorithm::ES256 => jsonwebtoken::Algorithm::ES256,
JwtSigningAlgorithm::ES384 => jsonwebtoken::Algorithm::ES384,
}
}
fn as_str(self) -> &'static str {
match self {
JwtSigningAlgorithm::RS256 => "RS256",
JwtSigningAlgorithm::RS384 => "RS384",
JwtSigningAlgorithm::RS512 => "RS512",
JwtSigningAlgorithm::ES256 => "ES256",
JwtSigningAlgorithm::ES384 => "ES384",
}
}
}
/// Configuration for OAuth 2.0 Client Credentials flow (SEP-1046)
///
/// This supports two authentication methods:
/// - `ClientSecret`: credentials sent in the request body
/// - `PrivateKeyJwt`: RFC 7523 signed JWT assertion (requires `auth-client-credentials-jwt` feature)
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ClientCredentialsConfig {
/// Client secret authentication (credentials in request body)
ClientSecret {
client_id: String,
client_secret: String,
scopes: Vec<String>,
resource: Option<String>,
},
/// Private key JWT authentication (RFC 7523)
#[cfg(feature = "auth-client-credentials-jwt")]
PrivateKeyJwt {
client_id: String,
signing_key: Vec<u8>,
signing_algorithm: JwtSigningAlgorithm,
/// Overrides the authorization server issuer used for the JWT `aud` claim.
token_endpoint_audience: Option<String>,
scopes: Vec<String>,
resource: Option<String>,
},
}
#[cfg(feature = "auth-client-credentials-jwt")]
fn client_authentication_audience<'a>(
metadata: &'a AuthorizationMetadata,
configured_audience: Option<&'a str>,
) -> Result<&'a str, AuthError> {
configured_audience
.or(metadata.issuer.as_deref())
.ok_or_else(|| {
AuthError::ClientCredentialsError(
"Authorization server metadata is missing the issuer required for private_key_jwt"
.to_string(),
)
})
}
#[cfg(feature = "auth-client-credentials-jwt")]
fn client_authentication_header(algorithm: JwtSigningAlgorithm) -> jsonwebtoken::Header {
let mut header = jsonwebtoken::Header::new(algorithm.to_jsonwebtoken_algorithm());
header.typ = Some("client-authentication+jwt".to_string());
header
}
impl ClientCredentialsConfig {
fn client_id(&self) -> &str {
match self {
ClientCredentialsConfig::ClientSecret { client_id, .. } => client_id,
#[cfg(feature = "auth-client-credentials-jwt")]
ClientCredentialsConfig::PrivateKeyJwt { client_id, .. } => client_id,
}
}
fn scopes(&self) -> &[String] {
match self {
ClientCredentialsConfig::ClientSecret { scopes, .. } => scopes,
#[cfg(feature = "auth-client-credentials-jwt")]
ClientCredentialsConfig::PrivateKeyJwt { scopes, .. } => scopes,
}
}
fn resource(&self) -> Option<&str> {
match self {
ClientCredentialsConfig::ClientSecret { resource, .. } => resource.as_deref(),
#[cfg(feature = "auth-client-credentials-jwt")]
ClientCredentialsConfig::PrivateKeyJwt { resource, .. } => resource.as_deref(),
}
}
fn auth_method(&self) -> &str {
match self {
ClientCredentialsConfig::ClientSecret { .. } => "client_secret_post",
#[cfg(feature = "auth-client-credentials-jwt")]
ClientCredentialsConfig::PrivateKeyJwt { .. } => "private_key_jwt",
}
}
}
/// Configuration for scope upgrade behavior
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ScopeUpgradeConfig {
/// Maximum number of scope upgrade attempts before giving up