Something went wrong. Try again.
Chris’s PDS implementation
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175// 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<RecordingEventSink>, pub repository: Arc<RepositoryService>, 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<dyn BlobStore>) -> 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<dyn BlobStore>, 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<Body>) -> Response<Body> { self.send_from("192.0.2.1:12345".parse().unwrap(), request) .await }
pub async fn send_from(&self, peer: SocketAddr, mut request: Request<Body>) -> Response<Body> { 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<Body>) -> Value { let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap(); serde_json::from_slice(&bytes).unwrap()}