Skip to main content

capsule_sdk/
sync.rs

1//! The key-free **sync consumer** (SSoT: [Download & Sync]).
2//!
3//! [`SyncConsumer`] drives `GET /v1/sync` through the **generated REST client** — the same
4//! paged `(cursor, page_size)` feed the server serves — authorizing through the
5//! SDK session and retrying once on a `401`. The opaque, server-MAC'd cursor is round-tripped
6//! verbatim: the client stores `next_cursor` and hands it back untouched.
7//!
8//! **There was a second transport here and there is not any more**. The feed rode
9//! `capsule.sync.v1.SyncService` over tonic, which meant the SDK described one wire contract in
10//! a `.proto` and every other in an OpenAPI document. Nothing below the transport moved:
11//! [`SyncState`] and its two rules were never about gRPC.
12//!
13//! [`SyncState`] is the **client-side anti-rewind + forward-version layer**, split
14//! out as a pure, network-free state machine so every rejection rule is a
15//! deterministic unit test (sync doc, "Cursor Authenticity and Anti-Rewind"):
16//!
17//! - **Forward-version rejection.** A feed entry whose `protocol_version` is above
18//!   the client's max known is rejected *without partial application* — the whole
19//!   page is validated before any high-water mark advances (the tightened Postel's
20//!   Law).
21//! - **Rewind rejection.** The client holds a per-album `sync_seq` high-water mark;
22//!   a page whose `sync_seq` regresses against it is surfaced, not applied. This is
23//!   the independent anti-rewind layer that the server's cursor MAC cannot provide:
24//!   a malicious server can always hand back one of its own *older*, validly-MAC'd
25//!   cursors, and only the client-held high-water mark defeats that
26//!   ([Download & Sync — cursor authenticity]).
27//!
28//! Blob bytes never ride this surface; on-demand ranged blob fetch is [`crate::fetch`].
29//!
30//! The feed carries only an asset's latest provenance record. [`fetch_history`] walks the
31//! chain back from it to the asset's `create` through that blob fetch, for a device that first
32//! sees an asset past its create and adopts it from its whole chain; [`history_sources`] names
33//! the live metadata blob and the original that adoption fetches, which an album page's
34//! tombstone does not.
35//!
36//! [Download & Sync]: https://docs/design/sync/
37//! [Download & Sync — cursor authenticity]: https://docs/design/sync/#cursor-authenticity-and-anti-rewind
38
39use std::collections::HashMap;
40use std::sync::Arc;
41
42use base64::Engine as _;
43use base64::engine::general_purpose::STANDARD as BASE64;
44use capsule_i18n::error_codes;
45use tracing::instrument;
46
47use crate::auth::{AuthError, Session};
48use crate::client::Bearer;
49use crate::federation::RequestSigner;
50use crate::net::{RetryClass, RetryDecision, RetryEngine, Sleeper, TokioSleeper};
51use crate::rest;
52
53pub mod reannounce;
54
55// ─── Cursor ──────────────────────────────────────────────────────────────────
56
57/// The opaque, server-MAC'd sync cursor. The client never interprets it — it is
58/// round-tripped verbatim: empty on first sync, then whatever the server last
59/// returned as `next_cursor`.
60#[derive(Debug, Clone, Default, PartialEq, Eq)]
61pub struct SyncCursor(Vec<u8>);
62
63impl SyncCursor {
64    /// The first-sync sentinel (empty cursor).
65    #[must_use]
66    pub fn start() -> Self {
67        Self(Vec::new())
68    }
69
70    /// Wrap raw cursor bytes handed back by the server.
71    #[must_use]
72    pub fn from_bytes(bytes: Vec<u8>) -> Self {
73        Self(bytes)
74    }
75
76    /// The opaque bytes, for persistence across restarts.
77    #[must_use]
78    pub fn as_bytes(&self) -> &[u8] {
79        &self.0
80    }
81
82    /// The cursor as the wire spells it, or `None` if it is not text.
83    ///
84    /// The REST feed carries the cursor as a string; it is stored as bytes because that is what
85    /// a client persists and because the *client* is not entitled to an opinion about the
86    /// encoding — it round-trips whatever it was handed. A non-UTF-8 cursor is one this client
87    /// never received, so it is answered as absent and the next pull starts from the beginning
88    /// rather than sending something the server will refuse.
89    #[must_use]
90    pub fn as_text(&self) -> Option<&str> {
91        std::str::from_utf8(&self.0).ok()
92    }
93
94    /// Whether this is the first-sync sentinel.
95    #[must_use]
96    pub fn is_start(&self) -> bool {
97        self.0.is_empty()
98    }
99}
100
101// ─── Decoded feed entry ──────────────────────────────────────────────────────
102
103/// What changed, mirroring `capsule.sync.v1.ChangeKind`.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum ChangeKind {
106    /// A new asset became visible in the album.
107    Created,
108    /// An existing asset's metadata (or `original_held`) advanced.
109    Updated,
110    /// The asset was tombstoned (the manifest itself is the delete).
111    Deleted,
112}
113
114/// A single blob's content address and role, carried on a feed entry (never blob bytes).
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct BlobRef {
117    /// Ciphertext content address (lowercase hex).
118    pub ciphertext_hash: String,
119    /// `original | metadata | derivative | provenance` (closed enum, server-set).
120    pub role: String,
121    /// Ciphertext size in bytes.
122    pub size: u64,
123}
124
125/// The asset's blobs by role.
126#[derive(Debug, Clone, Default, PartialEq, Eq)]
127pub struct BlobManifest {
128    /// The original ciphertext blob, when this entry carries one.
129    pub original: Option<BlobRef>,
130    /// Derivative / metadata / provenance blobs.
131    pub derivatives: Vec<BlobRef>,
132}
133
134/// One decoded sync feed entry. Ids arrive as opaque bytes (UTF-8 nanoids / raw
135/// UUIDs); the manifest and metadata blob pass through as opaque bytes.
136#[derive(Debug, Clone)]
137pub struct FeedEntry {
138    /// The album this entry belongs to.
139    pub album_id: Vec<u8>,
140    /// Per-album, strictly-increasing sequence — the anti-rewind high-water mark.
141    pub sync_seq: u64,
142    /// The album protocol pin (`YYYY-MM-DD`) this entry conforms to.
143    pub protocol_version: String,
144    /// What changed.
145    pub kind: ChangeKind,
146    /// The asset id.
147    pub asset_id: Vec<u8>,
148    /// The asset's head **provenance record** as opaque canonical CBOR — the `provenance`
149    /// blob's bytes, served back unchanged, carrying the signed `AssetManifest` inside it
150    /// (decoded and verified by core's `apply_remote_entry`). Never re-encoded here.
151    pub manifest_cbor: Vec<u8>,
152    /// The encrypted metadata blob's **content address**, as its UTF-8 bytes; empty when the
153    /// entry carries none (a purged tombstone, or any tombstone from a server that predates
154    /// naming it). A tombstone in trash names the asset's live metadata blob, which a device
155    /// that first sees the asset at its delete opens the sidecar from to adopt and restore it.
156    ///
157    /// An address, not the bytes: blob bytes never ride the feed. The field name predates the
158    /// REST port and the type is kept so a caller's storage does not move.
159    pub metadata_blob: Vec<u8>,
160    /// Content addresses of the asset's blobs by role. A tombstone in trash names only its
161    /// original, the blob a restore needs; a purged one names none.
162    pub blobs: BlobManifest,
163    /// The asset's signed derivative manifests, each the **exact** canonical CBOR of one
164    /// `derivative_manifest` blob, served back unchanged (#556). Empty on a tombstone.
165    ///
166    /// What opens a thumbnail or preview: each names its derivative's `ciphertext_hash`,
167    /// `nonce_prefix` and AMK epoch, which [`BlobManifest`] does not carry.
168    /// [`crate::fetch::verify_derivative_manifests`] decodes and verifies them; hand its
169    /// `accepted` list to [`crate::fetch::AssetBlobs::derivative_manifests`]. Never re-encoded
170    /// here, for the reason [`Self::manifest_cbor`] is not.
171    pub derivative_manifests: Vec<Vec<u8>>,
172    /// Whether the original blob is finalized on the server (`awaiting-original`
173    /// derived state when `false`; staged uploads).
174    pub original_held: bool,
175    /// Whether the server has purged the asset (#885): its retention window closed and its
176    /// references are gone, so no `trash-restore` can bring it back. Only ever set on a
177    /// [`ChangeKind::Deleted`] entry, and `false` from a server that predates the signal.
178    ///
179    /// The positive evidence of a purge. An empty [`Self::manifest_cbor`] is not: the server
180    /// also serves none when it cannot produce the blob.
181    pub purged: bool,
182    /// When the change happened, RFC 3339, on the server's clock.
183    pub changed_at: String,
184}
185
186/// The derived per-asset **original availability** — the badge a client's timeline
187/// reads (staged uploads; transfer download doc, "The `awaiting-original`
188/// state"). It is **always derived** from the feed's `original_held` fact, never
189/// stored as a second source of truth: an asset whose original has not yet landed
190/// on the server shows in the timeline immediately (LQIP, then T1 tiers as they
191/// arrive) with an "original still on device" badge, and its full-resolution fetch
192/// returns the transient `error.blob.pending_upload` rather than a failure.
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub enum OriginalAvailability {
195    /// The original is finalized on the server; full resolution is fetchable.
196    Held,
197    /// The original has not landed yet — the `awaiting-original` state. Show the
198    /// badge, keep the asset listed, and re-fetch when the feed flips `original_held`.
199    AwaitingOriginal,
200}
201
202impl FeedEntry {
203    /// The derived [`OriginalAvailability`] badge state for this asset — a pure
204    /// projection of [`original_held`](Self::original_held), so the "awaiting-original"
205    /// badge is never a stored second source of truth (staged uploads).
206    #[must_use]
207    pub fn original_availability(&self) -> OriginalAvailability {
208        if self.original_held {
209            OriginalAvailability::Held
210        } else {
211            OriginalAvailability::AwaitingOriginal
212        }
213    }
214
215    /// Whether this asset is in the derived **awaiting-original** state (its original
216    /// is still on the source device). The UI shows the "original still on *device*"
217    /// badge while this holds and never removes the asset's metadata or index entry.
218    #[must_use]
219    pub fn is_awaiting_original(&self) -> bool {
220        !self.original_held
221    }
222}
223
224/// A decoded page of the feed plus the cursor for the next page.
225#[derive(Debug, Clone)]
226pub struct SyncPage {
227    /// The changes in this page, in strictly-increasing per-album `sync_seq` order.
228    pub entries: Vec<FeedEntry>,
229    /// The opaque cursor to pass to the next [`SyncConsumer::pull`].
230    pub next_cursor: SyncCursor,
231    /// Whether the server holds changes beyond this page.
232    ///
233    /// Answered from the owner's high-water mark rather than by fetching one more entry, so a
234    /// caught-up client learns it is caught up without paying for an empty page.
235    pub has_more: bool,
236}
237
238// ─── Errors ──────────────────────────────────────────────────────────────────
239
240/// Everything the sync consumer / reconciliation can fail with. Callers switch on
241/// the typed variant (never a bare gRPC status); [`SyncError::error_code`] yields
242/// the stable `error.*` catalog code where one applies.
243#[derive(Debug, thiserror::Error)]
244pub enum SyncError {
245    /// A feed entry's `protocol_version` is above the client's max known — the
246    /// forward-version rejection. The whole page is refused with no partial apply.
247    #[error(
248        "feed entry protocol {entry_version} exceeds the client's max known {max_known} (album {album})"
249    )]
250    ForwardVersion {
251        /// The offending album (lossy UTF-8 of the id bytes).
252        album: String,
253        /// The entry's protocol version.
254        entry_version: String,
255        /// The client's max known protocol version.
256        max_known: String,
257    },
258    /// A feed entry's `sync_seq` regresses against the locally-seen high-water mark
259    /// for its album — a malicious/buggy server attempting to rewind the client.
260    #[error(
261        "feed entry sync_seq {entry_seq} regresses against high-water {high_water} (album {album})"
262    )]
263    Rewind {
264        /// The offending album (lossy UTF-8 of the id bytes).
265        album: String,
266        /// The entry's (regressing) `sync_seq`.
267        entry_seq: u64,
268        /// The high-water mark the client already applied for the album.
269        high_water: u64,
270    },
271    /// A feed entry carried a `protocol_version` that is not a `YYYY-MM-DD` date.
272    #[error("malformed feed entry protocol version {0:?}")]
273    MalformedProtocol(String),
274    /// A feed entry's `manifest_cbor`, or one of its `derivative_manifests`, is not base64.
275    ///
276    /// The feed is JSON and a manifest is CBOR, so the signed bytes ride base64. A body that
277    /// fails to decode is a server that cannot be talked to, not an asset to quarantine.
278    #[error("a feed entry's manifest is not base64: {0}")]
279    MalformedManifest(String),
280    /// The server rejected the call (cursor invalid, forward-version, auth, …).
281    /// Carries the stable `error.*` code when the server supplied one.
282    #[error("sync rejected (code {code:?}): {message}")]
283    Rejected {
284        /// The stable `error.*` code from `x-capsule-error-code`, when present.
285        code: Option<String>,
286        /// The English detail message from the gRPC status.
287        message: String,
288    },
289    /// Transport-level failure (connection, TLS, timeout, malformed metadata).
290    #[error("sync transport error: {0}")]
291    Transport(String),
292    /// The session's auth layer failed (not authenticated, refresh rejected).
293    #[error("authentication error: {0}")]
294    Auth(#[from] AuthError),
295}
296
297impl SyncError {
298    /// The stable `error.*` catalog code a client localizes, when one applies.
299    #[must_use]
300    pub fn error_code(&self) -> Option<&str> {
301        match self {
302            Self::ForwardVersion { .. } => Some(error_codes::PROTOCOL_VERSION_UNSUPPORTED),
303            Self::Rejected { code, .. } => code.as_deref(),
304            _ => None,
305        }
306    }
307
308    /// Whether the server refused the cursor because the library's sync epoch moved: the server
309    /// rebuilt its index and could not prove the numbering the cursor resumes (#697).
310    ///
311    /// The recovery is [`SyncState::reset_for_resync`] and a pull from the start. Nothing the
312    /// client holds is discarded: the resync re-delivers what the server holds, and what it no
313    /// longer does is for the client to re-announce, never to delete.
314    #[must_use]
315    pub fn is_stale_cursor(&self) -> bool {
316        self.error_code() == Some(error_codes::SYNC_CURSOR_STALE)
317    }
318}
319
320// ─── Reconciliation state (pure) ─────────────────────────────────────────────
321
322/// The client-side reconciliation state: the per-album `sync_seq` high-water
323/// marks, the max-known protocol version, and the opaque cursor. Pure and
324/// network-free — [`SyncState::apply_page`] is the whole anti-rewind /
325/// forward-version contract in one testable function.
326#[derive(Debug, Clone)]
327pub struct SyncState {
328    max_known_protocol: String,
329    high_water: HashMap<Vec<u8>, u64>,
330    cursor: SyncCursor,
331}
332
333impl SyncState {
334    /// A fresh state pinned to the client's max-known protocol version.
335    #[must_use]
336    pub fn new(max_known_protocol: impl Into<String>) -> Self {
337        Self {
338            max_known_protocol: max_known_protocol.into(),
339            high_water: HashMap::new(),
340            cursor: SyncCursor::start(),
341        }
342    }
343
344    /// Rehydrate a state from a durably-persisted cursor and per-album high-water
345    /// marks (the client's store loaded at startup), pinned to the client's
346    /// current max-known protocol. The inverse of [`SyncState::cursor`] +
347    /// [`SyncState::high_water_marks`]: a client persists those two after every
348    /// [`apply_page`](SyncState::apply_page) and restores here on the next run so
349    /// the anti-rewind high-water mark survives process restarts (the CLI's
350    /// `capsule sync`). `max_known_protocol` is intentionally *not*
351    /// persisted — it is the running build's own ceiling, so a client that
352    /// upgraded raises it here rather than restoring a stale one.
353    #[must_use]
354    pub fn restore(
355        max_known_protocol: impl Into<String>,
356        cursor: SyncCursor,
357        high_water: impl IntoIterator<Item = (Vec<u8>, u64)>,
358    ) -> Self {
359        Self {
360            max_known_protocol: max_known_protocol.into(),
361            high_water: high_water.into_iter().collect(),
362            cursor,
363        }
364    }
365
366    /// Every applied per-album high-water mark, for persistence across restarts.
367    /// Pair with [`SyncState::cursor`] and reload through [`SyncState::restore`].
368    pub fn high_water_marks(&self) -> impl Iterator<Item = (&[u8], u64)> {
369        self.high_water
370            .iter()
371            .map(|(album, seq)| (album.as_slice(), *seq))
372    }
373
374    /// Start over after the server moved the library to a new sync epoch
375    /// ([`SyncError::is_stale_cursor`]): the cursor goes back to the start and every
376    /// high-water mark is dropped.
377    ///
378    /// The marks go too, unlike a `--force` re-drain, because the rebuilt numbering may sit
379    /// below them, and a floor the server can no longer honour would refuse every entry as a
380    /// rewind. The anti-rewind layer is re-established from the first page of the new epoch.
381    /// Only the reconciliation state is reset: nothing the client holds is discarded.
382    pub fn reset_for_resync(&mut self) {
383        tracing::info!(
384            albums = self.high_water.len(),
385            "the server moved this library to a new sync epoch; resyncing from the start"
386        );
387        self.high_water.clear();
388        self.cursor = SyncCursor::start();
389    }
390
391    /// The cursor to hand to the next pull (round-tripped verbatim).
392    #[must_use]
393    pub fn cursor(&self) -> &SyncCursor {
394        &self.cursor
395    }
396
397    /// The applied per-album high-water mark, if the album has been seen.
398    #[must_use]
399    pub fn high_water(&self, album_id: &[u8]) -> Option<u64> {
400        self.high_water.get(album_id).copied()
401    }
402
403    /// Validate and apply a page: check every entry (forward-version, then
404    /// per-album `sync_seq` monotonicity against the high-water mark) **before**
405    /// mutating any state, then advance the high-water marks and the cursor.
406    ///
407    /// On any rejection nothing is applied — no high-water mark moves and the
408    /// cursor does not advance — so a poisoned page can never partially land.
409    #[instrument(skip(self, page), fields(entries = page.entries.len()))]
410    pub fn apply_page(&mut self, page: &SyncPage) -> Result<(), SyncError> {
411        self.validate(page)?;
412        for entry in &page.entries {
413            let slot = self.high_water.entry(entry.album_id.clone()).or_insert(0);
414            *slot = (*slot).max(entry.sync_seq);
415        }
416        self.cursor = page.next_cursor.clone();
417        tracing::debug!(
418            entries = page.entries.len(),
419            "sync page applied; high-water marks advanced"
420        );
421        Ok(())
422    }
423
424    /// The full validation pass, sharing nothing with the apply pass so a failure
425    /// leaves `self` untouched.
426    fn validate(&self, page: &SyncPage) -> Result<(), SyncError> {
427        // Per-album working floor: the max of the persisted high-water mark and the
428        // highest seq seen earlier in this page (enforces strictly-increasing
429        // within the page too).
430        let mut seen: HashMap<&[u8], u64> = HashMap::new();
431        for entry in &page.entries {
432            if !is_protocol_date(&entry.protocol_version) {
433                return Err(SyncError::MalformedProtocol(entry.protocol_version.clone()));
434            }
435            // Forward-version: refuse any entry beyond the client's max known.
436            if entry.protocol_version.as_str() > self.max_known_protocol.as_str() {
437                return Err(SyncError::ForwardVersion {
438                    album: lossy(&entry.album_id),
439                    entry_version: entry.protocol_version.clone(),
440                    max_known: self.max_known_protocol.clone(),
441                });
442            }
443            // Rewind: the sequence must strictly exceed the album's floor.
444            let floor = seen
445                .get(entry.album_id.as_slice())
446                .copied()
447                .or_else(|| self.high_water.get(&entry.album_id).copied());
448            if let Some(hw) = floor
449                && entry.sync_seq <= hw
450            {
451                return Err(SyncError::Rewind {
452                    album: lossy(&entry.album_id),
453                    entry_seq: entry.sync_seq,
454                    high_water: hw,
455                });
456            }
457            seen.insert(entry.album_id.as_slice(), entry.sync_seq);
458        }
459        Ok(())
460    }
461}
462
463// ─── REST consumer ───────────────────────────────────────────────────────────
464
465/// How the feed's `Authorization` header is populated. Closed on purpose, mirroring the upload
466/// client: either the SDK session (pre-flight refresh, single-flight coalescing, and one
467/// refresh-and-retry on a `401`) or a fixed bearer for tests and callers that already hold a
468/// live token.
469#[derive(Clone)]
470enum SyncAuth {
471    Session(Session),
472    /// A fixed token, held by the client itself. The variant carries nothing because there is
473    /// nothing left to do with it: the credential is already registered on the generated client,
474    /// and what this arm decides is that a `401` is **final** — a static token cannot be
475    /// refreshed, so retrying would only ask the same question twice.
476    Static,
477    /// A federation capability, held by the client like [`Self::Static`], whose every request
478    /// also carries the puller's request signature. Its `401` is final for the same reason.
479    Signed {
480        token: Arc<str>,
481        signer: Arc<dyn RequestSigner>,
482    },
483}
484
485/// The path the feed is signed over: the operation's own, whatever prefix the base URL has,
486/// because the issuer verifies against the path it routes (design/federation.md, `path`).
487const FEED_PATH: &str = "/v1/sync";
488
489/// The sync consumer, over the **generated REST client**.
490///
491/// It used to drive `capsule.sync.v1.SyncService` over tonic. The feed is `GET /v1/sync` now and
492/// is a generated operation like every other, which removes the SDK's second transport and, with
493/// it, the second place a wire contract could be described. What did **not** change is
494/// everything below the transport: [`SyncState`], the anti-rewind high-water marks and the
495/// forward-version rule are the same pure state machine, because none of them was ever about
496/// gRPC.
497#[derive(Clone)]
498pub struct SyncConsumer {
499    client: rest::Client,
500    auth: SyncAuth,
501}
502
503impl SyncConsumer {
504    /// A consumer for the API at `base_url`, authorizing through an SDK [`Session`] — the
505    /// sanctioned production path.
506    ///
507    /// # Errors
508    ///
509    /// [`SyncError::Transport`] when `base_url` is not a URL the client can hang paths off.
510    pub fn with_session(base_url: &str, session: Session) -> Result<Self, SyncError> {
511        Ok(Self {
512            client: build_client(base_url, bearer_provider(session.clone()))?,
513            auth: SyncAuth::Session(session),
514        })
515    }
516
517    /// A consumer over a fixed bearer token (tests; callers holding a live token).
518    ///
519    /// # Errors
520    ///
521    /// [`SyncError::Transport`] when `base_url` is not a URL the client can hang paths off.
522    pub fn with_static_token(base_url: &str, token: impl Into<String>) -> Result<Self, SyncError> {
523        let token = token.into();
524        Ok(Self {
525            client: build_client(base_url, Bearer::Token(token))?,
526            auth: SyncAuth::Static,
527        })
528    }
529
530    /// A consumer presenting a federation capability `token`, each request signed by `signer` —
531    /// the puller's key, which the home server pinned for the peer the capability names.
532    ///
533    /// # Errors
534    ///
535    /// [`SyncError::Transport`] when `base_url` is not a URL the client can hang paths off.
536    pub fn with_signed_capability(
537        base_url: &str,
538        token: impl Into<String>,
539        signer: Arc<dyn RequestSigner>,
540    ) -> Result<Self, SyncError> {
541        let token: String = token.into();
542        Ok(Self {
543            client: build_client(base_url, Bearer::Token(token.clone()))?,
544            auth: SyncAuth::Signed {
545                token: token.into(),
546                signer,
547            },
548        })
549    }
550
551    /// Pull one page after `cursor`.
552    ///
553    /// On a `401` under a session, refreshes once and retries — the reactive half of the session
554    /// contract, which the pre-flight refresh cannot cover when a token is revoked mid-flight.
555    /// A `503` or a transport failure rides the shared retry engine's `interactive` class: short
556    /// timeout, at most two retries, then a visible failure — no configuration hot-loops.
557    #[instrument(skip(self, cursor), fields(page_size, entries))]
558    pub async fn pull(&self, cursor: &SyncCursor, page_size: u32) -> Result<SyncPage, SyncError> {
559        self.pull_scoped(cursor, page_size, None).await
560    }
561
562    /// The body both [`Self::pull`] and [`Self::pull_album`] run: one album or the whole feed.
563    async fn pull_scoped(
564        &self,
565        cursor: &SyncCursor,
566        page_size: u32,
567        album_id: Option<&str>,
568    ) -> Result<SyncPage, SyncError> {
569        let mut engine: RetryEngine = RetryClass::Interactive.engine();
570        let response = loop {
571            match self
572                .call(cursor, page_size, album_id, self.signature()?)
573                .await
574            {
575                Ok(page) => break page,
576                Err(error) if is_unauthenticated(&error) => match &self.auth {
577                    SyncAuth::Session(session) => {
578                        tracing::info!("the feed answered 401; refreshing once and retrying");
579                        session.refresh().await?;
580                        break self
581                            .call(cursor, page_size, album_id, None)
582                            .await
583                            .map_err(map_error)?;
584                    }
585                    SyncAuth::Static | SyncAuth::Signed { .. } => return Err(map_error(error)),
586                },
587                Err(error) if is_transient(&error) => match engine.next_backoff(None) {
588                    RetryDecision::GiveUp => {
589                        tracing::info!("the feed is unavailable; retry budget spent");
590                        return Err(map_error(error));
591                    }
592                    RetryDecision::Retry { after } => {
593                        tracing::debug!(?after, "the feed is unavailable; backing off");
594                        TokioSleeper.sleep(after).await;
595                    }
596                },
597                Err(error) => return Err(map_error(error)),
598            }
599        };
600        let page = decode_page(response)?;
601        tracing::Span::current().record("entries", page.entries.len());
602        Ok(page)
603    }
604
605    /// The request signature for one attempt at the feed, when this consumer presents a
606    /// capability.
607    ///
608    /// Made per attempt, retries included, so each carries a fresh nonce: the home server
609    /// accepts each signature once.
610    fn signature(&self) -> Result<Option<String>, SyncError> {
611        match &self.auth {
612            SyncAuth::Signed { token, signer } => {
613                crate::federation::request_signature(signer.as_ref(), "GET", FEED_PATH, token)
614                    .map(Some)
615                    .map_err(|error| {
616                        tracing::error!(%error, "a federated feed request could not be signed");
617                        SyncError::Transport(error)
618                    })
619            }
620            SyncAuth::Session(_) | SyncAuth::Static => Ok(None),
621        }
622    }
623
624    /// Pull one page of **one album** after `cursor`.
625    ///
626    /// The album arm of the same operation: an account reads it as the album's
627    /// owner or a member of its current roster, and a federated peer reads it under a capability
628    /// whose audience is that album. Same retry and same refresh-once behaviour as
629    /// [`Self::pull`]; the only difference is the parameter, because the *server* is where the
630    /// two arms differ and the client has one feed.
631    ///
632    /// # Errors
633    ///
634    /// As [`Self::pull`], plus the album refusals the server renders — a peer's revoked or
635    /// out-of-audience capability among them.
636    #[instrument(skip(self, cursor), fields(page_size, entries))]
637    pub async fn pull_album(
638        &self,
639        cursor: &SyncCursor,
640        page_size: u32,
641        album_id: &str,
642    ) -> Result<SyncPage, SyncError> {
643        self.pull_scoped(cursor, page_size, Some(album_id)).await
644    }
645
646    /// Pull the next page for `state` (using its stored cursor), validate and apply it, and
647    /// return it. The one call that ties the opaque-cursor round-trip to the anti-rewind layer.
648    #[instrument(skip(self, state), fields(page_size))]
649    pub async fn pull_into(
650        &self,
651        state: &mut SyncState,
652        page_size: u32,
653    ) -> Result<SyncPage, SyncError> {
654        let cursor = state.cursor().clone();
655        let page = self.pull(&cursor, page_size).await?;
656        state.apply_page(&page)?;
657        Ok(page)
658    }
659
660    async fn call(
661        &self,
662        cursor: &SyncCursor,
663        page_size: u32,
664        album_id: Option<&str>,
665        signature: Option<String>,
666    ) -> Result<rest::types::SyncPageResponse, rest::Error<rest::SyncFeedError>> {
667        let params = rest::SyncFeedParams {
668            x_capsule_request_signature: signature,
669            // Absent is the caller's own feed; present is one album's page.
670            album_id: album_id.map(str::to_owned),
671            // The cursor is round-tripped verbatim. Empty means "from the beginning", which the
672            // server spells as an absent parameter rather than an empty one.
673            cursor: cursor
674                .as_text()
675                .filter(|value| !value.is_empty())
676                .map(str::to_owned),
677            page_size: Some(page_size),
678            // The suite and the sidecar schema are validated when present and a feed pull has
679            // no use for either; the suite already rides the transport's default headers.
680            //
681            // The protocol date is a required parameter of every gated operation in the
682            // document, so the generated `…ParamsRequired` asks for it; the value is the build's
683            // own, the same one the transport's default header carries.
684            ..rest::SyncFeedParams::from(rest::SyncFeedParamsRequired {
685                x_capsule_protocol: capsule_core::crypto::primitives::PROTOCOL_VERSION.into(),
686            })
687        };
688        Ok(self.client.sync_feed(params).await?.into_inner())
689    }
690}
691
692/// A generated client for `base_url` carrying `credential` under the bearer scheme.
693fn build_client(base_url: &str, credential: Bearer) -> Result<rest::Client, SyncError> {
694    // The SDK's one HTTP client, so the feed pull carries the protocol handshake.
695    let http =
696        crate::net::http_client().map_err(|error| SyncError::Transport(error.to_string()))?;
697    let client = crate::client::negotiated_client(http, base_url).map_err(SyncError::Transport)?;
698    Ok(credential.attach(client))
699}
700
701/// A credential that pulls a fresh access token from `session` on every request.
702fn bearer_provider(session: Session) -> Bearer {
703    let provider: rest::TokenProvider = Arc::new(move || {
704        let session = session.clone();
705        Box::pin(async move {
706            session
707                .bearer()
708                .await
709                .map_err(|error| rest::AuthError::new(error.to_string()))
710        })
711    });
712    Bearer::Provider(provider)
713}
714
715/// Whether the feed refused the credential.
716fn is_unauthenticated(error: &rest::Error<rest::SyncFeedError>) -> bool {
717    matches!(
718        error,
719        rest::Error::Api(response) if matches!(response.inner(), rest::SyncFeedError::Status401(_))
720    )
721}
722
723/// Whether the failure is one worth backing off and retrying.
724///
725/// A `500` is included deliberately: the feed's only `500` is *"a collaborator could not
726/// answer"*, which is exactly the transient the retry engine exists for. A `400` (bad cursor) or
727/// a `403` (wrong credential kind) is not — retrying either changes nothing.
728fn is_transient(error: &rest::Error<rest::SyncFeedError>) -> bool {
729    match error {
730        rest::Error::Transport(_) | rest::Error::Timeout(_) | rest::Error::Protocol(_) => true,
731        rest::Error::Api(response) => {
732            matches!(response.inner(), rest::SyncFeedError::Status500(_))
733        }
734        _ => false,
735    }
736}
737
738// ─── Wire decoding ───────────────────────────────────────────────────────────
739
740/// Map a generated client error to a typed [`SyncError`], keeping the stable `error.*` code the
741/// problem body carries (the server always sends it and always describes it).
742fn map_error(error: rest::Error<rest::SyncFeedError>) -> SyncError {
743    match error {
744        rest::Error::Api(response) => {
745            let (code, message) = match response.into_inner() {
746                // The 400 includes the protocol gate's malformed-handshake answer (issue #404).
747                // There is no 426 to map: the feed is a read, and a read is admitted at any
748                // grammatical protocol date — the window rides the response headers instead.
749                // The 429 is a federated peer's events budget: a capability puller
750                // over its hour. Rejected rather than retried, because the window is an hour
751                // and the interactive retry class would give up long before it turned.
752                // The 409 is a cursor from before the library's sync epoch moved (#697); the
753                // caller recognises it by its code (`SyncError::is_stale_cursor`).
754                rest::SyncFeedError::Status400(problem)
755                | rest::SyncFeedError::Status401(problem)
756                | rest::SyncFeedError::Status403(problem)
757                | rest::SyncFeedError::Status409(problem)
758                | rest::SyncFeedError::Status429(problem)
759                | rest::SyncFeedError::Status500(problem) => (
760                    Some(problem.code.clone()),
761                    problem.detail.clone().unwrap_or_default(),
762                ),
763                // The body-size backstop.
764                rest::SyncFeedError::Status413(problem) => (
765                    Some(problem.code.clone()),
766                    "the request was too large".into(),
767                ),
768            };
769            SyncError::Rejected { code, message }
770        }
771        other => SyncError::Transport(other.to_string()),
772    }
773}
774
775fn decode_page(page: rest::types::SyncPageResponse) -> Result<SyncPage, SyncError> {
776    let entries = page
777        .entries
778        .into_iter()
779        .map(decode_entry)
780        .collect::<Result<Vec<_>, _>>()?;
781    Ok(SyncPage {
782        entries,
783        next_cursor: SyncCursor::from_bytes(page.next_cursor.into_bytes()),
784        has_more: page.has_more,
785    })
786}
787
788fn decode_entry(entry: rest::types::SyncEntry) -> Result<FeedEntry, SyncError> {
789    let kind = match entry.change {
790        rest::types::WireChangeKind::Created => ChangeKind::Created,
791        rest::types::WireChangeKind::Updated => ChangeKind::Updated,
792        rest::types::WireChangeKind::Deleted => ChangeKind::Deleted,
793    };
794    // Base64, because the manifest is CBOR and the feed is JSON. Decoded here so a caller holds
795    // the *exact* signed bytes `verify_asset` needs — re-encoding them anywhere would be the
796    // corruption that carrying the signed bytes verbatim exists to prevent.
797    let manifest_cbor = match entry.manifest_cbor.as_option() {
798        Some(encoded) => BASE64
799            .decode(encoded)
800            .map_err(|error| SyncError::MalformedManifest(error.to_string()))?,
801        None => Vec::new(),
802    };
803    // Optional on the wire: a server that predates the field sends no key, which is an asset
804    // with no manifests to hand over rather than a malformed entry.
805    let derivative_manifests = entry
806        .derivative_manifests
807        .iter()
808        .flatten()
809        .map(|encoded| {
810            BASE64
811                .decode(encoded)
812                .map_err(|error| SyncError::MalformedManifest(error.to_string()))
813        })
814        .collect::<Result<Vec<_>, _>>()?;
815    Ok(FeedEntry {
816        album_id: entry.album_id.into_bytes(),
817        sync_seq: entry.sync_seq,
818        protocol_version: entry.protocol_version,
819        kind,
820        asset_id: entry.asset_id.into_bytes(),
821        manifest_cbor,
822        metadata_blob: entry
823            .metadata_blob
824            .into_option()
825            .unwrap_or_default()
826            .into_bytes(),
827        blobs: decode_blobs(entry.blobs),
828        derivative_manifests,
829        original_held: entry.original_held,
830        // Optional on the wire: a server that predates the signal sends no key, and that is no
831        // purge. A signal on anything but a tombstone is not one either.
832        purged: kind == ChangeKind::Deleted && entry.purged.unwrap_or(false),
833        changed_at: entry.changed_at,
834    })
835}
836
837/// Split the feed's flat blob list into the by-role shape a caller reads.
838///
839/// The wire carries one list because the server has no reason to group it; the SDK groups it
840/// because every caller asks "is there an original" first.
841fn decode_blobs(blobs: Vec<rest::types::SyncBlobRef>) -> BlobManifest {
842    let mut manifest = BlobManifest::default();
843    for blob in blobs {
844        let reference = BlobRef {
845            ciphertext_hash: blob.hash,
846            role: role_str(&blob.role).to_owned(),
847            size: blob.size,
848        };
849        if matches!(blob.role, rest::types::WireBlobRole::Original) {
850            manifest.original = Some(reference);
851        } else {
852            manifest.derivatives.push(reference);
853        }
854    }
855    manifest
856}
857
858/// The wire token for a blob role.
859fn role_str(role: &rest::types::WireBlobRole) -> &'static str {
860    match role {
861        rest::types::WireBlobRole::Original => "original",
862        rest::types::WireBlobRole::Metadata => "metadata",
863        rest::types::WireBlobRole::Derivative => "derivative",
864        rest::types::WireBlobRole::Provenance => "provenance",
865        rest::types::WireBlobRole::Backup => "backup",
866        // The server never lists this role in `blobs` — the manifests ride the entry's own
867        // `derivative_manifests` — but the wire enum is shared with the upload body, so the
868        // arm exists and spells the token the server would.
869        rest::types::WireBlobRole::DerivativeManifest => "derivative_manifest",
870    }
871}
872
873// ─── Provenance history ──────────────────────────────────────────────────────
874
875/// The most records [`fetch_history`] walks back from a head: a chain longer than this is
876/// refused ([`HistoryError::TooLong`]) rather than held in memory without bound. Every record of
877/// a chain is one lifecycle write of one asset, so a real chain is far shorter.
878pub const MAX_HISTORY_RECORDS: usize = 4096;
879
880/// The largest provenance record [`fetch_history`] accepts (1 MiB). A record is a signed
881/// manifest and its chain link, a few KiB; anything past this is not one.
882pub const MAX_RECORD_BYTES: u64 = 1024 * 1024;
883
884/// Why an asset's earlier provenance records could not be fetched, or the blobs its adoption
885/// needs could not be named from them ([`history_sources`]). Nothing is verified here —
886/// [`Workspace::adopt_remote_history`](capsule_library::lifecycle::Workspace::adopt_remote_history)
887/// does that — so each variant is a fact about the walk, not a verdict on the chain.
888#[derive(Debug, thiserror::Error)]
889pub enum HistoryError {
890    /// A record does not decode, so the link to the record before it cannot be read. `hash` is
891    /// the record's address, or `head` for the record the walk started from.
892    #[error("the provenance record {hash} does not decode: {detail}")]
893    Malformed {
894        /// The record's content address, or `head`.
895        hash: String,
896        /// English detail (developer/log message).
897        detail: String,
898    },
899    /// The record a link names could not be fetched: the server refused it (an asset the caller
900    /// may not read, a deleted one past its retention window, or a purged one), it did not hash
901    /// to its address, or the transport failed.
902    #[error("fetching the provenance record {hash} failed: {source}")]
903    Fetch {
904        /// The content address the link names.
905        hash: String,
906        /// Why the fetch failed.
907        #[source]
908        source: crate::fetch::FetchError,
909    },
910    /// The chain is longer than [`MAX_HISTORY_RECORDS`].
911    #[error("the provenance chain is longer than {limit} records")]
912    TooLong {
913        /// The bound, [`MAX_HISTORY_RECORDS`].
914        limit: usize,
915    },
916    /// Neither the head nor any record of its history binds a metadata blob, so there is no live
917    /// metadata blob to name. A chain starts at a `create`, which binds one, so a history that
918    /// reaches its create never answers this.
919    #[error("no record of the chain binds a metadata blob")]
920    Unbound,
921}
922
923/// The blobs adopting an asset from its fetched history needs beyond its records, by content
924/// address: what [`history_sources`] reads off a head and the records before it.
925#[derive(Debug, Clone, PartialEq, Eq)]
926pub struct HistorySources {
927    /// The asset's live metadata blob: the head's own when it binds one, else the newest record
928    /// of the history that binds one.
929    pub metadata_blob_hash: capsule_core::crypto::hash::Hash32,
930    /// The original the head commits to (its `ciphertext_hash`).
931    pub original_hash: capsule_core::crypto::hash::Hash32,
932    /// The original's exact ciphertext length, from the head's `plaintext_size`.
933    pub original_size: u64,
934}
935
936/// Name the live metadata blob and the original an asset's adoption needs, from its head record
937/// (a feed entry's `manifest_cbor`) and the records before it ([`fetch_history`]'s answer).
938///
939/// This is how a device that first sees an asset at its `delete` on an album page, which names
940/// no byte reference on a tombstone, finds what to fetch: the delete binds no metadata blob, so
941/// the live one is the newest record of the history that binds one, and the delete still commits
942/// to the asset's original. Both are served by the blob route to the asset's readers until its
943/// retention window closes. A head that binds a metadata blob names its own, so an entry that
944/// names one agrees with this.
945///
946/// Nothing is trusted for being read here: the adoption binds the metadata blob to the record
947/// that names it and the original to the head's content address, so a wrong answer is refused
948/// there, never adopted.
949///
950/// # Errors
951///
952/// [`HistoryError::Malformed`] when the head or a history record does not decode (`hash` is
953/// `head` or the record's position), and [`HistoryError::Unbound`] when no record binds a
954/// metadata blob.
955#[instrument(skip_all, fields(head_bytes = head_record.len(), records = history.len()))]
956pub fn history_sources(
957    head_record: &[u8],
958    history: &[Vec<u8>],
959) -> Result<HistorySources, HistoryError> {
960    use capsule_core::crypto::provenance::ProvenanceRecord;
961
962    let decode = |bytes: &[u8], at: String| {
963        ProvenanceRecord::decode(bytes).map_err(|error| HistoryError::Malformed {
964            hash: at,
965            detail: error.to_string(),
966        })
967    };
968    let head = decode(head_record, "head".to_owned())?;
969    let mut metadata_blob_hash = head.manifest.core.metadata_blob_hash;
970    for (position, bytes) in history.iter().enumerate().rev() {
971        if metadata_blob_hash.is_some() {
972            break;
973        }
974        let record = decode(bytes, format!("history[{position}]"))?;
975        if record.manifest.core.action.binds_metadata_blob() {
976            metadata_blob_hash = record.manifest.core.metadata_blob_hash;
977        }
978    }
979    let Some(metadata_blob_hash) = metadata_blob_hash else {
980        tracing::warn!(
981            records = history.len(),
982            "sync-history: no record of the chain binds a metadata blob"
983        );
984        return Err(HistoryError::Unbound);
985    };
986    let sources = HistorySources {
987        metadata_blob_hash,
988        original_hash: head.manifest.core.ciphertext_hash,
989        original_size: capsule_core::crypto::encryption::ciphertext_len(
990            head.manifest.core.plaintext_size,
991        ),
992    };
993    tracing::debug!(
994        metadata = %sources.metadata_blob_hash.to_hex(),
995        original = %sources.original_hash.to_hex(),
996        original_size = sources.original_size,
997        action = ?head.manifest.core.action,
998        "sync-history: the blobs an adoption needs were named from the chain"
999    );
1000    Ok(sources)
1001}
1002
1003/// Whether the retention window of the `delete` that is `head_record` (a feed entry's
1004/// `manifest_cbor`) had closed at `at`: `at` is at or after the `retention_until` signed into
1005/// it, the instant from which the server refuses a `trash-restore` and stops serving the asset's
1006/// records and bytes to its readers.
1007///
1008/// A device that first sees an asset at an album page's tombstone reads this before it fetches
1009/// the asset's history: a closed window means the fetch is refused, and there is nothing left to
1010/// adopt or restore. A record that is not a `delete`, or a `delete` whose `retention_until` is
1011/// absent or unreadable, has no closed window (`false`), as the trash judges one: a guessed
1012/// deadline could only ever lose data.
1013///
1014/// # Errors
1015///
1016/// [`HistoryError::Malformed`] (`hash` is `head`) when `head_record` does not decode.
1017#[instrument(skip_all, fields(head_bytes = head_record.len(), %at))]
1018pub fn retention_closed(head_record: &[u8], at: jiff::Timestamp) -> Result<bool, HistoryError> {
1019    use capsule_core::crypto::provenance::{Action, ProvenanceRecord};
1020
1021    let head = ProvenanceRecord::decode(head_record).map_err(|error| HistoryError::Malformed {
1022        hash: "head".to_owned(),
1023        detail: error.to_string(),
1024    })?;
1025    let core = &head.manifest.core;
1026    if core.action != Action::Delete {
1027        tracing::trace!(action = ?core.action, "sync-retention: not a delete; no window");
1028        return Ok(false);
1029    }
1030    let Some(until) = core.retention_until.as_deref() else {
1031        tracing::debug!(asset_id = %core.file_id, "sync-retention: the delete signs no retention_until; the window is open");
1032        return Ok(false);
1033    };
1034    let until = match until.parse::<jiff::Timestamp>() {
1035        Ok(until) => until,
1036        Err(error) => {
1037            tracing::warn!(asset_id = %core.file_id, retention_until = %until, %error, "sync-retention: unreadable retention_until; treating the window as open");
1038            return Ok(false);
1039        }
1040    };
1041    let closed = at >= until;
1042    tracing::debug!(asset_id = %core.file_id, %until, closed, "sync-retention: the delete's window judged");
1043    Ok(closed)
1044}
1045
1046/// Walk an asset's provenance chain back from `head_record` (the `manifest_cbor` a feed entry
1047/// carries) to its `create`, fetching each record the one after it names by
1048/// `prior_provenance_hash` through `source` (`GET /v1/blob/{hash}`, where the server keeps an
1049/// asset's superseded records under the live record's read authority).
1050///
1051/// Returns the records **before** the head, oldest first, each the exact bytes the server
1052/// holds, verified against its content address by the fetch: what
1053/// [`Workspace::adopt_remote_history`](capsule_library::lifecycle::Workspace::adopt_remote_history)
1054/// takes. A head that is its asset's `create` has no history, and the walk fetches nothing.
1055///
1056/// Nothing is trusted for being fetched: the walk only follows links, and the chain is verified
1057/// record by record when it is adopted.
1058///
1059/// # Errors
1060///
1061/// [`HistoryError`]; the walk stops at the first record it cannot fetch or decode.
1062#[instrument(skip_all, fields(head_bytes = head_record.len()))]
1063pub async fn fetch_history<B, S, C>(
1064    fetcher: &crate::fetch::RangedFetcher<S, C>,
1065    source: &B,
1066    head_record: &[u8],
1067) -> Result<Vec<Vec<u8>>, HistoryError>
1068where
1069    B: crate::fetch::BlobSource,
1070    S: Sleeper,
1071    C: crate::net::MonotonicClock,
1072{
1073    let mut prior = prior_of(head_record, "head")?;
1074    let mut history = Vec::new();
1075    while let Some(link) = prior {
1076        if history.len() == MAX_HISTORY_RECORDS {
1077            tracing::warn!(
1078                limit = MAX_HISTORY_RECORDS,
1079                "sync-history: the chain is longer than the walk's bound"
1080            );
1081            return Err(HistoryError::TooLong {
1082                limit: MAX_HISTORY_RECORDS,
1083            });
1084        }
1085        let hash = link.to_hex();
1086        let record = fetcher
1087            .fetch_unsized(source, &hash, MAX_RECORD_BYTES)
1088            .await
1089            .map_err(|source| {
1090                tracing::warn!(%hash, error = %source, "sync-history: an earlier record could not be fetched");
1091                HistoryError::Fetch {
1092                    hash: hash.clone(),
1093                    source,
1094                }
1095            })?;
1096        prior = prior_of(&record, &hash)?;
1097        tracing::debug!(%hash, bytes = record.len(), at_create = prior.is_none(), "sync-history: an earlier record fetched");
1098        history.push(record);
1099    }
1100    history.reverse();
1101    tracing::info!(
1102        records = history.len(),
1103        "sync-history: the chain was walked back to its create"
1104    );
1105    Ok(history)
1106}
1107
1108/// The `prior_provenance_hash` of the record `bytes`, read off its decode.
1109fn prior_of(
1110    bytes: &[u8],
1111    hash: &str,
1112) -> Result<Option<capsule_core::crypto::hash::Hash32>, HistoryError> {
1113    capsule_core::crypto::provenance::ProvenanceRecord::decode(bytes)
1114        .map(|record| record.prior_provenance_hash)
1115        .map_err(|error| HistoryError::Malformed {
1116            hash: hash.to_owned(),
1117            detail: error.to_string(),
1118        })
1119}
1120
1121/// Lossy UTF-8 of an id byte string, for error display only.
1122fn lossy(id: &[u8]) -> String {
1123    String::from_utf8_lossy(id).into_owned()
1124}
1125
1126/// True if `v` is a well-formed `YYYY-MM-DD` date (the only grammar
1127/// `protocol_version` accepts). Lexicographic comparison of valid values equals
1128/// chronological order — mirrors `capsule_core::validation::protocol`'s server-side
1129/// gate on the client side.
1130fn is_protocol_date(v: &str) -> bool {
1131    let b = v.as_bytes();
1132    b.len() == 10
1133        && b[4] == b'-'
1134        && b[7] == b'-'
1135        && b[..4].iter().all(u8::is_ascii_digit)
1136        && b[5..7].iter().all(u8::is_ascii_digit)
1137        && b[8..].iter().all(u8::is_ascii_digit)
1138}
1139
1140#[cfg(test)]
1141mod tests;