this repo has no description
1use aws_config::BehaviorVersion; 2use aws_sdk_s3::Client as S3Client; 3use aws_sdk_s3::config::Credentials; 4use bspds::state::AppState; 5use chrono::Utc; 6use reqwest::{Client, StatusCode, header}; 7use serde_json::{Value, json}; 8use sqlx::postgres::PgPoolOptions; 9#[allow(unused_imports)] 10use std::collections::HashMap; 11use std::sync::OnceLock; 12#[allow(unused_imports)] 13use std::time::Duration; 14use testcontainers::core::ContainerPort; 15use testcontainers::{ContainerAsync, GenericImage, ImageExt, runners::AsyncRunner}; 16use testcontainers_modules::postgres::Postgres; 17use tokio::net::TcpListener; 18use wiremock::matchers::{method, path}; 19use wiremock::{Mock, MockServer, ResponseTemplate}; 20 21static SERVER_URL: OnceLock<String> = OnceLock::new(); 22static DB_CONTAINER: OnceLock<ContainerAsync<Postgres>> = OnceLock::new(); 23static S3_CONTAINER: OnceLock<ContainerAsync<GenericImage>> = OnceLock::new(); 24static MOCK_APPVIEW: OnceLock<MockServer> = OnceLock::new(); 25 26#[allow(dead_code)] 27pub const AUTH_TOKEN: &str = "test-token"; 28#[allow(dead_code)] 29pub const BAD_AUTH_TOKEN: &str = "bad-token"; 30#[allow(dead_code)] 31pub const AUTH_DID: &str = "did:plc:fake"; 32#[allow(dead_code)] 33pub const TARGET_DID: &str = "did:plc:target"; 34 35#[cfg(test)] 36#[ctor::dtor] 37fn cleanup() { 38 // my attempt to force clean up containers created by this test binary. 39 // this is a fallback in case ryuk fails or is not supported 40 if std::env::var("XDG_RUNTIME_DIR").is_ok() { 41 let _ = std::process::Command::new("podman") 42 .args(&["rm", "-f", "--filter", "label=bspds_test=true"]) 43 .output(); 44 } 45 46 let _ = std::process::Command::new("docker") 47 .args(&["container", "prune", "-f", "--filter", "label=bspds_test=true"]) 48 .output(); 49} 50 51#[allow(dead_code)] 52pub fn client() -> Client { 53 Client::new() 54} 55 56pub async fn base_url() -> &'static str { 57 SERVER_URL.get_or_init(|| { 58 let (tx, rx) = std::sync::mpsc::channel(); 59 60 std::thread::spawn(move || { 61 if std::env::var("DOCKER_HOST").is_err() { 62 if let Ok(runtime_dir) = std::env::var("XDG_RUNTIME_DIR") { 63 let podman_sock = std::path::Path::new(&runtime_dir).join("podman/podman.sock"); 64 if podman_sock.exists() { 65 unsafe { 66 std::env::set_var( 67 "DOCKER_HOST", 68 format!("unix://{}", podman_sock.display()), 69 ); 70 } 71 } 72 } 73 } 74 75 let rt = tokio::runtime::Runtime::new().unwrap(); 76 rt.block_on(async move { 77 let s3_container = GenericImage::new("minio/minio", "latest") 78 .with_exposed_port(ContainerPort::Tcp(9000)) 79 .with_env_var("MINIO_ROOT_USER", "minioadmin") 80 .with_env_var("MINIO_ROOT_PASSWORD", "minioadmin") 81 .with_cmd(vec!["server".to_string(), "/data".to_string()]) 82 .with_label("bspds_test", "true") 83 .start() 84 .await 85 .expect("Failed to start MinIO"); 86 87 let s3_port = s3_container 88 .get_host_port_ipv4(9000) 89 .await 90 .expect("Failed to get S3 port"); 91 let s3_endpoint = format!("http://127.0.0.1:{}", s3_port); 92 93 unsafe { 94 std::env::set_var("S3_BUCKET", "test-bucket"); 95 std::env::set_var("AWS_ACCESS_KEY_ID", "minioadmin"); 96 std::env::set_var("AWS_SECRET_ACCESS_KEY", "minioadmin"); 97 std::env::set_var("AWS_REGION", "us-east-1"); 98 std::env::set_var("S3_ENDPOINT", &s3_endpoint); 99 } 100 101 let sdk_config = aws_config::defaults(BehaviorVersion::latest()) 102 .region("us-east-1") 103 .endpoint_url(&s3_endpoint) 104 .credentials_provider(Credentials::new( 105 "minioadmin", 106 "minioadmin", 107 None, 108 None, 109 "test", 110 )) 111 .load() 112 .await; 113 114 let s3_config = aws_sdk_s3::config::Builder::from(&sdk_config) 115 .force_path_style(true) 116 .build(); 117 let s3_client = S3Client::from_conf(s3_config); 118 119 let _ = s3_client.create_bucket().bucket("test-bucket").send().await; 120 121 let mock_server = MockServer::start().await; 122 123 Mock::given(method("GET")) 124 .and(path("/xrpc/app.bsky.actor.getProfile")) 125 .respond_with(ResponseTemplate::new(200).set_body_json(json!({ 126 "handle": "mock.handle", 127 "did": "did:plc:mock", 128 "displayName": "Mock User" 129 }))) 130 .mount(&mock_server) 131 .await; 132 133 Mock::given(method("GET")) 134 .and(path("/xrpc/app.bsky.actor.searchActors")) 135 .respond_with(ResponseTemplate::new(200).set_body_json(json!({ 136 "actors": [], 137 "cursor": null 138 }))) 139 .mount(&mock_server) 140 .await; 141 142 unsafe { 143 std::env::set_var("APPVIEW_URL", mock_server.uri()); 144 } 145 MOCK_APPVIEW.set(mock_server).ok(); 146 147 S3_CONTAINER.set(s3_container).ok(); 148 149 let container = Postgres::default() 150 .with_tag("18-alpine") 151 .with_label("bspds_test", "true") 152 .start() 153 .await 154 .expect("Failed to start Postgres"); 155 let connection_string = format!( 156 "postgres://postgres:postgres@127.0.0.1:{}/postgres", 157 container 158 .get_host_port_ipv4(5432) 159 .await 160 .expect("Failed to get port") 161 ); 162 163 DB_CONTAINER.set(container).ok(); 164 165 let url = spawn_app(connection_string).await; 166 tx.send(url).unwrap(); 167 std::future::pending::<()>().await; 168 }); 169 }); 170 171 rx.recv().expect("Failed to start test server") 172 }) 173} 174 175async fn spawn_app(database_url: String) -> String { 176 let pool = PgPoolOptions::new() 177 .max_connections(50) 178 .connect(&database_url) 179 .await 180 .expect("Failed to connect to Postgres. Make sure the database is running."); 181 182 sqlx::migrate!("./migrations") 183 .run(&pool) 184 .await 185 .expect("Failed to run migrations"); 186 187 let state = AppState::new(pool).await; 188 let app = bspds::app(state); 189 190 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); 191 let addr = listener.local_addr().unwrap(); 192 193 tokio::spawn(async move { 194 axum::serve(listener, app).await.unwrap(); 195 }); 196 197 format!("http://{}", addr) 198} 199 200#[allow(dead_code)] 201pub async fn upload_test_blob(client: &Client, data: &'static str, mime: &'static str) -> Value { 202 let res = client 203 .post(format!( 204 "{}/xrpc/com.atproto.repo.uploadBlob", 205 base_url().await 206 )) 207 .header(header::CONTENT_TYPE, mime) 208 .bearer_auth(AUTH_TOKEN) 209 .body(data) 210 .send() 211 .await 212 .expect("Failed to send uploadBlob request"); 213 214 assert_eq!(res.status(), StatusCode::OK, "Failed to upload blob"); 215 let body: Value = res.json().await.expect("Blob upload response was not JSON"); 216 body["blob"].clone() 217} 218 219#[allow(dead_code)] 220pub async fn create_test_post( 221 client: &Client, 222 text: &str, 223 reply_to: Option<Value>, 224) -> (String, String, String) { 225 let collection = "app.bsky.feed.post"; 226 let mut record = json!({ 227 "$type": collection, 228 "text": text, 229 "createdAt": Utc::now().to_rfc3339() 230 }); 231 232 if let Some(reply_obj) = reply_to { 233 record["reply"] = reply_obj; 234 } 235 236 let payload = json!({ 237 "repo": AUTH_DID, 238 "collection": collection, 239 "record": record 240 }); 241 242 let res = client 243 .post(format!( 244 "{}/xrpc/com.atproto.repo.createRecord", 245 base_url().await 246 )) 247 .bearer_auth(AUTH_TOKEN) 248 .json(&payload) 249 .send() 250 .await 251 .expect("Failed to send createRecord"); 252 253 assert_eq!(res.status(), StatusCode::OK, "Failed to create post record"); 254 let body: Value = res 255 .json() 256 .await 257 .expect("createRecord response was not JSON"); 258 259 let uri = body["uri"] 260 .as_str() 261 .expect("Response had no URI") 262 .to_string(); 263 let cid = body["cid"] 264 .as_str() 265 .expect("Response had no CID") 266 .to_string(); 267 let rkey = uri 268 .split('/') 269 .last() 270 .expect("URI was malformed") 271 .to_string(); 272 273 (uri, cid, rkey) 274} 275 276#[allow(dead_code)] 277pub async fn create_account_and_login(client: &Client) -> (String, String) { 278 let mut last_error = String::new(); 279 280 for attempt in 0..3 { 281 if attempt > 0 { 282 tokio::time::sleep(Duration::from_millis(100 * (attempt as u64 + 1))).await; 283 } 284 285 let handle = format!("user_{}", uuid::Uuid::new_v4()); 286 let payload = json!({ 287 "handle": handle, 288 "email": format!("{}@example.com", handle), 289 "password": "password" 290 }); 291 292 let res = match client 293 .post(format!( 294 "{}/xrpc/com.atproto.server.createAccount", 295 base_url().await 296 )) 297 .json(&payload) 298 .send() 299 .await 300 { 301 Ok(r) => r, 302 Err(e) => { 303 last_error = format!("Request failed: {}", e); 304 continue; 305 } 306 }; 307 308 if res.status() == StatusCode::OK { 309 let body: Value = res.json().await.expect("Invalid JSON"); 310 let access_jwt = body["accessJwt"] 311 .as_str() 312 .expect("No accessJwt") 313 .to_string(); 314 let did = body["did"].as_str().expect("No did").to_string(); 315 return (access_jwt, did); 316 } 317 318 last_error = format!("Status {}: {:?}", res.status(), res.text().await); 319 } 320 321 panic!("Failed to create account after 3 attempts: {}", last_error); 322}