// Each integration test compiles this shared support module independently, so // helpers used by sibling tests can appear unused in one test binary. #![allow(dead_code)] use std::{net::SocketAddr, sync::Arc}; use axum::{ Router, body::{Body, to_bytes}, extract::ConnectInfo, http::{Request, Response, header::CONTENT_TYPE}, }; use cpds::{ AppState, blob_store::{BlobStore, MemoryBlobStore}, config::{AccountConfig, Config, DeploymentMode, HttpOrigin}, database::Database, domain::oauth::OAuthClient, events::RecordingEventSink, http, oauth::challenge_for_verifier, repository::RepositoryService, }; use serde_json::Value; use tower::ServiceExt; use url::Url; pub const VERIFIER: &str = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; #[derive(Clone)] pub struct TestApp { pub router: Router, pub events: Arc, pub repository: Arc, pub public_origin: HttpOrigin, } impl TestApp { pub fn new() -> Self { Self::with_blob_store(Arc::new(MemoryBlobStore::default())) } pub fn with_blob_store(blobs: Arc) -> Self { Self::assemble( blobs, HttpOrigin::parse_public("http://pds.test/", DeploymentMode::Local).unwrap(), ) } pub fn with_public_origin(public_origin: HttpOrigin) -> Self { Self::assemble(Arc::new(MemoryBlobStore::default()), public_origin) } fn assemble(blobs: Arc, public_origin: HttpOrigin) -> Self { let config = Config { deployment_mode: DeploymentMode::Local, listen_address: "127.0.0.1:3000".parse().unwrap(), public_origin: public_origin.clone(), database_path: ":memory:".into(), blob_directory: "unused".into(), blob_orphan_ttl: std::time::Duration::from_secs(86_400), blob_gc_interval: std::time::Duration::from_secs(3_600), identity_revalidation_interval: std::time::Duration::from_secs(3_600), repo_event_retention: 100_000, repo_stream_send_timeout: std::time::Duration::from_secs(10), relay_origins: Vec::new(), account: AccountConfig { did: "did:web:alice.test".to_owned(), handle: "alice.test".to_owned(), password: "correct horse battery staple".to_owned(), signing_key: [7; 32], }, oauth_clients: vec![OAuthClient { client_id: Url::parse("http://client.test/metadata.json").unwrap(), redirect_uris: vec![Url::parse("http://client.test/callback").unwrap()], name: "offline test client".to_owned(), }], }; let events = Arc::new(RecordingEventSink::default()); let state = AppState::assemble( config.clone(), Database::open_in_memory().unwrap(), blobs, events.clone(), ) .unwrap(); let repository = state.repository.clone(); Self { router: http::router(state), events, repository, public_origin, } } pub async fn send(&self, request: Request) -> Response { self.send_from("192.0.2.1:12345".parse().unwrap(), request) .await } pub async fn send_from(&self, peer: SocketAddr, mut request: Request) -> Response { request.extensions_mut().insert(ConnectInfo(peer)); self.router.clone().oneshot(request).await.unwrap() } pub async fn access_token(&self) -> String { self.access_token_with_scope("atproto").await } pub async fn access_token_with_scope(&self, scope: &str) -> String { let challenge = challenge_for_verifier(VERIFIER).unwrap(); let authorize_body = form(&[ ("client_id", "http://client.test/metadata.json"), ("redirect_uri", "http://client.test/callback"), ("state", "test-state"), ("scope", scope), ("code_challenge", &challenge), ("identifier", "alice.test"), ("password", "correct horse battery staple"), ]); let response = self .send( Request::post("/oauth/authorize") .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .body(Body::from(authorize_body)) .unwrap(), ) .await; assert_eq!(response.status(), 303); let location = response .headers() .get("location") .unwrap() .to_str() .unwrap(); let redirect = Url::parse(location).unwrap(); let code = redirect .query_pairs() .find_map(|(name, value)| (name == "code").then(|| value.into_owned())) .unwrap(); let token_body = form(&[ ("grant_type", "authorization_code"), ("code", &code), ("client_id", "http://client.test/metadata.json"), ("redirect_uri", "http://client.test/callback"), ("code_verifier", VERIFIER), ]); let response = self .send( Request::post("/oauth/token") .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .body(Body::from(token_body)) .unwrap(), ) .await; assert_eq!(response.status(), 200); json(response).await["access_token"] .as_str() .unwrap() .to_owned() } } pub fn form(pairs: &[(&str, &str)]) -> String { let mut serializer = url::form_urlencoded::Serializer::new(String::new()); serializer.extend_pairs(pairs.iter().copied()); serializer.finish() } pub async fn json(response: Response) -> Value { let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap(); serde_json::from_slice(&bytes).unwrap() }