1use anyhow::Context as _;
7use base64::Engine as _;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10use std::sync::Arc;
11use std::time::{Duration, Instant};
12use tokio::sync::RwLock;
13
14use super::token_store::TokenStore;
15use super::user_service::UserService;
16use crate::auth::user_store::UserStore;
17use crate::config::OAuthConfig;
18use hyprstream_rpc_std::discovery_client::DiscoveryClient;
19use hyprstream_rpc_std::policy_client::PolicyClient;
20use hyprstream_util::{InsertIfAbsentNoEvictResult, TtlCache};
21
22use super::replay_key::ReplayKey;
23
24#[derive(Clone, Debug)]
25pub struct PublicGitCanaryRecord {
26 pub did: String,
27 pub rkey: String,
28}
29
30#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35pub(crate) enum DpopJtiAdmission {
36 Inserted,
37 Duplicate,
38 Full,
39 InvalidLifetime,
40}
41
42impl DpopJtiAdmission {
43 pub(crate) fn is_inserted(self) -> bool {
44 self == Self::Inserted
45 }
46}
47
48#[async_trait::async_trait]
50pub trait AtprotoDidDocumentResolver: Send + Sync {
51 async fn resolve_document(&self, did: &str) -> anyhow::Result<serde_json::Value>;
52}
53
54struct HttpAtprotoDidDocumentResolver {
55 plc: hyprstream_rpc::did_plc::DidPlcResolver<hyprstream_rpc::did_plc::HttpPlcFetcher>,
56 web: hyprstream_rpc::did_web::HttpDidDocFetcher,
57}
58
59#[async_trait::async_trait]
60impl AtprotoDidDocumentResolver for HttpAtprotoDidDocumentResolver {
61 async fn resolve_document(&self, did: &str) -> anyhow::Result<serde_json::Value> {
62 if hyprstream_rpc::did_plc::is_did_plc(did) {
63 return self.plc.resolve_document(did).await;
64 }
65 if did.starts_with("did:web:") {
66 use hyprstream_rpc::did_web::DidDocFetcher as _;
67 let url = hyprstream_rpc::did_web::did_web_to_url(did)?;
68 let doc = self.web.fetch(&url).await?;
69 anyhow::ensure!(
70 doc.get("id").and_then(serde_json::Value::as_str) == Some(did),
71 "did:web document id does not match requested DID"
72 );
73 return Ok(doc);
74 }
75 anyhow::bail!("unsupported ATProto account DID method")
76 }
77}
78
79struct DenyAtprotoDidDocumentResolver(String);
80
81#[async_trait::async_trait]
82impl AtprotoDidDocumentResolver for DenyAtprotoDidDocumentResolver {
83 async fn resolve_document(&self, _did: &str) -> anyhow::Result<serde_json::Value> {
84 anyhow::bail!("ATProto DID resolver is unavailable: {}", self.0)
85 }
86}
87
88fn atproto_did_resolver(config: &OAuthConfig) -> Arc<dyn AtprotoDidDocumentResolver> {
89 let build = (|| -> anyhow::Result<HttpAtprotoDidDocumentResolver> {
90 let ttl = Duration::from_secs(config.atproto_did_cache_ttl_secs);
91 let base = url::Url::parse(&config.atproto_plc_directory_url)?;
92 let plc_config = hyprstream_rpc::did_plc::PlcResolverConfig::new(base, ttl)?;
93 Ok(HttpAtprotoDidDocumentResolver {
94 plc: hyprstream_rpc::did_plc::DidPlcResolver::new(plc_config)?,
95 web: hyprstream_rpc::did_web::HttpDidDocFetcher::new(ttl)?,
96 })
97 })();
98 match build {
99 Ok(resolver) => Arc::new(resolver),
100 Err(error) => {
101 tracing::error!(%error, "ATProto DID resolver configuration rejected");
102 Arc::new(DenyAtprotoDidDocumentResolver(error.to_string()))
103 }
104 }
105}
106
107fn extract_rsa_jwk_from_der(pkcs8_der: &[u8], kid: &str) -> Option<serde_json::Value> {
111 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
112
113 let temp = tempfile::NamedTempFile::new().ok()?;
119 std::fs::write(temp.path(), pkcs8_der).ok()?;
120
121 let output = std::process::Command::new("openssl")
122 .args([
123 "pkey",
124 "-inform",
125 "DER",
126 "-in",
127 temp.path().to_str()?,
128 "-noout",
129 "-text",
130 ])
131 .stdout(std::process::Stdio::piped())
132 .stderr(std::process::Stdio::null())
133 .output()
134 .ok()?;
135
136 let text = String::from_utf8_lossy(&output.stdout);
139 let mut n_hex = String::new();
140 let mut in_modulus = false;
141
142 for line in text.lines() {
143 let trimmed = line.trim();
144 if trimmed.starts_with("Modulus:") || trimmed == "modulus:" {
145 in_modulus = true;
146 continue;
147 }
148 if trimmed.starts_with("Exponent:") || trimmed.starts_with("publicExponent:") {
149 in_modulus = false;
150 continue;
153 }
154 if in_modulus {
155 let hex_part: String = trimmed.chars().filter(char::is_ascii_hexdigit).collect();
157 n_hex.push_str(&hex_part);
158 }
159 }
160
161 if n_hex.is_empty() {
162 return None;
163 }
164
165 if n_hex.starts_with("00") && n_hex.len() > 2 {
167 n_hex = n_hex[2..].to_owned();
168 }
169
170 let n_bytes = hex::decode(&n_hex).ok()?;
171 let e_bytes = vec![0x01, 0x00, 0x01]; let n_b64 = URL_SAFE_NO_PAD.encode(&n_bytes);
174 let e_b64 = URL_SAFE_NO_PAD.encode(&e_bytes);
175
176 Some(serde_json::json!({
177 "kty": "RSA",
178 "use": "sig",
179 "alg": "RS256",
180 "kid": kid,
181 "n": n_b64,
182 "e": e_b64,
183 }))
184}
185
186#[derive(Debug, Clone)]
194pub struct RegisteredClient {
195 pub client_id: String,
196 pub redirect_uris: Vec<String>,
197 pub client_name: Option<String>,
198 pub client_uri: Option<String>,
200 pub logo_uri: Option<String>,
202 pub grant_types: Vec<String>,
205 pub response_types: Vec<String>,
207 pub token_endpoint_auth_method: Option<String>,
211 pub jwks: Option<serde_json::Value>,
215 pub jwks_uri: Option<String>,
217 pub hyprstream_node_did: Option<String>,
220 pub scope: Option<String>,
225 pub dpop_bound_access_tokens: Option<bool>,
230 pub is_cimd: bool,
232 pub registered_at: Instant,
233}
234
235impl RegisteredClient {
236 pub fn declared_scopes(&self) -> Vec<String> {
239 self.scope
240 .as_deref()
241 .map(|s| s.split_whitespace().map(str::to_owned).collect())
242 .unwrap_or_default()
243 }
244}
245
246#[derive(Debug, Clone)]
251pub struct PushedAuthRequest {
252 pub params: super::authorize::AuthorizeParams,
253 pub expires_at: Instant,
254}
255
256impl PushedAuthRequest {
257 pub fn is_expired(&self) -> bool {
258 Instant::now() > self.expires_at
259 }
260}
261
262#[derive(Debug, Clone)]
266pub struct AuthorizeBinding {
267 pub request: super::authorize::AuthorizeParams,
268}
269
270#[cfg(all(test, feature = "postgres"))]
271#[path = "federate_model_tests.rs"]
272mod federate_model_tests;
273
274#[cfg(all(test, feature = "postgres"))]
275#[path = "federate_tui_tests.rs"]
276mod federate_tui_tests;
277
278#[cfg(test)]
279#[allow(clippy::unwrap_used)]
280mod tests {
281 use super::*;
282 use crate::auth::user_store::UserProfile;
283 use async_trait::async_trait;
284 use hyprstream_rpc::crypto::CryptoPolicy;
285 use rand::rngs::OsRng;
286
287 #[cfg(feature = "postgres")]
288 #[test]
289 fn federate_issuer_is_disabled_at_construction() {
290 assert!(state_for_replay_barrier_tests().federate_issuer.is_none());
291 }
292
293 #[cfg(feature = "postgres")]
294 pub(super) fn composite_signer_fixture(
295 version: u64,
296 pairs: Vec<hyprstream_rpc::auth::CompositeKeyPair>,
297 ) -> (
298 tempfile::TempDir,
299 std::sync::Arc<hyprstream_rpc::auth::CompositeKeySet>,
300 ) {
301 use hyprstream_rpc::auth::CompositeKeySet;
302
303 let dir = tempfile::tempdir().unwrap();
304 let digest = format!("federate-test-generation-{version}");
305 let ledger = dir.path().join("ledger.json");
306 let committed = dir.path().join("committed.json");
307 let prefix = dir.path().join("committed-ledger");
308 let key_set = std::sync::Arc::new(CompositeKeySet::default());
309 key_set.configure_authority(
310 ledger.clone(),
311 committed.clone(),
312 prefix.clone(),
313 dir.path().join("ledger.lock"),
314 );
315 key_set.publish(version, digest.clone(), pairs).unwrap();
316 let generation = prefix.with_file_name(format!(
317 "{}-{version}-{digest}.json",
318 prefix.file_name().unwrap().to_str().unwrap()
319 ));
320 let contents = serde_json::json!({"version": version, "component_digest": digest});
321 std::fs::write(&ledger, serde_json::to_vec(&contents).unwrap()).unwrap();
322 std::fs::write(&generation, serde_json::to_vec(&contents).unwrap()).unwrap();
323 std::fs::write(&committed, serde_json::to_vec(&contents).unwrap()).unwrap();
324 (dir, key_set)
325 }
326
327 #[cfg(feature = "postgres")]
328 pub(super) fn oauth_signing_pair(seed: u8) -> hyprstream_rpc::auth::CompositeKeyPair {
329 use std::sync::Arc;
330 let ed = Arc::new(ed25519_dalek::SigningKey::from_bytes(&[seed; 32]));
331 let (pq, _) = hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair();
332 let pq = Arc::new(pq);
333 let kid = hyprstream_rpc::auth::composite_kid(
334 &ml_dsa::Keypair::verifying_key(&*pq),
335 &ed.verifying_key(),
336 );
337 hyprstream_rpc::auth::CompositeKeyPair::signing(
338 kid,
339 pq,
340 ed,
341 hyprstream_rpc::auth::CompositePairRole::OAuth,
342 hyprstream_rpc::auth::CompositePairState::Active,
343 0,
344 i64::MAX,
345 )
346 }
347
348 #[cfg(feature = "postgres")]
349 #[tokio::test]
350 async fn federate_signer_uses_authorized_hybrid_oauth_pair() {
351 let pair = oauth_signing_pair(0x43);
352 let (dir, key_set) = composite_signer_fixture(1, vec![pair.clone()]);
353 let signer = super::HybridFederateSigner::new(key_set).unwrap();
354 let now = chrono::Utc::now().timestamp();
355 let claims = hyprstream_rpc::auth::claims::Claims::new(
356 "did:plc:abcdefghijklmnopqrstuvwx".to_owned(),
357 now,
358 now + 60,
359 )
360 .with_issuer("https://local".to_owned())
361 .with_jti();
362
363 let token = super::super::federate_host::FederateSigner::sign(&signer, &claims)
364 .await
365 .unwrap();
366 let dispatch = hyprstream_rpc::auth::parse_composite_dispatch(&token, &["at+jwt"]).unwrap();
367 assert_eq!(dispatch.kid(), pair.kid());
368 let verified = hyprstream_rpc::auth::jwt::decode_composite(
369 &token,
370 pair.ml_dsa(),
371 pair.ed25519(),
372 None,
373 &dispatch,
374 )
375 .unwrap();
376 assert_eq!(verified.sub, claims.sub);
377 drop(dir);
378 }
379
380 #[cfg(feature = "postgres")]
381 #[tokio::test]
382 async fn federate_signer_uses_new_committed_pair_after_rotation() {
383 use hyprstream_rpc::auth::{CompositePairRole, CompositePairState};
384 let first = oauth_signing_pair(0x44);
385 let second = oauth_signing_pair(0x45);
386 let old_kid = first.kid().to_owned();
387 let (dir, key_set) = composite_signer_fixture(1, vec![first.clone()]);
388 let signer = super::HybridFederateSigner::new(std::sync::Arc::clone(&key_set)).unwrap();
389 let now = chrono::Utc::now().timestamp();
390 let claims = hyprstream_rpc::auth::claims::Claims::new(
391 "did:plc:abcdefghijklmnopqrstuvwx".to_owned(),
392 now,
393 now + 60,
394 )
395 .with_issuer("https://local".to_owned())
396 .with_jti();
397 let before = super::super::federate_host::FederateSigner::sign(&signer, &claims)
398 .await
399 .unwrap();
400 let before_dispatch =
401 hyprstream_rpc::auth::parse_composite_dispatch(&before, &["at+jwt"]).unwrap();
402 assert_eq!(before_dispatch.kid(), old_kid);
403
404 let (first_pq, first_ed) = first.signing_keys().unwrap();
405 let draining = hyprstream_rpc::auth::CompositeKeyPair::signing(
406 first.kid().to_owned(),
407 first_pq,
408 first_ed,
409 CompositePairRole::OAuth,
410 CompositePairState::Drain,
411 0,
412 i64::MAX,
413 );
414 let (version, digest) = (2, "federate-test-generation-2");
415 key_set
416 .publish(version, digest.to_owned(), vec![draining, second.clone()])
417 .unwrap();
418 let prefix = dir.path().join("committed-ledger");
419 let generation = prefix.with_file_name(format!("committed-ledger-{version}-{digest}.json"));
420 let contents = serde_json::json!({"version": version, "component_digest": digest});
421 std::fs::write(
422 dir.path().join("ledger.json"),
423 serde_json::to_vec(&contents).unwrap(),
424 )
425 .unwrap();
426 std::fs::write(generation, serde_json::to_vec(&contents).unwrap()).unwrap();
427 std::fs::write(
428 dir.path().join("committed.json"),
429 serde_json::to_vec(&contents).unwrap(),
430 )
431 .unwrap();
432
433 let after = super::super::federate_host::FederateSigner::sign(&signer, &claims)
434 .await
435 .unwrap();
436 let after_dispatch =
437 hyprstream_rpc::auth::parse_composite_dispatch(&after, &["at+jwt"]).unwrap();
438 assert_eq!(after_dispatch.kid(), second.kid());
439 assert_ne!(after_dispatch.kid(), old_kid);
440 let verified = hyprstream_rpc::auth::jwt::decode_composite(
441 &after,
442 second.ml_dsa(),
443 second.ed25519(),
444 None,
445 &after_dispatch,
446 )
447 .unwrap();
448 assert_eq!(verified.sub, claims.sub);
449 }
450
451 #[cfg(feature = "postgres")]
452 #[tokio::test]
453 async fn federate_signer_fails_closed_without_oauth_signing_key() {
454 let empty = std::sync::Arc::new(hyprstream_rpc::auth::CompositeKeySet::default());
455 assert!(super::HybridFederateSigner::new(empty).is_err());
456 }
457
458 #[cfg(feature = "postgres")]
459 #[tokio::test]
460 async fn federate_routes_deny_without_policy_adapter() {
461 let state = Arc::new(state_for_replay_barrier_tests());
462 let challenge = super::super::federate_host::challenge(
463 axum::extract::State(Arc::clone(&state)),
464 axum::http::HeaderMap::new(),
465 axum::body::Bytes::from_static(b"{}"),
466 )
467 .await;
468 assert_eq!(
469 challenge.status(),
470 axum::http::StatusCode::SERVICE_UNAVAILABLE
471 );
472 let exchange = super::super::federate_host::exchange(
473 &state,
474 &axum::http::HeaderMap::new(),
475 b"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange",
476 )
477 .await;
478 assert_eq!(
479 exchange.status(),
480 axum::http::StatusCode::SERVICE_UNAVAILABLE
481 );
482 }
483
484 fn state_with_user_store(store: Arc<dyn UserStore>) -> OAuthState {
485 use hyprstream_rpc::rpc_client::RpcClientImpl;
486 use hyprstream_rpc::signer::LocalSigner;
487 use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
488
489 let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x41; 32]);
490 let remote_key = ed25519_dalek::SigningKey::from_bytes(&[0x42; 32]).verifying_key();
491 let make_client = || {
492 Arc::new(
493 RpcClientImpl::new(
494 LocalSigner::new(signing_key.clone()),
495 LazyUdsTransport::new("/dev/null/oauth-eligibility-test.sock".into()),
496 Some(remote_key),
497 )
498 .with_response_verify_policy(CryptoPolicy::Classical),
499 )
500 };
501 let mut config = OAuthConfig::default();
502 config.external_url = Some("https://pds.example.test".to_owned());
503 OAuthState::new(
504 &config,
505 PolicyClient::new(make_client()),
506 DiscoveryClient::new(make_client()),
507 signing_key.verifying_key().to_bytes(),
508 )
509 .with_user_store(crate::auth::ProductionUserStore::for_test(store))
510 }
511
512 fn state_for_replay_barrier_tests() -> OAuthState {
513 use hyprstream_rpc::rpc_client::RpcClientImpl;
514 use hyprstream_rpc::signer::LocalSigner;
515 use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
516
517 let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x43; 32]);
518 let remote_key = ed25519_dalek::SigningKey::from_bytes(&[0x44; 32]).verifying_key();
519 let make_client = || {
520 Arc::new(
521 RpcClientImpl::new(
522 LocalSigner::new(signing_key.clone()),
523 LazyUdsTransport::new("/dev/null/replay-barrier-test.sock".into()),
524 Some(remote_key),
525 )
526 .with_response_verify_policy(CryptoPolicy::Classical),
527 )
528 };
529 OAuthState::new(
530 &OAuthConfig::default(),
531 PolicyClient::new(make_client()),
532 DiscoveryClient::new(make_client()),
533 signing_key.verifying_key().to_bytes(),
534 )
535 }
536
537 #[test]
538 fn replay_callers_keep_seen_jtis_after_a_full_barrier() {
539 let mut state = state_for_replay_barrier_tests();
540 state.dpop_jti_seen = TtlCache::new(2, 16);
541 let now = chrono::Utc::now().timestamp();
542
543 assert_eq!(
544 state.check_and_record_dpop_jti_admission("dpop-first", now),
545 DpopJtiAdmission::Inserted
546 );
547 assert_eq!(
548 state.check_and_record_dpop_jti_admission("dpop-second", now),
549 DpopJtiAdmission::Inserted
550 );
551 assert_eq!(
552 state.check_and_record_dpop_jti_admission("dpop-fresh-when-full", now),
553 DpopJtiAdmission::Full,
554 "a fresh DPoP JTI must be refused once the barrier is full"
555 );
556 assert_eq!(
557 state.check_and_record_dpop_jti_admission("dpop-first", now),
558 DpopJtiAdmission::Duplicate,
559 "a full barrier must not evict an earlier DPoP JTI"
560 );
561
562 state.assertion_jti_seen = TtlCache::new(2, 16);
563 let exp = now + 60;
564 assert!(state.check_and_record_assertion_jti("client", "assertion-first", exp));
565 assert!(state.check_and_record_assertion_jti("client", "assertion-second", exp));
566 assert!(
567 !state.check_and_record_assertion_jti("client", "assertion-fresh-when-full", exp),
568 "a fresh client assertion JTI must be refused once the barrier is full"
569 );
570 assert!(
571 !state.check_and_record_assertion_jti("client", "assertion-first", exp),
572 "a full barrier must not evict an earlier client assertion JTI"
573 );
574 }
575
576 #[test]
577 fn replay_caps_cover_maximum_admitted_future_skew() {
578 assert_eq!(OAuthState::DPOP_JTI_MAX_ENTRIES, 216_000);
579 assert_eq!(OAuthState::ASSERTION_JTI_MAX_ENTRIES, 43_200);
580
581 let state = state_for_replay_barrier_tests();
582 let now = chrono::Utc::now().timestamp();
583 assert!(state.check_and_record_dpop_jti("dpop-future-skew", now + 60));
584 assert!(state.check_and_record_assertion_jti("client", "assertion-future-skew", now + 360));
585 }
586
587 #[test]
588 fn extreme_replay_expirations_are_rejected_without_consuming_capacity() {
589 let mut state = state_for_replay_barrier_tests();
590 state.assertion_jti_seen = TtlCache::new(1, 16);
591 assert!(!state.check_and_record_assertion_jti("client", "min", i64::MIN));
592 assert!(!state.check_and_record_assertion_jti("client", "max", i64::MAX));
593 assert!(state.check_and_record_assertion_jti(
594 "client",
595 "ordinary",
596 chrono::Utc::now().timestamp() + 60
597 ));
598
599 state.atproto_service_jti_seen = TtlCache::new(1, 16);
600 assert!(!state.check_and_record_atproto_service_jti("did:plc:test", "min", i64::MIN));
601 assert!(!state.check_and_record_atproto_service_jti("did:plc:test", "max", i64::MAX));
602 assert!(state.check_and_record_atproto_service_jti(
603 "did:plc:test",
604 "ordinary",
605 chrono::Utc::now().timestamp() + 60
606 ));
607 }
608
609 struct KeyReadErrorStore {
610 profile: UserProfile,
611 fail_key_read: bool,
612 }
613
614 #[async_trait]
615 impl UserStore for KeyReadErrorStore {
616 async fn get_profile(&self, _username: &str) -> anyhow::Result<Option<UserProfile>> {
617 Ok(Some(self.profile.clone()))
618 }
619
620 async fn register(&self, _username: &str) -> anyhow::Result<String> {
621 anyhow::bail!("not used")
622 }
623
624 async fn set_profile(
625 &self,
626 _username: &str,
627 _profile: crate::auth::UserProfilePatch,
628 ) -> anyhow::Result<()> {
629 anyhow::bail!("not used")
630 }
631
632 async fn remove(&self, _username: &str) -> anyhow::Result<bool> {
633 anyhow::bail!("not used")
634 }
635
636 async fn list_users(&self) -> anyhow::Result<Vec<String>> {
637 Ok(Vec::new())
638 }
639
640 async fn search(
641 &self,
642 _filter: &crate::auth::user_store::UserFilter,
643 ) -> anyhow::Result<Vec<(String, UserProfile)>> {
644 anyhow::bail!("not used")
645 }
646
647 async fn set_active(&self, _username: &str, _active: bool) -> anyhow::Result<()> {
648 anyhow::bail!("not used")
649 }
650
651 async fn list_pubkeys(
652 &self,
653 _username: &str,
654 ) -> anyhow::Result<Vec<crate::auth::user_store::PubkeyEntry>> {
655 if self.fail_key_read {
656 anyhow::bail!("synthetic key read failure")
657 }
658 Ok(vec![crate::auth::user_store::PubkeyEntry {
659 fingerprint: "key1".to_owned(),
660 pubkey: ed25519_dalek::VerifyingKey::from_bytes(&[1u8; 32])?,
661 label: None,
662 created_at: 0,
663 last_used_at: None,
664 algorithm: crate::auth::user_store::KeyAlgorithm::Ed25519,
665 pq_pubkey: None,
666 }])
667 }
668
669 async fn add_pubkey(
670 &self,
671 _username: &str,
672 _pubkey: ed25519_dalek::VerifyingKey,
673 _label: Option<String>,
674 ) -> anyhow::Result<String> {
675 anyhow::bail!("not used")
676 }
677
678 async fn add_pubkey_hybrid(
679 &self,
680 _username: &str,
681 _pubkey: ed25519_dalek::VerifyingKey,
682 _ml_dsa_vk: Vec<u8>,
683 _label: Option<String>,
684 ) -> anyhow::Result<String> {
685 anyhow::bail!("not used")
686 }
687
688 async fn remove_pubkey(&self, _username: &str, _fingerprint: &str) -> anyhow::Result<bool> {
689 anyhow::bail!("not used")
690 }
691
692 async fn get_pubkey_user(&self, _fingerprint: &str) -> anyhow::Result<Option<String>> {
693 anyhow::bail!("not used")
694 }
695
696 async fn touch_pubkey(&self, _username: &str, _fingerprint: &str) -> anyhow::Result<()> {
697 anyhow::bail!("not used")
698 }
699 }
700
701 #[test]
702 fn mesh_kem_derivation_failure_fails_closed_under_hybrid() {
703 let key = ed25519_dalek::SigningKey::generate(&mut OsRng);
704 let err = mesh_kem_public_for_policy(&key, CryptoPolicy::Hybrid, |_| {
705 Err(anyhow::anyhow!("synthetic derivation failure"))
706 })
707 .unwrap_err();
708
709 assert!(
710 err.to_string().contains("Hybrid policy"),
711 "unexpected error: {err:?}",
712 );
713 }
714
715 #[test]
716 fn mesh_kem_derivation_failure_is_empty_under_classical() {
717 let key = ed25519_dalek::SigningKey::generate(&mut OsRng);
718 let public = mesh_kem_public_for_policy(&key, CryptoPolicy::Classical, |_| {
719 Err(anyhow::anyhow!("synthetic derivation failure"))
720 })
721 .unwrap();
722
723 assert!(public.is_none());
724 }
725
726 #[test]
730 fn subject_did_for_local_username_rejected() {
731 let err = subject_did_for("https://pds.example.com", "alice").unwrap_err();
732 assert_eq!(err, SubjectDidError::NoAtprotoIdentity);
733 }
734
735 #[test]
737 fn subject_did_for_did_plc_accepted() {
738 assert_eq!(
739 subject_did_for("https://x", "did:plc:abcdefghijklmnqrstuvwx2p").unwrap(),
740 "did:plc:abcdefghijklmnqrstuvwx2p"
741 );
742 }
743
744 #[test]
746 fn subject_did_for_host_form_did_web_accepted() {
747 assert_eq!(
748 subject_did_for("https://x", "did:web:pds.example.com").unwrap(),
749 "did:web:pds.example.com"
750 );
751 assert_eq!(
752 subject_did_for("https://x", "did:web:127.0.0.1:6791").unwrap(),
753 "did:web:127.0.0.1:6791"
754 );
755 }
756
757 #[test]
760 fn subject_did_for_path_form_did_web_rejected() {
761 let err = subject_did_for("https://x", "did:web:pds.example.com:users:alice").unwrap_err();
762 assert_eq!(err, SubjectDidError::PathFormDidWeb);
763 }
764
765 #[test]
768 fn subject_did_for_at9p_fails_closed() {
769 let err = subject_did_for("https://pds.example.com", "did:at9p:abc").unwrap_err();
770 assert_eq!(err, SubjectDidError::UnsupportedMethod);
771 }
772
773 #[test]
775 fn subject_did_for_malformed_plc_rejected() {
776 let err = subject_did_for("https://x", "did:plc:").unwrap_err();
777 assert_eq!(err, SubjectDidError::MalformedDid);
778 }
779
780 #[test]
784 fn subject_did_for_short_plc_rejected() {
785 let err = subject_did_for("https://x", "did:plc:abc123xyz").unwrap_err();
786 assert_eq!(err, SubjectDidError::MalformedDid);
787 }
788
789 #[test]
792 fn atproto_eligibility_mapped_did_plc_succeeds() {
793 use crate::auth::user_store::{KeyAlgorithm, PubkeyEntry, UserProfile};
794 let pubkeys = vec![PubkeyEntry {
795 fingerprint: "key1".into(),
796 pubkey: ed25519_dalek::VerifyingKey::from_bytes(&[1u8; 32]).unwrap(),
797 label: None,
798 created_at: 0,
799 last_used_at: None,
800 algorithm: KeyAlgorithm::Ed25519,
801 pq_pubkey: None,
802 }];
803 let mut profile = UserProfile::default();
804 profile.atproto_did = Some("did:plc:abcdefghijklmnqrstuvwx2p".into());
805 let did = evaluate_atproto_eligibility(&pubkeys, Some(&profile), "https://x").unwrap();
806 assert_eq!(did, "did:plc:abcdefghijklmnqrstuvwx2p");
807 }
808
809 #[test]
810 fn atproto_eligibility_rejects_inactive_account() {
811 use crate::auth::user_store::{KeyAlgorithm, PubkeyEntry, UserProfile};
812 let pubkeys = vec![PubkeyEntry {
813 fingerprint: "key1".into(),
814 pubkey: ed25519_dalek::VerifyingKey::from_bytes(&[1u8; 32]).unwrap(),
815 label: None,
816 created_at: 0,
817 last_used_at: None,
818 algorithm: KeyAlgorithm::Ed25519,
819 pq_pubkey: None,
820 }];
821 let mut profile = UserProfile::default();
822 profile.active = Some(false);
823 profile.atproto_did = Some("did:plc:abcdefghijklmnqrstuvwx2p".into());
824 let err = evaluate_atproto_eligibility(&pubkeys, Some(&profile), "https://x").unwrap_err();
825 assert_eq!(err, SubjectDidError::InactiveAccount);
826 }
827
828 #[test]
830 fn atproto_eligibility_no_mapping_fails_closed() {
831 use crate::auth::user_store::{KeyAlgorithm, PubkeyEntry, UserProfile};
832 let pubkeys = vec![PubkeyEntry {
833 fingerprint: "key1".into(),
834 pubkey: ed25519_dalek::VerifyingKey::from_bytes(&[1u8; 32]).unwrap(),
835 label: None,
836 created_at: 0,
837 last_used_at: None,
838 algorithm: KeyAlgorithm::Ed25519,
839 pq_pubkey: None,
840 }];
841 let profile = UserProfile::default();
842 let err = evaluate_atproto_eligibility(&pubkeys, Some(&profile), "https://x").unwrap_err();
843 assert_eq!(err, SubjectDidError::NoAtprotoIdentity);
844 }
845
846 #[test]
849 fn atproto_eligibility_at9p_account_rejected() {
850 use crate::auth::user_store::{KeyAlgorithm, PubkeyEntry, UserProfile};
851 let pubkeys = vec![PubkeyEntry {
852 fingerprint: "pq-key".into(),
853 pubkey: ed25519_dalek::VerifyingKey::from_bytes(&[1u8; 32]).unwrap(),
854 label: None,
855 created_at: 0,
856 last_used_at: None,
857 algorithm: KeyAlgorithm::HybridEd25519MlDsa65,
858 pq_pubkey: Some(vec![0u8; 1952]), }];
860 let mut profile = UserProfile::default();
861 profile.atproto_did = Some("did:plc:abcdefghijklmnqrstuvwx2p".into());
863 let err = evaluate_atproto_eligibility(&pubkeys, Some(&profile), "https://x").unwrap_err();
864 assert_eq!(err, SubjectDidError::At9pBackedAccount);
865 }
866
867 #[cfg(feature = "rocksdb")]
871 #[tokio::test]
872 async fn atproto_eligibility_succeeds_after_rocksdb_roundtrip() {
873 use crate::auth::rocksdb_store::RocksDbUserStore;
874 use crate::auth::user_store::UserProfile;
875 use tempfile::TempDir;
876
877 let dir = TempDir::new().unwrap();
878 let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x33; 32]);
879 {
880 let store = RocksDbUserStore::open(dir.path()).unwrap();
881 store.register("alice").await.unwrap();
882 store
883 .add_pubkey(
884 "alice",
885 signing_key.verifying_key(),
886 Some("login".to_owned()),
887 )
888 .await
889 .unwrap();
890 store
891 .set_profile(
892 "alice",
893 UserProfile {
894 atproto_did: Some("did:plc:abcdefghijklmnqrstuvwx2p".to_owned()),
895 ..Default::default()
896 }
897 .into(),
898 )
899 .await
900 .unwrap();
901 }
902
903 let reopened: Arc<dyn UserStore> = Arc::new(RocksDbUserStore::open(dir.path()).unwrap());
904 assert_eq!(
905 reopened
906 .get_profile("alice")
907 .await
908 .unwrap()
909 .unwrap()
910 .atproto_did
911 .as_deref(),
912 Some("did:plc:abcdefghijklmnqrstuvwx2p")
913 );
914 let state = state_with_user_store(reopened);
915 assert_eq!(
916 state
917 .check_atproto_account_eligibility("alice")
918 .await
919 .unwrap(),
920 "did:plc:abcdefghijklmnqrstuvwx2p"
921 );
922 }
923
924 #[tokio::test]
928 async fn atproto_eligibility_key_read_error_fails_closed() {
929 let store = Arc::new(KeyReadErrorStore {
930 profile: UserProfile {
931 atproto_did: Some("did:plc:abcdefghijklmnqrstuvwx2p".to_owned()),
932 ..Default::default()
933 },
934 fail_key_read: true,
935 });
936 let state = state_with_user_store(store);
937 assert_eq!(
938 state
939 .check_atproto_account_eligibility("alice")
940 .await
941 .unwrap_err(),
942 SubjectDidError::NoAtprotoIdentity
943 );
944 }
945
946 #[test]
949 fn atproto_profile_detection() {
950 assert!(atproto_profile_active(&["atproto".to_owned()]));
951 assert!(atproto_profile_active(&[
952 "atproto".to_owned(),
953 "read:*:*".to_owned()
954 ]));
955 assert!(!atproto_profile_active(&["read:*:*".to_owned()]));
956 assert!(!atproto_profile_active(&[]));
957 }
958
959 #[tokio::test]
960 async fn authorize_binding_sweep_tracks_live_nonces() {
961 let store = Arc::new(KeyReadErrorStore {
962 profile: UserProfile::default(),
963 fail_key_read: true,
964 });
965 let state = state_with_user_store(store);
966 let binding = AuthorizeBinding {
967 request: crate::services::oauth::authorize::AuthorizeParams {
968 client_id: "client".to_owned(),
969 redirect_uri: "https://client.example/callback".to_owned(),
970 code_challenge: "challenge".to_owned(),
971 code_challenge_method: "S256".to_owned(),
972 response_type: "code".to_owned(),
973 state: None,
974 scope: Some("read:*:*".to_owned()),
975 resource: None,
976 nonce: None,
977 dpop_jkt: None,
978 client_assertion_jkt: None,
979 },
980 };
981 let now = Instant::now();
982 state
983 .pending_nonces
984 .write()
985 .await
986 .insert("live".to_owned(), now + Duration::from_secs(60));
987 state
988 .pending_nonces
989 .write()
990 .await
991 .insert("expired".to_owned(), now - Duration::from_secs(1));
992 let mut bindings = state.pending_authorize_bindings.write().await;
993 bindings.insert("live".to_owned(), binding.clone());
994 bindings.insert("expired".to_owned(), binding.clone());
995 bindings.insert("orphan".to_owned(), binding);
996 drop(bindings);
997
998 state.sweep_authorize_sessions(now).await;
999
1000 let bindings = state.pending_authorize_bindings.read().await;
1001 assert_eq!(bindings.len(), 1);
1002 assert!(bindings.contains_key("live"));
1003 }
1004
1005 #[tokio::test]
1006 async fn inactive_linked_hosted_account_is_rejected_during_token_binding_resolution() {
1007 let store = Arc::new(KeyReadErrorStore {
1008 profile: UserProfile {
1009 active: Some(false),
1010 atproto_did: Some("did:plc:abcdefghijklmnqrstuvwx2p".to_owned()),
1011 ..Default::default()
1012 },
1013 fail_key_read: false,
1014 });
1015 let state = state_with_user_store(store);
1016 assert_eq!(
1017 state
1018 .check_atproto_account_eligibility("alice")
1019 .await
1020 .unwrap_err(),
1021 SubjectDidError::InactiveAccount
1022 );
1023 }
1024
1025 #[test]
1029 fn validate_requested_scopes_rejects_garbage() {
1030 let server = [
1031 "atproto".to_owned(),
1032 "transition:generic".to_owned(),
1033 "read:*:*".to_owned(),
1034 ];
1035 let res = validate_requested_scopes(
1036 &["atproto".to_owned(), "bogus".to_owned()],
1037 &server,
1038 None,
1039 true,
1040 );
1041 assert_eq!(res.unwrap_err(), ScopeError::InvalidScope);
1042 }
1043
1044 #[test]
1047 fn validate_requested_scopes_intersects_client_declared() {
1048 let server = [
1049 "atproto".to_owned(),
1050 "transition:generic".to_owned(),
1051 "read:*:*".to_owned(),
1052 ];
1053 let declared = ["atproto".to_owned(), "read:*:*".to_owned()];
1054 let granted = validate_requested_scopes(
1055 &["atproto".to_owned(), "read:*:*".to_owned()],
1056 &server,
1057 Some(&declared),
1058 true,
1059 )
1060 .unwrap();
1061 assert_eq!(granted, vec!["atproto".to_owned(), "read:*:*".to_owned()]);
1062 let res = validate_requested_scopes(
1064 &["atproto".to_owned(), "transition:generic".to_owned()],
1065 &server,
1066 Some(&declared),
1067 true,
1068 );
1069 assert_eq!(res.unwrap_err(), ScopeError::InvalidScope);
1070 }
1071
1072 #[test]
1075 fn validate_requested_scopes_requires_atproto_when_profile_active() {
1076 let server = ["atproto".to_owned(), "read:*:*".to_owned()];
1077 let res = validate_requested_scopes(&["read:*:*".to_owned()], &server, None, true);
1078 assert_eq!(res.unwrap_err(), ScopeError::AtprotoRequired);
1079 let granted =
1081 validate_requested_scopes(&["read:*:*".to_owned()], &server, None, false).unwrap();
1082 assert_eq!(granted, vec!["read:*:*".to_owned()]);
1083 }
1084
1085 #[test]
1089 fn canonical_issuer_origin_strips_path_and_slash() {
1090 assert_eq!(
1091 canonical_issuer_origin("https://pds.example.com/").as_deref(),
1092 Some("https://pds.example.com")
1093 );
1094 assert_eq!(
1095 canonical_issuer_origin("https://pds.example.com/oauth/par").as_deref(),
1096 Some("https://pds.example.com")
1097 );
1098 assert_eq!(
1099 canonical_issuer_origin("http://127.0.0.1:6791").as_deref(),
1100 Some("http://127.0.0.1:6791")
1101 );
1102 assert!(canonical_issuer_origin("pds.example.com").is_none());
1103 }
1104
1105 #[test]
1106 fn atproto_service_did_matches_browser_origin_encoding() {
1107 assert_eq!(
1108 atproto_service_did_for_origin("https://pds.example.test").as_deref(),
1109 Some("did:web:pds.example.test")
1110 );
1111 assert_eq!(
1112 atproto_service_did_for_origin("https://pds.example.test/oauth/par").as_deref(),
1113 Some("did:web:pds.example.test")
1114 );
1115 assert_eq!(
1116 atproto_service_did_for_origin("https://pds.example.test:443/oauth/par").as_deref(),
1117 Some("did:web:pds.example.test")
1118 );
1119 assert_eq!(
1120 atproto_service_did_for_origin("https://pds.example.test:8443/oauth/par").as_deref(),
1121 Some("did:web:pds.example.test%3A8443")
1122 );
1123 assert_eq!(
1124 atproto_service_did_for_origin("http://127.0.0.1:6791").as_deref(),
1125 Some("did:web:127.0.0.1%3A6791")
1126 );
1127 assert!(atproto_service_did_for_origin("https://[::1]:8443").is_none());
1128 assert!(atproto_service_did_for_origin("ftp://pds.example.test").is_none());
1129 }
1130
1131 #[test]
1135 fn default_scopes_do_not_include_atproto() {
1136 let cfg = crate::config::OAuthConfig::default();
1137 assert!(
1138 !cfg.default_scopes.iter().any(|s| s == "atproto"),
1139 "default_scopes must NOT include atproto (supported-but-explicit): {:?}",
1140 cfg.default_scopes
1141 );
1142 let supported = advertised_scopes_for_test(&cfg.default_scopes);
1144 assert!(supported.iter().any(|s| s == "atproto"));
1145 assert!(supported.iter().any(|s| s == "transition:generic"));
1146 }
1147
1148 fn advertised_scopes_for_test(default_scopes: &[String]) -> Vec<String> {
1150 let mut scopes = default_scopes.to_vec();
1151 for s in &["atproto", "transition:generic"] {
1152 if !scopes.iter().any(|x| x == *s) {
1153 scopes.push((*s).to_owned());
1154 }
1155 }
1156 scopes
1157 }
1158}
1159
1160#[derive(Debug, Clone)]
1162pub struct PendingAuthCode {
1163 pub code: String,
1164 pub client_id: String,
1165 pub redirect_uri: String,
1166 pub code_challenge: String,
1167 pub scopes: Vec<String>,
1168 pub resource: Option<String>,
1170 pub oidc_nonce: Option<String>,
1172 pub created_at: Instant,
1173 pub expires_at: Instant,
1174 pub username: String,
1177 pub verifying_key: Option<ed25519_dalek::VerifyingKey>,
1180 pub dpop_jkt: Option<String>,
1184 pub client_assertion_jkt: Option<String>,
1189}
1190
1191impl PendingAuthCode {
1192 pub fn is_expired(&self) -> bool {
1193 Instant::now() > self.expires_at
1194 }
1195}
1196
1197#[derive(Debug, Clone)]
1202pub struct PendingExternalAuth {
1203 pub provider_slug: String,
1204 pub external_state: String,
1205 pub external_nonce: String,
1206 pub provider_kind: crate::config::ProviderKind,
1208 pub pkce_supported: bool,
1210 pub pkce_verifier: String,
1211 pub client_secret: Option<String>,
1212 pub token_endpoint: String,
1213 pub original_request: Option<super::authorize::AuthorizeParams>,
1215 pub federate_owner_link: Option<PendingFederateOwnerLink>,
1219 pub created_at: Instant,
1220 pub expires_at: Instant,
1221}
1222
1223#[derive(Debug, Clone)]
1224pub struct PendingFederateOwnerLink {
1225 pub session_id: String,
1226 pub owner_did: String,
1227 pub username: String,
1228 pub hosted_did: String,
1229 pub tenant: String,
1230 pub return_origin: String,
1231}
1232
1233#[derive(Debug, Clone, PartialEq, Eq)]
1235pub enum DeviceCodeStatus {
1236 Pending,
1238 Approved,
1240 Denied,
1242}
1243
1244#[derive(Debug, Clone)]
1246pub struct PendingDeviceCode {
1247 pub device_code: String,
1248 pub user_code: String,
1249 pub client_id: String,
1250 pub scopes: Vec<String>,
1251 pub resource: Option<String>,
1253 pub status: DeviceCodeStatus,
1254 pub created_at: Instant,
1255 pub expires_at: Instant,
1256 pub interval: u64,
1258 pub last_polled: Option<Instant>,
1260 pub nonce: String,
1262 pub approved_by: Option<String>,
1264 pub verifying_key: Option<ed25519_dalek::VerifyingKey>,
1267}
1268
1269impl PendingDeviceCode {
1270 pub fn is_expired(&self) -> bool {
1271 Instant::now() > self.expires_at
1272 }
1273}
1274
1275#[derive(Debug, Clone, Serialize, Deserialize)]
1277pub struct RefreshTokenEntry {
1278 pub client_id: String,
1279 pub username: String,
1281 pub scopes: Vec<String>,
1282 pub resource: Option<String>,
1283 pub expires_at_unix: i64,
1285 pub verifying_key_bytes: Option<[u8; 32]>,
1287 #[serde(default)]
1290 pub dpop_jkt: Option<String>,
1291 #[serde(default)]
1297 pub client_assertion_jkt: Option<String>,
1298 #[serde(default)]
1308 pub ucan_grant: Option<UcanGrantRefresh>,
1309 #[serde(default)]
1315 pub session_id: Option<String>,
1316}
1317
1318#[derive(Debug, Clone, Serialize, Deserialize)]
1323pub struct UcanGrantRefresh {
1324 pub grant_cbor_b64: String,
1327 pub grant_cid: String,
1331 pub requested_scope: Option<String>,
1334 pub audience: Option<String>,
1336}
1337
1338impl RefreshTokenEntry {
1339 pub fn is_expired(&self) -> bool {
1340 chrono::Utc::now().timestamp() > self.expires_at_unix
1341 }
1342}
1343
1344pub struct OAuthState {
1346 pub(crate) browser_provisioning_signer: Option<Arc<hyprstream_rpc::crypto::SigningKey>>,
1349 pub(crate) browser_provisioning_rate_limiter: Arc<crate::server::middleware::RateLimiter>,
1350 #[cfg(feature = "postgres")]
1353 pub(crate) federate_issuer: Option<Arc<super::federate_host::FederateIssuer>>,
1354 pub clients: RwLock<HashMap<String, RegisteredClient>>,
1359 pub cimd_cache: Arc<super::cimd_cache::CimdCache>,
1363 pub jwks_uri_cache: RwLock<HashMap<String, (serde_json::Value, Instant)>>,
1369 pub client_jwks_uri_cache_ttl: Duration,
1372 pub pending_codes: RwLock<HashMap<String, PendingAuthCode>>,
1374 pub pending_nonces: RwLock<HashMap<String, Instant>>,
1377 pub pending_authorize_bindings: RwLock<HashMap<String, AuthorizeBinding>>,
1380 pub pending_par_requests: RwLock<HashMap<String, super::state::PushedAuthRequest>>,
1383 pub pending_device_codes: RwLock<HashMap<String, PendingDeviceCode>>,
1385 pub device_code_by_user_code: RwLock<HashMap<String, String>>,
1387 pub token_db: Option<Arc<dyn TokenStore>>,
1390 pub policy_client: PolicyClient,
1392 pub discovery_client: DiscoveryClient,
1394 pub issuer_url: String,
1396 pub hosted_account_zone: Option<crate::account::AccountZone>,
1399 pub ninep_canonical_read: Option<crate::config::NinepCanonicalReadConfig>,
1403 pub default_scopes: Vec<String>,
1405 pub token_ttl: u32,
1407 pub refresh_token_ttl: u32,
1409 pub require_pushed_authorization_requests: bool,
1412 pub http_client: reqwest::Client,
1414 pub verifying_key_bytes: [u8; 32],
1416 pub user_service: Option<Arc<UserService>>,
1420 pub hosted_account_store: Option<Arc<hyprstream_pds_service::AccountRecordStore>>,
1424 pub identity_registration_api:
1427 Option<Arc<super::identity_registration::IdentityRegistrationApi>>,
1428 pub signing_key: Option<ed25519_dalek::SigningKey>,
1431 pub root_identity_key_store: Option<Arc<crate::auth::SigningKeyStore>>,
1437 pub authority_hints: Vec<String>,
1440 pub pending_external_auths: RwLock<HashMap<String, PendingExternalAuth>>,
1442 pub external_providers: HashMap<String, crate::config::OidcProviderConfig>,
1445 pub oidc_discovery: super::oidc_discovery::SharedDiscoveryCache,
1447 pub sessions: super::session::SessionStore,
1449 pub xrpc_repos: Arc<super::xrpc::XrpcRepoStore>,
1453 pub public_repo_writer: Option<Arc<crate::services::public_repo::PublicRepoWriter>>,
1456 pub hosted_public_repo_writer:
1459 Option<Arc<crate::services::public_repo::HostedAccountPublicRepoWriter>>,
1460 pub public_git_canary_record: Option<PublicGitCanaryRecord>,
1463 pub atproto_session_resolver: Option<Arc<dyn super::xrpc::AtprotoSessionResolver>>,
1466 pub xrpc_read_slice: bool,
1469 pub public_git_canary_backend_port: Option<u16>,
1472 pub deployment_well_known_dir: Option<std::path::PathBuf>,
1482 pub rsa_encoding_key: Option<jsonwebtoken::EncodingKey>,
1484 pub rsa_jwk: Option<serde_json::Value>,
1486 pub rsa_kid: Option<String>,
1488 pub dpop_jti_seen: TtlCache<ReplayKey, ()>,
1493 pub assertion_jti_seen: TtlCache<ReplayKey, ()>,
1499 pub atproto_service_jti_seen: TtlCache<ReplayKey, ()>,
1502 pub atproto_did_resolver: Arc<dyn AtprotoDidDocumentResolver>,
1504 pub dpop_nonces: RwLock<HashMap<String, i64>>,
1506 pub dpop_clients_seen: RwLock<HashMap<String, i64>>,
1512 pub trusted_issuers: std::collections::HashMap<String, crate::config::TrustedIssuerConfig>,
1514 pub ca_jwt_key: Option<Arc<ed25519_dalek::SigningKey>>,
1518 pub device_store: Option<Arc<dyn crate::auth::DeviceStore>>,
1520 pub jwt_key_nbf: i64,
1522 pub jwt_key_exp: i64,
1525 pub signing_key_store: Option<Arc<crate::auth::SigningKeyStore>>,
1528 pub es256_key_store: Option<Arc<crate::auth::Es256SigningKeyStore>>,
1531 pub ml_dsa_key_store: Option<Arc<crate::auth::MlDsaSigningKeyStore>>,
1533 pub audit_sink: Option<Arc<dyn crate::mac::audit::AuditSink>>,
1542 pub quic_cert_hashes: Vec<[u8; 32]>,
1546 pub quic_public_uri: Option<String>,
1549 pub mesh_pq_verifying_key: Option<Vec<u8>>,
1556 pub mesh_kem_public: Option<hyprstream_rpc::crypto::hybrid_kem::RecipientPublic>,
1566 pub(crate) at9p_identity: Option<super::did_document::RenderedAt9pIdentity>,
1569 pub iroh_node_id: Option<[u8; 32]>,
1573 pub iroh_relays: Vec<String>,
1577}
1578
1579fn mesh_kem_public_for_policy(
1580 key: &ed25519_dalek::SigningKey,
1581 policy: hyprstream_rpc::crypto::CryptoPolicy,
1582 derive: impl FnOnce(
1583 &ed25519_dalek::SigningKey,
1584 ) -> anyhow::Result<hyprstream_rpc::crypto::hybrid_kem::RecipientKeypair>,
1585) -> anyhow::Result<Option<hyprstream_rpc::crypto::hybrid_kem::RecipientPublic>> {
1586 match derive(key) {
1587 Ok(kem_kp) => Ok(Some(kem_kp.public())),
1588 Err(e) if policy.uses_pq() => Err(e)
1589 .context("failed to derive #mesh-kem hybrid keyAgreement identity under Hybrid policy"),
1590 Err(e) => {
1591 tracing::warn!(
1592 error = %e,
1593 "failed to derive #mesh-kem hybrid keyAgreement identity under Classical policy; \
1594 root DID document will publish an empty keyAgreement relationship",
1595 );
1596 Ok(None)
1597 }
1598 }
1599}
1600
1601#[cfg(feature = "postgres")]
1603struct HybridFederateSigner {
1604 key_set: std::sync::Arc<hyprstream_rpc::auth::CompositeKeySet>,
1605}
1606
1607#[cfg(feature = "postgres")]
1608impl HybridFederateSigner {
1609 fn new(key_set: std::sync::Arc<hyprstream_rpc::auth::CompositeKeySet>) -> anyhow::Result<Self> {
1610 let snapshot = key_set
1611 .mint_snapshot()
1612 .context("committed OAuth composite signing authority is unavailable")?;
1613 anyhow::ensure!(
1614 snapshot
1615 .active_signing_pair(hyprstream_rpc::auth::CompositePairRole::OAuth)
1616 .is_some(),
1617 "no authorized active OAuth composite signing pair"
1618 );
1619 Ok(Self { key_set })
1620 }
1621}
1622
1623#[async_trait::async_trait]
1624#[cfg(feature = "postgres")]
1625impl super::federate_host::FederateSigner for HybridFederateSigner {
1626 async fn sign(&self, claims: &hyprstream_rpc::auth::claims::Claims) -> anyhow::Result<String> {
1627 let snapshot = self
1628 .key_set
1629 .mint_snapshot()
1630 .context("committed OAuth composite signing authority is unavailable")?;
1631 let (pq, ed) = snapshot
1632 .active_signing_pair(hyprstream_rpc::auth::CompositePairRole::OAuth)
1633 .and_then(hyprstream_rpc::auth::CompositeKeyPair::signing_keys)
1634 .ok_or_else(|| anyhow::anyhow!("no authorized active OAuth composite signing pair"))?;
1635 Ok(crate::auth::jwt::encode_composite_ml_dsa_65_ed25519(
1636 claims, &pq, &ed,
1637 ))
1638 }
1639}
1640
1641impl OAuthState {
1642 #[cfg(feature = "postgres")]
1647 pub(crate) fn install_federate_issuer(
1648 &mut self,
1649 admission: std::sync::Arc<dyn super::federate_host::FederateAdmission>,
1650 signer: std::sync::Arc<dyn super::federate_host::FederateSigner>,
1651 tui_client: Option<super::federate_source::ClientClass>,
1652 ) -> anyhow::Result<()> {
1653 let host = super::federate_source::FederateHost::new(&self.issuer_url)?;
1654 let issuer =
1655 super::federate_host::FederateIssuer::new(admission, signer, host, tui_client)?;
1656 self.federate_issuer = Some(std::sync::Arc::new(issuer));
1657 Ok(())
1658 }
1659
1660 #[cfg(feature = "postgres")]
1662 pub(crate) async fn federate_signer(
1663 &self,
1664 ) -> anyhow::Result<std::sync::Arc<dyn super::federate_host::FederateSigner>> {
1665 Ok(std::sync::Arc::new(HybridFederateSigner::new(
1666 hyprstream_rpc::auth::global_composite_key_set(),
1667 )?))
1668 }
1669 const MAX_CLIENT_ASSERTION_REPLAY_SECS: i64 = 360;
1670 const MAX_ATPROTO_SERVICE_ASSERTION_REPLAY_SECS: i64 = 3_600;
1671 const DPOP_JTI_MAX_ENTRIES: usize = 216_000;
1675 const DPOP_JTI_REAP_BUDGET: usize = 64;
1677 const ASSERTION_JTI_MAX_ENTRIES: usize = 43_200;
1681 const ASSERTION_JTI_REAP_BUDGET: usize = 64;
1683
1684 pub fn new(
1685 config: &OAuthConfig,
1686 policy_client: PolicyClient,
1687 discovery_client: DiscoveryClient,
1688 verifying_key_bytes: [u8; 32],
1689 ) -> Self {
1690 Self {
1691 browser_provisioning_signer: None,
1692 browser_provisioning_rate_limiter: Arc::new(
1693 crate::server::middleware::RateLimiter::new(60, 60),
1694 ),
1695 #[cfg(feature = "postgres")]
1696 federate_issuer: None,
1697 clients: RwLock::new(HashMap::new()),
1698 pending_authorize_bindings: RwLock::new(HashMap::new()),
1699 cimd_cache: Arc::new(super::cimd_cache::CimdCache::new(
1700 super::cimd_cache::CimdCacheConfig::default(),
1701 )),
1702 jwks_uri_cache: RwLock::new(HashMap::new()),
1703 client_jwks_uri_cache_ttl: Duration::from_secs(config.client_jwks_uri_cache_ttl_secs),
1704 pending_codes: RwLock::new(HashMap::new()),
1705 pending_nonces: RwLock::new(HashMap::new()),
1706 pending_par_requests: RwLock::new(HashMap::new()),
1707 pending_device_codes: RwLock::new(HashMap::new()),
1708 device_code_by_user_code: RwLock::new(HashMap::new()),
1709 token_db: None,
1710 policy_client,
1711 discovery_client,
1712 issuer_url: config.issuer_url(),
1713 hosted_account_zone: None,
1714 ninep_canonical_read: None,
1715 default_scopes: config.default_scopes.clone(),
1716 token_ttl: config.token_ttl_seconds,
1717 refresh_token_ttl: config.refresh_token_ttl_seconds,
1718 require_pushed_authorization_requests: config.require_pushed_authorization_requests,
1719 http_client: reqwest::Client::builder()
1720 .timeout(Duration::from_secs(10))
1721 .build()
1722 .unwrap_or_default(),
1723 verifying_key_bytes,
1724 user_service: None,
1725 hosted_account_store: None,
1726 identity_registration_api: None,
1727 signing_key: None,
1728 root_identity_key_store: None,
1729 authority_hints: config.authority_hints.clone(),
1730 pending_external_auths: RwLock::new(HashMap::new()),
1731 external_providers: config.oidc_providers.clone(),
1732 oidc_discovery: std::sync::Arc::new(
1733 super::oidc_discovery::OidcDiscoveryCache::default(),
1734 ),
1735 sessions: super::session::SessionStore::default(),
1736 xrpc_repos: Arc::new(super::xrpc::XrpcRepoStore::new()),
1737 public_repo_writer: None,
1738 hosted_public_repo_writer: None,
1739 public_git_canary_record: None,
1740 atproto_session_resolver: None,
1741 xrpc_read_slice: config.xrpc_read_slice,
1742 public_git_canary_backend_port: config.public_git_canary_backend_port,
1743 deployment_well_known_dir: config.deployment_well_known_dir.clone(),
1744 rsa_encoding_key: None,
1745 rsa_jwk: None,
1746 rsa_kid: None,
1747 dpop_jti_seen: TtlCache::new(Self::DPOP_JTI_MAX_ENTRIES, Self::DPOP_JTI_REAP_BUDGET),
1748 assertion_jti_seen: TtlCache::new(
1749 Self::ASSERTION_JTI_MAX_ENTRIES,
1750 Self::ASSERTION_JTI_REAP_BUDGET,
1751 ),
1752 atproto_service_jti_seen: TtlCache::new(
1753 432_000,
1763 Self::ASSERTION_JTI_REAP_BUDGET,
1764 ),
1765 atproto_did_resolver: atproto_did_resolver(config),
1766 dpop_nonces: RwLock::new(HashMap::new()),
1767 dpop_clients_seen: RwLock::new(HashMap::new()),
1768 trusted_issuers: config.trusted_issuers.clone(),
1769 ca_jwt_key: None,
1770 device_store: None,
1771 jwt_key_nbf: chrono::Utc::now().timestamp(),
1772 jwt_key_exp: chrono::Utc::now().timestamp() + 14 * 86400,
1773 signing_key_store: None,
1774 es256_key_store: None,
1775 ml_dsa_key_store: None,
1776 audit_sink: None,
1777 quic_cert_hashes: Vec::new(),
1778 quic_public_uri: None,
1779 mesh_pq_verifying_key: None,
1780 mesh_kem_public: None,
1781 at9p_identity: None,
1782 iroh_node_id: None,
1783 iroh_relays: Vec::new(),
1784 }
1785 }
1786
1787 pub(crate) fn with_browser_provisioning_signer(
1788 mut self,
1789 signing_key: hyprstream_rpc::crypto::SigningKey,
1790 ) -> Self {
1791 self.browser_provisioning_signer = Some(Arc::new(signing_key));
1792 self
1793 }
1794
1795 pub fn with_device_store(mut self, store: Arc<dyn crate::auth::DeviceStore>) -> Self {
1797 self.device_store = Some(store);
1798 self
1799 }
1800
1801 pub fn with_atproto_did_resolver(
1803 mut self,
1804 resolver: Arc<dyn AtprotoDidDocumentResolver>,
1805 ) -> Self {
1806 self.atproto_did_resolver = resolver;
1807 self
1808 }
1809
1810 pub fn with_hosted_account_store(
1812 mut self,
1813 store: Arc<hyprstream_pds_service::AccountRecordStore>,
1814 ) -> Self {
1815 self.hosted_account_store = Some(store);
1816 self
1817 }
1818
1819 pub fn with_public_repo_writer(
1822 mut self,
1823 writer: Arc<crate::services::public_repo::PublicRepoWriter>,
1824 ) -> Self {
1825 self.public_repo_writer = Some(writer);
1826 self
1827 }
1828
1829 pub fn with_hosted_public_repo_writer(
1830 mut self,
1831 writer: Arc<crate::services::public_repo::HostedAccountPublicRepoWriter>,
1832 ) -> Self {
1833 self.hosted_public_repo_writer = Some(writer);
1834 self
1835 }
1836
1837 pub fn with_public_git_canary_record(mut self, record: PublicGitCanaryRecord) -> Self {
1838 self.public_git_canary_record = Some(record);
1839 self
1840 }
1841
1842 pub fn with_atproto_session_resolver(
1846 mut self,
1847 resolver: Arc<dyn super::xrpc::AtprotoSessionResolver>,
1848 ) -> Self {
1849 self.atproto_session_resolver = Some(resolver);
1850 self
1851 }
1852
1853 pub fn with_identity_registration_api(
1855 mut self,
1856 api: Arc<super::identity_registration::IdentityRegistrationApi>,
1857 ) -> Self {
1858 self.identity_registration_api = Some(api);
1859 self
1860 }
1861
1862 pub async fn hosted_account_tenant(&self, did: &str) -> Result<Option<String>, String> {
1868 if let Some(store) = &self.hosted_account_store {
1869 return store
1870 .resolve_tenant_for_hosted_did(
1871 &hyprstream_rpc::Subject::new(
1872 hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT,
1873 ),
1874 did,
1875 )
1876 .await
1877 .map_err(|error| format!("hosted account tenant resolution failed: {error}"));
1878 }
1879 match &self.identity_registration_api {
1880 Some(api) => api
1881 .hosted_tenant(did)
1882 .map_err(|error| format!("hosted account tenant resolution failed: {error:#}")),
1883 None => Ok(None),
1884 }
1885 }
1886
1887 pub async fn refresh_hosted_account_index_after_signup(&self) -> Result<(), String> {
1892 let Some(store) = &self.hosted_account_store else {
1893 return Ok(());
1894 };
1895 super::refresh_hosted_did_index_after_publish(
1896 Arc::clone(store),
1897 hyprstream_rpc::Subject::new(hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT),
1898 std::time::Duration::from_secs(30),
1899 )
1900 .await
1901 .map_err(|error| format!("hosted account index refresh after signup failed: {error}"))
1902 }
1903
1904 pub fn atproto_service_did(&self) -> Option<String> {
1906 atproto_service_did_for_origin(&self.issuer_url)
1907 }
1908
1909 pub fn with_jwt_key_timestamps(mut self, nbf: i64, exp: i64) -> Self {
1911 self.jwt_key_nbf = nbf;
1912 self.jwt_key_exp = exp;
1913 self
1914 }
1915
1916 pub fn with_ca_jwt_key(mut self, key: ed25519_dalek::SigningKey) -> Self {
1918 self.ca_jwt_key = Some(Arc::new(key));
1919 self
1920 }
1921
1922 pub fn with_signing_key_store(mut self, store: Arc<crate::auth::SigningKeyStore>) -> Self {
1926 self.signing_key_store = Some(store);
1927 self
1928 }
1929
1930 pub fn with_root_identity_key_store(
1932 mut self,
1933 store: Arc<crate::auth::SigningKeyStore>,
1934 ) -> Self {
1935 self.root_identity_key_store = Some(store);
1936 self
1937 }
1938
1939 pub fn with_es256_key_store(mut self, store: Arc<crate::auth::Es256SigningKeyStore>) -> Self {
1941 self.es256_key_store = Some(store);
1942 self
1943 }
1944
1945 pub fn with_ml_dsa_key_store(mut self, store: Arc<crate::auth::MlDsaSigningKeyStore>) -> Self {
1947 self.ml_dsa_key_store = Some(store);
1948 self
1949 }
1950
1951 pub fn with_audit_sink(mut self, sink: Arc<dyn crate::mac::audit::AuditSink>) -> Self {
1955 self.audit_sink = Some(sink);
1956 self
1957 }
1958
1959 pub fn with_quic_transport(mut self, public_uri: String, cert_hashes: Vec<[u8; 32]>) -> Self {
1965 self.quic_public_uri = Some(public_uri);
1966 self.quic_cert_hashes = cert_hashes;
1967 self
1968 }
1969
1970 pub fn with_iroh_transport(mut self, node_id: [u8; 32], relays: Vec<String>) -> Self {
1978 self.iroh_node_id = Some(node_id);
1979 self.iroh_relays = relays;
1980 self
1981 }
1982
1983 pub async fn jwt_bearer_verifying_key(&self) -> Option<ed25519_dalek::VerifyingKey> {
1988 if let Some(store) = &self.signing_key_store {
1989 if let Some(bytes) = store.active_verifying_key_bytes().await {
1990 return ed25519_dalek::VerifyingKey::from_bytes(&bytes).ok();
1991 }
1992 }
1993 ed25519_dalek::VerifyingKey::from_bytes(&self.verifying_key_bytes).ok()
1994 }
1995
1996 pub async fn active_jwt_signing_key(&self) -> Option<Arc<ed25519_dalek::SigningKey>> {
2000 if let Some(store) = &self.signing_key_store {
2001 if let Some(key) = store.active_key().await {
2002 return Some(key);
2003 }
2004 }
2005 self.ca_jwt_key.clone()
2006 }
2007
2008 pub async fn active_root_identity_signing_key(&self) -> Option<Arc<ed25519_dalek::SigningKey>> {
2010 if let Some(store) = &self.root_identity_key_store {
2011 if let Some(key) = store.active_key().await {
2012 return Some(key);
2013 }
2014 }
2015 self.signing_key.clone().map(Arc::new)
2016 }
2017
2018 pub fn with_user_store(mut self, store: crate::auth::ProductionUserStore) -> Self {
2021 self.user_service = Some(Arc::new(UserService::new(store)));
2022 self
2023 }
2024
2025 pub fn with_hosted_account_zone(mut self, zone: crate::account::AccountZone) -> Self {
2027 self.hosted_account_zone = Some(zone);
2028 self
2029 }
2030
2031 pub fn with_ninep_canonical_read(
2034 mut self,
2035 export: crate::config::NinepCanonicalReadConfig,
2036 ) -> Self {
2037 self.ninep_canonical_read = Some(export);
2038 self
2039 }
2040
2041 #[cfg(test)]
2044 pub(crate) fn with_user_service(mut self, service: Arc<UserService>) -> Self {
2045 self.user_service = Some(service);
2046 self
2047 }
2048
2049 pub(crate) fn user_store_reader(&self) -> Option<Arc<dyn UserStore>> {
2052 self.user_service.as_ref().map(|s| s.store())
2053 }
2054
2055 pub fn has_user_store(&self) -> bool {
2057 self.user_service.is_some()
2058 }
2059
2060 pub fn with_signing_key(
2073 mut self,
2074 key: ed25519_dalek::SigningKey,
2075 policy: hyprstream_rpc::crypto::CryptoPolicy,
2076 ) -> anyhow::Result<Self> {
2077 let pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&key);
2078 self.mesh_pq_verifying_key =
2079 Some(hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&pq_sk));
2080 match super::did_document::render_at9p_identity(&self.issuer_url, &key, &pq_sk) {
2081 Ok(identity) => self.at9p_identity = Some(identity),
2082 Err(error) => {
2083 tracing::warn!(
2084 %error,
2085 issuer = %self.issuer_url,
2086 "skipping at9p identity publication"
2087 );
2088 self.at9p_identity = None;
2089 }
2090 }
2091 self.mesh_kem_public = mesh_kem_public_for_policy(&key, policy, |key| {
2092 hyprstream_rpc::node_identity::derive_mesh_kem_recipient(key)
2093 })?;
2094 self.signing_key = Some(key);
2095 Ok(self)
2096 }
2097
2098 pub fn with_token_store_impl(&mut self, store: Arc<dyn TokenStore>) {
2100 self.token_db = Some(store);
2101 }
2102
2103 pub async fn put_refresh_token(
2105 &self,
2106 token: &str,
2107 entry: &RefreshTokenEntry,
2108 ttl_secs: u64,
2109 ) -> anyhow::Result<()> {
2110 let Some(ref store) = self.token_db else {
2111 tracing::warn!("Refresh token store not configured — token will not survive restart");
2112 return Ok(());
2113 };
2114 store.put(token, entry, ttl_secs).await
2115 }
2116
2117 pub async fn get_refresh_token(
2119 &self,
2120 token: &str,
2121 ) -> anyhow::Result<Option<RefreshTokenEntry>> {
2122 let Some(ref store) = self.token_db else {
2123 return Ok(None);
2124 };
2125 store.get(token).await
2126 }
2127
2128 pub async fn take_refresh_token(
2131 &self,
2132 token: &str,
2133 ) -> anyhow::Result<Option<RefreshTokenEntry>> {
2134 let Some(ref store) = self.token_db else {
2135 return Ok(None);
2136 };
2137 store.take(token).await
2138 }
2139
2140 pub async fn delete_refresh_token(&self, token: &str) -> anyhow::Result<()> {
2142 let Some(ref store) = self.token_db else {
2143 return Ok(());
2144 };
2145 store.delete(token).await
2146 }
2147
2148 pub fn check_and_record_dpop_jti(&self, jti: &str, iat: i64) -> bool {
2154 self.check_and_record_dpop_jti_admission(jti, iat)
2155 .is_inserted()
2156 }
2157
2158 pub(crate) fn check_and_record_dpop_jti_admission(
2161 &self,
2162 jti: &str,
2163 iat: i64,
2164 ) -> DpopJtiAdmission {
2165 let now = chrono::Utc::now().timestamp();
2166 let Some(ttl_secs) = iat
2168 .checked_add(120)
2169 .and_then(|deadline| deadline.checked_sub(now))
2170 .filter(|remaining| *remaining > 0 && *remaining <= 180)
2171 .and_then(|remaining| u64::try_from(remaining).ok())
2172 else {
2173 return DpopJtiAdmission::InvalidLifetime;
2174 };
2175 let result = self.dpop_jti_seen.insert_if_absent_no_evict(
2176 super::replay_key::dpop_jti(jti),
2177 (),
2178 Duration::from_secs(ttl_secs),
2179 );
2180 if result != InsertIfAbsentNoEvictResult::Inserted {
2181 super::replay_metrics::record_rejection(super::replay_metrics::DPOP, result);
2182 if super::replay_metrics::should_warn_full(super::replay_metrics::DPOP, result) {
2183 tracing::warn!("DPoP replay barrier is full; refusing fresh proof");
2184 }
2185 }
2186 match result {
2187 InsertIfAbsentNoEvictResult::Inserted => DpopJtiAdmission::Inserted,
2188 InsertIfAbsentNoEvictResult::Duplicate => DpopJtiAdmission::Duplicate,
2189 InsertIfAbsentNoEvictResult::Full => DpopJtiAdmission::Full,
2190 }
2191 }
2192
2193 pub fn check_and_record_atproto_service_jti(&self, issuer: &str, jti: &str, exp: i64) -> bool {
2195 let Some(ttl_secs) = exp
2196 .checked_sub(chrono::Utc::now().timestamp())
2197 .filter(|remaining| {
2198 *remaining > 0 && *remaining <= Self::MAX_ATPROTO_SERVICE_ASSERTION_REPLAY_SECS
2199 })
2200 .and_then(|remaining| u64::try_from(remaining).ok())
2201 else {
2202 return false;
2203 };
2204 let result = self.atproto_service_jti_seen.insert_if_absent_no_evict(
2205 super::replay_key::atproto_service_assertion_jti(issuer, jti),
2206 (),
2207 Duration::from_secs(ttl_secs),
2208 );
2209 if result != InsertIfAbsentNoEvictResult::Inserted {
2210 super::replay_metrics::record_rejection(
2211 super::replay_metrics::ATPROTO_SERVICE_ASSERTION,
2212 result,
2213 );
2214 if super::replay_metrics::should_warn_full(
2215 super::replay_metrics::ATPROTO_SERVICE_ASSERTION,
2216 result,
2217 ) {
2218 tracing::warn!(
2219 "ATProto service-assertion replay barrier is full; refusing fresh assertion"
2220 );
2221 }
2222 }
2223 result == InsertIfAbsentNoEvictResult::Inserted
2224 }
2225
2226 pub fn check_and_record_assertion_jti(&self, client_id: &str, jti: &str, exp: i64) -> bool {
2238 let now = chrono::Utc::now().timestamp();
2239 let Some(ttl_secs) = exp
2240 .checked_sub(now)
2241 .filter(|remaining| {
2242 *remaining > 0 && *remaining <= Self::MAX_CLIENT_ASSERTION_REPLAY_SECS
2243 })
2244 .and_then(|remaining| u64::try_from(remaining).ok())
2245 else {
2246 return false;
2247 };
2248 let result = self.assertion_jti_seen.insert_if_absent_no_evict(
2249 super::replay_key::client_assertion_jti(client_id, jti),
2250 (),
2251 Duration::from_secs(ttl_secs),
2252 );
2253 if result != InsertIfAbsentNoEvictResult::Inserted {
2254 super::replay_metrics::record_rejection(
2255 super::replay_metrics::CLIENT_ASSERTION,
2256 result,
2257 );
2258 if super::replay_metrics::should_warn_full(
2259 super::replay_metrics::CLIENT_ASSERTION,
2260 result,
2261 ) {
2262 tracing::warn!("client-assertion replay barrier is full; refusing fresh assertion");
2263 }
2264 }
2265 result == InsertIfAbsentNoEvictResult::Inserted
2266 }
2267
2268 pub async fn issue_dpop_nonce(&self) -> String {
2273 use rand::RngCore;
2274 let mut bytes = [0u8; 16];
2275 rand::rngs::OsRng.fill_bytes(&mut bytes);
2276 let nonce = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes);
2277 let expiry = chrono::Utc::now().timestamp() + 300; self.dpop_nonces.write().await.insert(nonce.clone(), expiry);
2279 nonce
2280 }
2281
2282 pub async fn verify_dpop_nonce(&self, nonce: &str) -> bool {
2284 let now = chrono::Utc::now().timestamp();
2285 let store = self.dpop_nonces.read().await;
2286 store.get(nonce).is_some_and(|&exp| exp > now)
2287 }
2288
2289 pub async fn dpop_client_requires_nonce(&self, jkt: &str) -> bool {
2293 let now = chrono::Utc::now().timestamp();
2294 let mut store = self.dpop_clients_seen.write().await;
2295 store.retain(|_, exp| *exp > now);
2296 store.contains_key(jkt)
2297 }
2298
2299 pub async fn mark_dpop_client_nonced(&self, jkt: &str) {
2303 let expiry = chrono::Utc::now().timestamp() + 300;
2304 self.dpop_clients_seen
2305 .write()
2306 .await
2307 .insert(jkt.to_owned(), expiry);
2308 }
2309
2310 pub fn subject_did(&self, subject: &str) -> Result<String, SubjectDidError> {
2321 subject_did_for(&self.issuer_url, subject)
2322 }
2323
2324 pub fn atproto_issuer_url(&self) -> String {
2326 canonical_issuer_origin(&self.issuer_url).unwrap_or_else(|| self.issuer_url.clone())
2327 }
2328
2329 pub fn issuer_for_scopes(&self, scopes: &[String]) -> String {
2331 if atproto_profile_active(scopes) {
2332 self.atproto_issuer_url()
2333 } else {
2334 self.issuer_url.clone()
2335 }
2336 }
2337
2338 pub async fn check_atproto_account_eligibility(
2353 &self,
2354 username: &str,
2355 ) -> Result<String, SubjectDidError> {
2356 let user_store = self
2357 .user_store_reader()
2358 .ok_or(SubjectDidError::NoAtprotoIdentity)?;
2359
2360 let pubkeys = user_store.list_pubkeys(username).await.map_err(|error| {
2365 tracing::warn!(%username, %error, "atproto eligibility key lookup failed closed");
2366 SubjectDidError::NoAtprotoIdentity
2367 })?;
2368 let profile = user_store.get_profile(username).await.ok().flatten();
2369
2370 evaluate_atproto_eligibility(&pubkeys, profile.as_ref(), &self.issuer_url)
2371 }
2372
2373 pub fn server_supported_scopes(&self) -> Vec<String> {
2379 let mut scopes = self.default_scopes.clone();
2380 for atproto_scope in &["atproto", "transition:generic"] {
2381 if !scopes.iter().any(|s| s == *atproto_scope) {
2382 scopes.push((*atproto_scope).to_owned());
2383 }
2384 }
2385 scopes
2386 }
2387
2388 pub fn with_rsa_key(mut self, rsa_der: &[u8]) -> Self {
2392 self.rsa_encoding_key = Some(jsonwebtoken::EncodingKey::from_rsa_der(rsa_der));
2394
2395 if let Some(mut jwk) = extract_rsa_jwk_from_der(rsa_der, "") {
2397 let n = jwk.get("n").and_then(|v| v.as_str()).unwrap_or_default();
2398 let e = jwk.get("e").and_then(|v| v.as_str()).unwrap_or_default();
2399 let kid = super::jwks::compute_rsa_kid(n, e);
2400 if let Some(obj) = jwk.as_object_mut() {
2401 obj.insert("kid".to_owned(), serde_json::Value::String(kid.clone()));
2402 }
2403 self.rsa_kid = Some(kid);
2404 self.rsa_jwk = Some(jwk);
2405 }
2406
2407 self
2408 }
2409
2410 pub fn spawn_code_sweeper(self: &Arc<Self>) {
2412 let state = Arc::clone(self);
2413 tokio::spawn(async move {
2414 loop {
2415 tokio::time::sleep(Duration::from_secs(30)).await;
2416
2417 {
2419 let mut codes = state.pending_codes.write().await;
2420 codes.retain(|_, code| !code.is_expired());
2421 }
2422
2423 state.sweep_authorize_sessions(Instant::now()).await;
2425
2426 {
2428 let mut par = state.pending_par_requests.write().await;
2429 par.retain(|_, req| !req.is_expired());
2430 }
2431
2432 {
2434 let mut device_codes = state.pending_device_codes.write().await;
2435 let mut user_code_map = state.device_code_by_user_code.write().await;
2436 device_codes.retain(|_, dc| {
2437 if dc.is_expired() {
2438 user_code_map.remove(&dc.user_code);
2439 false
2440 } else {
2441 true
2442 }
2443 });
2444 }
2445
2446 {
2448 let now = chrono::Utc::now().timestamp();
2449 state.dpop_nonces.write().await.retain(|_, exp| *exp > now);
2452 state
2453 .dpop_clients_seen
2454 .write()
2455 .await
2456 .retain(|_, exp| *exp > now);
2457 }
2458
2459 {
2461 let now = Instant::now();
2462 let mut auths = state.pending_external_auths.write().await;
2463 auths.retain(|_, auth| auth.expires_at > now);
2464 }
2465
2466 state.sessions.sweep().await;
2468 }
2469 });
2470 }
2471
2472 async fn sweep_authorize_sessions(&self, now: Instant) {
2473 let mut nonces = self.pending_nonces.write().await;
2474 nonces.retain(|_, expiry| *expiry > now);
2475 let mut bindings = self.pending_authorize_bindings.write().await;
2476 bindings.retain(|nonce, _| nonces.contains_key(nonce));
2477 }
2478}
2479
2480pub fn evaluate_atproto_eligibility(
2488 pubkeys: &[crate::auth::user_store::PubkeyEntry],
2489 profile: Option<&crate::auth::user_store::UserProfile>,
2490 issuer_url: &str,
2491) -> Result<String, SubjectDidError> {
2492 use crate::auth::user_store::KeyAlgorithm;
2493
2494 if pubkeys
2496 .iter()
2497 .any(|pk| pk.algorithm == KeyAlgorithm::HybridEd25519MlDsa65)
2498 {
2499 return Err(SubjectDidError::At9pBackedAccount);
2500 }
2501
2502 if profile.is_some_and(|profile| profile.active == Some(false)) {
2503 return Err(SubjectDidError::InactiveAccount);
2504 }
2505
2506 if let Some(did) = profile.and_then(|p| p.atproto_did.as_deref()) {
2508 return subject_did_for(issuer_url, did);
2509 }
2510
2511 Err(SubjectDidError::NoAtprotoIdentity)
2513}
2514
2515pub fn subject_did_for(_issuer_url: &str, subject: &str) -> Result<String, SubjectDidError> {
2533 if let Some(rest) = subject.strip_prefix("did:plc:") {
2539 if rest.len() == 24 && rest.chars().all(|c| matches!(c, 'a'..='z' | '2'..='7')) {
2540 return Ok(subject.to_owned());
2541 }
2542 return Err(SubjectDidError::MalformedDid);
2543 }
2544 if let Some(rest) = subject.strip_prefix("did:web:") {
2550 if rest.is_empty() {
2551 return Err(SubjectDidError::MalformedDid);
2552 }
2553 if rest.contains('/') {
2557 return Err(SubjectDidError::PathFormDidWeb);
2558 }
2559 let segment_count = rest.split(':').count();
2560 if segment_count > 2 {
2562 return Err(SubjectDidError::PathFormDidWeb);
2563 }
2564 return Ok(subject.to_owned());
2565 }
2566 if subject.starts_with("did:") {
2568 return Err(SubjectDidError::UnsupportedMethod);
2569 }
2570 Err(SubjectDidError::NoAtprotoIdentity)
2573}
2574
2575#[derive(Debug, thiserror::Error, PartialEq, Eq)]
2577pub enum SubjectDidError {
2578 #[error("DID method not eligible for atproto OAuth tokens")]
2581 UnsupportedMethod,
2582 #[error("malformed atproto DID")]
2584 MalformedDid,
2585 #[error("path-form did:web rejected by atproto DID profile")]
2588 PathFormDidWeb,
2589 #[error("account has no atproto identity; provisioning tracked in #1124")]
2592 NoAtprotoIdentity,
2593 #[error("at9p-backed account not eligible for atproto OAuth")]
2597 At9pBackedAccount,
2598 #[error("hosted account is inactive")]
2601 InactiveAccount,
2602}
2603
2604pub const ATPROTO_SCOPE: &str = "atproto";
2608
2609pub fn atproto_profile_active(scopes: &[String]) -> bool {
2611 scopes.iter().any(|s| s == ATPROTO_SCOPE)
2612}
2613
2614pub fn normalize_scope_token(tok: &str) -> Option<&str> {
2618 if tok.is_empty() {
2619 return None;
2620 }
2621 if tok.bytes().all(|b| b >= 0x21 && b != b'"' && b != 0x7f) {
2622 Some(tok)
2623 } else {
2624 None
2625 }
2626}
2627
2628pub fn validate_requested_scopes(
2641 requested: &[String],
2642 server_supported: &[String],
2643 client_declared: Option<&[String]>,
2644 require_atproto: bool,
2645) -> Result<Vec<String>, ScopeError> {
2646 let allowed: Vec<&str> = match client_declared {
2648 Some(declared) if !declared.is_empty() => server_supported
2649 .iter()
2650 .filter(|s| declared.iter().any(|d| d == *s))
2651 .map(String::as_str)
2652 .collect(),
2653 _ => server_supported.iter().map(String::as_str).collect(),
2654 };
2655
2656 let mut granted: Vec<String> = Vec::new();
2657 for tok in requested {
2658 let tok = normalize_scope_token(tok).ok_or(ScopeError::InvalidScope)?;
2659 if !allowed.contains(&tok) {
2660 return Err(ScopeError::InvalidScope);
2661 }
2662 if !granted.iter().any(|g| g == tok) {
2663 granted.push(tok.to_owned());
2664 }
2665 }
2666 if require_atproto && !granted.iter().any(|s| s == ATPROTO_SCOPE) {
2667 return Err(ScopeError::AtprotoRequired);
2668 }
2669 Ok(granted)
2670}
2671
2672#[derive(Debug, thiserror::Error, PartialEq, Eq)]
2674pub enum ScopeError {
2675 #[error("invalid or unsupported scope")]
2678 InvalidScope,
2679 #[error("atproto scope required for this profile")]
2681 AtprotoRequired,
2682}
2683
2684pub fn canonical_issuer_origin(issuer_url: &str) -> Option<String> {
2688 let (scheme, rest) = issuer_url.split_once("://")?;
2689 if scheme.is_empty() {
2690 return None;
2691 }
2692 let authority = rest.split('/').next()?;
2693 if authority.is_empty() {
2694 return None;
2695 }
2696 Some(format!("{scheme}://{authority}"))
2697}
2698
2699pub(crate) fn atproto_service_did_for_origin(issuer_url: &str) -> Option<String> {
2710 let url = url::Url::parse(issuer_url).ok()?;
2711 if !matches!(url.scheme(), "http" | "https")
2712 || !url.username().is_empty()
2713 || url.password().is_some()
2714 {
2715 return None;
2716 }
2717 let host = match url.host()? {
2718 url::Host::Domain(domain) => domain.to_owned(),
2719 url::Host::Ipv4(address) => address.to_string(),
2720 url::Host::Ipv6(_) => return None,
2721 };
2722 Some(match url.port() {
2723 Some(port) => format!("did:web:{host}%3A{port}"),
2724 None => format!("did:web:{host}"),
2725 })
2726}