Repository navigation
Expand file tree
/
Copy pathauth.rs
More file actions
2487 lines (2179 loc) · 86.3 KB
/
Copy pathauth.rs
File metadata and controls
2487 lines (2179 loc) · 86.3 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
//! OAuth 2.1 authentication for MCP servers.
//!
//! Implements the MCP Authorization specification using OAuth 2.1 with PKCE.
//! See: https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/authorization/
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::{Arc, Weak};
use std::time::Duration;
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tokio::net::TcpListener;
use url::Url;
use crate::auth::oauth::{self, OAUTH_CALLBACK_PORT};
use crate::auth::resolve_access_token_string_with_refresh;
use crate::secrets::{CreateSecretParams, SecretsStore};
use crate::tools::mcp::config::McpServerConfig;
/// Shared HTTP client for all OAuth/discovery requests.
///
/// Redirects are disabled for security (prevents redirect-based SSRF).
/// Per-request timeouts can override the default via `.timeout()` on
/// the request builder.
fn oauth_http_client() -> Result<&'static reqwest::Client, AuthError> {
static CLIENT: std::sync::OnceLock<Result<reqwest::Client, AuthError>> =
std::sync::OnceLock::new();
CLIENT
.get_or_init(|| {
reqwest::Client::builder()
.timeout(Duration::from_secs(30))
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|e| AuthError::Http(e.to_string()))
})
.as_ref()
.map_err(Clone::clone)
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct RefreshLockKey {
server_name: String,
user_id: String,
}
fn refresh_lock_key(server_name: &str, user_id: &str) -> RefreshLockKey {
RefreshLockKey {
server_name: server_name.to_string(),
user_id: user_id.to_string(),
}
}
async fn refresh_lock(server_name: &str, user_id: &str) -> Arc<tokio::sync::Mutex<()>> {
static LOCKS: std::sync::OnceLock<
tokio::sync::Mutex<HashMap<RefreshLockKey, Weak<tokio::sync::Mutex<()>>>>,
> = std::sync::OnceLock::new();
let registry = LOCKS.get_or_init(|| tokio::sync::Mutex::new(HashMap::new()));
let mut locks = registry.lock().await;
locks.retain(|_, lock| lock.strong_count() > 0);
let key = refresh_lock_key(server_name, user_id);
if let Some(lock) = locks.get(&key).and_then(Weak::upgrade) {
return lock;
}
let lock = Arc::new(tokio::sync::Mutex::new(()));
locks.insert(key, Arc::downgrade(&lock));
lock
}
/// Log a debug message when a discovery/auth response is a redirect.
/// Helps users diagnose configuration issues when legitimate servers
/// redirect and our no-redirect policy causes a failure.
fn log_redirect_if_applicable(url: &str, response: &reqwest::Response) {
if response.status().is_redirection() {
let location = response
.headers()
.get("location")
.and_then(|v| v.to_str().ok());
tracing::debug!(
"OAuth request to '{}' returned redirect {} -> {:?} (redirects disabled for security)",
url,
response.status(),
location
);
}
}
/// OAuth authorization error.
#[derive(Debug, Clone, thiserror::Error)]
pub enum AuthError {
#[error("Server does not support OAuth authorization")]
NotSupported,
#[error("Failed to discover authorization endpoints: {0}")]
DiscoveryFailed(String),
#[error("Authorization denied by user")]
AuthorizationDenied,
#[error("Token exchange failed: {0}")]
TokenExchangeFailed(String),
#[error("Token expired and refresh failed: {0}")]
RefreshFailed(String),
#[error("No access token available")]
NoToken,
#[error("Timeout waiting for authorization callback")]
Timeout,
#[error("Could not bind to callback port")]
PortUnavailable,
#[error("HTTP error: {0}")]
Http(String),
#[error("Secrets error: {0}")]
Secrets(String),
/// The server-advertised `authorization_endpoint` is not a parseable URL.
/// We reject malformed endpoints rather than concat-normalizing them so a
/// broken OAuth-server discovery document can't be silently "fixed up"
/// into a half-formed authorization request (gemini-code-assist review
/// on #2746).
#[error("Malformed OAuth configuration: {0}")]
MalformedConfig(String),
}
/// OAuth protected resource metadata.
/// Discovered from /.well-known/oauth-protected-resource.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProtectedResourceMetadata {
/// The protected resource identifier.
pub resource: String,
/// Authorization servers that can issue tokens for this resource.
#[serde(default)]
pub authorization_servers: Vec<String>,
/// Scopes supported by this resource.
#[serde(default)]
pub scopes_supported: Vec<String>,
}
/// OAuth authorization server metadata.
/// Discovered from /.well-known/oauth-authorization-server.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorizationServerMetadata {
/// Authorization server issuer.
pub issuer: String,
/// Authorization endpoint URL.
pub authorization_endpoint: String,
/// Token endpoint URL.
pub token_endpoint: String,
/// Dynamic client registration endpoint (if DCR is supported).
#[serde(default)]
pub registration_endpoint: Option<String>,
/// Supported response types.
#[serde(default)]
pub response_types_supported: Vec<String>,
/// Supported grant types.
#[serde(default)]
pub grant_types_supported: Vec<String>,
/// Supported code challenge methods.
#[serde(default)]
pub code_challenge_methods_supported: Vec<String>,
/// Scopes supported by this server.
#[serde(default)]
pub scopes_supported: Vec<String>,
}
/// Dynamic Client Registration request.
#[derive(Debug, Clone, Serialize)]
pub struct ClientRegistrationRequest {
/// Human-readable client name.
pub client_name: String,
/// Redirect URIs for OAuth callbacks.
pub redirect_uris: Vec<String>,
/// Grant types the client will use.
pub grant_types: Vec<String>,
/// Response types the client will use.
pub response_types: Vec<String>,
/// Token endpoint authentication method.
pub token_endpoint_auth_method: String,
}
/// Dynamic Client Registration response.
#[derive(Debug, Clone, Deserialize)]
pub struct ClientRegistrationResponse {
/// The assigned client ID.
pub client_id: String,
/// Client secret (if issued).
#[serde(default)]
pub client_secret: Option<String>,
/// When the client secret expires (if applicable).
#[serde(default)]
pub client_secret_expires_at: Option<u64>,
/// Registration access token for managing the registration.
#[serde(default)]
pub registration_access_token: Option<String>,
/// Registration client URI for managing the registration.
#[serde(default)]
pub registration_client_uri: Option<String>,
}
/// Access token with optional refresh token and expiry.
#[derive(Debug, Clone)]
pub struct AccessToken {
/// The access token value.
pub access_token: String,
/// Token type (usually "Bearer").
pub token_type: String,
/// Seconds until expiration (if provided).
pub expires_in: Option<u64>,
/// Refresh token for obtaining new access tokens.
pub refresh_token: Option<String>,
/// Scopes granted.
pub scope: Option<String>,
}
#[derive(Debug, Clone)]
struct ClientCredentials {
client_id: String,
client_secret: Option<String>,
}
/// Token response from the authorization server.
#[derive(Debug, Deserialize)]
struct TokenResponse {
access_token: String,
token_type: String,
expires_in: Option<u64>,
refresh_token: Option<String>,
scope: Option<String>,
}
/// PKCE verifier and challenge pair.
#[derive(Debug, Clone)]
pub struct PkceChallenge {
/// Code verifier (high-entropy random string).
pub verifier: String,
/// Code challenge (S256 hash of verifier).
pub challenge: String,
}
impl PkceChallenge {
/// Generate a new PKCE challenge pair.
pub fn generate() -> Self {
let mut verifier_bytes = [0u8; 32];
rand::rngs::OsRng.fill_bytes(&mut verifier_bytes);
let verifier = URL_SAFE_NO_PAD.encode(verifier_bytes);
let mut hasher = Sha256::new();
hasher.update(verifier.as_bytes());
let challenge = URL_SAFE_NO_PAD.encode(hasher.finalize());
Self {
verifier,
challenge,
}
}
}
// ---------------------------------------------------------------------------
// Well-known URI construction (RFC 8414 / RFC 9728)
// ---------------------------------------------------------------------------
/// Build a well-known URI according to RFC 8414 / RFC 9728.
///
/// The path component of the base URL is placed *after* the well-known suffix:
/// ```text
/// https://example.com/path + oauth-authorization-server
/// -> https://example.com/.well-known/oauth-authorization-server/path
/// ```
pub fn build_well_known_uri(base_url: &str, suffix: &str) -> Result<String, AuthError> {
let parsed = reqwest::Url::parse(base_url)
.map_err(|e| AuthError::DiscoveryFailed(format!("Invalid URL: {}", e)))?;
let origin = parsed.origin().ascii_serialization();
let path = parsed.path().trim_end_matches('/');
Ok(format!("{}/.well-known/{}{}", origin, suffix, path))
}
// ---------------------------------------------------------------------------
// RFC 8707 resource parameter
// ---------------------------------------------------------------------------
/// Compute the canonical resource URI for RFC 8707.
///
/// Strips fragments and trailing slashes from the server URL.
pub fn canonical_resource_uri(server_url: &str) -> String {
match reqwest::Url::parse(server_url) {
Ok(mut parsed) => {
parsed.set_fragment(None);
let s = parsed.to_string();
s.trim_end_matches('/').to_string()
}
Err(_) => server_url.trim_end_matches('/').to_string(),
}
}
// ---------------------------------------------------------------------------
// SSRF protection
// ---------------------------------------------------------------------------
/// Check if an IP address is dangerous (loopback, link-local, private, etc.)
fn is_dangerous_ip(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => {
v4.is_loopback()
|| v4.is_private()
|| v4.is_link_local()
|| v4.is_broadcast()
|| v4.is_unspecified()
|| (v4.octets()[0] == 169 && v4.octets()[1] == 254) // link-local
|| (v4.octets()[0] == 100 && (v4.octets()[1] & 0xC0) == 64) // CGNAT 100.64/10
}
IpAddr::V6(v6) => {
let segs = v6.segments();
v6.is_loopback()
|| v6.is_unspecified()
// Link-local (fe80::/10)
|| (segs[0] & 0xffc0) == 0xfe80
// Site-local / deprecated (fec0::/10)
|| (segs[0] & 0xffc0) == 0xfec0
// Unique local (fc00::/7)
|| (segs[0] & 0xfe00) == 0xfc00
// Documentation (2001:db8::/32)
|| (segs[0] == 0x2001 && segs[1] == 0x0db8)
// Check for IPv4-mapped IPv6 (::ffff:x.x.x.x)
|| v6
.to_ipv4_mapped()
.is_some_and(|v4| is_dangerous_ip(IpAddr::V4(v4)))
}
}
}
/// Validate that a URL is safe for server-side requests (SSRF protection).
async fn validate_url_safe(url: &str) -> Result<(), AuthError> {
let parsed = reqwest::Url::parse(url)
.map_err(|e| AuthError::DiscoveryFailed(format!("Invalid URL: {}", e)))?;
// Must be HTTPS. HTTP is only allowed for localhost/loopback (dev scenarios).
let scheme = parsed.scheme();
if scheme != "https" && scheme != "http" {
return Err(AuthError::DiscoveryFailed(format!(
"Unsupported scheme: {}",
scheme
)));
}
if scheme == "http" {
if !crate::tools::mcp::config::is_localhost_url(url) {
let host = parsed.host_str().unwrap_or("");
return Err(AuthError::DiscoveryFailed(format!(
"HTTP is only allowed for localhost; use HTTPS for '{}'",
host
)));
}
// Localhost HTTP is allowed for dev — skip SSRF checks since we've
// already validated the host is localhost/loopback.
return Ok(());
}
let host = parsed
.host_str()
.ok_or_else(|| AuthError::DiscoveryFailed("URL has no host".to_string()))?;
// For IP literals, parse directly and check.
if let Ok(ip) = host.parse::<IpAddr>()
&& is_dangerous_ip(ip)
{
return Err(AuthError::DiscoveryFailed(format!(
"URL points to a restricted IP address: {}",
host
)));
}
// For hostnames, resolve DNS and check each resolved address.
// This prevents DNS-based SSRF where a hostname resolves to an internal IP
// (e.g., 169.254.169.254 for cloud metadata endpoints).
if host.parse::<IpAddr>().is_err() {
let addr = format!("{}:{}", host, parsed.port_or_known_default().unwrap_or(443));
match tokio::net::lookup_host(&addr).await {
Ok(addrs) => {
for socket_addr in addrs {
if is_dangerous_ip(socket_addr.ip()) {
return Err(AuthError::DiscoveryFailed(format!(
"URL hostname '{}' resolves to restricted IP address: {}",
host,
socket_addr.ip()
)));
}
}
}
Err(e) => {
// DNS failure = fail closed (do not allow the request)
return Err(AuthError::DiscoveryFailed(format!(
"DNS resolution failed for '{}': {}",
host, e
)));
}
}
}
Ok(())
}
// ---------------------------------------------------------------------------
// Multi-strategy OAuth discovery helpers
// ---------------------------------------------------------------------------
/// Parse the resource_metadata URL from a WWW-Authenticate header value.
fn parse_resource_metadata_url(www_authenticate: &str) -> Option<String> {
// Try comma-separated parameters first
for part in www_authenticate.split(',') {
let part = part.trim();
if let Some(rest) = part.strip_prefix("resource_metadata=\"") {
return rest.strip_suffix('"').map(|s| s.to_string());
}
if let Some(rest) = part.strip_prefix("resource_metadata=") {
let val = rest.trim_matches('"');
return Some(val.to_string());
}
}
// Also try whitespace-separated tokens (e.g. Bearer resource_metadata="url")
for part in www_authenticate.split_whitespace() {
if let Some(rest) = part.strip_prefix("resource_metadata=\"") {
return rest
.trim_end_matches(',')
.strip_suffix('"')
.map(|s| s.to_string());
}
if let Some(rest) = part.strip_prefix("resource_metadata=") {
let val = rest.trim_matches('"').trim_end_matches(',');
return Some(val.to_string());
}
}
None
}
/// Fetch protected resource metadata from a URL.
async fn fetch_resource_metadata(url: &str) -> Result<ProtectedResourceMetadata, AuthError> {
validate_url_safe(url).await?;
let client = oauth_http_client()?;
let response = client
.get(url)
.timeout(Duration::from_secs(10))
.send()
.await
.map_err(|e| AuthError::DiscoveryFailed(e.to_string()))?;
log_redirect_if_applicable(url, &response);
if !response.status().is_success() {
return Err(AuthError::DiscoveryFailed(format!(
"HTTP {}",
response.status()
)));
}
response
.json()
.await
.map_err(|e| AuthError::DiscoveryFailed(format!("Invalid metadata: {}", e)))
}
/// Try to discover OAuth metadata via 401 challenge response.
///
/// Also accepts 400 responses, since some servers return 400 for
/// unauthenticated requests. In practice the 400 path rarely yields a
/// `WWW-Authenticate` header (GitHub's MCP does not), so discovery
/// typically falls through to strategy 2 (RFC 9728) or 3 (direct).
async fn discover_via_401(server_url: &str) -> Result<AuthorizationServerMetadata, AuthError> {
validate_url_safe(server_url).await?;
let client = oauth_http_client()?;
let response = client
.post(server_url)
.timeout(Duration::from_secs(10))
.header("Content-Type", "application/json")
.body("{}")
.send()
.await
.map_err(|e| AuthError::DiscoveryFailed(e.to_string()))?;
log_redirect_if_applicable(server_url, &response);
let status = response.status().as_u16();
// Accept 401 (standard) and 400 (some servers like GitHub MCP use this).
// In both cases, look for WWW-Authenticate header with discovery metadata.
if status != 401 && status != 400 {
return Err(AuthError::DiscoveryFailed(format!(
"Expected 401 or 400, got {}",
response.status()
)));
}
let www_auth = response
.headers()
.get("WWW-Authenticate")
.and_then(|v| v.to_str().ok())
.ok_or_else(|| {
AuthError::DiscoveryFailed(format!("No WWW-Authenticate header in {} response", status))
})?;
let resource_metadata_url = parse_resource_metadata_url(www_auth).ok_or_else(|| {
AuthError::DiscoveryFailed(
"No resource_metadata URL in WWW-Authenticate header".to_string(),
)
})?;
let resource_meta = fetch_resource_metadata(&resource_metadata_url).await?;
try_discover_from_auth_servers(&resource_meta).await
}
/// Try to discover auth server metadata from resource metadata's authorization_servers list.
async fn try_discover_from_auth_servers(
resource_meta: &ProtectedResourceMetadata,
) -> Result<AuthorizationServerMetadata, AuthError> {
let auth_server_url = resource_meta
.authorization_servers
.first()
.ok_or_else(|| AuthError::DiscoveryFailed("No authorization servers listed".to_string()))?;
discover_authorization_server(auth_server_url).await
}
// ---------------------------------------------------------------------------
// Discovery functions
// ---------------------------------------------------------------------------
/// Discover protected resource metadata from an MCP server.
pub async fn discover_protected_resource(
server_url: &str,
) -> Result<ProtectedResourceMetadata, AuthError> {
validate_url_safe(server_url).await?;
let client = oauth_http_client()?;
let well_known_url = build_well_known_uri(server_url, "oauth-protected-resource")?;
let response = client
.get(&well_known_url)
.timeout(Duration::from_secs(10))
.send()
.await
.map_err(|e| AuthError::DiscoveryFailed(e.to_string()))?;
log_redirect_if_applicable(&well_known_url, &response);
if !response.status().is_success() {
return Err(AuthError::NotSupported);
}
response
.json()
.await
.map_err(|e| AuthError::DiscoveryFailed(format!("Invalid metadata: {}", e)))
}
/// Discover authorization server metadata.
pub async fn discover_authorization_server(
auth_server_url: &str,
) -> Result<AuthorizationServerMetadata, AuthError> {
validate_url_safe(auth_server_url).await?;
let client = oauth_http_client()?;
let well_known_url = build_well_known_uri(auth_server_url, "oauth-authorization-server")?;
let response = client
.get(&well_known_url)
.timeout(Duration::from_secs(10))
.send()
.await
.map_err(|e| AuthError::DiscoveryFailed(e.to_string()))?;
log_redirect_if_applicable(&well_known_url, &response);
if !response.status().is_success() {
return Err(AuthError::DiscoveryFailed(format!(
"HTTP {}",
response.status()
)));
}
response
.json()
.await
.map_err(|e| AuthError::DiscoveryFailed(format!("Invalid metadata: {}", e)))
}
/// Discover OAuth endpoints for an MCP server.
///
/// First checks if endpoints are explicitly configured, then falls back to discovery.
pub async fn discover_oauth_endpoints(
server_config: &McpServerConfig,
) -> Result<(String, String), AuthError> {
let oauth = server_config
.oauth
.as_ref()
.ok_or(AuthError::NotSupported)?;
// If endpoints are explicitly configured, use them
if let (Some(auth_url), Some(token_url)) = (&oauth.authorization_url, &oauth.token_url) {
return Ok((auth_url.clone(), token_url.clone()));
}
// Try to discover from the server
let resource_meta = discover_protected_resource(&server_config.url).await?;
// Get the first authorization server
let auth_server_url = resource_meta
.authorization_servers
.first()
.ok_or_else(|| AuthError::DiscoveryFailed("No authorization servers listed".to_string()))?;
// Discover the authorization server metadata
let auth_meta = discover_authorization_server(auth_server_url).await?;
Ok((auth_meta.authorization_endpoint, auth_meta.token_endpoint))
}
/// Discover full OAuth metadata including DCR support.
///
/// Returns authorization server metadata which includes registration_endpoint if DCR is supported.
/// Uses a 3-strategy discovery chain:
/// 1. **401-based**: POST to MCP server, parse WWW-Authenticate header for resource_metadata URL
/// 2. **RFC 9728**: Discover protected resource metadata, then authorization server from it
/// 3. **Direct**: Treat MCP server as its own auth server
pub async fn discover_full_oauth_metadata(
server_url: &str,
) -> Result<AuthorizationServerMetadata, AuthError> {
// Strategy 1: 401-based discovery
if let Ok(meta) = discover_via_401(server_url).await {
return Ok(meta);
}
// Strategy 2: RFC 9728 protected resource discovery
if let Ok(resource_meta) = discover_protected_resource(server_url).await
&& let Ok(meta) = try_discover_from_auth_servers(&resource_meta).await
{
return Ok(meta);
}
// Strategy 3: Direct - treat MCP server as its own auth server
discover_authorization_server(server_url).await
}
/// Perform Dynamic Client Registration with an authorization server.
///
/// This allows clients to register themselves at runtime without pre-configured credentials.
pub async fn register_client(
registration_endpoint: &str,
redirect_uri: &str,
) -> Result<ClientRegistrationResponse, AuthError> {
validate_url_safe(registration_endpoint).await?;
let client = oauth_http_client()?;
let request = ClientRegistrationRequest {
client_name: "IronClaw".to_string(),
redirect_uris: vec![redirect_uri.to_string()],
grant_types: vec![
"authorization_code".to_string(),
"refresh_token".to_string(),
],
response_types: vec!["code".to_string()],
token_endpoint_auth_method: "none".to_string(), // Public client (no secret)
};
let response = client
.post(registration_endpoint)
.json(&request)
.send()
.await
.map_err(|e| AuthError::DiscoveryFailed(format!("DCR request failed: {}", e)))?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(AuthError::DiscoveryFailed(format!(
"DCR failed: HTTP {} - {}",
status, body
)));
}
response
.json()
.await
.map_err(|e| AuthError::DiscoveryFailed(format!("Invalid DCR response: {}", e)))
}
/// Perform the OAuth 2.1 authorization flow for an MCP server.
///
/// Supports two modes:
/// 1. Pre-configured OAuth: Uses the client_id from server config
/// 2. Dynamic Client Registration: Discovers and registers with the server automatically
///
/// Flow:
/// 1. Discovers authorization endpoints from the server
/// 2. If no client_id configured, attempts Dynamic Client Registration (DCR)
/// 3. Generates PKCE challenge
/// 4. Opens browser for user authorization
/// 5. Receives callback with authorization code
/// 6. Exchanges code for access token
/// 7. Stores token securely
pub async fn authorize_mcp_server(
server_config: &McpServerConfig,
secrets: &Arc<dyn SecretsStore + Send + Sync>,
user_id: &str,
) -> Result<AccessToken, AuthError> {
// Find an available port for the callback first (needed for DCR)
let (listener, port) = find_available_port().await?;
let host = oauth::callback_host();
let redirect_uri = format!("http://{}:{}/callback", host, port);
// Warn when the callback is served over plain HTTP to a remote host.
// Authorization codes travel unencrypted; SSH port forwarding is safer:
// ssh -L <port>:127.0.0.1:<port> user@your-server
if !oauth::is_loopback_host(&host) {
println!("Warning: MCP OAuth callback is using plain HTTP to a remote host ({host}).");
println!(" Authorization codes will be transmitted unencrypted.");
println!(" Consider SSH port forwarding instead:");
println!(" ssh -L {port}:127.0.0.1:{port} user@{host}");
}
// Determine client_id and endpoints
let (
client_id,
client_secret,
client_secret_expires_at,
authorization_url,
token_url,
use_pkce,
scopes,
mut extra_params,
) = if let Some(oauth) = &server_config.oauth {
// Pre-configured OAuth
let (auth_url, tok_url) = discover_oauth_endpoints(server_config).await?;
(
oauth.client_id.clone(),
None,
None,
auth_url,
tok_url,
oauth.use_pkce,
oauth.scopes.clone(),
oauth.extra_params.clone(),
)
} else {
// Try Dynamic Client Registration
println!(" Discovering OAuth endpoints...");
let auth_meta = discover_full_oauth_metadata(&server_config.url).await?;
let registration_endpoint = auth_meta
.registration_endpoint
.ok_or(AuthError::NotSupported)?;
println!(" Registering client dynamically...");
let registration = register_client(®istration_endpoint, &redirect_uri).await?;
println!(" Client registered: {}", registration.client_id);
(
registration.client_id,
registration.client_secret,
registration.client_secret_expires_at,
auth_meta.authorization_endpoint,
auth_meta.token_endpoint,
true, // Always use PKCE for DCR clients
auth_meta.scopes_supported,
HashMap::new(),
)
};
// Generate PKCE challenge
let pkce = if use_pkce {
Some(PkceChallenge::generate())
} else {
None
};
// Generate OAuth state parameter. While optional in OAuth 2.1 with PKCE,
// PKCE alone does not protect against login CSRF — an attacker can run a
// PKCE flow against their own account and trick the victim into linking
// attacker-controlled MCP credentials. We therefore both send `state` in
// the authorization URL and validate it on callback (see
// `wait_for_authorization_callback`). Some MCP servers (e.g. Attio) also
// require state to be present in the request.
let mut state_bytes = [0u8; 16];
rand::rngs::OsRng.fill_bytes(&mut state_bytes);
let state = URL_SAFE_NO_PAD.encode(state_bytes);
extra_params.insert("state".to_string(), state.clone());
// Compute canonical resource URI for RFC 8707
let resource = canonical_resource_uri(&server_config.url);
// Validate the discovered authorization URL to prevent a malicious MCP server
// from redirecting the user to a phishing page or non-HTTPS endpoint.
validate_url_safe(&authorization_url)
.await
.map_err(|e| AuthError::DiscoveryFailed(format!("Unsafe authorization endpoint: {}", e)))?;
// Build authorization URL
let auth_url = build_authorization_url(
&authorization_url,
&client_id,
&redirect_uri,
&scopes,
pkce.as_ref(),
&extra_params,
Some(&resource),
)?;
// Open browser
println!(" Opening browser for {} login...", server_config.name);
if let Err(e) = open::that(&auth_url) {
println!(" Could not open browser: {}", e);
println!(" Please open this URL manually:");
println!(" {}", auth_url);
}
println!(" Waiting for authorization...");
// Wait for callback. We require the server to echo `state` back and
// validate it: PKCE alone does not protect against login CSRF (see
// comment where `state` is generated above). A non-compliant MCP server
// that drops `state` will surface as a `StateMismatch` error rather than
// silently allowing the flow to complete under an attacker's session.
let code = wait_for_authorization_callback(listener, &server_config.name, Some(&state)).await?;
println!(" Exchanging code for token...");
// Exchange code for token
let token = exchange_code_for_token(
&token_url,
&client_id,
client_secret.as_deref(),
&code,
&redirect_uri,
pkce.as_ref(),
Some(&resource),
)
.await?;
// Store the tokens
store_tokens(secrets, user_id, server_config, &token).await?;
// Store the client_id for DCR (needed for token refresh)
if server_config.oauth.is_none() {
store_client_id(secrets, user_id, server_config, &client_id).await?;
if let Some(ref client_secret) = client_secret {
store_client_secret(
secrets,
user_id,
server_config,
client_secret,
client_secret_expires_at,
)
.await?;
}
}
Ok(token)
}
/// Bind the OAuth callback listener on the shared fixed port.
pub async fn find_available_port() -> Result<(TcpListener, u16), AuthError> {
let listener = oauth::bind_callback_listener()
.await
.map_err(|_| AuthError::PortUnavailable)?;
Ok((listener, OAUTH_CALLBACK_PORT))
}
/// Build the authorization URL with all required parameters.
///
/// Returns `Err(AuthError::MalformedConfig)` if `base_url` cannot be parsed.
/// A malformed authorization endpoint is a server/config bug that must be
/// surfaced to the operator, not concat-normalized into a half-valid URL
/// (gemini-code-assist review on #2746).
pub fn build_authorization_url(
base_url: &str,
client_id: &str,
redirect_uri: &str,
scopes: &[String],
pkce: Option<&PkceChallenge>,
extra_params: &HashMap<String, String>,
resource: Option<&str>,
) -> Result<String, AuthError> {
// Use the `url` crate for query-string encoding so every value flows
// through a single well-tested `application/x-www-form-urlencoded`
// serializer. See nearai/ironclaw#2391 for the parallel bug in the
// WASM-tool OAuth URL builder where manual string concat was dropping
// the last character of the final query parameter.
let mut url = Url::parse(base_url).map_err(|e| {
AuthError::MalformedConfig(format!(
"could not parse authorization URL {base_url:?}: {e}"
))
})?;
{
let mut qp = url.query_pairs_mut();
qp.append_pair("client_id", client_id);
qp.append_pair("response_type", "code");
qp.append_pair("redirect_uri", redirect_uri);
if !scopes.is_empty() {
qp.append_pair("scope", &scopes.join(" "));
}
if let Some(pkce) = pkce {
qp.append_pair("code_challenge", &pkce.challenge);
qp.append_pair("code_challenge_method", "S256");
}
for (key, value) in extra_params {
qp.append_pair(key, value);
}
if let Some(resource) = resource {
qp.append_pair("resource", resource);
}
}
Ok(url.into())
}
/// Wait for the authorization callback and extract the code.
///
/// `expected_state`, when supplied, is validated against the `state` query
/// parameter on the callback. A missing or mismatched `state` returns
/// `AuthError::Http("CSRF state mismatch ...")` rather than producing an
/// authorization code.
pub async fn wait_for_authorization_callback(
listener: TcpListener,
server_name: &str,
expected_state: Option<&str>,
) -> Result<String, AuthError> {
oauth::wait_for_callback(listener, "/callback", "code", server_name, expected_state)
.await
.map_err(|e| match e {
oauth::OAuthCallbackError::Denied => AuthError::AuthorizationDenied,
oauth::OAuthCallbackError::Timeout => AuthError::Timeout,
oauth::OAuthCallbackError::PortInUse(_, msg) => {
AuthError::Http(format!("Port error: {}", msg))
}
oauth::OAuthCallbackError::StateMismatch { .. } => {
AuthError::Http("CSRF state mismatch in OAuth callback".to_string())
}
oauth::OAuthCallbackError::Io(msg) => AuthError::Http(msg),
})
}
/// Exchange the authorization code for an access token.
pub async fn exchange_code_for_token(
token_url: &str,
client_id: &str,
client_secret: Option<&str>,
code: &str,
redirect_uri: &str,
pkce: Option<&PkceChallenge>,
resource: Option<&str>,
) -> Result<AccessToken, AuthError> {
validate_url_safe(token_url).await?;
let client = oauth_http_client()?;
let mut params = vec![
("grant_type", "authorization_code".to_string()),
("code", code.to_string()),
("redirect_uri", redirect_uri.to_string()),
("client_id", client_id.to_string()),
];
if let Some(secret) = client_secret {
params.push(("client_secret", secret.to_string()));
}