Something went wrong. Try again.
Chris’s PDS implementation
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386//! Authorized Space recovery, operation history, and blob reads.
use crate::http::request::SpaceQuery;use std::{collections::BTreeMap, str::FromStr};
use axum::{ Json, extract::{OriginalUri, Query, State}, response::Response,};use cid::Cid;use serde::{Deserialize, Serialize};
use crate::{ error::{Error, ErrorContext as _}, http::{ApiResult, auth, blob_response, car_response}, space::{ListBlobsQuery, ListOpsQuery, RepoOpsPage, car, commit::SignedCommit},};
pub(crate) async fn list_repo_ops( (State(state), OriginalUri(uri), headers, Query(query)): SpaceQuery<ListOpsQuery>,) -> ApiResult<Json<RepoOpsPage>> { let auth = auth::space_read_token(&headers, &state, &uri, "GET").await?; let mut page = state.spaces.list_repo_ops(&auth, &query)?; if query.exclude_values.unwrap_or(false) { for op in &mut page.ops { op.value = None; } } Ok(Json(page))}
#[derive(Deserialize)]pub(crate) struct LatestCommitQuery { space: String, repo: String,}
pub(crate) async fn get_latest_commit( (State(state), OriginalUri(uri), headers, Query(query)): SpaceQuery<LatestCommitQuery>,) -> ApiResult<Json<BTreeMap<&'static str, SignedCommit>>> { let auth = auth::space_read_token(&headers, &state, &uri, "GET").await?; Ok(Json(BTreeMap::from([( "commit", state .spaces .signed_snapshot(&auth, &query.space, &query.repo)? .0, )])))}
#[derive(Deserialize)]#[serde(rename_all = "camelCase")]pub(crate) struct GetRepoQuery { space: String, repo: String, exclude_values: Option<bool>,}
pub(crate) async fn get_repo( (State(state), OriginalUri(uri), headers, Query(query)): SpaceQuery<GetRepoQuery>,) -> ApiResult<Response> { let auth = auth::space_read_token(&headers, &state, &uri, "GET").await?; let exclude_values = query.exclude_values.unwrap_or(false); let (commit, records) = state .spaces .signed_snapshot(&auth, &query.space, &query.repo)?; let car = car::serialize_repo(&commit, records, exclude_values)?; Ok(car_response(car))}
#[derive(Deserialize)]pub(crate) struct BlobQuery { space: String, repo: String, cid: String,}
pub(crate) async fn get_blob( (State(state), OriginalUri(uri), headers, Query(query)): SpaceQuery<BlobQuery>,) -> ApiResult<Response> { let auth = auth::space_read_token(&headers, &state, &uri, "GET").await?; let cid = Cid::from_str(&query.cid).context(Error::InvalidRequest, "invalid CID")?; state .spaces .get_blob_allowed(&auth, &query.space, &query.repo, &cid)?; let (blob, bytes) = state .repository .read_blob(&query.repo, &cid) .await .map_err(|error| match error { Error::NotFound => Error::xrpc("BlobNotFound", "blob data was not found"), other => other, })?; blob_response(&blob.media_type, bytes)}
#[derive(Serialize)]pub(crate) struct ListBlobsOutput { cids: Vec<String>, #[serde(skip_serializing_if = "Option::is_none")] cursor: Option<String>,}
pub(crate) async fn list_blobs( (State(state), OriginalUri(uri), headers, Query(query)): SpaceQuery<ListBlobsQuery>,) -> ApiResult<Json<ListBlobsOutput>> { let auth = auth::space_read_token(&headers, &state, &uri, "GET").await?; let limit = query.limit.unwrap_or(500).clamp(1, 1000); let cids = state.spaces.list_blobs(&auth, &query)?; let cursor = (cids.len() == limit) .then(|| cids.last().cloned()) .flatten(); Ok(Json(ListBlobsOutput { cids, cursor }))}
#[cfg(test)]mod tests { use super::{BTreeMap, Json, ListBlobsQuery, ListOpsQuery, Query, RepoOpsPage}; use crate::space::{ commit::{LexBytes, SignedCommit}, domain::SpaceOp, }; use axum::{body::to_bytes, response::IntoResponse}; use serde::{Deserialize, Serialize}; use serde_json::json;
#[tokio::test] async fn singleton_commit_map_keeps_typed_inner_response_bytes_without_decoding() { #[derive(Serialize)] struct PreviousLatestCommitOutput { commit: SignedCommit, } for bytes in ["", "AAECAw", "AA==", "not valid base64!", "\"\\\n\0-雪"] { for rev in ["", "3jqfcqzm3fo2j", "rev-\"\\\n\0-雪"] { for ver in [1, u8::MAX] { let commit = SignedCommit { ver, hash: LexBytes { value: bytes.to_owned(), }, ikm: LexBytes { value: bytes.to_owned(), }, sig: LexBytes { value: bytes.to_owned(), }, mac: LexBytes { value: bytes.to_owned(), }, rev: rev.to_owned(), }; let previous = Json(PreviousLatestCommitOutput { commit: commit.clone(), }) .into_response(); let actual = Json(BTreeMap::from([("commit", commit)])).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(), "bytes: {bytes:?}, revision: {rev:?}, version: {ver}", ); } } } }
#[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct PreviousListOpsQuery { space: String, repo: String, since: Option<String>, limit: Option<usize>, cursor: Option<String>, exclude_values: Option<bool>, }
#[derive(Deserialize)] struct PreviousListBlobsQuery { space: String, repo: String, since: Option<String>, limit: Option<usize>, cursor: Option<String>, }
#[test] fn shared_recovery_queries_match_previous_extractors() { let base = "/?space=at%3A%2F%2Fdid%3Aexample%3Aalice%2Fapp.test.space%2Fone&repo=did%3Aexample%3Aalice"; let mut paths = vec![ "/".to_owned(), "/?space=space".to_owned(), "/?repo=repo".to_owned(), ]; paths.extend( [ "", "&limit=0", "&limit=1001", "&limit=", "&limit=-1", "&limit=abc", "&excludeValues=true", "&excludeValues=false", "&excludeValues=1", "&excludeValues=", "&exclude_values=true", "&space=another", "&repo=another", "&limit=1&limit=2", "&since=one&since=two", "&cursor=one&cursor=two", "&excludeValues=true&excludeValues=false", "&since=invalid&cursor=not-a-number", "&since=&cursor=", "&unknown=one&unknown=two", "&limit=100&since=3jqfcqzm3fo2j&cursor=42&excludeValues=true", ] .map(|suffix| format!("{base}{suffix}")), ); paths.push(format!("{base}&limit={}", usize::MAX)); paths.push(format!("{base}&limit={}0", usize::MAX)); for path in paths { let uri = path.parse().unwrap(); let previous = Query::<PreviousListOpsQuery>::try_from_uri(&uri) .map(|Query(query)| { ( query.space, query.repo, query.since, query.limit, query.cursor, query.exclude_values, ) }) .map_err(|error| (error.status(), error.body_text())); let actual = Query::<ListOpsQuery>::try_from_uri(&uri) .map(|Query(query)| { ( query.space, query.repo, query.since, query.limit, query.cursor, query.exclude_values, ) }) .map_err(|error| (error.status(), error.body_text())); assert_eq!(actual, previous, "operation query {path}");
let previous = Query::<PreviousListBlobsQuery>::try_from_uri(&uri) .map(|Query(query)| { ( query.space, query.repo, query.since, query.limit, query.cursor, ) }) .map_err(|error| (error.status(), error.body_text())); let actual = Query::<ListBlobsQuery>::try_from_uri(&uri) .map(|Query(query)| { ( query.space, query.repo, query.since, query.limit, query.cursor, ) }) .map_err(|error| (error.status(), error.body_text())); assert_eq!(actual, previous, "blob query {path}"); } }
#[test] fn operation_output_preserves_null_links_and_omits_internal_ids_and_absent_values() { let cid = cpds_protocol::record_cid(&json!({"$type": "app.test.record"})) .unwrap() .to_string(); let ops = [ (Some(cid.clone()), None, Some(json!({"text": "created"}))), (Some(cid.clone()), Some(cid.clone()), Some(json!(null))), (None, Some(cid.clone()), None), ] .into_iter() .map(|(cid, prev, value)| SpaceOp { id: 42, rev: "3jqfcqzm3fo2j".to_owned(), collection: "app.test.record".to_owned(), rkey: "key".to_owned(), cid, prev, value, }) .collect(); let output = RepoOpsPage { ops, commit: None, cursor: None, }; assert_eq!( serde_json::to_value(output).unwrap(), json!({"ops": [ {"rev": "3jqfcqzm3fo2j", "collection": "app.test.record", "rkey": "key", "cid": cid, "prev": null, "value": {"text": "created"}}, {"rev": "3jqfcqzm3fo2j", "collection": "app.test.record", "rkey": "key", "cid": cid, "prev": cid, "value": null}, {"rev": "3jqfcqzm3fo2j", "collection": "app.test.record", "rkey": "key", "cid": null, "prev": cid}, ]}), ); }
#[test] fn shared_operation_pages_preserve_previous_json_bytes_and_lazy_commit_encoding() { #[derive(Serialize)] struct PreviousListOpsOutput { ops: Vec<SpaceOp>, #[serde(skip_serializing_if = "Option::is_none")] commit: Option<SignedCommit>, #[serde(skip_serializing_if = "Option::is_none")] cursor: Option<String>, }
let cid = cpds_protocol::record_cid(&json!({"$type": "app.test.record"})) .unwrap() .to_string(); let ops = [ ( Some(cid.clone()), None, Some(json!({"link": {"$link": cid}})), ), (Some(cid.clone()), Some(cid.clone()), Some(json!(null))), (None, Some("stored-without-decoding".to_owned()), None), ] .into_iter() .map(|(cid, prev, value)| SpaceOp { id: 42, rev: "3jqfcqzm3fo2j".to_owned(), collection: "app.test.record".to_owned(), rkey: "key".to_owned(), cid, prev, value, }) .collect::<Vec<_>>(); let commit = SignedCommit { ver: 1, hash: LexBytes { value: "not valid base64!".to_owned(), }, ikm: LexBytes::new([2]), sig: LexBytes::new([3]), mac: LexBytes::new([4]), rev: "3jqfcqzm3fo2j".to_owned(), }; assert!(commit.hash.decode().is_err()); for commit in [None, Some(commit)] { for cursor in [None, Some("cursor-token".to_owned())] { for ops in [Vec::new(), ops.clone()] { let previous = PreviousListOpsOutput { ops: ops.clone(), commit: commit.clone(), cursor: cursor.clone(), }; let output = RepoOpsPage { ops, commit: commit.clone(), cursor: cursor.clone(), }; assert_eq!( serde_json::to_vec(&output).unwrap(), serde_json::to_vec(&previous).unwrap(), ); } } } }}