Microservice to bring 2FA to self hosted PDSes
at main 22 kB view raw
1use crate::AppState; 2use crate::helpers::{ 3 AuthResult, ProxiedResult, TokenCheckError, VerifyServiceAuthError, json_error_response, 4 preauth_check, proxy_get_json, verify_gate_token, verify_service_auth, 5}; 6use crate::middleware::Did; 7use axum::body::{Body, to_bytes}; 8use axum::extract::State; 9use axum::http::{HeaderMap, StatusCode, header}; 10use axum::response::{IntoResponse, Response}; 11use axum::{Extension, Json, debug_handler, extract, extract::Request}; 12use chrono::{Duration, Utc}; 13use jacquard_common::types::did::Did as JacquardDid; 14use serde::{Deserialize, Serialize}; 15use serde_json; 16use tracing::log; 17 18#[derive(Serialize, Deserialize, Debug, Clone)] 19#[serde(rename_all = "camelCase")] 20enum AccountStatus { 21 Takendown, 22 Suspended, 23 Deactivated, 24} 25 26#[derive(Serialize, Deserialize, Debug, Clone)] 27#[serde(rename_all = "camelCase")] 28struct GetSessionResponse { 29 handle: String, 30 did: String, 31 #[serde(skip_serializing_if = "Option::is_none")] 32 email: Option<String>, 33 #[serde(skip_serializing_if = "Option::is_none")] 34 email_confirmed: Option<bool>, 35 #[serde(skip_serializing_if = "Option::is_none")] 36 email_auth_factor: Option<bool>, 37 #[serde(skip_serializing_if = "Option::is_none")] 38 did_doc: Option<String>, 39 #[serde(skip_serializing_if = "Option::is_none")] 40 active: Option<bool>, 41 #[serde(skip_serializing_if = "Option::is_none")] 42 status: Option<AccountStatus>, 43} 44 45#[derive(Serialize, Deserialize, Debug, Clone)] 46#[serde(rename_all = "camelCase")] 47pub struct UpdateEmailResponse { 48 email: String, 49 #[serde(skip_serializing_if = "Option::is_none")] 50 email_auth_factor: Option<bool>, 51 #[serde(skip_serializing_if = "Option::is_none")] 52 token: Option<String>, 53} 54 55#[allow(dead_code)] 56#[derive(Deserialize, Serialize)] 57#[serde(rename_all = "camelCase")] 58pub struct CreateSessionRequest { 59 identifier: String, 60 password: String, 61 #[serde(skip_serializing_if = "Option::is_none")] 62 auth_factor_token: Option<String>, 63 #[serde(skip_serializing_if = "Option::is_none")] 64 allow_takendown: Option<bool>, 65} 66 67#[derive(Deserialize, Serialize, Debug)] 68#[serde(rename_all = "camelCase")] 69pub struct CreateAccountRequest { 70 handle: String, 71 #[serde(skip_serializing_if = "Option::is_none")] 72 email: Option<String>, 73 #[serde(skip_serializing_if = "Option::is_none")] 74 password: Option<String>, 75 #[serde(skip_serializing_if = "Option::is_none")] 76 did: Option<String>, 77 #[serde(skip_serializing_if = "Option::is_none")] 78 invite_code: Option<String>, 79 #[serde(skip_serializing_if = "Option::is_none")] 80 verification_code: Option<String>, 81 #[serde(skip_serializing_if = "Option::is_none")] 82 plc_op: Option<serde_json::Value>, 83} 84 85#[derive(Deserialize, Serialize, Debug, Clone)] 86#[serde(rename_all = "camelCase")] 87pub struct DescribeServerContact { 88 #[serde(skip_serializing_if = "Option::is_none")] 89 email: Option<String>, 90} 91 92#[derive(Deserialize, Serialize, Debug, Clone)] 93#[serde(rename_all = "camelCase")] 94pub struct DescribeServerLinks { 95 #[serde(skip_serializing_if = "Option::is_none")] 96 privacy_policy: Option<String>, 97 #[serde(skip_serializing_if = "Option::is_none")] 98 terms_of_service: Option<String>, 99} 100 101#[derive(Deserialize, Serialize, Debug, Clone)] 102#[serde(rename_all = "camelCase")] 103pub struct DescribeServerResponse { 104 #[serde(skip_serializing_if = "Option::is_none")] 105 invite_code_required: Option<bool>, 106 #[serde(skip_serializing_if = "Option::is_none")] 107 phone_verification_required: Option<bool>, 108 #[serde(skip_serializing_if = "Option::is_none")] 109 available_user_domains: Option<Vec<String>>, 110 #[serde(skip_serializing_if = "Option::is_none")] 111 links: Option<DescribeServerLinks>, 112 #[serde(skip_serializing_if = "Option::is_none")] 113 contact: Option<DescribeServerContact>, 114 #[serde(skip_serializing_if = "Option::is_none")] 115 did: Option<String>, 116} 117 118pub async fn create_session( 119 State(state): State<AppState>, 120 headers: HeaderMap, 121 Json(payload): extract::Json<CreateSessionRequest>, 122) -> Result<Response<Body>, StatusCode> { 123 let identifier = payload.identifier.clone(); 124 let password = payload.password.clone(); 125 let auth_factor_token = payload.auth_factor_token.clone(); 126 127 // Run the shared pre-auth logic to validate and check 2FA requirement 128 match preauth_check(&state, &identifier, &password, auth_factor_token, false).await { 129 Ok(result) => match result { 130 AuthResult::WrongIdentityOrPassword => json_error_response( 131 StatusCode::UNAUTHORIZED, 132 "AuthenticationRequired", 133 "Invalid identifier or password", 134 ), 135 AuthResult::TwoFactorRequired(_) => { 136 // Email sending step can be handled here if needed in the future. 137 json_error_response( 138 StatusCode::UNAUTHORIZED, 139 "AuthFactorTokenRequired", 140 "A sign in code has been sent to your email address", 141 ) 142 } 143 AuthResult::ProxyThrough => { 144 //No 2FA or already passed 145 let uri = format!( 146 "{}{}", 147 state.app_config.pds_base_url, "/xrpc/com.atproto.server.createSession" 148 ); 149 150 let mut req = axum::http::Request::post(uri); 151 if let Some(req_headers) = req.headers_mut() { 152 req_headers.extend(headers.clone()); 153 } 154 155 let payload_bytes = 156 serde_json::to_vec(&payload).map_err(|_| StatusCode::BAD_REQUEST)?; 157 let req = req 158 .body(Body::from(payload_bytes)) 159 .map_err(|_| StatusCode::BAD_REQUEST)?; 160 161 let proxied = state 162 .reverse_proxy_client 163 .request(req) 164 .await 165 .map_err(|_| StatusCode::BAD_REQUEST)? 166 .into_response(); 167 168 Ok(proxied) 169 } 170 AuthResult::TokenCheckFailed(err) => match err { 171 TokenCheckError::InvalidToken => { 172 json_error_response(StatusCode::BAD_REQUEST, "InvalidToken", "Token is invalid") 173 } 174 TokenCheckError::ExpiredToken => { 175 json_error_response(StatusCode::BAD_REQUEST, "ExpiredToken", "Token is expired") 176 } 177 }, 178 }, 179 Err(err) => { 180 log::error!( 181 "Error during pre-auth check. This happens on the create_session endpoint when trying to decide if the user has access:\n {err}" 182 ); 183 json_error_response( 184 StatusCode::INTERNAL_SERVER_ERROR, 185 "InternalServerError", 186 "This error was not generated by the PDS, but PDS Gatekeeper. Please contact your PDS administrator for help and for them to review the server logs.", 187 ) 188 } 189 } 190} 191 192#[debug_handler] 193pub async fn update_email( 194 State(state): State<AppState>, 195 Extension(did): Extension<Did>, 196 headers: HeaderMap, 197 Json(payload): extract::Json<UpdateEmailResponse>, 198) -> Result<Response<Body>, StatusCode> { 199 //If email auth is not set at all it is a update email address 200 let email_auth_not_set = payload.email_auth_factor.is_none(); 201 //If email auth is set it is to either turn on or off 2fa 202 let email_auth_update = payload.email_auth_factor.unwrap_or(false); 203 204 //This means the middleware successfully extracted a did from the request, if not it just needs to be forward to the PDS 205 //This is also empty if it is an oauth request, which is not supported by gatekeeper turning on 2fa since the dpop stuff needs to be implemented 206 let did_is_not_empty = did.0.is_some(); 207 208 if did_is_not_empty { 209 // Email update asked for 210 if email_auth_update { 211 let email = payload.email.clone(); 212 let email_confirmed = match sqlx::query_as::<_, (String,)>( 213 "SELECT did FROM account WHERE emailConfirmedAt IS NOT NULL AND email = ?", 214 ) 215 .bind(&email) 216 .fetch_optional(&state.account_pool) 217 .await 218 { 219 Ok(row) => row, 220 Err(err) => { 221 log::error!("Error checking if email is confirmed: {err}"); 222 return Err(StatusCode::BAD_REQUEST); 223 } 224 }; 225 226 //Since the email is already confirmed we can enable 2fa 227 return match email_confirmed { 228 None => Err(StatusCode::BAD_REQUEST), 229 Some(did_row) => { 230 let _ = sqlx::query( 231 "INSERT INTO two_factor_accounts (did, required) VALUES (?, 1) ON CONFLICT(did) DO UPDATE SET required = 1", 232 ) 233 .bind(&did_row.0) 234 .execute(&state.pds_gatekeeper_pool) 235 .await 236 .map_err(|_| StatusCode::BAD_REQUEST)?; 237 238 Ok(StatusCode::OK.into_response()) 239 } 240 }; 241 } 242 243 // User wants auth turned off 244 if !email_auth_update && !email_auth_not_set { 245 //User wants auth turned off and has a token 246 if let Some(token) = &payload.token { 247 let token_found = match sqlx::query_as::<_, (String,)>( 248 "SELECT token FROM email_token WHERE token = ? AND did = ? AND purpose = 'update_email'", 249 ) 250 .bind(token) 251 .bind(&did.0) 252 .fetch_optional(&state.account_pool) 253 .await{ 254 Ok(token) => token, 255 Err(err) => { 256 log::error!("Error checking if token is valid: {err}"); 257 return Err(StatusCode::BAD_REQUEST); 258 } 259 }; 260 261 return if token_found.is_some() { 262 //TODO I think there may be a bug here and need to do some retry logic 263 // First try was erroring, seconds was allowing 264 match sqlx::query( 265 "INSERT INTO two_factor_accounts (did, required) VALUES (?, 0) ON CONFLICT(did) DO UPDATE SET required = 0", 266 ) 267 .bind(&did.0) 268 .execute(&state.pds_gatekeeper_pool) 269 .await { 270 Ok(_) => {} 271 Err(err) => { 272 log::error!("Error updating email auth: {err}"); 273 return Err(StatusCode::BAD_REQUEST); 274 } 275 } 276 277 Ok(StatusCode::OK.into_response()) 278 } else { 279 Err(StatusCode::BAD_REQUEST) 280 }; 281 } 282 } 283 } 284 // Updating the actual email address by sending it on to the PDS 285 let uri = format!( 286 "{}{}", 287 state.app_config.pds_base_url, "/xrpc/com.atproto.server.updateEmail" 288 ); 289 let mut req = axum::http::Request::post(uri); 290 if let Some(req_headers) = req.headers_mut() { 291 req_headers.extend(headers.clone()); 292 } 293 294 let payload_bytes = serde_json::to_vec(&payload).map_err(|_| StatusCode::BAD_REQUEST)?; 295 let req = req 296 .body(Body::from(payload_bytes)) 297 .map_err(|_| StatusCode::BAD_REQUEST)?; 298 299 let proxied = state 300 .reverse_proxy_client 301 .request(req) 302 .await 303 .map_err(|_| StatusCode::BAD_REQUEST)? 304 .into_response(); 305 306 Ok(proxied) 307} 308 309pub async fn get_session( 310 State(state): State<AppState>, 311 req: Request, 312) -> Result<Response<Body>, StatusCode> { 313 match proxy_get_json::<GetSessionResponse>(&state, req, "/xrpc/com.atproto.server.getSession") 314 .await? 315 { 316 ProxiedResult::Parsed { 317 value: mut session, .. 318 } => { 319 let did = session.did.clone(); 320 let required_opt = sqlx::query_as::<_, (u8,)>( 321 "SELECT required FROM two_factor_accounts WHERE did = ? LIMIT 1", 322 ) 323 .bind(&did) 324 .fetch_optional(&state.pds_gatekeeper_pool) 325 .await 326 .map_err(|_| StatusCode::BAD_REQUEST)?; 327 328 let email_auth_factor = match required_opt { 329 Some(row) => row.0 != 0, 330 None => false, 331 }; 332 333 session.email_auth_factor = Some(email_auth_factor); 334 Ok(Json(session).into_response()) 335 } 336 ProxiedResult::Passthrough(resp) => Ok(resp), 337 } 338} 339 340pub async fn describe_server( 341 State(state): State<AppState>, 342 req: Request, 343) -> Result<Response<Body>, StatusCode> { 344 match proxy_get_json::<DescribeServerResponse>( 345 &state, 346 req, 347 "/xrpc/com.atproto.server.describeServer", 348 ) 349 .await? 350 { 351 ProxiedResult::Parsed { 352 value: mut server_info, 353 .. 354 } => { 355 //This signifies the server is configured for captcha verification 356 server_info.phone_verification_required = Some(state.app_config.use_captcha); 357 Ok(Json(server_info).into_response()) 358 } 359 ProxiedResult::Passthrough(resp) => Ok(resp), 360 } 361} 362 363/// Verify a gate code matches the handle and is not expired 364async fn verify_gate_code( 365 state: &AppState, 366 code: &str, 367 handle: &str, 368) -> Result<bool, anyhow::Error> { 369 // First, decrypt and verify the JWE token 370 let payload = match verify_gate_token(code, &state.app_config.gate_jwe_key) { 371 Ok(p) => p, 372 Err(e) => { 373 log::warn!("Failed to decrypt gate token: {}", e); 374 return Ok(false); 375 } 376 }; 377 378 // Verify the handle matches 379 if payload.handle != handle { 380 log::warn!( 381 "Gate code handle mismatch: expected {}, got {}", 382 handle, 383 payload.handle 384 ); 385 return Ok(false); 386 } 387 388 let created_at = chrono::DateTime::parse_from_rfc3339(&payload.created_at) 389 .map_err(|e| anyhow::anyhow!("Failed to parse created_at from token: {}", e))? 390 .with_timezone(&Utc); 391 392 let now = Utc::now(); 393 let age = now - created_at; 394 395 // Check if the token is expired (5 minutes) 396 if age > Duration::minutes(5) { 397 log::warn!("Gate code expired for handle {}", handle); 398 return Ok(false); 399 } 400 401 // Verify the token exists in the database (to prevent reuse) 402 let row: Option<(String,)> = 403 sqlx::query_as("SELECT code FROM gate_codes WHERE code = ? and handle = ? LIMIT 1") 404 .bind(code) 405 .bind(handle) 406 .fetch_optional(&state.pds_gatekeeper_pool) 407 .await?; 408 409 if row.is_none() { 410 log::warn!("Gate code not found in database or already used"); 411 return Ok(false); 412 } 413 414 // Token is valid, delete it so it can't be reused 415 //TODO probably also delete expired codes? Will need to do that at some point probably altho the where is on code and handle 416 417 sqlx::query("DELETE FROM gate_codes WHERE code = ?") 418 .bind(code) 419 .execute(&state.pds_gatekeeper_pool) 420 .await?; 421 422 Ok(true) 423} 424 425pub async fn create_account( 426 State(state): State<AppState>, 427 req: Request, 428) -> Result<Response<Body>, StatusCode> { 429 let headers = req.headers().clone(); 430 let body_bytes = to_bytes(req.into_body(), usize::MAX) 431 .await 432 .map_err(|_| StatusCode::BAD_REQUEST)?; 433 434 // Parse the body to check for verification code 435 let account_request: CreateAccountRequest = 436 serde_json::from_slice(&body_bytes).map_err(|e| { 437 log::error!("Failed to parse create account request: {}", e); 438 StatusCode::BAD_REQUEST 439 })?; 440 441 // Check for service auth (migrations) if configured 442 if state.app_config.allow_only_migrations { 443 // Expect Authorization: Bearer <jwt> 444 let auth_header = headers 445 .get(header::AUTHORIZATION) 446 .and_then(|v| v.to_str().ok()) 447 .map(str::to_string); 448 449 let Some(value) = auth_header else { 450 log::error!("No Authorization header found in the request"); 451 return json_error_response( 452 StatusCode::UNAUTHORIZED, 453 "InvalidAuth", 454 "This PDS is configured to only allow accounts created by migrations via this endpoint.", 455 ); 456 }; 457 458 // Ensure Bearer prefix 459 let token = value.strip_prefix("Bearer ").unwrap_or("").trim(); 460 if token.is_empty() { 461 log::error!("No Service Auth token found in the Authorization header"); 462 return json_error_response( 463 StatusCode::UNAUTHORIZED, 464 "InvalidAuth", 465 "This PDS is configured to only allow accounts created by migrations via this endpoint.", 466 ); 467 } 468 469 // Ensure a non-empty DID was provided when migrations are enabled 470 let requested_did_str = match account_request.did.as_deref() { 471 Some(s) if !s.trim().is_empty() => s, 472 _ => { 473 return json_error_response( 474 StatusCode::BAD_REQUEST, 475 "InvalidRequest", 476 "The 'did' field is required when migrations are enforced.", 477 ); 478 } 479 }; 480 481 // Parse the DID into the expected type for verification 482 let requested_did: JacquardDid<'static> = match requested_did_str.parse() { 483 Ok(d) => d, 484 Err(e) => { 485 log::error!( 486 "Invalid DID format provided in createAccount: {} | error: {}", 487 requested_did_str, 488 e 489 ); 490 return json_error_response( 491 StatusCode::BAD_REQUEST, 492 "InvalidRequest", 493 "The 'did' field is not a valid DID.", 494 ); 495 } 496 }; 497 498 let nsid = "com.atproto.server.createAccount".parse().unwrap(); 499 match verify_service_auth( 500 token, 501 &nsid, 502 state.resolver.clone(), 503 &state.app_config.pds_service_did, 504 &requested_did, 505 ) 506 .await 507 { 508 //Just do nothing if it passes so it continues. 509 Ok(_) => {} 510 Err(err) => match err { 511 VerifyServiceAuthError::AuthFailed => { 512 return json_error_response( 513 StatusCode::UNAUTHORIZED, 514 "InvalidAuth", 515 "This PDS is configured to only allow accounts created by migrations via this endpoint.", 516 ); 517 } 518 VerifyServiceAuthError::Error(err) => { 519 log::error!("Error verifying service auth token: {err}"); 520 return json_error_response( 521 StatusCode::BAD_REQUEST, 522 "InvalidRequest", 523 "There has been an error, please contact your PDS administrator for help and for them to review the server logs.", 524 ); 525 } 526 }, 527 } 528 } 529 530 // Check for captcha verification if configured 531 if state.app_config.use_captcha { 532 if let Some(ref verification_code) = account_request.verification_code { 533 match verify_gate_code(&state, verification_code, &account_request.handle).await { 534 //TODO has a few errors to support 535 536 //expired token 537 // { 538 // "error": "ExpiredToken", 539 // "message": "Token has expired" 540 // } 541 542 //TODO ALSO add rate limits on the /gate endpoints so they can't be abused 543 Ok(true) => { 544 log::info!("Gate code verified for handle: {}", account_request.handle); 545 } 546 Ok(false) => { 547 log::warn!( 548 "Invalid or expired gate code for handle: {}", 549 account_request.handle 550 ); 551 return json_error_response( 552 StatusCode::BAD_REQUEST, 553 "InvalidToken", 554 "Token could not be verified", 555 ); 556 } 557 Err(e) => { 558 log::error!("Error verifying gate code: {}", e); 559 return json_error_response( 560 StatusCode::INTERNAL_SERVER_ERROR, 561 "InvalidToken", 562 "Token could not be verified", 563 ); 564 } 565 } 566 } else { 567 // No verification code provided but captcha is required 568 log::warn!( 569 "No verification code provided for account creation: {}", 570 account_request.handle 571 ); 572 return json_error_response( 573 StatusCode::BAD_REQUEST, 574 "InvalidRequest", 575 "Verification is now required on this server.", 576 ); 577 } 578 } 579 580 // Rebuild the request with the same body and headers 581 let uri = format!( 582 "{}{}", 583 state.app_config.pds_base_url, "/xrpc/com.atproto.server.createAccount" 584 ); 585 586 let mut new_req = axum::http::Request::post(&uri); 587 if let Some(req_headers) = new_req.headers_mut() { 588 *req_headers = headers; 589 } 590 591 let new_req = new_req 592 .body(Body::from(body_bytes)) 593 .map_err(|_| StatusCode::BAD_REQUEST)?; 594 595 let proxied = state 596 .reverse_proxy_client 597 .request(new_req) 598 .await 599 .map_err(|_| StatusCode::BAD_REQUEST)? 600 .into_response(); 601 602 Ok(proxied) 603}