Skip to main content

hyprstream_core/services/oauth/
registration.rs

1//! OAuth 2.1 Client Registration (RFC 7591) and Client ID Metadata Documents.
2//!
3//! Two registration paths:
4//! - **Client ID Metadata Documents** (preferred): client_id is an HTTPS URL
5//! - **Dynamic Client Registration** (fallback): POST /oauth/register
6
7use std::sync::Arc;
8
9use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
10use serde::{Deserialize, Serialize};
11use std::time::Instant;
12
13use super::state::{OAuthState, RegisteredClient};
14use std::time::Duration;
15
16/// Maximum number of dynamically-registered (RFC 7591) clients held in
17/// `state.clients`. The DCR endpoint is unauthenticated by design (the
18/// whole point is bootstrapping new clients), so a hard cap bounds the
19/// memory amplifier even when an attacker pummels POST /oauth/register.
20/// CIMD clients are NOT counted here — they live in cimd_cache, which
21/// has its own capacity bound.
22///
23/// 1000 is comfortable for an operator with a handful of MCP clients
24/// per user and the occasional dev/test churn. Operators expecting more
25/// can override via configuration in a future change.
26pub const DCR_MAX_CLIENTS: usize = 1000;
27
28/// Maximum DCR field lengths to bound request-payload memory.
29pub const DCR_MAX_REDIRECT_URIS: usize = 16;
30pub const DCR_MAX_URI_LEN: usize = 2048;
31pub const DCR_MAX_NAME_LEN: usize = 256;
32
33/// Dynamic client registration request (RFC 7591 §3.1).
34///
35/// Only the fields hyprstream actually honors are deserialized; unknown
36/// fields are dropped per RFC 7591 §2 ("server MAY ignore them").
37#[derive(Debug, Deserialize)]
38pub struct RegistrationRequest {
39    pub redirect_uris: Vec<String>,
40    #[serde(default)]
41    pub client_name: Option<String>,
42    #[serde(default)]
43    pub client_uri: Option<String>,
44    #[serde(default)]
45    pub logo_uri: Option<String>,
46    #[serde(default)]
47    pub grant_types: Vec<String>,
48    #[serde(default)]
49    pub response_types: Vec<String>,
50    #[serde(default)]
51    pub token_endpoint_auth_method: Option<String>,
52    #[serde(default)]
53    pub jwks: Option<serde_json::Value>,
54    #[serde(default)]
55    pub jwks_uri: Option<String>,
56    /// Optional `did:key` generated from the host's iroh node ID. PDS
57    /// deployments use it to associate the OAuth device grant with the host.
58    #[serde(default)]
59    pub hyprstream_node_did: Option<String>,
60    /// Space-separated scope tokens this client intends to request (RFC 7591 /
61    /// RFC 6749 §3.3). Stored verbatim and enforced as the upper bound on
62    /// requested scopes at PAR/authorize (#1113 rev2 finding 4).
63    #[serde(default)]
64    pub scope: Option<String>,
65}
66
67/// Dynamic client registration response (RFC 7591 §3.2.1).
68#[derive(Debug, Serialize)]
69pub struct RegistrationResponse {
70    pub client_id: String,
71    pub redirect_uris: Vec<String>,
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub client_name: Option<String>,
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub client_uri: Option<String>,
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub logo_uri: Option<String>,
78    #[serde(skip_serializing_if = "Vec::is_empty")]
79    pub grant_types: Vec<String>,
80    #[serde(skip_serializing_if = "Vec::is_empty")]
81    pub response_types: Vec<String>,
82    #[serde(skip_serializing_if = "Option::is_none")]
83    pub token_endpoint_auth_method: Option<String>,
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub jwks: Option<serde_json::Value>,
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub jwks_uri: Option<String>,
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub scope: Option<String>,
90}
91
92/// POST /oauth/register — Dynamic Client Registration (RFC 7591)
93pub async fn register_client(
94    State(state): State<Arc<OAuthState>>,
95    Json(req): Json<RegistrationRequest>,
96) -> impl IntoResponse {
97    if req.redirect_uris.is_empty() {
98        return (
99            StatusCode::BAD_REQUEST,
100            Json(serde_json::json!({
101                "error": "invalid_client_metadata",
102                "error_description": "At least one redirect_uri is required"
103            })),
104        )
105            .into_response();
106    }
107
108    if req.redirect_uris.len() > DCR_MAX_REDIRECT_URIS {
109        return (
110            StatusCode::BAD_REQUEST,
111            Json(serde_json::json!({
112                "error": "invalid_client_metadata",
113                "error_description": format!(
114                    "Too many redirect_uris (max {DCR_MAX_REDIRECT_URIS})"
115                ),
116            })),
117        )
118            .into_response();
119    }
120
121    // Validate redirect URIs: loopback only, bounded length.
122    for uri in &req.redirect_uris {
123        if uri.len() > DCR_MAX_URI_LEN {
124            return (
125                StatusCode::BAD_REQUEST,
126                Json(serde_json::json!({
127                    "error": "invalid_redirect_uri",
128                    "error_description": format!("redirect_uri exceeds {DCR_MAX_URI_LEN} chars"),
129                })),
130            )
131                .into_response();
132        }
133        if !is_loopback_uri(uri) {
134            return (
135                StatusCode::BAD_REQUEST,
136                Json(serde_json::json!({
137                    "error": "invalid_redirect_uri",
138                    "error_description": "Only loopback redirect URIs are allowed (http://127.0.0.1:* or http://localhost:*)"
139                })),
140            ).into_response();
141        }
142    }
143
144    // Bound the display-name field (rendered on consent screen).
145    if let Some(name) = req.client_name.as_deref() {
146        if name.len() > DCR_MAX_NAME_LEN {
147            return (
148                StatusCode::BAD_REQUEST,
149                Json(serde_json::json!({
150                    "error": "invalid_client_metadata",
151                    "error_description": format!("client_name exceeds {DCR_MAX_NAME_LEN} chars"),
152                })),
153            )
154                .into_response();
155        }
156    }
157
158    // RFC 7591 §2.1: jwks and jwks_uri are mutually exclusive.
159    if req.jwks.is_some() && req.jwks_uri.is_some() {
160        return (
161            StatusCode::BAD_REQUEST,
162            Json(serde_json::json!({
163                "error": "invalid_client_metadata",
164                "error_description": "jwks and jwks_uri are mutually exclusive (RFC 7591 §2.1)"
165            })),
166        )
167            .into_response();
168    }
169
170    // If token_endpoint_auth_method requires a key, enforce key presence.
171    if matches!(
172        req.token_endpoint_auth_method.as_deref(),
173        Some("private_key_jwt")
174    ) && req.jwks.is_none()
175        && req.jwks_uri.is_none()
176    {
177        return (
178            StatusCode::BAD_REQUEST,
179            Json(serde_json::json!({
180                "error": "invalid_client_metadata",
181                "error_description": "private_key_jwt requires jwks or jwks_uri"
182            })),
183        )
184            .into_response();
185    }
186
187    // Validate host identity metadata before persisting it. Invalid did:key
188    // values must never become an attachable PDS principal.
189    if let Some(did) = req.hyprstream_node_did.as_deref() {
190        if hyprstream_crypto::did_key::did_key_to_ed25519(did).is_err() {
191            return (
192                StatusCode::BAD_REQUEST,
193                Json(serde_json::json!({
194                    "error": "invalid_client_metadata",
195                    "error_description": "hyprstream_node_did must be an Ed25519 did:key"
196                })),
197            )
198                .into_response();
199        }
200    }
201
202    let client_id = uuid::Uuid::new_v4().to_string();
203
204    let client = RegisteredClient {
205        client_id: client_id.clone(),
206        redirect_uris: req.redirect_uris.clone(),
207        client_name: req.client_name.clone(),
208        client_uri: req.client_uri.clone(),
209        logo_uri: req.logo_uri.clone(),
210        grant_types: req.grant_types.clone(),
211        response_types: req.response_types.clone(),
212        token_endpoint_auth_method: req.token_endpoint_auth_method.clone(),
213        jwks: req.jwks.clone(),
214        jwks_uri: req.jwks_uri.clone(),
215        hyprstream_node_did: req.hyprstream_node_did.clone(),
216        scope: req.scope.clone(),
217        // DCR (RFC 7591) requests do not carry this atproto CIMD field.
218        dpop_bound_access_tokens: None,
219        is_cimd: false,
220        registered_at: Instant::now(),
221    };
222
223    // Capacity gate: refuse new registrations when at DCR_MAX_CLIENTS.
224    // Hold the write lock across the size check + insert so two
225    // concurrent registrations can't both squeeze in at len == cap-1.
226    {
227        let mut clients = state.clients.write().await;
228        if clients.len() >= DCR_MAX_CLIENTS {
229            return (
230                StatusCode::SERVICE_UNAVAILABLE,
231                Json(serde_json::json!({
232                    "error": "registration_capacity_exhausted",
233                    "error_description": format!(
234                        "DCR client registry at capacity ({DCR_MAX_CLIENTS}). \
235                         Operator must rotate stale clients or migrate to CIMD."
236                    ),
237                })),
238            )
239                .into_response();
240        }
241        clients.insert(client_id.clone(), client);
242    }
243
244    Json(RegistrationResponse {
245        client_id,
246        redirect_uris: req.redirect_uris,
247        client_name: req.client_name,
248        client_uri: req.client_uri,
249        logo_uri: req.logo_uri,
250        grant_types: req.grant_types,
251        response_types: req.response_types,
252        token_endpoint_auth_method: req.token_endpoint_auth_method,
253        jwks: req.jwks,
254        jwks_uri: req.jwks_uri,
255        scope: req.scope,
256    })
257    .into_response()
258}
259
260/// Client ID Metadata Document (draft-ietf-oauth-client-id-metadata-document-00 §4).
261#[derive(Debug, Deserialize)]
262pub struct ClientIdMetadataDocument {
263    pub client_id: String,
264    pub redirect_uris: Vec<String>,
265    #[serde(default)]
266    pub client_name: Option<String>,
267    #[serde(default)]
268    pub client_uri: Option<String>,
269    #[serde(default)]
270    pub logo_uri: Option<String>,
271    #[serde(default)]
272    pub grant_types: Vec<String>,
273    #[serde(default)]
274    pub response_types: Vec<String>,
275    #[serde(default)]
276    pub token_endpoint_auth_method: Option<String>,
277    #[serde(default)]
278    pub jwks: Option<serde_json::Value>,
279    #[serde(default)]
280    pub jwks_uri: Option<String>,
281    /// Space-separated scope tokens the client declares (RFC 7591 §2 /
282    /// CIMD §4). Enforced as the ceiling on requested scopes at
283    /// PAR/authorize — without this a fetched CIMD client could request
284    /// any server-supported scope (#1146 T1.1).
285    #[serde(default)]
286    pub scope: Option<String>,
287    /// atproto OAuth: confidential clients declare
288    /// `dpop_bound_access_tokens: true`. Parsed and retained; enforcement
289    /// is follow-up work (#1146 T1.1).
290    #[serde(default)]
291    pub dpop_bound_access_tokens: Option<bool>,
292}
293
294/// Convert a validated Client ID Metadata Document into a
295/// [`RegisteredClient`]. Carries the declared `scope` ceiling and
296/// `dpop_bound_access_tokens` flag — dropping them here is what silently
297/// disabled the client-declared scope ceiling for fetched clients
298/// (#1146 T1.1). Factored out of [`fetch_client_metadata`] so the
299/// mapping is unit-testable without a live HTTP fetch.
300pub(crate) fn registered_client_from_cimd_doc(
301    client_id_url: &str,
302    doc: ClientIdMetadataDocument,
303) -> RegisteredClient {
304    RegisteredClient {
305        client_id: client_id_url.to_owned(),
306        redirect_uris: doc.redirect_uris,
307        client_name: doc.client_name,
308        client_uri: doc.client_uri,
309        logo_uri: doc.logo_uri,
310        grant_types: doc.grant_types,
311        response_types: doc.response_types,
312        token_endpoint_auth_method: doc.token_endpoint_auth_method,
313        jwks: doc.jwks,
314        jwks_uri: doc.jwks_uri,
315        hyprstream_node_did: None,
316        scope: doc.scope,
317        dpop_bound_access_tokens: doc.dpop_bound_access_tokens,
318        is_cimd: true,
319        registered_at: Instant::now(),
320    }
321}
322
323/// Resolve a CIMD client: cache-aside lookup, fetch on miss.
324///
325/// Hot-path entry point used by `/oauth/par` and `/oauth/authorize`.
326/// Returns the registered client (cached or freshly fetched + cached).
327///
328/// Trust gate (unified federation policy): before fetching unknown
329/// metadata from the network, the client_id URL's **origin** must pass
330/// a PolicyService `federation:register` check. Same gate used for peer
331/// entity statements — one trust decision for "isolated vs federated"
332/// per the atproto model. Fails CLOSED — any RPC error rejects the
333/// registration rather than silently degrading security posture.
334pub async fn resolve_cimd_client(
335    state: &OAuthState,
336    client_id_url: &str,
337) -> Result<RegisteredClient, String> {
338    // Cache hit short-circuits the policy check: the entry was admitted
339    // by policy at insert time and is governed by cache TTL. If
340    // operators flip policy mid-flight, they should also invalidate the
341    // cache (handled by a separate reload signal — out of scope for
342    // v1).
343    if let Some(cached) = state.cimd_cache.get(client_id_url).await {
344        return Ok(cached);
345    }
346
347    let origin = extract_origin(client_id_url)
348        .ok_or_else(|| format!("invalid client_id URL: {client_id_url}"))?;
349    check_federation_register(state, &origin).await?;
350
351    let (client, max_age) = fetch_client_metadata(state, client_id_url).await?;
352    let ttl = state.cimd_cache.clamp_ttl(max_age);
353    state.cimd_cache.insert(client.clone(), ttl).await;
354    Ok(client)
355}
356
357/// Extract the **origin** (scheme + host + non-default port) from a
358/// URL, per RFC 6454 §4 normalization rules. Returns `None` for
359/// malformed URLs or URLs without a host.
360///
361/// Default ports elide: `https://app.example.com:443` → `https://app.example.com`.
362/// Host is lowercased; scheme is already lowercased by url::Url.
363pub(crate) fn extract_origin(url: &str) -> Option<String> {
364    let parsed = url::Url::parse(url).ok()?;
365    let scheme = parsed.scheme();
366    let host = parsed.host_str()?;
367    let port = parsed.port();
368    let default_port = match scheme {
369        "https" => Some(443),
370        "http" => Some(80),
371        _ => None,
372    };
373    let host_lower = host.to_ascii_lowercase();
374    Some(match port {
375        Some(p) if Some(p) != default_port => format!("{scheme}://{host_lower}:{p}"),
376        _ => format!("{scheme}://{host_lower}"),
377    })
378}
379
380/// Crate-public alias of [`check_federation_register`] for callers
381/// outside this module (client_auth's defense-in-depth re-check at the
382/// token endpoint, FederationKeyResolver's peer trust gate).
383pub(crate) async fn check_federation_register_for_client_auth(
384    state: &OAuthState,
385    origin: &str,
386) -> Result<(), String> {
387    check_federation_register(state, origin).await
388}
389
390/// Consult PolicyService for `federation:register` on the given origin.
391/// Fails closed on RPC errors.
392///
393/// This is the **unified federation trust gate** (atproto-style: one
394/// decision for "isolated vs federated"). The same Casbin resource is
395/// checked at three points:
396///   - CIMD client metadata fetch  (resolve_cimd_client)
397///   - private_key_jwt token-endpoint re-check  (client_auth::resolve_keys)
398///   - Peer entity-statement fetch  (FederationKeyResolver::get_key,
399///     DiscoveryService::handle_get_entity_statement)
400///
401/// **Default posture is deny.** The shipped base policy has no
402/// `federation:register` allow rule; operators opt in by:
403///   - applying the `federation-open` template (any HTTPS origin allowed —
404///     covers both third-party clients AND remote peer servers), or
405///   - allowlisting specific origins:
406///     `p, *, *, federation:register:https://*.partner.org, check, allow`
407///
408/// The same rule covers a CIMD client at app.partner.org AND a peer
409/// hyprstream instance at hyprstream.partner.org.
410///
411/// PolicyService outage → reject, with operator-visible error. Security
412/// posture is preserved over availability of new federation registrations.
413async fn check_federation_register(state: &OAuthState, origin: &str) -> Result<(), String> {
414    use hyprstream_rpc_std::policy_client::PolicyCheck;
415    let resource = crate::auth::federation_registration_resource(origin)
416        .map_err(|error| format!("invalid federation origin policy resource: {error}"))?;
417    match state
418        .policy_client
419        .check(&PolicyCheck {
420            subject: String::new(),
421            domain: String::new(),
422            resource,
423            operation: "check".to_owned(),
424        })
425        .await
426    {
427        Ok(true) => Ok(()),
428        Ok(false) => Err(format!(
429            "federation origin {origin} is not permitted by policy (federation:register denied)"
430        )),
431        Err(e) => {
432            tracing::error!(
433                origin = %origin,
434                error = %e,
435                "PolicyService unreachable during federation:register check — failing closed"
436            );
437            Err(format!(
438                "PolicyService unreachable; federation registration rejected (fail-closed): {e}"
439            ))
440        }
441    }
442}
443
444/// Parse `Cache-Control: max-age=N` from response headers. `None` if
445/// absent, malformed, or directive set to `no-store`/`no-cache`/`private`
446/// (the cache will fall back to `min_ttl` in that case via `clamp_ttl`).
447pub(crate) fn extract_max_age(headers: &reqwest::header::HeaderMap) -> Option<Duration> {
448    let raw = headers.get(reqwest::header::CACHE_CONTROL)?.to_str().ok()?;
449    let mut max_age: Option<Duration> = None;
450    for part in raw.split(',') {
451        let part = part.trim();
452        let lower = part.to_ascii_lowercase();
453        if lower == "no-store" || lower == "no-cache" || lower == "private" {
454            return None;
455        }
456        if let Some(value) = lower.strip_prefix("max-age=") {
457            if let Ok(secs) = value.trim().parse::<u64>() {
458                max_age = Some(Duration::from_secs(secs));
459            }
460        }
461    }
462    max_age
463}
464
465/// Fetch and validate a Client ID Metadata Document from an HTTPS URL.
466///
467/// Returns `(client, max_age_from_cache_control)`; the latter is passed
468/// to `CimdCache::clamp_ttl` by the caller. Callers should usually go
469/// through [`resolve_cimd_client`] instead, which handles caching.
470pub async fn fetch_client_metadata(
471    state: &OAuthState,
472    client_id_url: &str,
473) -> Result<(RegisteredClient, Option<Duration>), String> {
474    // SSRF protection: must be HTTPS
475    if !client_id_url.starts_with("https://") {
476        return Err("Client ID Metadata Document URL must use HTTPS".to_owned());
477    }
478
479    // SSRF protection: block private/loopback IPs
480    if let Ok(url) = url::Url::parse(client_id_url) {
481        if let Some(host) = url.host_str() {
482            if is_private_host(host) {
483                return Err("Client ID URL must not point to private/loopback addresses".to_owned());
484            }
485        }
486    }
487
488    let response = state
489        .http_client
490        .get(client_id_url)
491        .header("Accept", "application/json")
492        .send()
493        .await
494        .map_err(|e| format!("Failed to fetch client metadata: {}", e))?;
495
496    if !response.status().is_success() {
497        return Err(format!(
498            "Client metadata fetch returned HTTP {}",
499            response.status()
500        ));
501    }
502
503    let max_age = extract_max_age(response.headers());
504
505    let doc: ClientIdMetadataDocument = response
506        .json()
507        .await
508        .map_err(|e| format!("Failed to parse client metadata: {}", e))?;
509
510    // Validate client_id in document matches the URL
511    if doc.client_id != client_id_url {
512        return Err(format!(
513            "client_id mismatch: document contains '{}' but URL is '{}'",
514            doc.client_id, client_id_url
515        ));
516    }
517
518    if doc.redirect_uris.is_empty() {
519        return Err("Client metadata must include at least one redirect_uri".to_owned());
520    }
521
522    // RFC 7591 §2.1 (mirrored by CIMD §4): jwks and jwks_uri are mutually exclusive.
523    if doc.jwks.is_some() && doc.jwks_uri.is_some() {
524        return Err("CIMD must not declare both jwks and jwks_uri".to_owned());
525    }
526
527    if matches!(
528        doc.token_endpoint_auth_method.as_deref(),
529        Some("private_key_jwt")
530    ) && doc.jwks.is_none()
531        && doc.jwks_uri.is_none()
532    {
533        return Err("CIMD declares token_endpoint_auth_method=private_key_jwt but provides no jwks/jwks_uri".to_owned());
534    }
535
536    Ok((registered_client_from_cimd_doc(client_id_url, doc), max_age))
537}
538
539/// Check if a redirect URI is a loopback address.
540pub(crate) fn is_loopback_uri(uri: &str) -> bool {
541    if let Ok(url) = url::Url::parse(uri) {
542        // Accept both http and https for loopback URIs (https is used with mkcert in dev)
543        if url.scheme() != "http" && url.scheme() != "https" {
544            return false;
545        }
546        matches!(
547            url.host_str(),
548            Some("127.0.0.1") | Some("localhost") | Some("[::1]")
549        )
550    } else {
551        false
552    }
553}
554
555/// Public re-export of `is_private_host` for sibling modules
556/// (client_auth) that need the same SSRF policy for fetches.
557pub(crate) fn is_private_host_for_jwks(host: &str) -> bool {
558    is_private_host(host)
559}
560
561/// Reject hosts that point at private/loopback/internal address space.
562///
563/// **Important defense-in-depth limitation**: this only inspects the
564/// hostname *as written in the URL*. It does NOT resolve DNS — a name
565/// like `attacker.example.com` that resolves to `127.0.0.1` (DNS
566/// rebinding / pinning attack) will pass this check. To close that
567/// hole we'd need a custom reqwest connector that resolves and re-
568/// checks the IP at connect time; tracked as separate hardening work.
569///
570/// What we DO block at the URL layer:
571///   - `localhost` literal
572///   - IPv4 literals in any of the IANA-reserved/private ranges
573///     (loopback, RFC1918, link-local, CGNAT)
574///   - IPv6 literals in loopback, ULA (fc00::/7), link-local
575///     (fe80::/10), unspecified, and IPv4-mapped equivalents of the
576///     above (e.g. `::ffff:127.0.0.1`)
577fn is_private_host(host: &str) -> bool {
578    use std::net::IpAddr;
579
580    if host.eq_ignore_ascii_case("localhost") {
581        return true;
582    }
583
584    // url::Url::host_str() returns IPv6 without surrounding brackets, but
585    // be tolerant in case a caller passes a bracketed form.
586    let stripped = host
587        .strip_prefix('[')
588        .and_then(|s| s.strip_suffix(']'))
589        .unwrap_or(host);
590
591    let Ok(ip) = stripped.parse::<IpAddr>() else {
592        // Hostname (not an IP literal). We can't safely classify without
593        // resolving — fall through to allow. The TLS + cert-chain check
594        // on connect is the real gate for hostname-based URLs.
595        return false;
596    };
597
598    match ip {
599        IpAddr::V4(v4) => {
600            v4.is_loopback()
601                || v4.is_private()        // RFC 1918: 10/8, 172.16/12, 192.168/16
602                || v4.is_link_local()     // 169.254/16
603                || v4.is_unspecified()    // 0.0.0.0
604                || v4.is_broadcast()      // 255.255.255.255
605                || v4.is_multicast()
606                // CGNAT (RFC 6598) — not in std::net's classifier as of
607                // current stable. 100.64.0.0/10.
608                || (v4.octets()[0] == 100 && (v4.octets()[1] & 0b1100_0000) == 0b0100_0000)
609        }
610        IpAddr::V6(v6) => {
611            v6.is_loopback()
612                || v6.is_unspecified()
613                || v6.is_multicast()
614                // ULA fc00::/7
615                || (v6.segments()[0] & 0xfe00 == 0xfc00)
616                // Link-local fe80::/10
617                || (v6.segments()[0] & 0xffc0 == 0xfe80)
618                // IPv4-mapped IPv6 (::ffff:0:0/96) — recurse into v4 check
619                || v6
620                    .to_ipv4_mapped()
621                    .map(|v4| {
622                        v4.is_loopback()
623                            || v4.is_private()
624                            || v4.is_link_local()
625                            || v4.is_unspecified()
626                            || v4.is_broadcast()
627                            || (v4.octets()[0] == 100
628                                && (v4.octets()[1] & 0b1100_0000) == 0b0100_0000)
629                    })
630                    .unwrap_or(false)
631        }
632    }
633}
634
635/// Validate a redirect_uri against a client's registered URIs.
636///
637/// Exact match required, except for loopback URIs where port is ignored per RFC 8252.
638pub fn validate_redirect_uri(requested: &str, registered: &[String]) -> bool {
639    // Try exact match first
640    if registered.contains(&requested.to_owned()) {
641        return true;
642    }
643
644    // For loopback URIs, ignore port per RFC 8252 section 7.3
645    if let (Ok(req_url), true) = (url::Url::parse(requested), is_loopback_uri(requested)) {
646        for reg in registered {
647            if let Ok(reg_url) = url::Url::parse(reg) {
648                if is_loopback_uri(reg)
649                    && req_url.scheme() == reg_url.scheme()
650                    && req_url.host_str() == reg_url.host_str()
651                    && req_url.path() == reg_url.path()
652                {
653                    return true;
654                }
655            }
656        }
657    }
658
659    false
660}
661
662#[cfg(test)]
663#[allow(clippy::unwrap_used, clippy::expect_used)]
664mod tests {
665    use super::*;
666
667    #[test]
668    fn cimd_parses_extended_fields() {
669        let json = serde_json::json!({
670            "client_id": "https://app.example.com/client.json",
671            "redirect_uris": ["http://127.0.0.1:3000/cb"],
672            "client_name": "Example",
673            "client_uri": "https://app.example.com",
674            "logo_uri": "https://app.example.com/logo.png",
675            "grant_types": ["authorization_code", "refresh_token"],
676            "response_types": ["code"],
677            "token_endpoint_auth_method": "none",
678        });
679        let doc: ClientIdMetadataDocument = serde_json::from_value(json).unwrap();
680        assert_eq!(doc.client_uri.as_deref(), Some("https://app.example.com"));
681        assert_eq!(
682            doc.logo_uri.as_deref(),
683            Some("https://app.example.com/logo.png")
684        );
685        assert_eq!(doc.grant_types, vec!["authorization_code", "refresh_token"]);
686        assert_eq!(doc.response_types, vec!["code"]);
687        assert_eq!(doc.token_endpoint_auth_method.as_deref(), Some("none"));
688    }
689
690    #[test]
691    fn cimd_drops_unknown_fields() {
692        let json = serde_json::json!({
693            "client_id": "https://app.example.com/client.json",
694            "redirect_uris": ["http://127.0.0.1:3000/cb"],
695            "future_extension": "ignored",
696            "policy_uri": "https://app.example.com/policy",
697        });
698        let doc: ClientIdMetadataDocument = serde_json::from_value(json).unwrap();
699        assert!(doc.client_name.is_none());
700    }
701
702    /// #1146 T1.1: a fetched CIMD document's declared `scope` MUST survive
703    /// into the `RegisteredClient` — dropping it silently disabled the
704    /// client-declared scope ceiling for the fetched-metadata path.
705    #[test]
706    fn cimd_scope_ceiling_carried_into_registered_client() {
707        let json = serde_json::json!({
708            "client_id": "https://app.example.com/client.json",
709            "redirect_uris": ["https://app.example.com/cb"],
710            "scope": "atproto",
711            "dpop_bound_access_tokens": true,
712        });
713        let doc: ClientIdMetadataDocument = serde_json::from_value(json).unwrap();
714        let client = registered_client_from_cimd_doc("https://app.example.com/client.json", doc);
715        assert!(client.is_cimd);
716        assert_eq!(client.scope.as_deref(), Some("atproto"));
717        assert_eq!(client.declared_scopes(), vec!["atproto".to_owned()]);
718        assert_eq!(client.dpop_bound_access_tokens, Some(true));
719    }
720
721    /// #1146 T1.1: a CIMD document with no `scope` field declares no
722    /// client-side ceiling (`None` → unrestricted), distinct from an
723    /// explicit declaration.
724    #[test]
725    fn cimd_without_scope_declares_no_ceiling() {
726        let json = serde_json::json!({
727            "client_id": "https://app.example.com/client.json",
728            "redirect_uris": ["https://app.example.com/cb"],
729        });
730        let doc: ClientIdMetadataDocument = serde_json::from_value(json).unwrap();
731        assert!(doc.scope.is_none());
732        assert!(doc.dpop_bound_access_tokens.is_none());
733        let client = registered_client_from_cimd_doc("https://app.example.com/client.json", doc);
734        assert!(client.scope.is_none());
735        assert!(client.declared_scopes().is_empty());
736    }
737
738    #[test]
739    fn registration_request_jwks_and_jwks_uri_default_empty() {
740        let json = serde_json::json!({
741            "redirect_uris": ["http://localhost:3000/cb"]
742        });
743        let req: RegistrationRequest = serde_json::from_value(json).unwrap();
744        assert!(req.jwks.is_none());
745        assert!(req.jwks_uri.is_none());
746        assert!(req.grant_types.is_empty());
747    }
748
749    #[test]
750    fn registration_response_omits_empty_fields() {
751        let resp = RegistrationResponse {
752            client_id: "abc".into(),
753            redirect_uris: vec!["http://localhost/cb".into()],
754            client_name: None,
755            client_uri: None,
756            logo_uri: None,
757            grant_types: vec![],
758            response_types: vec![],
759            token_endpoint_auth_method: None,
760            jwks: None,
761            jwks_uri: None,
762            scope: None,
763        };
764        let json = serde_json::to_value(&resp).unwrap();
765        let obj = json.as_object().unwrap();
766        assert!(!obj.contains_key("client_name"));
767        assert!(!obj.contains_key("jwks"));
768        assert!(!obj.contains_key("grant_types"));
769        assert!(obj.contains_key("client_id"));
770        assert!(obj.contains_key("redirect_uris"));
771    }
772
773    #[test]
774    fn loopback_uri_rejects_external() {
775        assert!(is_loopback_uri("http://127.0.0.1:8080/cb"));
776        assert!(is_loopback_uri("http://localhost:8080/cb"));
777        assert!(is_loopback_uri("http://[::1]:8080/cb"));
778        assert!(!is_loopback_uri("http://example.com/cb"));
779        assert!(!is_loopback_uri("ftp://localhost/cb"));
780    }
781
782    #[test]
783    fn extract_max_age_parses_cache_control() {
784        use reqwest::header::{HeaderMap, HeaderValue, CACHE_CONTROL};
785
786        let mut h = HeaderMap::new();
787        h.insert(CACHE_CONTROL, HeaderValue::from_static("max-age=3600"));
788        assert_eq!(extract_max_age(&h), Some(Duration::from_secs(3600)));
789
790        let mut h = HeaderMap::new();
791        h.insert(
792            CACHE_CONTROL,
793            HeaderValue::from_static("public, max-age=600, must-revalidate"),
794        );
795        assert_eq!(extract_max_age(&h), Some(Duration::from_secs(600)));
796
797        // no-store / no-cache / private force a None result (we fall back to min_ttl).
798        let mut h = HeaderMap::new();
799        h.insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
800        assert!(extract_max_age(&h).is_none());
801
802        let mut h = HeaderMap::new();
803        h.insert(
804            CACHE_CONTROL,
805            HeaderValue::from_static("max-age=300, no-cache"),
806        );
807        assert!(extract_max_age(&h).is_none());
808
809        // Missing header → None.
810        assert!(extract_max_age(&HeaderMap::new()).is_none());
811    }
812
813    #[test]
814    fn extract_origin_basic_forms() {
815        assert_eq!(
816            extract_origin("https://app.example.com/client.json").unwrap(),
817            "https://app.example.com"
818        );
819        assert_eq!(
820            extract_origin("https://app.example.com:8443/client.json").unwrap(),
821            "https://app.example.com:8443"
822        );
823        assert_eq!(
824            extract_origin("http://internal.test/client").unwrap(),
825            "http://internal.test"
826        );
827    }
828
829    #[test]
830    fn extract_origin_elides_default_ports() {
831        // RFC 6454 §4: default ports elide.
832        assert_eq!(
833            extract_origin("https://app.example.com:443/c").unwrap(),
834            "https://app.example.com"
835        );
836        assert_eq!(
837            extract_origin("http://app.example.com:80/c").unwrap(),
838            "http://app.example.com"
839        );
840    }
841
842    #[test]
843    fn extract_origin_lowercases_host() {
844        assert_eq!(
845            extract_origin("https://APP.Example.COM/c").unwrap(),
846            "https://app.example.com"
847        );
848    }
849
850    #[test]
851    fn extract_origin_rejects_malformed() {
852        assert!(extract_origin("not a url").is_none());
853        assert!(
854            extract_origin("https://").is_none(),
855            "URL without host must reject"
856        );
857    }
858
859    #[test]
860    fn private_host_blocks_rfc1918() {
861        assert!(is_private_host("localhost"));
862        assert!(is_private_host("127.0.0.1"));
863        assert!(is_private_host("10.0.0.1"));
864        assert!(is_private_host("192.168.1.1"));
865        assert!(!is_private_host("example.com"));
866        assert!(!is_private_host("8.8.8.8"));
867    }
868
869    #[test]
870    fn private_host_blocks_full_172_16_through_31() {
871        // RFC 1918 172.16.0.0/12 = 172.16-172.31 only
872        for octet in 16..=31 {
873            assert!(
874                is_private_host(&format!("172.{octet}.0.1")),
875                "172.{octet}.0.1 must block (RFC 1918)"
876            );
877        }
878    }
879
880    #[test]
881    fn private_host_does_not_overshoot_into_public_172() {
882        // The old `starts_with("172.2")` heuristic would block these
883        // public IPs. Regression guard.
884        assert!(!is_private_host("172.200.0.1"));
885        assert!(!is_private_host("172.32.0.1"));
886        assert!(!is_private_host("172.15.0.1")); // also outside RFC 1918
887    }
888
889    #[test]
890    fn private_host_blocks_link_local_ipv4() {
891        // 169.254/16
892        assert!(is_private_host("169.254.169.254"));
893        assert!(is_private_host("169.254.0.1"));
894        // 169.255 is OUTSIDE link-local
895        assert!(!is_private_host("169.255.0.1"));
896    }
897
898    #[test]
899    fn private_host_blocks_cgnat() {
900        // RFC 6598 100.64.0.0/10
901        assert!(is_private_host("100.64.0.1"));
902        assert!(is_private_host("100.127.255.254"));
903        // 100.128.0.1 is OUTSIDE CGNAT
904        assert!(!is_private_host("100.128.0.1"));
905        assert!(!is_private_host("100.63.0.1"));
906    }
907
908    #[test]
909    fn private_host_blocks_unspecified_and_broadcast() {
910        assert!(is_private_host("0.0.0.0"));
911        assert!(is_private_host("255.255.255.255"));
912    }
913
914    #[test]
915    fn private_host_blocks_ipv6_loopback_variants() {
916        assert!(is_private_host("::1"));
917        assert!(is_private_host("[::1]"));
918        // expanded forms
919        assert!(is_private_host("0:0:0:0:0:0:0:1"));
920        // bracketed expanded
921        assert!(is_private_host("[0:0:0:0:0:0:0:1]"));
922    }
923
924    #[test]
925    fn private_host_blocks_ipv6_ula_and_link_local() {
926        // ULA fc00::/7
927        assert!(is_private_host("fc00::1"));
928        assert!(is_private_host("fd00::1"));
929        // Link-local fe80::/10
930        assert!(is_private_host("fe80::1"));
931        assert!(is_private_host("febf::1"));
932    }
933
934    #[test]
935    fn private_host_blocks_ipv4_mapped_ipv6() {
936        // IPv4-mapped IPv6 must inherit IPv4 classification — these were
937        // the previous bypass.
938        assert!(is_private_host("::ffff:127.0.0.1"));
939        assert!(is_private_host("::ffff:10.0.0.1"));
940        assert!(is_private_host("::ffff:192.168.1.1"));
941        assert!(is_private_host("::ffff:169.254.169.254"));
942        // Public IPv4 mapped through IPv6 should still NOT block.
943        assert!(!is_private_host("::ffff:8.8.8.8"));
944    }
945
946    #[test]
947    fn private_host_passes_through_public_dns_names() {
948        // Hostnames (non-IP-literal) can't be classified without DNS.
949        // We fall through to allow — the TLS chain check on connect is
950        // the gate. Documented limitation.
951        assert!(!is_private_host("attacker.example.com"));
952        assert!(!is_private_host("github.com"));
953    }
954}