Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
238 changes: 232 additions & 6 deletions pkgs/id/crates/id-import-atproto/src/blobs.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Blob references: what a stored record points at, without fetching
//! it (slice 3 of #13787 — the reference-only first step for the
//! issue's open question 5, "blobs: reference-only, or fetch-and-store?").
//! Blob references and blob fetching: what a stored record points
//! at, and the verified fetch of the bytes behind it (slices 3–4 of
//! #13787, answering the issue's open question 5 in two steps:
//! reference-only accounting first, then fetch-and-store).
//!
//! atproto records reference binary blobs through lexicon blob
//! objects: a map of the shape
Expand All @@ -21,15 +22,22 @@
//! malformed as a blob and is likewise skipped, so the output is
//! exactly the set of fetchable references.
//!
//! Fetching the bytes behind these CIDs (`com.atproto.sync.getBlob`)
//! remains a named remainder on #13787; nothing here does I/O.
//! Fetching the bytes behind these CIDs is slice 4, in the second
//! half of this module: [`fetch_missing_blobs`] pulls every referenced
//! blob the store does not already hold through the injected transport
//! and verifies each one hashes to the CID that referenced it before
//! it is stored — a PDS serving wrong bytes is caught, never filed.

use std::collections::BTreeSet;

use serde::Serialize;

use crate::apply::{RecordStore, StoredRecord};
use crate::cbor::Value;
use crate::cid::Cid;
use crate::error::Result;
use crate::error::{Error, Result};
use crate::pds::PdsClient;
use crate::resolve::{Fetcher, ResolvedIdentity};

/// One blob reference found inside a stored record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
Expand Down Expand Up @@ -105,6 +113,89 @@ fn collect(
}
}

/// The blob-bytes boundary: where fetched blobs live, keyed by
/// `(did, cid)`. Implementations store exact bytes; the CID is the
/// content address, so a stored blob is self-describing.
pub trait BlobStore {
/// Store `bytes` as the blob `cid` for `did`. Callers must have
/// verified the bytes hash to `cid` ([`fetch_missing_blobs`] does);
/// implementations may re-check.
///
/// # Errors
/// Returns [`Error::Blob`] on a backend failure.
fn put_blob(&mut self, did: &str, cid: &Cid, bytes: &[u8]) -> Result<()>;

/// The bytes stored for `(did, cid)`, if held.
///
/// # Errors
/// Returns [`Error::Blob`] on a backend failure.
fn get_blob(&self, did: &str, cid: &Cid) -> Result<Option<Vec<u8>>>;
}

/// What one [`fetch_missing_blobs`] pass did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlobFetchReport {
/// Total blob references found in the DID's stored records.
pub references: usize,
/// Distinct blob CIDs among those references.
pub unique_blobs: usize,
/// Blobs fetched and stored by this pass.
pub fetched: usize,
/// Distinct blobs the store already held (not re-fetched).
pub already_present: usize,
/// The CIDs fetched by this pass, sorted.
pub fetched_cids: Vec<Cid>,
}

/// Fetch every blob `identity`'s stored records reference that
/// `blob_store` does not already hold, from the account's PDS, through
/// the injected transport.
///
/// Each fetched blob is verified before it is stored: its bytes must
/// hash to the CID that referenced them. A blob that fails the check
/// aborts the pass with [`Error::Blob`] and is not stored (blobs
/// already fetched earlier in the pass stay stored — the pass is safe
/// to re-run, and re-running skips everything already held).
///
/// # Errors
/// Returns a transport error if the PDS fetch fails, [`Error::Blob`]
/// on a hash mismatch or blob-store failure, and [`Error::Store`] if
/// the record store cannot be listed.
pub fn fetch_missing_blobs(
fetcher: &mut dyn Fetcher,
identity: &ResolvedIdentity,
records: &dyn RecordStore,
blob_store: &mut dyn BlobStore,
) -> Result<BlobFetchReport> {
let references = store_blob_references(records, &identity.did)?;
let unique: BTreeSet<Cid> = references.iter().map(|r| r.cid).collect();
let mut report = BlobFetchReport {
references: references.len(),
unique_blobs: unique.len(),
fetched: 0,
already_present: 0,
fetched_cids: Vec::new(),
};
let mut client = PdsClient::new(fetcher, &identity.pds_endpoint);
for cid in unique {
if blob_store.get_blob(&identity.did, &cid)?.is_some() {
report.already_present += 1;
continue;
}
let bytes = client.get_blob(&identity.did, &cid)?;
let actual = Cid::for_bytes(&bytes);
if actual != cid {
return Err(Error::Blob(format!(
"PDS served bytes hashing to {actual} for blob {cid}; not stored"
)));
}
blob_store.put_blob(&identity.did, &cid, &bytes)?;
report.fetched += 1;
report.fetched_cids.push(cid);
}
Ok(report)
}

/// Interpret a map's entries as a lexicon blob object; `None` when the
/// map is not one (no `$type: "blob"`, or a `ref` that is not a CID
/// link).
Expand Down Expand Up @@ -140,8 +231,11 @@ fn as_blob_reference(
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use std::collections::BTreeMap;

use super::*;
use crate::apply::MemoryRecordStore;
use crate::did::DidDocument;

fn blob(cid: Cid, mime: Option<&str>, size: Option<i64>) -> Value {
let mut entries = vec![
Expand Down Expand Up @@ -240,4 +334,136 @@ mod tests {
.is_empty()
);
}

#[derive(Default)]
struct FakeFetcher {
routes: BTreeMap<String, Vec<u8>>,
}

impl Fetcher for FakeFetcher {
fn get(&mut self, url: &str) -> std::result::Result<Vec<u8>, String> {
self.routes
.get(url)
.cloned()
.ok_or_else(|| format!("no route for {url}"))
}
}

#[derive(Default)]
struct MemoryBlobStore {
blobs: BTreeMap<(String, Cid), Vec<u8>>,
}

impl BlobStore for MemoryBlobStore {
fn put_blob(&mut self, did: &str, cid: &Cid, bytes: &[u8]) -> Result<()> {
self.blobs.insert((did.to_string(), *cid), bytes.to_vec());
Ok(())
}

fn get_blob(&self, did: &str, cid: &Cid) -> Result<Option<Vec<u8>>> {
Ok(self.blobs.get(&(did.to_string(), *cid)).cloned())
}
}

fn fetch_identity() -> ResolvedIdentity {
ResolvedIdentity {
did: "did:plc:subject".to_string(),
document: DidDocument {
id: "did:plc:subject".to_string(),
also_known_as: Vec::new(),
verification_methods: Vec::new(),
services: Vec::new(),
},
repo_key: crate::did::AtprotoKey::P256([0u8; 33]),
pds_endpoint: "https://pds.example.com".to_string(),
}
}

fn blob_url(cid: &Cid) -> String {
format!(
"https://pds.example.com/xrpc/com.atproto.sync.getBlob?did=did%3Aplc%3Asubject&cid={cid}"
)
}

/// Oracle: a fetch pass dedupes references by CID, skips blobs the
/// store already holds, fetches and stores the rest — and a second
/// pass fetches nothing.
#[test]
fn fetch_missing_blobs_dedupes_skips_present_and_stores() {
let bytes_a = b"blob a bytes".to_vec();
let bytes_b = b"blob b bytes".to_vec();
let cid_a = Cid::for_bytes(&bytes_a);
let cid_b = Cid::for_bytes(&bytes_b);

// One record referencing A twice and B once.
let value = Value::Map(vec![
("one".to_string(), blob(cid_a, Some("image/png"), None)),
("two".to_string(), blob(cid_a, Some("image/png"), None)),
("three".to_string(), blob(cid_b, Some("image/png"), None)),
]);
let mut records = MemoryRecordStore::new();
records
.put_record("did:plc:subject", &record(value))
.unwrap();

let mut blob_store = MemoryBlobStore::default();
// B is already held.
blob_store
.put_blob("did:plc:subject", &cid_b, &bytes_b)
.unwrap();

let mut fetcher = FakeFetcher::default();
fetcher.routes.insert(blob_url(&cid_a), bytes_a.clone());
// No route for B: fetching it would error, proving it is skipped.

let identity = fetch_identity();
let report =
fetch_missing_blobs(&mut fetcher, &identity, &records, &mut blob_store).unwrap();
assert_eq!(report.references, 3);
assert_eq!(report.unique_blobs, 2);
assert_eq!(report.fetched, 1);
assert_eq!(report.already_present, 1);
assert_eq!(report.fetched_cids, vec![cid_a]);
assert_eq!(
blob_store.get_blob("did:plc:subject", &cid_a).unwrap(),
Some(bytes_a)
);

let mut fetcher2 = FakeFetcher::default();
let report2 =
fetch_missing_blobs(&mut fetcher2, &identity, &records, &mut blob_store).unwrap();
assert_eq!(report2.fetched, 0);
assert_eq!(report2.already_present, 2);
}

/// Oracle: bytes that do not hash to the referencing CID are
/// rejected and never stored.
#[test]
fn fetch_missing_blobs_rejects_bytes_that_do_not_hash_to_the_cid() {
let cid_a = Cid::for_bytes(b"the real blob");
let value = Value::Map(vec![(
"image".to_string(),
blob(cid_a, Some("image/png"), None),
)]);
let mut records = MemoryRecordStore::new();
records
.put_record("did:plc:subject", &record(value))
.unwrap();
let mut blob_store = MemoryBlobStore::default();
let mut fetcher = FakeFetcher::default();
fetcher
.routes
.insert(blob_url(&cid_a), b"forged bytes".to_vec());
let identity = fetch_identity();
assert!(matches!(
fetch_missing_blobs(&mut fetcher, &identity, &records, &mut blob_store),
Err(Error::Blob(_))
));
assert!(
blob_store
.get_blob("did:plc:subject", &cid_a)
.unwrap()
.is_none()
);
}
}
5 changes: 5 additions & 0 deletions pkgs/id/crates/id-import-atproto/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ pub enum Error {
/// previous manifest does not belong to the DID being applied.
#[error("store error: {0}")]
Store(String),
/// A blob fetch or blob store operation failed (slice 4): fetched
/// bytes that do not hash to the CID that referenced them, or a
/// blob backend failure.
#[error("blob error: {0}")]
Blob(String),
}

/// Result alias for this crate.
Expand Down
11 changes: 8 additions & 3 deletions pkgs/id/crates/id-import-atproto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,17 @@
//! objects stored records point at, with paths, CIDs and declared
//! mime types/sizes — reference-only accounting for what a mirror
//! does not yet hold.
//! 7. **Fetch blobs** ([`blobs::fetch_missing_blobs`], slice 4): pull
//! the referenced blobs the store lacks from the account's PDS
//! through the injected transport, verifying each blob's bytes hash
//! to the CID that referenced it before storing them in a
//! [`blobs::BlobStore`] (file-backed in [`store_file`]).
//!
//! Unknown lexicons ingest as opaque verbatim records — this crate never
//! interprets `app.bsky.*` or any other collection's contents.
//!
//! Deliberately **not** in these slices (named remainders on #13787):
//! live follow (`subscribeRepos` / Jetstream) and blob *fetching*.
//! Deliberately **not** in these slices (the named remainder on
//! #13787): live follow (`subscribeRepos` / Jetstream).
//! Transport is injected throughout, so the crate does no network I/O
//! itself; the binary reads its CAR, PLC-log and DID-document inputs
//! from files the caller fetched.
Expand All @@ -55,7 +60,7 @@ pub mod resolve;
pub mod store_file;

pub use apply::{ApplyOutcome, ApplyReport, MemoryRecordStore, RecordStore, StoredRecord};
pub use blobs::BlobReference;
pub use blobs::{BlobFetchReport, BlobReference, BlobStore};
pub use cid::Cid;
pub use did::AtprotoKey;
pub use error::{Error, Result};
Expand Down
17 changes: 17 additions & 0 deletions pkgs/id/crates/id-import-atproto/src/pds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,23 @@ impl<'a> PdsClient<'a> {
.get(&url)
.map_err(|message| Error::Fetch { url, message })
}

/// Fetch one blob's bytes (`com.atproto.sync.getBlob`). The bytes
/// are **not** verified by this call — a PDS can serve anything —
/// verification is the caller's step: the bytes must hash to `cid`
/// (see [`crate::blobs::fetch_missing_blobs`], which checks before
/// storing).
pub fn get_blob(&mut self, did: &str, cid: &crate::cid::Cid) -> Result<Vec<u8>> {
let url = format!(
"{}/xrpc/com.atproto.sync.getBlob?did={}&cid={}",
self.endpoint,
url_encode(did),
url_encode(&cid.to_string())
);
self.fetcher
.get(&url)
.map_err(|message| Error::Fetch { url, message })
}
}

/// Percent-encode a query parameter value (unreserved characters pass
Expand Down
Loading