1use std::sync::Arc;
9
10use axum::extract::State;
11use axum::http::{header, HeaderMap, StatusCode};
12use axum::response::{IntoResponse, Response};
13use axum::Json;
14use serde::Serialize;
15
16use super::session;
17use super::state::OAuthState;
18use super::token_exchange::{verify_atproto_service_jwt, ATPROTO_SESSION_EXCHANGE_NSID};
19
20pub const SESSION_EXCHANGE_PATH: &str = "/api/session/exchange";
21pub const WHOAMI_PATH: &str = "/api/session/whoami";
22
23#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
24#[serde(rename_all = "camelCase")]
25pub struct ViewerContext {
26 did: Option<String>,
27 kind: ViewerKind,
28 tenant: Option<String>,
29 can_act_locally: bool,
30}
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
33#[serde(rename_all = "lowercase")]
34enum ViewerKind {
35 Local,
36 Federated,
37 Unauthenticated,
38}
39
40impl ViewerContext {
41 fn unauthenticated() -> Self {
42 Self {
43 did: None,
44 kind: ViewerKind::Unauthenticated,
45 tenant: None,
46 can_act_locally: false,
47 }
48 }
49
50 fn atproto(did: String, tenant: Option<String>) -> Self {
51 let kind = if tenant.is_some() {
52 ViewerKind::Local
53 } else {
54 ViewerKind::Federated
55 };
56 Self {
57 did: Some(did),
58 kind,
59 can_act_locally: tenant.is_some(),
60 tenant,
61 }
62 }
63
64 fn from_session(session: session::Session) -> Self {
65 session
66 .atproto_did
67 .map(|did| Self::atproto(did, session.verified_tenant))
68 .unwrap_or_else(Self::unauthenticated)
69 }
70}
71
72pub async fn exchange(State(state): State<Arc<OAuthState>>, headers: HeaderMap) -> Response {
75 let Some(assertion) = bearer_token(&headers) else {
76 return session_error(
77 StatusCode::UNAUTHORIZED,
78 "invalid_token",
79 "Authorization: Bearer ATProto service-auth JWT is required",
80 );
81 };
82
83 let endpoint = format!(
84 "{}{SESSION_EXCHANGE_PATH}",
85 state.atproto_issuer_url().trim_end_matches('/')
86 );
87 let Some(dpop) = headers.get("DPoP").and_then(|value| value.to_str().ok()) else {
88 return session_error(
89 StatusCode::BAD_REQUEST,
90 "invalid_dpop_proof",
91 "DPoP proof is required",
92 );
93 };
94 let proof = match super::dpop::verify_dpop_proof(dpop, "POST", &endpoint, None) {
95 Ok(proof) => proof,
96 Err(error) => {
97 tracing::warn!(%error, "browser session exchange rejected DPoP proof");
98 return session_error(
99 StatusCode::BAD_REQUEST,
100 "invalid_dpop_proof",
101 "DPoP proof verification failed",
102 );
103 }
104 };
105
106 let verified =
107 match verify_atproto_service_jwt(&state, assertion, ATPROTO_SESSION_EXCHANGE_NSID).await {
108 Ok(verified) => verified,
109 Err(error) => {
110 tracing::warn!(%error, "browser session exchange rejected ATProto assertion");
111 return session_error(StatusCode::UNAUTHORIZED, "invalid_token", &error);
112 }
113 };
114
115 if !state.check_and_record_dpop_jti(&proof.jti, proof.iat) {
116 return session_error(
117 StatusCode::BAD_REQUEST,
118 "invalid_dpop_proof",
119 "DPoP proof already used",
120 );
121 }
122 let Some((issuer, jti, exp)) = verified.atproto_replay.as_ref() else {
123 return session_error(
124 StatusCode::UNAUTHORIZED,
125 "invalid_token",
126 "ATProto assertion has no replay identifier",
127 );
128 };
129 if !state.check_and_record_atproto_service_jti(issuer, jti, *exp) {
130 return session_error(
131 StatusCode::UNAUTHORIZED,
132 "invalid_token",
133 "ATProto service-auth JWT already used",
134 );
135 }
136
137 let context = ViewerContext::atproto(verified.sub.clone(), verified.verified_tenant.clone());
138 let session_id = state
139 .sessions
140 .create_atproto(verified.sub, verified.verified_tenant)
141 .await;
142 let secure = state.atproto_issuer_url().starts_with("https://");
143 (
144 StatusCode::OK,
145 [
146 (
147 header::SET_COOKIE,
148 session::session_cookie(&session_id, secure),
149 ),
150 (header::CACHE_CONTROL, "no-store, max-age=0".to_owned()),
151 (header::PRAGMA, "no-cache".to_owned()),
152 ],
153 Json(context),
154 )
155 .into_response()
156}
157
158pub async fn whoami(State(state): State<Arc<OAuthState>>, headers: HeaderMap) -> Response {
162 let context = match session::extract_session_id(&headers) {
163 Some(session_id) => state
164 .sessions
165 .get(&session_id)
166 .await
167 .map(ViewerContext::from_session)
168 .unwrap_or_else(ViewerContext::unauthenticated),
169 None => ViewerContext::unauthenticated(),
170 };
171 (
172 StatusCode::OK,
173 [
174 (header::CACHE_CONTROL, "no-store, max-age=0"),
175 (header::PRAGMA, "no-cache"),
176 ],
177 Json(context),
178 )
179 .into_response()
180}
181
182fn bearer_token(headers: &HeaderMap) -> Option<&str> {
183 headers
184 .get(header::AUTHORIZATION)?
185 .to_str()
186 .ok()?
187 .split_once(' ')
188 .filter(|(scheme, token)| {
189 scheme.eq_ignore_ascii_case("Bearer")
190 && !token.is_empty()
191 && !token.chars().any(char::is_whitespace)
192 })
193 .map(|(_, token)| token)
194}
195
196fn session_error(status: StatusCode, error: &str, description: &str) -> Response {
197 (
198 status,
199 [
200 (header::CACHE_CONTROL, "no-store"),
201 (header::PRAGMA, "no-cache"),
202 ],
203 Json(serde_json::json!({
204 "error": error,
205 "error_description": description,
206 })),
207 )
208 .into_response()
209}
210
211#[cfg(test)]
212#[allow(clippy::expect_used, clippy::unwrap_used)]
213mod tests {
214 use std::sync::atomic::{AtomicUsize, Ordering};
215
216 use super::*;
217 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
218 use p256::ecdsa::signature::Signer as _;
219 use tower::ServiceExt as _;
220
221 use hyprstream_rpc::crypto::CryptoPolicy;
222 use hyprstream_rpc::rpc_client::RpcClientImpl;
223 use hyprstream_rpc::signer::LocalSigner;
224 use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
225 use hyprstream_vfs::{SyntheticMount, SyntheticNode};
226
227 const ISSUER: &str = "https://pds.example.test";
228 const LOCAL_DID: &str = "did:web:alice.accounts.example.com";
229 const FEDERATED_DID: &str = "did:plc:ar7c4by46qjdydhdevvrndac";
230 const TENANT: &str = "tenant-a";
231
232 struct FixtureDidResolver {
233 did: String,
234 document: serde_json::Value,
235 }
236
237 #[async_trait::async_trait]
238 impl super::super::state::AtprotoDidDocumentResolver for FixtureDidResolver {
239 async fn resolve_document(&self, did: &str) -> anyhow::Result<serde_json::Value> {
240 anyhow::ensure!(did == self.did, "fixture DID mismatch");
241 Ok(self.document.clone())
242 }
243 }
244
245 struct CountingFederatedResolver {
246 calls: AtomicUsize,
247 }
248
249 #[async_trait::async_trait]
250 impl hyprstream_pds_service::federation_intake::FederatedDidDocumentResolver
251 for CountingFederatedResolver
252 {
253 async fn resolve_federated_document(&self, did: &str) -> anyhow::Result<serde_json::Value> {
254 self.calls.fetch_add(1, Ordering::SeqCst);
255 Ok(serde_json::json!({
256 "id": did,
257 "alsoKnownAs": ["at://foreign.example"],
258 "service": [{
259 "id": format!("{did}#atproto_pds"),
260 "type": "AtprotoPersonalDataServer",
261 "serviceEndpoint": "https://foreign.example",
262 }],
263 }))
264 }
265 }
266
267 struct RejectIdentityResolver;
268
269 impl super::super::identity_registration::IdentityConnectTimeResolver for RejectIdentityResolver {
270 fn recognizes(&self, _did: &str) -> bool {
271 false
272 }
273
274 fn resolve(
275 &self,
276 _did: &str,
277 ) -> anyhow::Result<hyprstream_discovery::ConnectTimeDiscovery> {
278 anyhow::bail!("identity resolution is outside the browser-session fixture")
279 }
280 }
281
282 struct PermitAccountReads;
283
284 impl hyprstream_pds_service::AccountRecordReadAuthorizer for PermitAccountReads {
285 fn check_read(
286 &self,
287 _subject: &hyprstream_rpc::Subject,
288 _verified_tenant: Option<&str>,
289 _security_context: Option<&hyprstream_rpc::auth::mac::SecurityContext>,
290 _object_id: &str,
291 ) -> hyprstream_rpc::auth::mac::MacDecision {
292 hyprstream_rpc::auth::mac::MacDecision::Permit
293 }
294 }
295
296 struct SessionFixture {
297 state: Arc<OAuthState>,
298 cors: crate::config::CorsConfig,
299 did: &'static str,
300 atproto_key: p256::ecdsa::SigningKey,
301 federated_resolver: Arc<CountingFederatedResolver>,
302 _storage: tempfile::TempDir,
303 }
304
305 async fn fixture(local: bool) -> SessionFixture {
306 let storage = tempfile::TempDir::new().unwrap();
307 let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x71; 32]);
308 let remote_key = ed25519_dalek::SigningKey::from_bytes(&[0x72; 32]).verifying_key();
309 let make_client = || {
310 Arc::new(
311 RpcClientImpl::new(
312 LocalSigner::new(signing_key.clone()),
313 LazyUdsTransport::new("/dev/null/browser-session-test.sock".into()),
314 Some(remote_key),
315 )
316 .with_response_verify_policy(CryptoPolicy::Classical),
317 )
318 };
319 let mut oauth = crate::config::OAuthConfig::default();
320 oauth.external_url = Some(ISSUER.to_owned());
321 oauth.identity_registration_did_web_origins = vec!["https://foreign.example".to_owned()];
322 let cors = crate::config::CorsConfig {
323 enabled: false,
324 ..oauth.cors.clone()
325 };
326
327 let (did, atproto_key, document, hosted_store) = if local {
328 let account_ed = ed25519_dalek::SigningKey::from_bytes(&[0x73; 32]);
329 let (account_pq, account_pq_vk) = hyprstream_crypto::pq::ml_dsa_generate_keypair();
330 let hybrid = hyprstream_pds::HybridRotationKey::new(
331 account_ed.verifying_key().to_bytes(),
332 hyprstream_crypto::pq::ml_dsa_vk_bytes(&account_pq_vk),
333 )
334 .unwrap();
335 let rotations = hyprstream_pds::GenesisRotationKeys::new(
336 hyprstream_pds::UserRotationKey::new(hybrid),
337 hyprstream_pds::RecoveryKeyEnrollment::Declined,
338 hyprstream_pds::HostKeyEnrollment::Absent,
339 )
340 .unwrap();
341 let mint = hyprstream_pds::HostedAccountMint::begin(
342 hyprstream_pds::AllocatedAccountName::new("alice", LOCAL_DID).unwrap(),
343 rotations,
344 )
345 .unwrap();
346 let account_document = mint.seal_did_document(ISSUER).unwrap();
347 let pending = mint
348 .prepare_genesis(
349 account_document,
350 hyprstream_pds::did_op::GenesisRepoHead::EmptyRepo,
351 )
352 .unwrap();
353 let signature =
354 hyprstream_pds::sign_genesis(pending.unsigned_genesis(), &account_ed, &account_pq)
355 .unwrap();
356 let sealed = pending.seal(signature).unwrap();
357 let atproto_key = sealed.atproto_signing_key().clone();
358 let document = serde_json::from_slice(sealed.did_document().as_bytes()).unwrap();
359 let root = SyntheticNode::dir().with_child(
360 TENANT,
361 SyntheticNode::dir().with_child(
362 "accounts",
363 SyntheticNode::dir().with_child(
364 "alice",
365 SyntheticNode::dir().with_child(
366 "account-record.cbor",
367 SyntheticNode::file(sealed.record_bytes().to_vec()),
368 ),
369 ),
370 ),
371 );
372 let store = Arc::new(hyprstream_pds_service::AccountRecordStore::new(
373 Arc::new(SyntheticMount::new(root)),
374 Arc::new(PermitAccountReads),
375 ));
376 (LOCAL_DID, atproto_key, document, Some(store))
377 } else {
378 let atproto_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
379 let document = did_document(FEDERATED_DID, &atproto_key);
380 (FEDERATED_DID, atproto_key, document, None)
381 };
382
383 let certified =
384 rcgen::generate_simple_self_signed(vec!["pds.example.test".to_owned()]).unwrap();
385 let cert_path = storage.path().join("quic-cert.pem");
386 let key_path = storage.path().join("quic-key.pem");
387 std::fs::write(&cert_path, certified.cert.pem()).unwrap();
388 std::fs::write(&key_path, certified.key_pair.serialize_pem()).unwrap();
389 let account = crate::account::AccountZoneConfig {
390 zone: Some("accounts.example.com".to_owned()),
391 ..Default::default()
392 };
393 let quic = crate::config::QuicConfig {
394 event_publishers: Default::default(),
395 stream_publishers: Default::default(),
396 enabled: true,
397 bind_addr: "127.0.0.1:4433".to_owned(),
398 server_name: "pds.example.test".to_owned(),
399 cert_path: cert_path.to_string_lossy().into_owned(),
400 key_path: key_path.to_string_lossy().into_owned(),
401 iroh: false,
402 native_network_profile: crate::config::NativeNetworkProfile::Compatibility,
403 relay: String::new(),
404 };
405 let federated_resolver = Arc::new(CountingFederatedResolver {
406 calls: AtomicUsize::new(0),
407 });
408 let registration_api =
409 super::super::identity_registration::compose_identity_registration_api(
410 &oauth,
411 &account,
412 &quic,
413 signing_key.clone(),
414 storage.path().join("pds"),
415 federated_resolver.clone(),
416 Arc::new(RejectIdentityResolver),
417 )
418 .unwrap();
419
420 if let Some(store) = hosted_store.as_ref() {
421 store
422 .refresh_hosted_did_index(&hyprstream_rpc::Subject::new(
423 hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT,
424 ))
425 .await
426 .unwrap();
427 }
428
429 let mut state = OAuthState::new(
430 &oauth,
431 hyprstream_rpc_std::policy_client::PolicyClient::new(make_client()),
432 hyprstream_rpc_std::discovery_client::DiscoveryClient::new(make_client()),
433 signing_key.verifying_key().to_bytes(),
434 )
435 .with_atproto_did_resolver(Arc::new(FixtureDidResolver {
436 did: did.to_owned(),
437 document,
438 }))
439 .with_identity_registration_api(registration_api);
440 if let Some(store) = hosted_store {
441 state = state.with_hosted_account_store(store);
442 }
443 SessionFixture {
444 state: Arc::new(state),
445 cors,
446 did,
447 atproto_key,
448 federated_resolver,
449 _storage: storage,
450 }
451 }
452
453 fn did_document(did: &str, key: &p256::ecdsa::SigningKey) -> serde_json::Value {
454 let mut multikey = vec![0x80, 0x24];
455 multikey.extend_from_slice(key.verifying_key().to_encoded_point(true).as_bytes());
456 serde_json::json!({
457 "id": did,
458 "verificationMethod": [{
459 "id": format!("{did}#atproto"),
460 "type": "Multikey",
461 "controller": did,
462 "publicKeyMultibase": format!("z{}", bs58::encode(multikey).into_string()),
463 }]
464 })
465 }
466
467 fn service_jwt(fixture: &SessionFixture, jti: &str) -> String {
468 let header = URL_SAFE_NO_PAD.encode(
469 serde_json::to_vec(&serde_json::json!({
470 "alg": "ES256", "typ": "JWT", "kid": "#atproto"
471 }))
472 .unwrap(),
473 );
474 let now = chrono::Utc::now().timestamp();
475 let payload = URL_SAFE_NO_PAD.encode(
476 serde_json::to_vec(&serde_json::json!({
477 "iss": fixture.did,
478 "aud": fixture.state.atproto_service_did().unwrap(),
479 "iat": now,
480 "exp": now + 60,
481 "lxm": ATPROTO_SESSION_EXCHANGE_NSID,
482 "jti": jti,
483 }))
484 .unwrap(),
485 );
486 let signing_input = format!("{header}.{payload}");
487 let signature: p256::ecdsa::Signature = fixture.atproto_key.sign(signing_input.as_bytes());
488 format!(
489 "{signing_input}.{}",
490 URL_SAFE_NO_PAD.encode(signature.to_bytes())
491 )
492 }
493
494 fn dpop_proof(jti: &str) -> String {
495 let key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
496 let point = key.verifying_key().to_encoded_point(false);
497 let header = URL_SAFE_NO_PAD.encode(
498 serde_json::to_vec(&serde_json::json!({
499 "alg": "ES256",
500 "typ": "dpop+jwt",
501 "jwk": {
502 "kty": "EC",
503 "crv": "P-256",
504 "x": URL_SAFE_NO_PAD.encode(point.x().unwrap()),
505 "y": URL_SAFE_NO_PAD.encode(point.y().unwrap()),
506 }
507 }))
508 .unwrap(),
509 );
510 let payload = URL_SAFE_NO_PAD.encode(
511 serde_json::to_vec(&serde_json::json!({
512 "htm": "POST",
513 "htu": format!("{ISSUER}{SESSION_EXCHANGE_PATH}"),
514 "iat": chrono::Utc::now().timestamp(),
515 "jti": jti,
516 }))
517 .unwrap(),
518 );
519 let signing_input = format!("{header}.{payload}");
520 let signature: p256::ecdsa::Signature = key.sign(signing_input.as_bytes());
521 format!(
522 "{signing_input}.{}",
523 URL_SAFE_NO_PAD.encode(signature.to_bytes())
524 )
525 }
526
527 async fn body(response: Response) -> serde_json::Value {
528 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
529 .await
530 .unwrap();
531 serde_json::from_slice(&bytes).unwrap()
532 }
533
534 fn cookie(response: &Response) -> String {
535 response.headers()[header::SET_COOKIE]
536 .to_str()
537 .unwrap()
538 .split(';')
539 .next()
540 .unwrap()
541 .to_owned()
542 }
543
544 async fn exchange_request(
545 fixture: &SessionFixture,
546 service_jti: &str,
547 dpop_jti: &str,
548 ) -> Response {
549 super::super::create_app(Arc::clone(&fixture.state), &fixture.cors)
550 .oneshot(
551 axum::http::Request::post(SESSION_EXCHANGE_PATH)
552 .header(
553 header::AUTHORIZATION,
554 format!("Bearer {}", service_jwt(fixture, service_jti)),
555 )
556 .header("DPoP", dpop_proof(dpop_jti))
557 .body(axum::body::Body::empty())
558 .unwrap(),
559 )
560 .await
561 .unwrap()
562 }
563
564 #[tokio::test]
565 async fn local_atproto_exchange_cookie_whoami_and_register_end_to_end() {
566 let fixture = fixture(true).await;
567 let exchange = exchange_request(&fixture, "local-service", "local-dpop").await;
568 assert_eq!(exchange.status(), StatusCode::OK);
569 let session_cookie = cookie(&exchange);
570 let context = body(exchange).await;
571 assert_eq!(context["did"], LOCAL_DID);
572 assert_eq!(context["kind"], "local");
573 assert_eq!(context["tenant"], TENANT);
574 assert_eq!(context["canActLocally"], true);
575
576 let app = super::super::create_app(Arc::clone(&fixture.state), &fixture.cors);
577 let whoami = app
578 .clone()
579 .oneshot(
580 axum::http::Request::get(WHOAMI_PATH)
581 .header(header::COOKIE, &session_cookie)
582 .body(axum::body::Body::empty())
583 .unwrap(),
584 )
585 .await
586 .unwrap();
587 assert_eq!(whoami.status(), StatusCode::OK);
588 assert_eq!(body(whoami).await, context);
589
590 let register = app
591 .oneshot(
592 axum::http::Request::post("/api/identity/register")
593 .header(header::COOKIE, session_cookie)
594 .header(header::CONTENT_TYPE, "application/json")
595 .body(axum::body::Body::from(r#"{"handle":"new-account"}"#))
596 .unwrap(),
597 )
598 .await
599 .unwrap();
600 assert_eq!(register.status(), StatusCode::OK);
601 assert_eq!(
602 body(register).await["did"],
603 "did:web:new-account.accounts.example.com"
604 );
605 }
606
607 #[tokio::test]
608 async fn federated_exchange_whoami_has_no_local_authority() {
609 let fixture = fixture(false).await;
610 let exchange = exchange_request(&fixture, "foreign-service", "foreign-dpop").await;
611 assert_eq!(exchange.status(), StatusCode::OK);
612 let session_cookie = cookie(&exchange);
613 let context = body(exchange).await;
614 assert_eq!(context["did"], FEDERATED_DID);
615 assert_eq!(context["kind"], "federated");
616 assert!(context["tenant"].is_null());
617 assert_eq!(context["canActLocally"], false);
618
619 let whoami = super::super::create_app(Arc::clone(&fixture.state), &fixture.cors)
620 .oneshot(
621 axum::http::Request::get(WHOAMI_PATH)
622 .header(header::COOKIE, session_cookie)
623 .body(axum::body::Body::empty())
624 .unwrap(),
625 )
626 .await
627 .unwrap();
628 assert_eq!(body(whoami).await, context);
629 }
630
631 #[tokio::test]
632 async fn intake_requires_local_exchange_authority_before_resolver_io() {
633 let fixture = fixture(false).await;
634 let exchange =
635 exchange_request(&fixture, "foreign-intake-service", "foreign-intake-dpop").await;
636 assert_eq!(exchange.status(), StatusCode::OK);
637 let session_cookie = cookie(&exchange);
638
639 let response = super::super::create_app(Arc::clone(&fixture.state), &fixture.cors)
640 .oneshot(
641 axum::http::Request::post("/api/identity/intake")
642 .header(header::COOKIE, session_cookie)
643 .header(header::CONTENT_TYPE, "application/json")
644 .body(axum::body::Body::from(
645 r#"{"did":"did:web:foreign.example"}"#,
646 ))
647 .unwrap(),
648 )
649 .await
650 .unwrap();
651 assert_eq!(response.status(), StatusCode::FORBIDDEN);
652 assert_eq!(body(response).await["error"], "local_authority_required");
653 assert_eq!(fixture.federated_resolver.calls.load(Ordering::SeqCst), 0);
654 }
655
656 #[tokio::test]
657 async fn local_exchange_authorizes_intake_and_logout_revokes_captured_cookie() {
658 let fixture = fixture(true).await;
659 let exchange =
660 exchange_request(&fixture, "local-intake-service", "local-intake-dpop").await;
661 assert_eq!(exchange.status(), StatusCode::OK);
662 let session_cookie = cookie(&exchange);
663 let app = super::super::create_app(Arc::clone(&fixture.state), &fixture.cors);
664
665 let intake = app
666 .clone()
667 .oneshot(
668 axum::http::Request::post("/api/identity/intake")
669 .header(header::COOKIE, &session_cookie)
670 .header(header::CONTENT_TYPE, "application/json")
671 .body(axum::body::Body::from(
672 r#"{"did":"did:web:foreign.example"}"#,
673 ))
674 .unwrap(),
675 )
676 .await
677 .unwrap();
678 assert_eq!(intake.status(), StatusCode::OK);
679 assert_eq!(fixture.federated_resolver.calls.load(Ordering::SeqCst), 1);
680
681 let logout = app
682 .clone()
683 .oneshot(
684 axum::http::Request::post("/oauth/logout")
685 .header(header::COOKIE, &session_cookie)
686 .body(axum::body::Body::empty())
687 .unwrap(),
688 )
689 .await
690 .unwrap();
691 assert_eq!(logout.status(), StatusCode::OK);
692 assert!(logout.headers()[header::SET_COOKIE]
693 .to_str()
694 .unwrap()
695 .contains("Max-Age=0"));
696
697 let whoami = app
698 .clone()
699 .oneshot(
700 axum::http::Request::get(WHOAMI_PATH)
701 .header(header::COOKIE, &session_cookie)
702 .body(axum::body::Body::empty())
703 .unwrap(),
704 )
705 .await
706 .unwrap();
707 assert_eq!(whoami.status(), StatusCode::OK);
708 assert_eq!(body(whoami).await["kind"], "unauthenticated");
709
710 let replayed_intake = app
711 .oneshot(
712 axum::http::Request::post("/api/identity/intake")
713 .header(header::COOKIE, session_cookie)
714 .header(header::CONTENT_TYPE, "application/json")
715 .body(axum::body::Body::from(
716 r#"{"did":"did:web:foreign.example"}"#,
717 ))
718 .unwrap(),
719 )
720 .await
721 .unwrap();
722 assert_eq!(replayed_intake.status(), StatusCode::UNAUTHORIZED);
723 assert_eq!(fixture.federated_resolver.calls.load(Ordering::SeqCst), 1);
724 }
725
726 #[tokio::test]
727 async fn unauthenticated_whoami_is_public_floor() {
728 let fixture = fixture(false).await;
729 let generic_id = fixture
730 .state
731 .sessions
732 .create(FEDERATED_DID.to_owned(), "atproto".to_owned())
733 .await;
734 let app = super::super::create_app(Arc::clone(&fixture.state), &fixture.cors);
735 for cookie in [
736 None,
737 Some(format!("{}=unknown", session::SESSION_COOKIE_NAME)),
738 Some(format!("{}={generic_id}", session::SESSION_COOKIE_NAME)),
739 ] {
740 let mut request = axum::http::Request::get(WHOAMI_PATH)
741 .body(axum::body::Body::empty())
742 .unwrap();
743 if let Some(cookie) = cookie {
744 request
745 .headers_mut()
746 .insert(header::COOKIE, cookie.parse().unwrap());
747 }
748 let response = app.clone().oneshot(request).await.unwrap();
749 assert_eq!(response.status(), StatusCode::OK);
750 assert_eq!(
751 body(response).await,
752 serde_json::json!({
753 "did": null,
754 "kind": "unauthenticated",
755 "tenant": null,
756 "canActLocally": false,
757 })
758 );
759 }
760 }
761
762 #[tokio::test]
763 async fn exchange_requires_dpop_and_consumes_service_assertion_once() {
764 let fixture = fixture(false).await;
765 let app = super::super::create_app(Arc::clone(&fixture.state), &fixture.cors);
766 let missing_dpop = app
767 .clone()
768 .oneshot(
769 axum::http::Request::post(SESSION_EXCHANGE_PATH)
770 .header(
771 header::AUTHORIZATION,
772 format!("Bearer {}", service_jwt(&fixture, "missing-dpop")),
773 )
774 .body(axum::body::Body::empty())
775 .unwrap(),
776 )
777 .await
778 .unwrap();
779 assert_eq!(missing_dpop.status(), StatusCode::BAD_REQUEST);
780 assert!(!missing_dpop.headers().contains_key(header::SET_COOKIE));
781
782 let first = exchange_request(&fixture, "one-use-service", "first-dpop").await;
783 assert_eq!(first.status(), StatusCode::OK);
784 let replay = exchange_request(&fixture, "one-use-service", "fresh-dpop").await;
785 assert_eq!(replay.status(), StatusCode::UNAUTHORIZED);
786 assert!(!replay.headers().contains_key(header::SET_COOKIE));
787 assert_eq!(body(replay).await["error"], "invalid_token");
788 }
789}