Skip to main content

capsule_sdk/
directory.rs

1//! Publishing and fetching the **signed device directory** (over the server's
2//! directory surface).
3//!
4//! The directory is the user-IK-signed list of enrolled device signing keys that
5//! [`verify_asset`] resolves a manifest's `created_by_device` against. Until a device's entry
6//! is published, every asset it signs is [`RejectReason::UnknownDevice`] to every *other*
7//! device — which is why first-device enrollment publishes before it uploads anything.
8//!
9//! Two rules shape this module:
10//!
11//! - **The bytes are opaque and travel verbatim.** The server projects exactly one field out
12//!   of the document — `directory_version`, for the invariant-23 monotonicity check — and
13//!   stores the rest byte-for-byte. Re-encoding the document here would detach it from the
14//!   signature it carries, so the canonical CBOR `capsule-core` produced is what goes on the
15//!   wire and what comes back off it.
16//! - **A fetched directory is not trusted until it verifies.** [`DirectoryClient::fetch`]
17//!   requires the pinned user identity key and refuses a document that does not verify under
18//!   it, so a server cannot hand a client a directory listing devices the user never enrolled.
19//!   The signature check itself is `capsule-core`'s ([`DeviceDirectory::verify`]); nothing
20//!   cryptographic is re-implemented here.
21//!
22//! - **A publish names the key it is signed under.** The document carries the user identity
23//!   key's signature but not the key, so [`DirectoryClient::publish`] sends the verifying key
24//!   beside it, base64 in `X-Capsule-Identity-Key`. The server anchors that key on
25//!   first publish, refuses any other thereafter, and refuses a document that does not verify
26//!   under it — invariant 23's second clause. Without the header every publish is a `400`.
27//!
28//! Hand-written rather than generated: the committed OpenAPI declares no request body for the
29//! publish operation, so the generated client's `publish_device_directory()` takes none. The
30//! wire below is the documented one (`application/cbor` plus the identity-key header in,
31//! `{directory_version}` out).
32//!
33//! [`verify_asset`]: capsule_core::crypto::verify_asset::verify_asset
34//! [`RejectReason::UnknownDevice`]: capsule_core::crypto::verify_asset::RejectReason::UnknownDevice
35
36use base64::Engine as _;
37use base64::engine::general_purpose::STANDARD as BASE64;
38use capsule_core::crypto::keys::{DeviceDirectory, HybridVerifyingKey};
39use capsule_i18n::error_codes;
40use serde::Deserialize;
41use tracing::instrument;
42use uuid::Uuid;
43
44use crate::auth::{AuthError, Session};
45
46/// The device-directory path, appended to the caller's API base.
47const DIRECTORY_PATH: &str = "devices/directory";
48
49/// The `application/cbor` media type the directory surface speaks in both directions.
50const CBOR: &str = "application/cbor";
51
52/// The header a publish names its user identity verifying key in, base64 (STANDARD) of
53/// [`HybridVerifyingKey::to_bytes`] — the anchor the server checks the signature against.
54const IDENTITY_KEY_HEADER: &str = "X-Capsule-Identity-Key";
55
56/// Everything the device-directory flows can fail with. Callers switch on the typed variant
57/// (or its stable `error.*` code), never on a bare status.
58#[derive(Debug, thiserror::Error)]
59pub enum DirectoryError {
60    /// The authenticated request itself failed (transport, session expiry, refresh).
61    #[error(transparent)]
62    Auth(#[from] AuthError),
63    /// Reading the response body off the wire failed.
64    #[error("reading device-directory response body failed: {0}")]
65    Body(#[source] reqwest::Error),
66    /// The server rejected the document as malformed (`400`).
67    #[error("the server rejected the device directory as malformed")]
68    Malformed,
69    /// The presented identity key is not the account's anchored one (`403`): the
70    /// document is well-formed and verifies, but under somebody else's key.
71    #[error("the device directory is signed under a key that is not the account's identity anchor")]
72    IdentityMismatch,
73    /// The submitted `directory_version` does not advance the stored one (`409`, invariant 23 —
74    /// the anti-rollback rule). Re-fetch, re-key, and re-publish at a higher version.
75    #[error("device directory version does not advance the published one")]
76    VersionConflict,
77    /// No directory has been published for the requested user (`404`).
78    #[error("no device directory published for this user")]
79    NotPublished,
80    /// The directory bytes could not be (de)serialized as the canonical `DeviceDirectory`.
81    #[error("device directory codec error: {0}")]
82    Codec(String),
83    /// A fetched directory does not verify under the pinned user identity key — a foreign or
84    /// forged document. Fail-closed: it is never returned to the caller.
85    #[error("the fetched device directory does not verify under the pinned user identity key")]
86    UntrustedSignature,
87    /// The server returned an unmodeled status.
88    #[error("unexpected {status} response from the device-directory endpoint")]
89    Unexpected {
90        /// The HTTP status code the server returned.
91        status: u16,
92    },
93}
94
95impl DirectoryError {
96    /// The stable `error.*` catalog code for this failure, when one applies. Clients localize
97    /// the code; the English detail message stays English.
98    pub fn error_code(&self) -> Option<&'static str> {
99        match self {
100            Self::Malformed => Some(error_codes::DIRECTORY_MALFORMED),
101            Self::IdentityMismatch => Some(error_codes::DIRECTORY_IDENTITY_MISMATCH),
102            Self::VersionConflict => Some(error_codes::DIRECTORY_VERSION_CONFLICT),
103            Self::UntrustedSignature => Some(error_codes::DIRECTORY_UNTRUSTED_SIGNATURE),
104            _ => None,
105        }
106    }
107}
108
109/// The `POST` response body: the version now stored for the user.
110#[derive(Debug, Deserialize)]
111struct PublishDirectoryResponseWire {
112    directory_version: u64,
113}
114
115/// The device-directory client. Borrows an authenticated [`Session`], so every call rides the
116/// SDK's bearer/refresh machinery and no token is handled here.
117#[derive(Clone)]
118pub struct DirectoryClient {
119    session: Session,
120    base_url: String,
121}
122
123impl DirectoryClient {
124    /// Build a client against the API base URL — the same base the auth session authenticates
125    /// against (e.g. `https://api.example.com/v1/auth`).
126    pub fn new(session: Session, api_base_url: &str) -> Self {
127        Self {
128            session,
129            base_url: format!("{}/{DIRECTORY_PATH}", api_base_url.trim_end_matches('/')),
130        }
131    }
132
133    /// Publish `directory` for the authenticated caller, returning the `directory_version` the
134    /// server now stores.
135    ///
136    /// `identity_key` is the account's user identity **verifying** key — the key `directory` is
137    /// signed under. It travels base64 in `X-Capsule-Identity-Key`; the server anchors it on
138    /// the first publish, answers [`DirectoryError::Malformed`] for a document that does not
139    /// verify under it, and [`DirectoryError::IdentityMismatch`] for a key other than the
140    /// anchored one.
141    ///
142    /// Idempotent only at the *same* version is **not** the contract: invariant 23 requires the
143    /// version to advance, so re-publishing an unchanged document answers
144    /// [`DirectoryError::VersionConflict`]. Publish when the document actually changes — a
145    /// device enrolled, a device revoked.
146    #[instrument(skip_all, fields(directory_version = directory.core.directory_version))]
147    pub async fn publish(
148        &self,
149        directory: &DeviceDirectory,
150        identity_key: &HybridVerifyingKey,
151    ) -> Result<u64, DirectoryError> {
152        let body = capsule_core::cbor::to_canonical_vec(directory)
153            .map_err(|e| DirectoryError::Codec(e.to_string()))?;
154        let identity = BASE64.encode(identity_key.to_bytes());
155        tracing::debug!(bytes = body.len(), "publishing the signed device directory");
156        let response = self
157            .session
158            .execute(|c| {
159                c.post(&self.base_url)
160                    .header(reqwest::header::CONTENT_TYPE, CBOR)
161                    .header(IDENTITY_KEY_HEADER, &identity)
162                    .body(body.clone())
163            })
164            .await?;
165
166        let status = response.status();
167        if !status.is_success() {
168            return Err(publish_status_error(status.as_u16()));
169        }
170        let wire: PublishDirectoryResponseWire =
171            response.json().await.map_err(DirectoryError::Body)?;
172        tracing::info!(
173            directory_version = wire.directory_version,
174            "device directory published"
175        );
176        Ok(wire.directory_version)
177    }
178
179    /// Fetch `user_id`'s signed device directory and **verify it under `pinned_user_ik`** before
180    /// returning it. A document that does not verify is [`DirectoryError::UntrustedSignature`]
181    /// and never reaches the caller.
182    ///
183    /// The anti-rollback high-water mark is the caller's to keep: compare
184    /// `core.directory_version` against the highest version already seen for this user and
185    /// refuse a regression, exactly as the sync feed's `sync_seq` is refused.
186    #[instrument(skip_all, fields(user_id = %user_id))]
187    pub async fn fetch(
188        &self,
189        user_id: Uuid,
190        pinned_user_ik: &HybridVerifyingKey,
191    ) -> Result<DeviceDirectory, DirectoryError> {
192        let url = format!("{}/{}", self.base_url, user_id.hyphenated());
193        let response = self
194            .session
195            .execute(|c| c.get(&url).header(reqwest::header::ACCEPT, CBOR))
196            .await?;
197
198        let status = response.status();
199        match status {
200            reqwest::StatusCode::OK => {}
201            reqwest::StatusCode::NOT_FOUND => return Err(DirectoryError::NotPublished),
202            other => {
203                return Err(DirectoryError::Unexpected {
204                    status: other.as_u16(),
205                });
206            }
207        }
208        let bytes = response.bytes().await.map_err(DirectoryError::Body)?;
209        let directory: DeviceDirectory = capsule_core::cbor::from_slice(&bytes)
210            .map_err(|e| DirectoryError::Codec(e.to_string()))?;
211
212        // Fail closed: an unverified directory is worse than none, because it would let a
213        // server introduce a device key of its choosing into the trusted set.
214        if !directory.verify(pinned_user_ik) {
215            tracing::warn!("fetched device directory failed its user-IK signature check");
216            return Err(DirectoryError::UntrustedSignature);
217        }
218        tracing::info!(
219            directory_version = directory.core.directory_version,
220            devices = directory.core.devices.len(),
221            "device directory fetched and verified"
222        );
223        Ok(directory)
224    }
225}
226
227/// Map a publish refusal onto its typed variant. Kept separate so the status table is one
228/// readable list rather than a match arm buried in the request path.
229fn publish_status_error(status: u16) -> DirectoryError {
230    match status {
231        400 => DirectoryError::Malformed,
232        403 => DirectoryError::IdentityMismatch,
233        409 => DirectoryError::VersionConflict,
234        other => DirectoryError::Unexpected { status: other },
235    }
236}
237
238#[cfg(test)]
239mod tests;