diff --git a/Cargo.lock b/Cargo.lock index c443929..4114fa2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -105,6 +105,12 @@ dependencies = [ "tracing", ] +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base64" version = "0.22.1" @@ -176,7 +182,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fac4744fb15ae8337dc853fee7fb3f4e48c0fbaa23d0afe49c447b4fab126118" dependencies = [ "iana-time-zone", + "js-sys", "num-traits", + "serde", + "wasm-bindgen", "windows-link", ] @@ -250,6 +259,18 @@ version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -315,6 +336,20 @@ version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + [[package]] name = "either" version = "1.15.0" @@ -324,6 +359,26 @@ dependencies = [ "serde", ] +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "encoding_rs" version = "0.8.35" @@ -377,6 +432,16 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -510,6 +575,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", ] [[package]] @@ -550,6 +616,17 @@ dependencies = [ "wasip3", ] +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "h2" version = "0.4.13" @@ -575,8 +652,11 @@ version = "0.1.0" dependencies = [ "axum", "base64", + "bytes", + "chrono", "dotenvy", "jsonwebtoken", + "p256", "reqwest", "serde", "serde_json", @@ -587,6 +667,7 @@ dependencies = [ "tower-http", "tracing", "tracing-subscriber", + "uuid", ] [[package]] @@ -1231,6 +1312,18 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + [[package]] name = "parking" version = "2.2.1" @@ -1358,6 +1451,15 @@ dependencies = [ "syn", ] +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro2" version = "1.0.106" @@ -1516,6 +1618,16 @@ dependencies = [ "web-sys", ] +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + [[package]] name = "ring" version = "0.17.14" @@ -1624,6 +1736,20 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + [[package]] name = "security-framework" version = "2.11.1" @@ -2503,6 +2629,17 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "uuid" +version = "1.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee48d38b119b0cd71fe4141b30f5ba9c7c5d9f4e7a3a8b4a674e4b6ef789976f" +dependencies = [ + "getrandom 0.3.4", + "js-sys", + "wasm-bindgen", +] + [[package]] name = "valuable" version = "0.1.1" diff --git a/Cargo.toml b/Cargo.toml index 5adc70f..e9822b9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,10 @@ axum = "0.8" base64 = "0.22" dotenvy = "0.15" jsonwebtoken = "9" +bytes = "1" +chrono = { version = "0.4", features = ["serde"] } +p256 = { version = "0.13", features = ["pkcs8"] } +uuid = { version = "1", features = ["v4"] } reqwest = { version = "0.12", features = ["json"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/src/auth/middleware.rs b/src/auth/middleware.rs index e23b08e..2315dd3 100644 --- a/src/auth/middleware.rs +++ b/src/auth/middleware.rs @@ -9,6 +9,7 @@ use crate::AppState; #[derive(Debug, Clone)] pub struct Claims { did: String, + token: String, } impl Claims { @@ -16,6 +17,11 @@ impl Claims { pub fn did(&self) -> &str { &self.did } + + /// The raw Bearer token for forwarding to AIP's XRPC proxy. + pub fn token(&self) -> &str { + &self.token + } } #[derive(Deserialize)] @@ -67,6 +73,9 @@ impl FromRequestParts for Claims { .await .map_err(|e| AppError::Auth(format!("invalid userinfo response: {e}")))?; - Ok(Claims { did: info.sub }) + Ok(Claims { + did: info.sub, + token: token.to_string(), + }) } } diff --git a/src/error.rs b/src/error.rs index ebf1a43..7668c41 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,11 +1,13 @@ use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; +use bytes::Bytes; #[derive(Debug)] pub enum AppError { Auth(String), Internal(String), NotFound(String), + PdsError(StatusCode, Bytes), } impl std::fmt::Display for AppError { @@ -14,25 +16,37 @@ impl std::fmt::Display for AppError { AppError::Auth(msg) => write!(f, "auth error: {msg}"), AppError::Internal(msg) => write!(f, "internal error: {msg}"), AppError::NotFound(msg) => write!(f, "not found: {msg}"), + AppError::PdsError(status, _) => write!(f, "PDS error: {status}"), } } } impl IntoResponse for AppError { fn into_response(self) -> Response { - let (status, message) = match &self { - AppError::Auth(msg) => (StatusCode::UNAUTHORIZED, msg.clone()), - AppError::Internal(msg) => { - tracing::error!("{msg}"); - ( - StatusCode::INTERNAL_SERVER_ERROR, - "internal server error".into(), - ) - } - AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()), - }; + match self { + AppError::PdsError(status, body) => ( + status, + [(axum::http::header::CONTENT_TYPE, "application/json")], + body, + ) + .into_response(), + other => { + let (status, message) = match &other { + AppError::Auth(msg) => (StatusCode::UNAUTHORIZED, msg.clone()), + AppError::Internal(msg) => { + tracing::error!("{msg}"); + ( + StatusCode::INTERNAL_SERVER_ERROR, + "internal server error".into(), + ) + } + AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()), + AppError::PdsError(..) => unreachable!(), + }; - let body = serde_json::json!({ "error": message }); - (status, axum::Json(body)).into_response() + let body = serde_json::json!({ "error": message }); + (status, axum::Json(body)).into_response() + } + } } } diff --git a/src/main.rs b/src/main.rs index 7b053c6..a28b109 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,6 +2,7 @@ mod auth; mod config; mod error; mod profile; +mod repo; mod server; use config::Config; diff --git a/src/profile.rs b/src/profile.rs index f3fb526..7ecac36 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -66,6 +66,19 @@ pub async fn resolve_profile(http: &reqwest::Client, did: &str) -> Result Result { + let did_doc = resolve_did_document(http, did).await?; + + did_doc + .service + .iter() + .find(|s| s.id == "#atproto_pds") + .map(|s| s.service_endpoint.clone()) + .ok_or_else(|| AppError::NotFound("no PDS endpoint in DID document".into())) +} + /// Fetch a DID document from the PLC directory. // TODO: handle did:web:* resolution (fetch https://{domain}/.well-known/did.json) async fn resolve_did_document(http: &reqwest::Client, did: &str) -> Result { diff --git a/src/repo.rs b/src/repo.rs new file mode 100644 index 0000000..de7bd95 --- /dev/null +++ b/src/repo.rs @@ -0,0 +1,425 @@ +use axum::body::Bytes; +use axum::extract::State; +use axum::http::{HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::Json; +use base64::Engine; +use p256::pkcs8::EncodePrivateKey; +use serde::Deserialize; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; + +use crate::auth::Claims; +use crate::error::AppError; +use crate::AppState; + +const COLLECTION: &str = "games.gamesgamesgamesgames.game"; + +// --------------------------------------------------------------------------- +// AIP session types +// --------------------------------------------------------------------------- + +#[derive(Deserialize)] +struct AtpSession { + access_token: String, + pds_endpoint: String, + dpop_jwk: DpopJwk, +} + +#[derive(Deserialize)] +struct DpopJwk { + x: String, + y: String, + d: String, +} + +// --------------------------------------------------------------------------- +// DPoP proof generation +// --------------------------------------------------------------------------- + +#[derive(serde::Serialize)] +struct DpopClaims { + jti: String, + htm: String, + htu: String, + iat: i64, + exp: i64, + ath: String, + #[serde(skip_serializing_if = "Option::is_none")] + nonce: Option, +} + +/// Fetch the user's AT Protocol session (PDS credentials) from AIP. +async fn get_atp_session(state: &AppState, token: &str) -> Result { + let url = format!( + "{}/api/atprotocol/session", + state.config.aip_url.trim_end_matches('/') + ); + + let resp = state + .http + .get(&url) + .header("authorization", format!("Bearer {token}")) + .send() + .await + .map_err(|e| AppError::Internal(format!("AIP session request failed: {e}")))?; + + if !resp.status().is_success() { + return Err(AppError::Auth(format!( + "AIP session returned {}", + resp.status() + ))); + } + + resp.json() + .await + .map_err(|e| AppError::Internal(format!("invalid AIP session response: {e}"))) +} + +/// Generate a DPoP proof JWT for a PDS request. +fn generate_dpop_proof( + method: &str, + url: &str, + dpop_jwk: &DpopJwk, + access_token: &str, + nonce: Option<&str>, +) -> Result { + // Decode the private key from base64url + let d_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(&dpop_jwk.d) + .map_err(|e| AppError::Internal(format!("invalid DPoP key d: {e}")))?; + + let secret_key = p256::SecretKey::from_slice(&d_bytes) + .map_err(|e| AppError::Internal(format!("invalid P-256 key: {e}")))?; + + let pkcs8_der = secret_key + .to_pkcs8_der() + .map_err(|e| AppError::Internal(format!("PKCS#8 conversion failed: {e}")))?; + + let encoding_key = + jsonwebtoken::EncodingKey::from_ec_der(pkcs8_der.as_bytes()); + + // Public JWK for the header (no private component) + let public_jwk = jsonwebtoken::jwk::Jwk { + common: jsonwebtoken::jwk::CommonParameters { + public_key_use: None, + key_operations: None, + key_algorithm: None, + key_id: None, + x509_url: None, + x509_chain: None, + x509_sha1_fingerprint: None, + x509_sha256_fingerprint: None, + }, + algorithm: jsonwebtoken::jwk::AlgorithmParameters::EllipticCurve( + jsonwebtoken::jwk::EllipticCurveKeyParameters { + key_type: jsonwebtoken::jwk::EllipticCurveKeyType::EC, + curve: jsonwebtoken::jwk::EllipticCurve::P256, + x: dpop_jwk.x.clone(), + y: dpop_jwk.y.clone(), + }, + ), + }; + + let mut header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::ES256); + header.typ = Some("dpop+jwt".to_string()); + header.jwk = Some(public_jwk); + + // Access token hash (ath) + let ath_hash = Sha256::digest(access_token.as_bytes()); + let ath = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(ath_hash); + + let now = chrono::Utc::now().timestamp(); + let claims = DpopClaims { + jti: uuid::Uuid::new_v4().to_string(), + htm: method.to_uppercase(), + htu: url.to_string(), + iat: now, + exp: now + 300, + ath, + nonce: nonce.map(|n| n.to_string()), + }; + + jsonwebtoken::encode(&header, &claims, &encoding_key) + .map_err(|e| AppError::Internal(format!("DPoP proof signing failed: {e}"))) +} + +// --------------------------------------------------------------------------- +// PDS request helpers with DPoP + nonce retry +// --------------------------------------------------------------------------- + +/// Forward a PDS response back to the client, preserving status and body. +async fn forward_pds_response(resp: reqwest::Response) -> Result { + let status = resp.status(); + let body = resp + .bytes() + .await + .map_err(|e| AppError::Internal(format!("failed to read PDS response: {e}")))?; + + let axum_status = StatusCode::from_u16(status.as_u16()).unwrap(); + + if status.is_success() { + Ok(( + axum_status, + [(axum::http::header::CONTENT_TYPE, "application/json")], + body, + ) + .into_response()) + } else { + let body_str = String::from_utf8_lossy(&body); + tracing::warn!(status = %axum_status, body = %body_str, "PDS returned error"); + Err(AppError::PdsError(axum_status, body)) + } +} + +/// POST JSON to a PDS XRPC endpoint with DPoP auth and nonce retry. +async fn pds_post_json( + state: &AppState, + session: &AtpSession, + xrpc_method: &str, + body: &Value, +) -> Result { + let url = format!( + "{}/xrpc/{xrpc_method}", + session.pds_endpoint.trim_end_matches('/') + ); + + let dpop = generate_dpop_proof("POST", &url, &session.dpop_jwk, &session.access_token, None)?; + + let resp = state + .http + .post(&url) + .header("authorization", format!("DPoP {}", session.access_token)) + .header("dpop", &dpop) + .json(body) + .send() + .await + .map_err(|e| AppError::Internal(format!("PDS request failed: {e}")))?; + + // Retry with nonce if PDS requires it + if resp.status() == reqwest::StatusCode::UNAUTHORIZED { + if let Some(nonce) = resp + .headers() + .get("dpop-nonce") + .and_then(|v| v.to_str().ok()) + { + let nonce = nonce.to_string(); + tracing::debug!("retrying with DPoP nonce"); + + let dpop = generate_dpop_proof( + "POST", + &url, + &session.dpop_jwk, + &session.access_token, + Some(&nonce), + )?; + + let resp = state + .http + .post(&url) + .header("authorization", format!("DPoP {}", session.access_token)) + .header("dpop", &dpop) + .json(body) + .send() + .await + .map_err(|e| AppError::Internal(format!("PDS request retry failed: {e}")))?; + + return forward_pds_response(resp).await; + } + } + + forward_pds_response(resp).await +} + +/// POST a binary blob to the PDS with DPoP auth and nonce retry. +async fn pds_post_blob( + state: &AppState, + session: &AtpSession, + content_type: &str, + blob: Bytes, +) -> Result { + let url = format!( + "{}/xrpc/com.atproto.repo.uploadBlob", + session.pds_endpoint.trim_end_matches('/') + ); + + let dpop = generate_dpop_proof("POST", &url, &session.dpop_jwk, &session.access_token, None)?; + + let resp = state + .http + .post(&url) + .header("authorization", format!("DPoP {}", session.access_token)) + .header("dpop", &dpop) + .header("content-type", content_type) + .body(blob.clone()) + .send() + .await + .map_err(|e| AppError::Internal(format!("PDS uploadBlob failed: {e}")))?; + + if resp.status() == reqwest::StatusCode::UNAUTHORIZED { + if let Some(nonce) = resp + .headers() + .get("dpop-nonce") + .and_then(|v| v.to_str().ok()) + { + let nonce = nonce.to_string(); + tracing::debug!("retrying uploadBlob with DPoP nonce"); + + let dpop = generate_dpop_proof( + "POST", + &url, + &session.dpop_jwk, + &session.access_token, + Some(&nonce), + )?; + + let resp = state + .http + .post(&url) + .header("authorization", format!("DPoP {}", session.access_token)) + .header("dpop", &dpop) + .header("content-type", content_type) + .body(blob) + .send() + .await + .map_err(|e| AppError::Internal(format!("PDS uploadBlob retry failed: {e}")))?; + + return forward_pds_response(resp).await; + } + } + + forward_pds_response(resp).await +} + +// --------------------------------------------------------------------------- +// Public handlers +// --------------------------------------------------------------------------- + +pub async fn create_game( + State(state): State, + claims: Claims, + Json(input): Json, +) -> Result { + let session = get_atp_session(&state, claims.token()).await?; + + let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); + + let mut record = json!({ + "$type": COLLECTION, + "name": input["name"], + "createdAt": now, + }); + + let rec = record.as_object_mut().unwrap(); + + for key in &[ + "summary", + "applicationType", + "genres", + "modes", + "themes", + "playerPerspectives", + "releases", + "media", + "parent", + ] { + if let Some(val) = input.get(*key) { + if !val.is_null() { + rec.insert((*key).to_string(), val.clone()); + } + } + } + + if input.get("shouldPublish").and_then(|v| v.as_bool()) == Some(true) { + rec.insert("publishedAt".to_string(), json!(now)); + } + + let body = json!({ + "repo": claims.did(), + "collection": COLLECTION, + "record": record, + }); + + pds_post_json(&state, &session, "com.atproto.repo.createRecord", &body).await +} + +pub async fn put_game( + State(state): State, + claims: Claims, + Json(input): Json, +) -> Result { + let uri = input + .get("uri") + .and_then(|v| v.as_str()) + .ok_or_else(|| AppError::Auth("missing uri field".into()))?; + + // Extract rkey from AT URI: at://did/collection/rkey + let rkey = uri + .split('/') + .last() + .ok_or_else(|| AppError::Internal("invalid AT URI".into()))?; + + let session = get_atp_session(&state, claims.token()).await?; + + let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); + + let created_at = input + .get("createdAt") + .and_then(|v| v.as_str()) + .unwrap_or(&now); + + let mut record = json!({ + "$type": COLLECTION, + "name": input["name"], + "createdAt": created_at, + }); + + let rec = record.as_object_mut().unwrap(); + + for key in &[ + "summary", + "applicationType", + "genres", + "modes", + "themes", + "playerPerspectives", + "releases", + "media", + "parent", + ] { + if let Some(val) = input.get(*key) { + if !val.is_null() { + rec.insert((*key).to_string(), val.clone()); + } + } + } + + if input.get("shouldPublish").and_then(|v| v.as_bool()) == Some(true) { + rec.insert("publishedAt".to_string(), json!(now)); + } + + let body = json!({ + "repo": claims.did(), + "collection": COLLECTION, + "rkey": rkey, + "record": record, + }); + + pds_post_json(&state, &session, "com.atproto.repo.putRecord", &body).await +} + +pub async fn upload_blob( + State(state): State, + claims: Claims, + headers: HeaderMap, + body: Bytes, +) -> Result { + let session = get_atp_session(&state, claims.token()).await?; + + let content_type = headers + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + + pds_post_blob(&state, &session, content_type, body).await +} diff --git a/src/server.rs b/src/server.rs index 11d6478..e1b0074 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1,5 +1,5 @@ -use axum::extract::State; -use axum::routing::get; +use axum::extract::{DefaultBodyLimit, State}; +use axum::routing::{get, post}; use axum::{Json, Router}; use tower_http::cors::CorsLayer; use tower_http::trace::TraceLayer; @@ -7,12 +7,25 @@ use tower_http::trace::TraceLayer; use crate::auth::Claims; use crate::error::AppError; use crate::profile; +use crate::repo; use crate::AppState; pub fn router(state: AppState) -> Router { Router::new() .route("/health", get(health)) .route("/xrpc/app.bsky.actor.getProfile", get(get_profile)) + .route( + "/xrpc/games.gamesgamesgamesgames.createGame", + post(repo::create_game), + ) + .route( + "/xrpc/games.gamesgamesgamesgames.putGame", + post(repo::put_game), + ) + .route( + "/xrpc/com.atproto.repo.uploadBlob", + post(repo::upload_blob).layer(DefaultBodyLimit::max(50 * 1024 * 1024)), + ) .layer(TraceLayer::new_for_http()) .layer(CorsLayer::permissive()) .with_state(state)