Skip to main content

capsule_sdk/cohort/
mod.rs

1//! Client-side device-cohort emission and the devices-grouping view model
2//! (SSoT: [Authentication — Device Cohorts]).
3//!
4//! This module owns the **client half** of the cohort story whose server half
5//! (advisory storage + the `{devices, cohorts}` listing) lives in the server,
6//! and whose pure hash lives in [`capsule_core::cohort`]. Three cohesive pieces:
7//!
8//! - **[`PrimaryIdentifierReader`]** — the per-platform seam. Each platform reads
9//!   its single primary identifier (Keychain seed / SSAID / IOPlatformUUID /
10//!   MachineGuid / hashed `machine-id`) behind this trait; the SDK never bakes in a
11//!   platform's identifier source. [`compute_cohort_hash`] turns a reader plus the
12//!   account `user_id` into the advisory hash that [`crate::auth::AuthClient`] rides.
13//! - **[`devices`]** — the devices-grouping view model that consumes the server's
14//!   `GET /devices` `{devices, cohorts}` body into groups the UI renders, carrying
15//!   the **assert-don't-litigate** copy as `locales/` catalog keys.
16//! - **[`devices::SupportBundle`]** — the one-tap dispute payload
17//!   (`cohort_hash` + the device/session map), serializable and round-trippable.
18//!
19//! ## Why the hash needs the `user_id`
20//!
21//! The cohort hash folds the account `user_id` in so the same physical device under
22//! two accounts yields unlinkable hashes (the cross-account correlation surface is
23//! removed at the source — see the owner doc). A client therefore emits a cohort
24//! only once it knows which account it is authenticating: on a returning device the
25//! app has the cached `user_id`; on a first-ever registration it does not, so it
26//! simply emits nothing (**absent stays legal**) and starts emitting on the next
27//! login. This module never guesses a `user_id`.
28//!
29//! ## Never log the raw identifier
30//!
31//! A [`PrimaryIdentifierReader`] handles a stable device fingerprint. Implementations
32//! and this module **must never** emit the raw identifier to logs, errors, or the
33//! `Debug` surface — only the derived hash (already one-way) ever leaves. The
34//! adapters here uphold that: the Linux reader returns a *hashed* value, never the
35//! raw `machine-id`, and no error variant embeds the identifier.
36//!
37//! [Authentication — Device Cohorts]: https://docs/design/authentication/#device-cohorts
38
39pub mod devices;
40
41pub use capsule_core::cohort::PlatformTag;
42use capsule_core::cohort::cohort_hash;
43use uuid::Uuid;
44
45/// Domain-separation label for the Linux `machine-id` pre-hash. Hashing the raw
46/// `machine-id` before it is ever used is systemd's explicit guidance ("never used
47/// raw") and keeps the stable machine secret from leaving the device even inside the
48/// cohort input.
49const MACHINE_ID_PREHASH_V1: &str = "capsule-machine-id-prehash/v1";
50
51/// Everything a [`PrimaryIdentifierReader`] can fail with. **No variant embeds the
52/// raw identifier** — the whole point of the reader is that the fingerprint never
53/// leaks, so the errors carry only the *reason*, never the value.
54#[derive(Debug, thiserror::Error)]
55pub enum IdentifierError {
56    /// The platform exposes no primary identifier in this environment (e.g. the
57    /// source file/service is absent). The caller emits no cohort — legal.
58    #[error("no primary identifier available on this platform/environment")]
59    Unavailable,
60    /// The identifier source was reachable but returned an empty value.
61    #[error("primary identifier source returned an empty value")]
62    Empty,
63    /// Reading the identifier source failed for the given reason (path/kind only —
64    /// never the value).
65    #[error("reading the primary identifier failed: {reason}")]
66    Read {
67        /// Why the read failed (I/O kind, a missing tool, etc.) — never the value.
68        reason: String,
69    },
70}
71
72/// The per-platform seam: read this platform's single primary identifier.
73///
74/// One identifier per platform, chosen for reinstall-stability, never a concatenated
75/// fingerprint (owner doc). The returned string is the `primary_id` fed verbatim into
76/// [`capsule_core::cohort::cohort_hash`]. Implementations **must not** log or otherwise
77/// surface the raw identifier; where the raw value is itself a stable device secret
78/// (Linux `machine-id`), the implementation returns a one-way-derived value instead.
79pub trait PrimaryIdentifierReader {
80    /// The platform this reader speaks for — becomes the closed `platform_tag` in the
81    /// hash construction.
82    fn platform(&self) -> PlatformTag;
83
84    /// Read the platform's primary identifier (already safe to hash: raw device
85    /// secrets are pre-derived by the implementation).
86    fn read_primary_id(&self) -> Result<String, IdentifierError>;
87}
88
89/// Compute the advisory cohort hash (lowercase-hex SHA-256) for an account on this
90/// device: read the platform's primary identifier and fold it with `user_id` through
91/// [`capsule_core::cohort::cohort_hash`].
92///
93/// The result is exactly what [`crate::auth::AuthClient::with_cohort_hash`] wants.
94/// Returns [`IdentifierError`] when no identifier is available — the caller then emits
95/// nothing, which is legal.
96pub fn compute_cohort_hash(
97    reader: &dyn PrimaryIdentifierReader,
98    user_id: Uuid,
99) -> Result<String, IdentifierError> {
100    let primary_id = reader.read_primary_id()?;
101    // Traceable without leaking: log that we computed one, never the input.
102    tracing::debug!(
103        platform = reader.platform().as_str(),
104        "computed device-cohort hash"
105    );
106    Ok(cohort_hash(user_id, reader.platform(), &primary_id).to_hex())
107}
108
109/// Derive the non-reversible `primary_id` for a Linux `machine-id`: a domain-separated
110/// SHA-256 over the raw value, so the stable machine secret never leaves the device
111/// even as a cohort input (systemd's "never used raw" guidance).
112///
113/// The input is **length-delimited** (each field prefixed by its byte length), not
114/// naively concatenated, so the fixed domain label and the value can never blur into
115/// each other.
116fn prehash_machine_id(raw: &str) -> String {
117    use capsule_core::crypto::hash::hash_bytes;
118
119    let label = MACHINE_ID_PREHASH_V1.as_bytes();
120    let raw = raw.as_bytes();
121    let mut buf = Vec::with_capacity(8 + label.len() + raw.len());
122    buf.extend_from_slice(&(label.len() as u32).to_le_bytes());
123    buf.extend_from_slice(label);
124    buf.extend_from_slice(&(raw.len() as u32).to_le_bytes());
125    buf.extend_from_slice(raw);
126    hash_bytes(&buf).to_hex()
127}
128
129/// Linux primary-identifier reader: the systemd `machine-id`, **hashed** before use.
130///
131/// Reads `/etc/machine-id` (falling back to `/var/lib/dbus/machine-id`), then returns
132/// the domain-separated hash — never the raw value. The source path is configurable
133/// ([`from_path`](LinuxMachineIdReader::from_path)) so the derivation is host-testable
134/// off a fixture on any OS.
135#[derive(Debug, Clone)]
136pub struct LinuxMachineIdReader {
137    paths: Vec<std::path::PathBuf>,
138}
139
140impl LinuxMachineIdReader {
141    /// The standard reader: `/etc/machine-id` then the dbus fallback.
142    pub fn new() -> Self {
143        Self {
144            paths: vec![
145                std::path::PathBuf::from("/etc/machine-id"),
146                std::path::PathBuf::from("/var/lib/dbus/machine-id"),
147            ],
148        }
149    }
150
151    /// A reader over an explicit source path (for tests/fixtures).
152    pub fn from_path(path: impl Into<std::path::PathBuf>) -> Self {
153        Self {
154            paths: vec![path.into()],
155        }
156    }
157}
158
159impl Default for LinuxMachineIdReader {
160    fn default() -> Self {
161        Self::new()
162    }
163}
164
165impl PrimaryIdentifierReader for LinuxMachineIdReader {
166    fn platform(&self) -> PlatformTag {
167        PlatformTag::Linux
168    }
169
170    fn read_primary_id(&self) -> Result<String, IdentifierError> {
171        for path in &self.paths {
172            match std::fs::read_to_string(path) {
173                Ok(contents) => {
174                    let raw = contents.trim();
175                    if raw.is_empty() {
176                        return Err(IdentifierError::Empty);
177                    }
178                    return Ok(prehash_machine_id(raw));
179                }
180                // Try the next candidate on absence; surface other I/O errors by kind.
181                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
182                Err(e) => {
183                    return Err(IdentifierError::Read {
184                        reason: e.kind().to_string(),
185                    });
186                }
187            }
188        }
189        Err(IdentifierError::Unavailable)
190    }
191}
192
193/// macOS primary-identifier reader: `IOPlatformUUID`, used directly (macOS is the one
194/// platform where the identifier is reset-stable, per the owner doc).
195///
196/// Resolves the UUID via `ioreg -rd1 -c IOPlatformExpertDevice`. Compiled only on
197/// macOS; other platforms use their own reader.
198#[cfg(target_os = "macos")]
199#[derive(Debug, Clone, Default)]
200pub struct MacosPlatformUuidReader;
201
202#[cfg(target_os = "macos")]
203impl MacosPlatformUuidReader {
204    /// A new reader.
205    pub fn new() -> Self {
206        Self
207    }
208
209    /// Extract the `IOPlatformUUID` value from `ioreg` output.
210    fn parse_uuid(ioreg_output: &str) -> Option<String> {
211        // Lines look like: `    "IOPlatformUUID" = "XXXXXXXX-XXXX-..."`
212        for line in ioreg_output.lines() {
213            if let Some(rest) = line.split_once("\"IOPlatformUUID\"")
214                && let Some(value) = rest.1.split('=').nth(1)
215            {
216                let uuid = value.trim().trim_matches('"').trim();
217                if !uuid.is_empty() {
218                    return Some(uuid.to_string());
219                }
220            }
221        }
222        None
223    }
224}
225
226#[cfg(target_os = "macos")]
227impl PrimaryIdentifierReader for MacosPlatformUuidReader {
228    fn platform(&self) -> PlatformTag {
229        PlatformTag::Macos
230    }
231
232    fn read_primary_id(&self) -> Result<String, IdentifierError> {
233        let output = std::process::Command::new("ioreg")
234            .args(["-rd1", "-c", "IOPlatformExpertDevice"])
235            .output()
236            .map_err(|e| IdentifierError::Read {
237                reason: e.kind().to_string(),
238            })?;
239        if !output.status.success() {
240            return Err(IdentifierError::Unavailable);
241        }
242        let text = String::from_utf8_lossy(&output.stdout);
243        Self::parse_uuid(&text).ok_or(IdentifierError::Unavailable)
244    }
245}
246
247#[cfg(test)]
248mod tests;