1use 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
16pub const DCR_MAX_CLIENTS: usize = 1000;
27
28pub 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#[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 #[serde(default)]
59 pub hyprstream_node_did: Option<String>,
60 #[serde(default)]
64 pub scope: Option<String>,
65}
66
67#[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
92pub 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 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 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 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 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 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 dpop_bound_access_tokens: None,
219 is_cimd: false,
220 registered_at: Instant::now(),
221 };
222
223 {
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#[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 #[serde(default)]
286 pub scope: Option<String>,
287 #[serde(default)]
291 pub dpop_bound_access_tokens: Option<bool>,
292}
293
294pub(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
323pub async fn resolve_cimd_client(
335 state: &OAuthState,
336 client_id_url: &str,
337) -> Result<RegisteredClient, String> {
338 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
357pub(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
380pub(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
390async 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
444pub(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
465pub async fn fetch_client_metadata(
471 state: &OAuthState,
472 client_id_url: &str,
473) -> Result<(RegisteredClient, Option<Duration>), String> {
474 if !client_id_url.starts_with("https://") {
476 return Err("Client ID Metadata Document URL must use HTTPS".to_owned());
477 }
478
479 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 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 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
539pub(crate) fn is_loopback_uri(uri: &str) -> bool {
541 if let Ok(url) = url::Url::parse(uri) {
542 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
555pub(crate) fn is_private_host_for_jwks(host: &str) -> bool {
558 is_private_host(host)
559}
560
561fn 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 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 return false;
596 };
597
598 match ip {
599 IpAddr::V4(v4) => {
600 v4.is_loopback()
601 || v4.is_private() || v4.is_link_local() || v4.is_unspecified() || v4.is_broadcast() || v4.is_multicast()
606 || (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 || (v6.segments()[0] & 0xfe00 == 0xfc00)
616 || (v6.segments()[0] & 0xffc0 == 0xfe80)
618 || 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
635pub fn validate_redirect_uri(requested: &str, registered: &[String]) -> bool {
639 if registered.contains(&requested.to_owned()) {
641 return true;
642 }
643
644 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 #[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 #[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 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 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 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 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 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")); }
888
889 #[test]
890 fn private_host_blocks_link_local_ipv4() {
891 assert!(is_private_host("169.254.169.254"));
893 assert!(is_private_host("169.254.0.1"));
894 assert!(!is_private_host("169.255.0.1"));
896 }
897
898 #[test]
899 fn private_host_blocks_cgnat() {
900 assert!(is_private_host("100.64.0.1"));
902 assert!(is_private_host("100.127.255.254"));
903 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 assert!(is_private_host("0:0:0:0:0:0:0:1"));
920 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 assert!(is_private_host("fc00::1"));
928 assert!(is_private_host("fd00::1"));
929 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 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 assert!(!is_private_host("::ffff:8.8.8.8"));
944 }
945
946 #[test]
947 fn private_host_passes_through_public_dns_names() {
948 assert!(!is_private_host("attacker.example.com"));
952 assert!(!is_private_host("github.com"));
953 }
954}