Skip to main content

capsule_library/library/
auth_gate.rs

1//! Fresh-local-auth gates for the sensitive local-gallery views (SSoT: [Local Gallery — SR1]).
2//!
3//! Opening the **Recently Deleted** (trash) or **Hidden** view requires *fresh local
4//! authentication* — biometric where enrolled (Face ID / Touch ID / BiometricPrompt), else the
5//! device or account credential. This module owns the **policy**: which views are gated, the
6//! per-view grace clock (default 5 minutes), and the refuse-without-grant query surface. It does
7//! **not** own the authentication itself — biometrics and the credential fallback are a platform
8//! concern, reached through the [`LocalAuthGate`] seam. This mirrors the
9//! [`Signer`](capsule_core::crypto::keys::Signer) /
10//! [`HardwareSigner`](capsule_core::crypto::keys::HardwareSigner) discipline: the trait lives in core,
11//! the Secure Enclave / BiometricPrompt adapters live in `capsule-core-swift` / `capsule-core-kotlin`.
12//!
13//! The gate is view-time snoop protection, **not** a cryptographic boundary (SR1): the same bytes
14//! are reachable through the filesystem by anyone who defeats the platform sandbox (see SR2). It
15//! exists to stop a borrowed-unlocked-phone from casually browsing the trash or the hidden set.
16//!
17//! [Local Gallery — SR1]: https://docs/design/local-gallery/#security-requirements
18
19use std::collections::HashMap;
20use std::time::{Duration, Instant};
21
22use crate::db::DatabaseDriver;
23use crate::db::rows::AssetRow;
24
25/// The default per-view grace window (SR1): one fresh grant covers 5 minutes, after which the
26/// view re-locks and re-authentication is required.
27pub const DEFAULT_GRACE: Duration = Duration::from_mins(5);
28
29/// A view that requires fresh local auth before it opens (SR1). A grant is **per-view**:
30/// authenticating for one view never opens the other.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32pub enum GatedView {
33    /// The trash / "Recently Deleted" listing of soft-deleted assets.
34    RecentlyDeleted,
35    /// The user-hidden set (assets whose sidecar `hidden` register is set).
36    Hidden,
37}
38
39/// The per-platform local-authentication seam, implemented by native code (Swift/Kotlin) behind the
40/// `capsule_core_ffi` namespace's `LocalAuthGate` foreign-trait mirror; a plain Rust trait here.
41/// Rust calls *into* it to perform the fresh-auth challenge; core never sees the biometric or the
42/// credential.
43///
44/// The **biometric → credential fallback** is entirely the implementation's concern: an adapter
45/// tries the enrolled biometric first (Face ID / Touch ID / BiometricPrompt) and falls back to the
46/// device or account credential, surfacing only the *outcome* through this trait. Core treats any
47/// [`Ok`] as a successful fresh auth regardless of which method produced it.
48pub trait LocalAuthGate: Send + Sync {
49    /// Perform a fresh local-authentication challenge for `view`. Returns [`Ok`] on success (by
50    /// any enrolled method), or a [`LocalAuthError`] on denial, cancellation, or unavailability.
51    fn authenticate(&self, view: GatedView) -> Result<(), LocalAuthError>;
52}
53
54/// Failure surfaced by a [`LocalAuthGate`] backend.
55#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
56pub enum LocalAuthError {
57    /// The user dismissed or cancelled the authentication prompt.
58    #[error("local authentication was cancelled")]
59    Cancelled,
60    /// No local authentication method is available (no biometric enrolled and no device
61    /// credential set) — the platform cannot challenge.
62    #[error("no local authentication method is available")]
63    Unavailable,
64    /// The challenge was presented and refused (wrong credential, failed biometric).
65    #[error("local authentication failed")]
66    Failed,
67}
68
69/// Refusal returned by the gate's grant surface.
70#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
71pub enum GateError {
72    /// No live grant exists for the view: it is locked and requires a fresh
73    /// [`open`](GateKeeper::open).
74    #[error("view is locked: fresh local authentication is required")]
75    Locked,
76    /// The platform gate refused the fresh-auth challenge during [`open`](GateKeeper::open).
77    #[error(transparent)]
78    Auth(#[from] LocalAuthError),
79}
80
81/// Failure of a gated view query — either the gate refused, or the underlying index read failed.
82#[derive(Debug, thiserror::Error)]
83pub enum GatedQueryError {
84    /// The gate refused the read (no live grant).
85    #[error(transparent)]
86    Gate(#[from] GateError),
87    /// The underlying `library.sqlite` query failed.
88    #[error("gated view query failed: {0}")]
89    Db(String),
90}
91
92/// A monotonic clock for the grace window, injectable so tests drive time deterministically.
93/// Only *differences* between readings are meaningful; the absolute value has no meaning.
94pub trait GraceClock {
95    /// A monotonically non-decreasing reading in milliseconds.
96    fn now_millis(&self) -> i64;
97}
98
99/// The production [`GraceClock`]: a monotonic [`Instant`] anchored at construction. Monotonic (not
100/// wall-clock) so a user or NTP nudging the system clock can neither extend nor prematurely expire
101/// a grant.
102pub struct SystemGraceClock {
103    anchor: Instant,
104}
105
106impl SystemGraceClock {
107    /// Anchor the clock at "now".
108    pub fn new() -> Self {
109        Self {
110            anchor: Instant::now(),
111        }
112    }
113}
114
115impl Default for SystemGraceClock {
116    fn default() -> Self {
117        Self::new()
118    }
119}
120
121impl GraceClock for SystemGraceClock {
122    fn now_millis(&self) -> i64 {
123        self.anchor.elapsed().as_millis() as i64
124    }
125}
126
127/// A short-lived proof that a live grant existed for `view` at the moment it was minted. Consumed
128/// immediately by a gated read; it carries no capability of its own beyond naming the view.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub struct ViewGuard {
131    view: GatedView,
132}
133
134impl ViewGuard {
135    /// The view this guard proves access to.
136    pub fn view(&self) -> GatedView {
137        self.view
138    }
139}
140
141/// Tracks per-view fresh-auth grants and enforces the grace window (SR1). Owns no authentication
142/// itself: it drives a [`LocalAuthGate`] to mint grants and then gates the sensitive view reads.
143///
144/// Generic over the [`GraceClock`] so tests inject deterministic time; the default is the
145/// monotonic [`SystemGraceClock`].
146pub struct GateKeeper<C: GraceClock = SystemGraceClock> {
147    clock: C,
148    grace_ms: i64,
149    /// view → the clock reading at which the grant was minted.
150    grants: HashMap<GatedView, i64>,
151}
152
153impl Default for GateKeeper<SystemGraceClock> {
154    fn default() -> Self {
155        Self::new()
156    }
157}
158
159impl GateKeeper<SystemGraceClock> {
160    /// A gate keeper on the monotonic system clock with the [`DEFAULT_GRACE`] window.
161    pub fn new() -> Self {
162        Self::with_clock(SystemGraceClock::new())
163    }
164}
165
166impl<C: GraceClock> GateKeeper<C> {
167    /// A gate keeper on `clock` with the [`DEFAULT_GRACE`] window.
168    pub fn with_clock(clock: C) -> Self {
169        Self::with_clock_and_grace(clock, DEFAULT_GRACE)
170    }
171
172    /// A gate keeper on `clock` with an explicit grace window.
173    pub fn with_clock_and_grace(clock: C, grace: Duration) -> Self {
174        Self {
175            clock,
176            grace_ms: grace.as_millis() as i64,
177            grants: HashMap::new(),
178        }
179    }
180
181    /// Whether `view` currently has a live grant (minted within the grace window).
182    pub fn is_open(&self, view: GatedView) -> bool {
183        match self.grants.get(&view) {
184            Some(&minted_at) => self.clock.now_millis().saturating_sub(minted_at) < self.grace_ms,
185            None => false,
186        }
187    }
188
189    /// Open `view`, performing a fresh-auth challenge through `gate` **only if** there is no live
190    /// grant already. A grant is *not* slid forward by re-opening within its window: the window is
191    /// measured from the original mint, so a snoop cannot keep a view open indefinitely by
192    /// re-tapping it. Returns [`GateError::Auth`] if the platform gate refuses.
193    #[tracing::instrument(skip_all, fields(view = ?view))]
194    pub fn open(&mut self, view: GatedView, gate: &dyn LocalAuthGate) -> Result<(), GateError> {
195        if self.is_open(view) {
196            tracing::debug!("local-auth gate: reusing live grant, no re-auth");
197            return Ok(());
198        }
199        gate.authenticate(view)?;
200        let minted_at = self.clock.now_millis();
201        self.grants.insert(view, minted_at);
202        tracing::info!("local-auth gate: fresh grant minted");
203        Ok(())
204    }
205
206    /// A [`ViewGuard`] proving a live grant for `view`, or [`GateError::Locked`] if none. Performs
207    /// **no** authentication — pure state check; use [`open`](Self::open) to acquire a grant.
208    pub fn guard(&self, view: GatedView) -> Result<ViewGuard, GateError> {
209        if self.is_open(view) {
210            Ok(ViewGuard { view })
211        } else {
212            Err(GateError::Locked)
213        }
214    }
215
216    /// Revoke the grant for a single view (e.g. the user backgrounded that surface).
217    pub fn revoke(&mut self, view: GatedView) {
218        if self.grants.remove(&view).is_some() {
219            tracing::info!(?view, "local-auth gate: grant revoked");
220        }
221    }
222
223    /// Revoke every grant (e.g. app backgrounded / device locked). The next open re-authenticates.
224    pub fn lock(&mut self) {
225        if !self.grants.is_empty() {
226            self.grants.clear();
227            tracing::info!("local-auth gate: all grants revoked (locked)");
228        }
229    }
230
231    /// The **Recently Deleted** (trash) listing, gated: refuses with [`GateError::Locked`] unless a
232    /// live [`GatedView::RecentlyDeleted`] grant exists. Ordering / paging are the driver's
233    /// ([`DatabaseDriver::query_trash`]).
234    pub fn query_recently_deleted(
235        &self,
236        db: &DatabaseDriver,
237        offset: usize,
238        limit: usize,
239    ) -> Result<Vec<AssetRow>, GatedQueryError> {
240        let _guard = self.guard(GatedView::RecentlyDeleted)?;
241        db.query_trash(offset, limit)
242            .map_err(|e| GatedQueryError::Db(e.to_string()))
243    }
244
245    /// The **Hidden** listing, gated: refuses with [`GateError::Locked`] unless a live
246    /// [`GatedView::Hidden`] grant exists. The same 5-minute-grace contract as
247    /// [`query_recently_deleted`](Self::query_recently_deleted) — one policy, two views —
248    /// and the grants are independent, so opening the trash never opens this. Ordering /
249    /// paging are the driver's ([`DatabaseDriver::query_hidden`]).
250    ///
251    /// This is the *only* way hidden assets surface: every default projection
252    /// (timeline, album) excludes them (SSoT: design/organization § Hidden Assets).
253    pub fn query_hidden(
254        &self,
255        db: &DatabaseDriver,
256        offset: usize,
257        limit: usize,
258    ) -> Result<Vec<AssetRow>, GatedQueryError> {
259        let _guard = self.guard(GatedView::Hidden)?;
260        db.query_hidden(offset, limit)
261            .map_err(|e| GatedQueryError::Db(e.to_string()))
262    }
263}
264
265#[cfg(test)]
266mod tests;