Something went wrong. Try again.
Chris’s PDS implementation
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447//! Writer discovery, authenticated notices, and subscription registration.
use crate::http::request::{JsonRequest, SpaceJson, SpaceQuery};use axum::{ Json, extract::{OriginalUri, Query, State},};use futures::{StreamExt as _, stream};use serde::{Deserialize, Serialize};use serde_json::{Value, json};
use crate::{ AppState, clock::format_utc_datetime, error::{Error, ErrorContext as _}, events::best_effort_notice, http::{ApiResult, auth}, space::{ NotifiedWrite, NotifyRegistrationInput, SpacePageQuery, commit::LexBytes, domain::SpaceWriter, },};
use super::SpaceInput;
#[derive(Deserialize, Serialize)]pub(crate) struct NotifyWriteInput { space: String, repo: String, rev: String, hash: LexBytes,}
pub(crate) async fn notify_write( (State(state), headers, Json(input)): JsonRequest<NotifyWriteInput>,) -> ApiResult<Json<Value>> { let (issuer, audience) = auth::service(&headers, &state, "com.atproto.space.notifyWrite").await?; let managing_app = state .spaces .managing_app_for_writer(&input.space, &input.repo)?; let managing_app_authorized = if let Some(managing_app) = managing_app { state .space_auth .check_user_access(&managing_app, &input.space, &input.repo, None) .await } else { false }; let registrations = state.spaces.notify_registrations(&input.space)?; state.spaces.record_notified_writer(&NotifiedWrite { issuer: &issuer, audience: &audience, space: &input.space, repo: &input.repo, rev: &input.rev, hash: &input.hash.decode()?, managing_app_authorized, })?; let notification = json!(input); deliver_registrations( &state, ®istrations, "com.atproto.space.notifyWrite", ¬ification, ) .await; Ok(Json(json!({})))}
#[derive(Serialize)]pub(crate) struct ListReposOutput { repos: Vec<SpaceWriter<LexBytes>>, #[serde(skip_serializing_if = "Option::is_none")] cursor: Option<String>,}
pub(crate) async fn list_repos( (State(state), OriginalUri(uri), headers, Query(query)): SpaceQuery<SpacePageQuery>,) -> ApiResult<Json<ListReposOutput>> { let space = auth::space_credential(&headers, &state, &uri, "GET").await?; let limit = query.limit.unwrap_or(100).clamp(1, 1000); let writers = state.spaces.list_repos(&space, &query)?; let cursor = (writers.len() == limit) .then(|| writers.last().map(|writer| writer.did.clone())) .flatten(); Ok(Json(ListReposOutput { repos: writers .into_iter() .map(|writer| SpaceWriter { did: writer.did, rev: writer.rev, hash: LexBytes::new(writer.hash), }) .collect(), cursor, }))}
pub(crate) async fn register_notify( (State(state), OriginalUri(uri), headers, Json(input)): SpaceJson<NotifyRegistrationInput>,) -> ApiResult<Json<Value>> { let space = auth::space_credential(&headers, &state, &uri, "POST").await?; let endpoint = state .space_auth .resolve_service_endpoint(&input.service) .await?; let expires_at = state .spaces .register_notify(&space, &input, endpoint.as_str())?; Ok(Json(json!({ "expiresAt": format_utc_datetime(expires_at) .context(Error::Internal, "invalid timestamp")?, })))}
pub(crate) async fn unregister_notify( (State(state), OriginalUri(uri), headers, Json(input)): SpaceJson<NotifyRegistrationInput>,) -> ApiResult<Json<Value>> { let space = auth::space_credential(&headers, &state, &uri, "POST").await?; state.spaces.unregister_notify(&space, &input)?; Ok(Json(json!({})))}
pub(crate) async fn notify_space_deleted( (State(state), headers, Json(input)): JsonRequest<SpaceInput>,) -> ApiResult<Json<Value>> { let (issuer, audience) = auth::service(&headers, &state, "com.atproto.space.notifySpaceDeleted").await?; let space = input.space.parse::<crate::syntax::SpaceRef>()?; if issuer != space.authority { return Err(Error::Authorization( "notifySpaceDeleted issuer is not the space authority".to_owned(), )); } if audience != state.config.account.did { return Err(Error::Authorization( "notifySpaceDeleted audience does not match this service".to_owned(), )); } Ok(Json(json!({})))}
pub(super) async fn publish_repo_position(state: &AppState, space: &str, repo: &str) { best_effort_notice("Space repository position", async { let Some((rev, hash)) = state.spaces.repo_position(space, repo)? else { return Ok(()); }; let space_ref = space.parse::<crate::syntax::SpaceRef>()?; if space_ref.authority == state.config.account.did { return state.spaces.record_notified_writer(&NotifiedWrite { issuer: repo, audience: &space_ref.authority, space, repo, rev: &rev, hash: &hash, managing_app_authorized: false, }); } let endpoint = state .space_auth .resolve_service_endpoint(&space_ref.authority) .await?; let body = json!({ "space": space, "repo": repo, "rev": rev, "hash": LexBytes::new(hash), }); state .space_auth .deliver_notification( endpoint.as_str(), &space_ref.authority, "com.atproto.space.notifyWrite", &body, ) .await }) .await;}
pub(super) async fn deliver_registrations( state: &AppState, registrations: &[(String, String)], method: &'static str, body: &Value,) { best_effort_notice("Space subscriber notifications", async { stream::iter(registrations).for_each_concurrent(4, |(service, endpoint)| async move { if let Err(error) = state.space_auth.deliver_notification( endpoint, service, method, body, ).await { tracing::warn!(service = %service, %method, %error, "Space notification failed"); } }).await; Ok(()) }) .await;}
#[cfg(test)]mod tests { use super::*; use axum::{body::to_bytes, response::IntoResponse};
#[tokio::test] async fn single_string_registration_output_keeps_full_response_bytes() { #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct PreviousNotifyRegistrationOutput { expires_at: String, } let values = [ String::new(), "1970-01-01T00:00:00Z".to_owned(), "-9999-01-01T00:00:00Z".to_owned(), "quote-\"-backslash-\\-雪-🦀".to_owned(), (0u8..=31).map(char::from).collect(), ]; for value in values { let previous = Json(PreviousNotifyRegistrationOutput { expires_at: value.clone(), }) .into_response(); let actual = Json(json!({"expiresAt": value})).into_response(); assert_eq!(actual.status(), previous.status()); assert_eq!(actual.headers(), previous.headers()); assert_eq!( to_bytes(actual.into_body(), usize::MAX).await.unwrap(), to_bytes(previous.into_body(), usize::MAX).await.unwrap(), ); } }
#[test] fn registration_timestamps_preserve_exact_text_and_error_context() { let mut cases = vec![(0, "1970-01-01T00:00:00Z"), (-1, "1969-12-31T23:59:59Z")]; for (year, expected) in [ (-9999, "-9999-01-01T00:00:00Z"), (-1, "-001-01-01T00:00:00Z"), (0, "0000-01-01T00:00:00Z"), (1, "0001-01-01T00:00:00Z"), (2000, "2000-01-01T00:00:00Z"), (9999, "9999-01-01T00:00:00Z"), ] { let timestamp = time::Date::from_calendar_date(year, time::Month::January, 1) .unwrap() .midnight() .assume_utc() .unix_timestamp(); cases.push((timestamp, expected)); } for (timestamp, expected) in cases { let output = json!({ "expiresAt": format_utc_datetime(timestamp) .context(Error::Internal, "invalid timestamp") .unwrap(), }); assert_eq!(output["expiresAt"], expected); assert_eq!( serde_json::to_vec(&output).unwrap(), format!(r#"{{"expiresAt":"{expected}"}}"#).as_bytes(), ); } for timestamp in [i64::MIN, i64::MAX] { let previous = time::OffsetDateTime::from_unix_timestamp(timestamp) .map_err(|error| Error::Internal(format!("invalid timestamp: {error}"))) .unwrap_err(); let actual = format_utc_datetime(timestamp) .context(Error::Internal, "invalid timestamp") .unwrap_err(); assert!(matches!(actual, Error::Internal(_))); assert_eq!(format!("{actual:?}"), format!("{previous:?}")); assert_eq!(actual.to_string(), previous.to_string()); } }
#[test] fn writer_pages_keep_previous_json_bytes() { #[derive(Serialize)] struct PreviousRepoView { did: String, rev: String, hash: LexBytes, } #[derive(Serialize)] struct PreviousListReposOutput { repos: Vec<PreviousRepoView>, #[serde(skip_serializing_if = "Option::is_none")] cursor: Option<String>, } let hashes = [ Vec::new(), (0..=u8::MAX).collect(), vec![0], vec![0, 1], vec![0, 1, 2], vec![0, 1, 2, 3], vec![0; 31], vec![u8::MAX; 32], vec![128; 33], ]; for hash in hashes { for (did, rev) in [ ("", ""), ("did:web:alice.test", "3jqfcqzm3fo2j"), ("not a DID", "not a revision"), ("did:example:café/\"\\\n\t\0", "rev-\"\\\n\t\0-雪"), ] { for cursor in [None, Some("cursor-\"\\\n-雪".to_owned())] { let writer = SpaceWriter { did: did.to_owned(), rev: rev.to_owned(), hash: hash.clone(), }; assert_eq!( format!("{writer:?}"), format!("SpaceWriter {{ did: {did:?}, rev: {rev:?}, hash: {hash:?} }}"), ); let previous = PreviousListReposOutput { repos: vec![PreviousRepoView { did: writer.did.clone(), rev: writer.rev.clone(), hash: LexBytes::new(&writer.hash), }], cursor: cursor.clone(), }; let actual = ListReposOutput { repos: vec![SpaceWriter { did: writer.did, rev: writer.rev, hash: LexBytes::new(writer.hash), }], cursor, }; assert_eq!( serde_json::to_vec(&actual).unwrap(), serde_json::to_vec(&previous).unwrap(), "hash length {}: {did:?}, {rev:?}", hash.len(), ); } } } assert_eq!( serde_json::to_vec(&ListReposOutput { repos: Vec::new(), cursor: None, }) .unwrap(), br#"{"repos":[]}"#, ); }
#[test] fn shared_writer_query_keeps_previous_values_and_rejections() { #[derive(Deserialize)] struct PreviousListReposQuery { space: String, limit: Option<usize>, cursor: Option<String>, } for path in [ "/", "/?limit=1", "/?space=", "/?space=space", "/?space=space&cursor=", "/?space=space&limit=0", "/?space=space&limit=1001", "/?space=space&limit=", "/?space=space&limit=-1", "/?space=space&limit=no", "/?space=space&space=other", "/?space=space&limit=1&limit=2", "/?space=space&cursor=one&cursor=two", "/?space=space&unknown=one&unknown=two", "/?space=at%3A%2F%2Fdid%3Aexample%3Aalice%2Fspace%2Fapp.test.space%2Fone&cursor=not-a-did", ] { let uri = path.parse().unwrap(); let previous = Query::<PreviousListReposQuery>::try_from_uri(&uri) .map(|Query(query)| (query.space, query.limit, query.cursor)) .map_err(|error| (error.status(), error.body_text())); let actual = Query::<SpacePageQuery>::try_from_uri(&uri) .map(|Query(query)| (query.space, query.limit, query.cursor)) .map_err(|error| (error.status(), error.body_text())); assert_eq!(actual, previous, "writer query {path}"); } }
#[test] fn shared_registration_input_keeps_previous_json_parsing() { #[derive(Deserialize)] struct PreviousNotifyRegistrationInput { space: String, service: String, } for input in [ "{}", r#"{"space":"space"}"#, r#"{"service":"service"}"#, r#"{"space":"space","service":"service","unknown":true}"#, r#"{"space":"","service":""}"#, r#"{"space":null,"service":"service"}"#, r#"{"space":"space","service":null}"#, r#"{"space":"space","space":"duplicate","service":"service"}"#, r#"{"space":"space","service":"service","service":"duplicate"}"#, ] { let previous = serde_json::from_str::<PreviousNotifyRegistrationInput>(input) .map(|input| (input.space, input.service)) .map_err(|error| error.to_string()); let actual = serde_json::from_str::<NotifyRegistrationInput>(input) .map(|input| (input.space, input.service)) .map_err(|error| error.to_string()); assert_eq!(actual, previous, "registration input {input}"); } }
#[test] fn notification_input_serializes_to_the_previous_notice_bytes_without_decoding_hashes() { for hash in ["AAECAw", "AA==", "", "not valid base64!"] { let input: NotifyWriteInput = serde_json::from_value(json!({ "space": "at://did:example:alice/space/app.test.space/one", "repo": "did:example:alice", "rev": "3jqfcqzm3fo2j", "hash": {"$bytes": hash, "ignored": true}, "ignored": true, })) .unwrap(); let previous = json!({ "space": input.space, "repo": input.repo, "rev": input.rev, "hash": input.hash, }); let actual = json!(input); assert_eq!(actual, previous); assert_eq!( serde_json::to_vec(&actual).unwrap(), serde_json::to_vec(&previous).unwrap() ); assert_eq!(actual["hash"], json!({"$bytes": hash})); assert_eq!(actual.as_object().unwrap().len(), 4); } }}