//! 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, ) -> ApiResult> { 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, ) -> ApiResult>> { 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, } pub(crate) async fn get_repo( (State(state), OriginalUri(uri), headers, Query(query)): SpaceQuery, ) -> ApiResult { 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, ) -> ApiResult { 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, #[serde(skip_serializing_if = "Option::is_none")] cursor: Option, } pub(crate) async fn list_blobs( (State(state), OriginalUri(uri), headers, Query(query)): SpaceQuery, ) -> ApiResult> { 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, limit: Option, cursor: Option, exclude_values: Option, } #[derive(Deserialize)] struct PreviousListBlobsQuery { space: String, repo: String, since: Option, limit: Option, cursor: Option, } #[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::::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::::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::::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::::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, #[serde(skip_serializing_if = "Option::is_none")] commit: Option, #[serde(skip_serializing_if = "Option::is_none")] cursor: Option, } 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::>(); 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(), ); } } } } }