Skip to main content

capsule_core/
client_build.rs

1//! Client build identification — the `client_version` / `generated_by_client` grammar.
2//!
3//! Every *real* manifest producer pins a write to the exact client build that authored it, so a
4//! defect in one shipped build — of any client, in-repo or not — is traceable across every asset
5//! it touched. The normative grammar (SSoT: [Provenance — Client Build Identification]) is:
6//!
7//! ```text
8//! client_version = client_id "/" semver "+" commit [".dirty"]
9//! ```
10//!
11//! - `client_id` — the client product, which also names the platform (`capsule-ios`,
12//!   `capsule-android`, `capsule-desktop`, `capsule-cli`, `capsule-web`, or an out-of-repo
13//!   client's own stable id).
14//! - `commit` — the git commit of the client's own source tree (a `≥ 12`-hex prefix), embedded
15//!   at build time by [`build.rs`](../build.rs) as
16//!   [`BUILD_COMMIT`](crate::client_build::BUILD_COMMIT).
17//! - `.dirty` — appended ([`BUILD_DIRTY_SUFFIX`](crate::client_build::BUILD_DIRTY_SUFFIX)) when
18//!   built from a modified tree.
19//!
20//! The value is **audit-only** and never load-bearing for authorization: `verify_asset` does not
21//! gate on the grammar (a nonconforming string still verifies), so this module is producer
22//! discipline plus a parser for audit tooling and the grammar round-trip test.
23//!
24//! In-repo clients inject only their `client_id` + own `semver` (via
25//! `Workspace::with_client_id` or the FFI
26//! constructor); the build-embedded commit and dirty flag are appended here so every client on
27//! this tree reports the same commit.
28//!
29//! [Provenance — Client Build Identification]: https://docs/design/cryptography/provenance/#client-build-identification
30
31/// Git commit (a `≥ 12`-hex prefix) of the capsule-core source tree, embedded at build time.
32///
33/// Falls back to [`UNKNOWN_COMMIT`] when the build ran without a usable git probe (missing
34/// binary, non-repository, or a shallow clone with no reachable commit) — a documented sentinel,
35/// never a build failure. See [`build.rs`](../build.rs).
36pub const BUILD_COMMIT: &str = env!("CAPSULE_BUILD_COMMIT");
37
38/// `".dirty"` when capsule-core was built from a modified (tracked) tree, else `""`.
39pub const BUILD_DIRTY_SUFFIX: &str = env!("CAPSULE_BUILD_DIRTY");
40
41/// The all-zero sentinel [`BUILD_COMMIT`] carries when no commit could be probed at build time.
42/// Kept at 16 hex digits so a fallback build still emits a grammar-conformant `client_version`.
43pub const UNKNOWN_COMMIT: &str = "0000000000000000";
44
45/// The default in-repo product id a bare capsule-core producer reports until an app injects its
46/// own identity through the SDK/FFI surface.
47pub const CORE_CLIENT_ID: &str = "capsule-core";
48
49/// Compose a grammar-conformant `client_version` for an in-repo client. `client_id` names the
50/// product (`capsule-cli`, `capsule-ios`, …); `semver` is that client's own crate version. The
51/// build-embedded [`BUILD_COMMIT`] and [`BUILD_DIRTY_SUFFIX`] are appended.
52#[must_use]
53pub fn client_version(client_id: &str, semver: &str) -> String {
54    format!("{client_id}/{semver}+{BUILD_COMMIT}{BUILD_DIRTY_SUFFIX}")
55}
56
57/// The default `capsule-core/{semver}+{commit}[.dirty]` identity, used until an app injects its
58/// own `client_id`. `semver` is capsule-core's own crate version.
59#[must_use]
60pub fn core_client_version() -> String {
61    client_version(CORE_CLIENT_ID, env!("CARGO_PKG_VERSION"))
62}
63
64/// A parsed `client_version`, for the grammar round-trip in tests and for audit tooling. The
65/// grammar is producer discipline only — a manifest carrying a nonconforming string still
66/// verifies, so parsing is never a `verify_asset` gate.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct ClientVersion {
69    /// The client product / platform id (e.g. `capsule-cli`).
70    pub client_id: String,
71    /// The client's own semantic version (e.g. `0.1.0`).
72    pub semver: String,
73    /// The git commit prefix (`≥ 12` hex digits).
74    pub commit: String,
75    /// Whether the producing tree was modified (`.dirty`).
76    pub dirty: bool,
77}
78
79impl ClientVersion {
80    /// Parse a `client_id "/" semver "+" commit [".dirty"]` string, enforcing the normative
81    /// grammar: a non-empty `client_id` and `semver`, and a `commit` of `≥ 12` hex digits.
82    /// Returns `None` for a nonconforming value (audit-only; never a verify gate).
83    ///
84    /// `commit` is split at the **last** `+` so a semver build-metadata `+` (e.g.
85    /// `1.2.3+meta+abc123def456`) never steals the commit boundary.
86    #[must_use]
87    pub fn parse(s: &str) -> Option<Self> {
88        let (client_id, rest) = s.split_once('/')?;
89        let (semver, commit_full) = rest.rsplit_once('+')?;
90        let (commit, dirty) = match commit_full.strip_suffix(".dirty") {
91            Some(commit) => (commit, true),
92            None => (commit_full, false),
93        };
94        if client_id.is_empty() || semver.is_empty() {
95            return None;
96        }
97        if commit.len() < 12 || !commit.bytes().all(|b| b.is_ascii_hexdigit()) {
98            return None;
99        }
100        Some(Self {
101            client_id: client_id.to_owned(),
102            semver: semver.to_owned(),
103            commit: commit.to_owned(),
104            dirty,
105        })
106    }
107}
108
109impl std::fmt::Display for ClientVersion {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        write!(f, "{}/{}+{}", self.client_id, self.semver, self.commit)?;
112        if self.dirty {
113            f.write_str(".dirty")?;
114        }
115        Ok(())
116    }
117}
118
119#[cfg(test)]
120mod tests;