Skip to main content

adk_kernel/pairing/
mod.rs

1//! Device pairing (spec 3.3 §10 K2, §11 S-I7): short-lived pairing codes, then scoped,
2//! expiring, revocable device tokens, stored hashed.
3//!
4//! A phone, a tray or a terminal on another machine reaches the kernel's control plane with
5//! a device token instead of the operator's own credentials:
6//!
7//! 1. The person at the kernel issues a code (`adk-rust pair`, `POST /api/kernel/pairing`):
8//!    twelve characters shown as `ABCD-EFGH-2345` (60 bits), valid for ten minutes, naming
9//!    the scopes the device gets. The store keeps the code's SHA-256 only.
10//! 2. The device claims it (`POST /api/kernel/pairing/claim`, the one route that needs no
11//!    caller, since the code is the credential) and receives its token once:
12//!    `adkd_<id>_<secret>`. The store keeps the secret's SHA-256 only. A claim takes the
13//!    code, so each code pairs one device. Every claim is counted in the store before its
14//!    code is looked up, so replicas share the count: after twenty claims without a success,
15//!    every waiting code is cancelled and claims are refused until the next code is issued.
16//! 3. The device sends the token as `Authorization: Bearer` over HTTP. Each request is
17//!    admitted only to the routes its scopes open ([`device_scope_for`]), as the person who
18//!    issued the code, with that person's approval groups, until the token expires or is
19//!    revoked (`adk-rust pair revoke`, `POST /api/kernel/devices/{id}/revoke`). An event
20//!    stream a device holds open ends when the device is revoked or its pairing ends: at once
21//!    for a revocation on the same kernel, within five seconds for one on another replica.
22//!    A decision a device answers is checked for its risk and recorded by the device guard
23//!    in front of the routes: the kernel's own HTTP listener runs it, and a server's app
24//!    runs it through [`guard_devices`](crate::control::guard_devices); without the guard,
25//!    [`DeviceTokenExtractor`] refuses the decision.
26//!
27//! | Scope | Routes (under `/api`) |
28//! |---|---|
29//! | [`DeviceScope::Read`] | `GET /kernel/health`, `GET /kernel/processes`, `GET /kernel/events`, `POST /kernel/attach/{session}`, `GET /kernel/agenda`, `GET /approvals`, `GET /approvals/{id}`; `GET /kernel/settings[/{partition}]`, `GET /kernel/away`, `POST /kernel/away/seen`, `GET /kernel/away/lines/{seq}`, `GET /kernel/memory`, `GET /kernel/record`, `GET /kernel/record/check` (spec 3.3 §10 K3–K5); `GET /kernel/agents[/{id}]` (spec 3.3 §10 K7) |
30//! | [`DeviceScope::Decide`] | `POST /approvals/{id}/decide`, low and medium risk; high risk waits for confirming it is the person (spec 3.3 §7.2) |
31//! | [`DeviceScope::Stop`] | `POST /kernel/freeze` |
32//!
33//! Every other route refuses a device token, `unfreeze` included: resuming happens only in
34//! the web home or on a paired local terminal (S-I10). Pairing never widens the bind: the
35//! loopback default and the rule that a non-loopback bind needs a token or SSO stay as they
36//! are (K-I18, S-I7).
37//!
38//! A server opens its own routes to devices with [`Pairing::with_device_routes`], a
39//! [`DeviceRoutes`] map consulted after [`device_scope_for`], so the kernel never names a
40//! surface's paths. The guard checks the risk of, and records, the kernel's own decide route
41//! only; a decide route of the server's map is admitted for the server's engine, which
42//! enforces what each surface may decide (spec 3.3 §7.2) and records the answer.
43//!
44//! Every device has a [`DeviceKind`] — phone, terminal or tray — set by whoever issued its
45//! code, never by the claim: a request carries it in [`DEVICE_KIND_METADATA`]. A device
46//! paired without one is a remote terminal. Surfaces keep what belongs to a device or a person
47//! beside it as [`DeviceAttachment`]s (a phone's push subscription, a passkey); revoking a
48//! device removes its attachments.
49//!
50//! | Backend | Type | Feature |
51//! |---|---|---|
52//! | In-memory | [`InMemoryDeviceStore`] | — |
53//! | SQLite | `SqliteDeviceStore` | `sqlite` (default) |
54//! | PostgreSQL | `PostgresDeviceStore` | `postgres` |
55//! | Redis | `RedisDeviceStore` | `redis` |
56//!
57//! # Example
58//!
59//! ```rust
60//! use std::sync::Arc;
61//! use adk_kernel::pairing::{DeviceScope, InMemoryDeviceStore, IssueCode, Pairing};
62//!
63//! # #[tokio::main(flavor = "current_thread")]
64//! # async fn main() -> adk_kernel::Result<()> {
65//! let pairing = Pairing::new(Arc::new(InMemoryDeviceStore::new()));
66//! let issued = pairing
67//!     .issue(IssueCode::new("ana", ["operator"]).with_scopes([DeviceScope::Read]).with_name("Ana's phone"))
68//!     .await?;
69//! let claimed = pairing.claim(&issued.code, None).await?;
70//! let device = pairing.authenticate(&claimed.token).await?;
71//! assert_eq!(device.owner, "ana");
72//! assert!(pairing.claim(&issued.code, None).await.is_err(), "a code pairs one device");
73//! # Ok(())
74//! # }
75//! ```
76
77use std::collections::{BTreeSet, HashMap};
78use std::fmt;
79use std::future::Future;
80use std::sync::Arc;
81use std::time::Duration;
82
83use adk_core::{AdkError, Clock, ErrorCategory, ErrorComponent, RequestContext, SystemClock};
84use adk_server::auth_bridge::{RequestContextError, RequestContextExtractor};
85use async_trait::async_trait;
86use axum::http::Method;
87use axum::http::request::Parts;
88use chrono::{DateTime, Utc};
89use serde::{Deserialize, Serialize};
90
91use crate::error::{KernelError, Result, UNAUTHORIZED_CODE, UNSUPPORTED_CODE};
92
93mod attachments;
94mod kinds;
95mod memory;
96#[cfg(feature = "postgres")]
97pub(crate) mod postgres;
98#[cfg(feature = "redis")]
99pub(crate) mod redis;
100pub(crate) mod secret;
101#[cfg(any(feature = "sqlite", feature = "postgres"))]
102pub(crate) mod sql;
103#[cfg(feature = "sqlite")]
104mod sqlite;
105
106pub use attachments::{AttachmentHolder, DeviceAttachment};
107pub use kinds::{DeviceKind, DeviceRoutes};
108pub use memory::InMemoryDeviceStore;
109#[cfg(feature = "postgres")]
110pub use postgres::PostgresDeviceStore;
111#[cfg(feature = "redis")]
112pub use redis::RedisDeviceStore;
113#[cfg(feature = "sqlite")]
114pub use sqlite::SqliteDeviceStore;
115
116/// The request-context metadata key naming the device a request came from.
117pub const DEVICE_ID_METADATA: &str = "adk.device.id";
118/// The request-context metadata key with the device's name.
119pub const DEVICE_NAME_METADATA: &str = "adk.device.name";
120/// The request-context metadata key with the device's scopes, comma-separated.
121pub const DEVICE_SCOPES_METADATA: &str = "adk.device.scopes";
122/// The request-context metadata key with the device's kind: `phone`, `terminal` or `tray`
123/// (spec 3.3 §7.2, §10 K2).
124pub const DEVICE_KIND_METADATA: &str = "adk.device.kind";
125
126/// Claims without a success after which the next one cancels every waiting code.
127const MAX_FAILED_CLAIMS: u64 = 20;
128/// How often an open event stream re-reads its device, for a revocation on another replica.
129const DEFAULT_RECHECK: Duration = Duration::from_secs(5);
130/// The longest a device name may be.
131const MAX_NAME_CHARS: usize = 64;
132/// The longest a device's pairing may last.
133const MAX_DEVICE_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60);
134
135/// What a device may do (spec 3.3 §10 K2): answer decisions, read, or stop everything.
136///
137/// # Example
138///
139/// ```rust
140/// use adk_kernel::pairing::DeviceScope;
141///
142/// assert_eq!(serde_json::to_value(DeviceScope::Decide).unwrap(), "decide");
143/// assert_eq!("stop".parse::<DeviceScope>().unwrap(), DeviceScope::Stop);
144/// ```
145#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
146#[serde(rename_all = "camelCase")]
147#[non_exhaustive]
148pub enum DeviceScope {
149    /// Answer decisions: allow once, edit or deny (`POST /approvals/{id}/decide`).
150    Decide,
151    /// Read the process table, the event stream, the agenda, the decisions and the caller's
152    /// own sessions.
153    Read,
154    /// Stop everything (`POST /kernel/freeze`).
155    Stop,
156}
157
158impl DeviceScope {
159    /// Every scope, the default a code grants.
160    pub const ALL: [Self; 3] = [Self::Decide, Self::Read, Self::Stop];
161
162    /// The scope's name: `decide`, `read` or `stop`.
163    pub fn as_str(self) -> &'static str {
164        match self {
165            Self::Decide => "decide",
166            Self::Read => "read",
167            Self::Stop => "stop",
168        }
169    }
170}
171
172impl fmt::Display for DeviceScope {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        f.write_str(self.as_str())
175    }
176}
177
178impl std::str::FromStr for DeviceScope {
179    type Err = KernelError;
180
181    fn from_str(text: &str) -> Result<Self> {
182        match text.trim().to_ascii_lowercase().as_str() {
183            "decide" => Ok(Self::Decide),
184            "read" => Ok(Self::Read),
185            "stop" => Ok(Self::Stop),
186            other => Err(KernelError::Config {
187                reason: format!("unknown device scope `{other}`: use decide, read or stop"),
188            }),
189        }
190    }
191}
192
193/// A paired device as the store keeps it (spec 3.3 §10 K2): its token's hash, never the
194/// token.
195///
196/// # Example
197///
198/// ```rust
199/// use adk_kernel::pairing::{DeviceRecord, DeviceScope};
200///
201/// let now = chrono::Utc::now();
202/// let device = DeviceRecord::new("0a1b2c3d4e5f6071", "Ana's phone", "ana", "9f…", now, now + chrono::Duration::days(90))
203///     .with_scopes([DeviceScope::Read]);
204/// assert!(device.is_active(now));
205/// assert!(!device.view(now).scopes.contains(&DeviceScope::Decide));
206/// ```
207#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(rename_all = "camelCase")]
209#[non_exhaustive]
210pub struct DeviceRecord {
211    /// The device id, sixteen hex digits, part of its token.
212    pub id: String,
213    /// What the person calls it, such as "Ana's phone".
214    pub name: String,
215    /// The person the device acts for: the user who issued its code.
216    pub owner: String,
217    /// The approval groups the device decides with: its owner's when the code was issued.
218    #[serde(default, skip_serializing_if = "Vec::is_empty")]
219    pub groups: Vec<String>,
220    /// What it may do, sorted.
221    pub scopes: Vec<DeviceScope>,
222    /// The SHA-256 of the token's secret, in hex.
223    pub token_hash: String,
224    /// When it was paired.
225    pub created_at: DateTime<Utc>,
226    /// When its token stops working.
227    pub expires_at: DateTime<Utc>,
228    /// When it was removed, if it was.
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub revoked_at: Option<DateTime<Utc>>,
231    /// What it is, as its code's issuer said; none for a remote terminal paired before kinds.
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub kind: Option<DeviceKind>,
234}
235
236impl DeviceRecord {
237    /// A device with every scope and no groups.
238    pub fn new(
239        id: impl Into<String>,
240        name: impl Into<String>,
241        owner: impl Into<String>,
242        token_hash: impl Into<String>,
243        created_at: DateTime<Utc>,
244        expires_at: DateTime<Utc>,
245    ) -> Self {
246        Self {
247            id: id.into(),
248            name: name.into(),
249            owner: owner.into(),
250            groups: Vec::new(),
251            scopes: DeviceScope::ALL.to_vec(),
252            token_hash: token_hash.into(),
253            created_at,
254            expires_at,
255            revoked_at: None,
256            kind: None,
257        }
258    }
259
260    /// Sets what the device is.
261    #[must_use]
262    pub fn with_kind(mut self, kind: DeviceKind) -> Self {
263        self.kind = Some(kind);
264        self
265    }
266
267    /// What the device is: a device paired without a kind is a remote terminal.
268    pub fn kind(&self) -> DeviceKind {
269        self.kind.unwrap_or(DeviceKind::Terminal)
270    }
271
272    /// Sets the scopes, sorted and without repeats.
273    #[must_use]
274    pub fn with_scopes(mut self, scopes: impl IntoIterator<Item = DeviceScope>) -> Self {
275        self.scopes = scopes.into_iter().collect::<BTreeSet<_>>().into_iter().collect();
276        self
277    }
278
279    /// Sets the approval groups.
280    #[must_use]
281    pub fn with_groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
282        self.groups = groups.into_iter().map(Into::into).collect();
283        self
284    }
285
286    /// Whether the token works at `now`: not revoked and not expired.
287    pub fn is_active(&self, now: DateTime<Utc>) -> bool {
288        self.revoked_at.is_none() && now < self.expires_at
289    }
290
291    /// Whether the device holds `scope`.
292    pub fn has_scope(&self, scope: DeviceScope) -> bool {
293        self.scopes.contains(&scope)
294    }
295
296    /// The device as listed: everything but the token's hash.
297    pub fn view(&self, now: DateTime<Utc>) -> DeviceView {
298        let state = match (self.revoked_at, now < self.expires_at) {
299            (Some(_), _) => DeviceState::Revoked,
300            (None, true) => DeviceState::Active,
301            (None, false) => DeviceState::Expired,
302        };
303        DeviceView {
304            id: self.id.clone(),
305            name: self.name.clone(),
306            owner: self.owner.clone(),
307            scopes: self.scopes.clone(),
308            created_at: self.created_at,
309            expires_at: self.expires_at,
310            revoked_at: self.revoked_at,
311            state,
312            kind: self.kind(),
313        }
314    }
315}
316
317/// Whether a device's token works (spec 3.3 §10 K2).
318///
319/// # Example
320///
321/// ```rust
322/// use adk_kernel::pairing::DeviceState;
323///
324/// assert_eq!(serde_json::to_value(DeviceState::Revoked).unwrap(), "revoked");
325/// ```
326#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
327#[serde(rename_all = "camelCase")]
328#[non_exhaustive]
329pub enum DeviceState {
330    /// The token works.
331    Active,
332    /// The pairing ran out.
333    Expired,
334    /// The device was removed.
335    Revoked,
336}
337
338/// A paired device as `GET /kernel/devices` lists it (spec 3.3 §10 K2): no token, no hash.
339#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
340#[serde(rename_all = "camelCase")]
341#[non_exhaustive]
342pub struct DeviceView {
343    /// The device id.
344    pub id: String,
345    /// What the person calls it.
346    pub name: String,
347    /// The person it acts for.
348    pub owner: String,
349    /// What it may do.
350    pub scopes: Vec<DeviceScope>,
351    /// When it was paired.
352    pub created_at: DateTime<Utc>,
353    /// When its token stops working.
354    pub expires_at: DateTime<Utc>,
355    /// When it was removed.
356    #[serde(default, skip_serializing_if = "Option::is_none")]
357    pub revoked_at: Option<DateTime<Utc>>,
358    /// Whether its token works now.
359    pub state: DeviceState,
360    /// What it is.
361    #[serde(default = "terminal")]
362    pub kind: DeviceKind,
363}
364
365fn terminal() -> DeviceKind {
366    DeviceKind::Terminal
367}
368
369/// An issued pairing code as the store keeps it (spec 3.3 §10 K2): its hash, never the code.
370#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
371#[serde(rename_all = "camelCase")]
372#[non_exhaustive]
373pub struct PairingCode {
374    /// The SHA-256 of the normalized code, in hex.
375    pub code_hash: String,
376    /// The person the claimed device will act for.
377    pub owner: String,
378    /// Their approval groups.
379    #[serde(default, skip_serializing_if = "Vec::is_empty")]
380    pub groups: Vec<String>,
381    /// The scopes the device gets, sorted.
382    pub scopes: Vec<DeviceScope>,
383    /// The device's name, when the issuer gave one.
384    #[serde(default, skip_serializing_if = "Option::is_none")]
385    pub name: Option<String>,
386    /// How long the device's pairing lasts, in seconds.
387    pub device_ttl_secs: u64,
388    /// When the code was issued.
389    pub issued_at: DateTime<Utc>,
390    /// When it stops working.
391    pub expires_at: DateTime<Utc>,
392    /// What the claimed device is, as the issuer said.
393    #[serde(default, skip_serializing_if = "Option::is_none")]
394    pub kind: Option<DeviceKind>,
395}
396
397impl PairingCode {
398    /// A code hashed `code_hash` for `owner`, with every scope, no groups and no name.
399    pub fn new(
400        code_hash: impl Into<String>,
401        owner: impl Into<String>,
402        device_ttl: Duration,
403        issued_at: DateTime<Utc>,
404        expires_at: DateTime<Utc>,
405    ) -> Self {
406        Self {
407            code_hash: code_hash.into(),
408            owner: owner.into(),
409            groups: Vec::new(),
410            scopes: DeviceScope::ALL.to_vec(),
411            name: None,
412            device_ttl_secs: device_ttl.as_secs(),
413            issued_at,
414            expires_at,
415            kind: None,
416        }
417    }
418}
419
420/// Where paired devices and waiting pairing codes are kept (spec 3.3 §10 K2, S-I7), on the
421/// backends the kernel's other stores use, with one conformance suite
422/// (`device_store_conformance_tests!`, feature `conformance`).
423///
424/// Neither a code nor a token is ever stored: codes by their hash, devices by their
425/// token's hash.
426#[async_trait]
427pub trait DeviceStore: Send + Sync {
428    /// Keeps a waiting code, replacing one with the same hash.
429    async fn put_code(&self, code: PairingCode) -> Result<()>;
430
431    /// Removes and returns the code hashed `code_hash`, expired or not; `None` when no code
432    /// has it. Two claims of one code take it once.
433    async fn take_code(&self, code_hash: &str) -> Result<Option<PairingCode>>;
434
435    /// Removes the codes that expired at or before `before`; returns how many.
436    async fn prune_codes(&self, before: DateTime<Utc>) -> Result<usize>;
437
438    /// Removes every waiting code; returns how many.
439    async fn clear_codes(&self) -> Result<usize>;
440
441    /// Keeps a device, replacing the one with the same id.
442    async fn put_device(&self, device: DeviceRecord) -> Result<()>;
443
444    /// The device `id`, revoked and expired ones included.
445    async fn get_device(&self, id: &str) -> Result<Option<DeviceRecord>>;
446
447    /// Every device, oldest pairing first, then by id.
448    async fn list_devices(&self) -> Result<Vec<DeviceRecord>>;
449
450    /// Counts one claim attempt and returns how many were counted since the last reset.
451    /// Every replica over the store shares the count, and concurrent attempts each get a
452    /// distinct count.
453    async fn count_claim_attempt(&self) -> Result<u64>;
454
455    /// Starts the count of claim attempts again.
456    async fn reset_claim_attempts(&self) -> Result<()>;
457
458    /// Keeps `attachment`, replacing the one with its holder, kind and key (spec 3.3 §5.4).
459    ///
460    /// The default refuses: a backend that keeps no attachments says so.
461    async fn put_attachment(&self, attachment: DeviceAttachment) -> Result<()> {
462        let _ = attachment;
463        Err(no_attachments())
464    }
465
466    /// Keeps `attachment` unless one with its holder, kind and key exists; whether it wrote.
467    /// Of concurrent puts of one attachment, from any replica, exactly one writes.
468    async fn put_attachment_if_absent(&self, attachment: DeviceAttachment) -> Result<bool> {
469        let _ = attachment;
470        Err(no_attachments())
471    }
472
473    /// `holder`'s attachments of `kind`, by key.
474    async fn attachments(
475        &self,
476        holder: &AttachmentHolder,
477        kind: &str,
478    ) -> Result<Vec<DeviceAttachment>> {
479        let _ = (holder, kind);
480        Err(no_attachments())
481    }
482
483    /// Removes `holder`'s attachment of `kind` under `key`; whether there was one.
484    async fn remove_attachment(
485        &self,
486        holder: &AttachmentHolder,
487        kind: &str,
488        key: &str,
489    ) -> Result<bool> {
490        let _ = (holder, kind, key);
491        Err(no_attachments())
492    }
493
494    /// Removes every attachment of `holder`; returns how many.
495    async fn remove_attachments(&self, holder: &AttachmentHolder) -> Result<usize> {
496        let _ = holder;
497        Err(no_attachments())
498    }
499}
500
501/// The error of a [`DeviceStore`] that keeps no attachments.
502fn no_attachments() -> KernelError {
503    KernelError::Core(AdkError::new(
504        ErrorComponent::Server,
505        ErrorCategory::Unsupported,
506        UNSUPPORTED_CODE,
507        "this device store keeps no attachments: use the in-memory, SQLite, PostgreSQL or Redis \
508         device store",
509    ))
510}
511
512/// What `adk-rust pair` asks for (spec 3.3 §10 K2): a code for a device acting for `owner`.
513///
514/// # Example
515///
516/// ```rust
517/// use std::time::Duration;
518/// use adk_kernel::pairing::{DeviceScope, IssueCode};
519///
520/// let request = IssueCode::new("ana", ["operator"])
521///     .with_scopes([DeviceScope::Read, DeviceScope::Decide])
522///     .with_device_ttl(Duration::from_secs(30 * 24 * 3600));
523/// assert_eq!(request.scopes.len(), 2);
524/// ```
525#[derive(Debug, Clone, PartialEq, Eq)]
526#[non_exhaustive]
527pub struct IssueCode {
528    /// The person the device will act for.
529    pub owner: String,
530    /// Their approval groups.
531    pub groups: Vec<String>,
532    /// The scopes; every scope when empty.
533    pub scopes: Vec<DeviceScope>,
534    /// The device's name.
535    pub name: Option<String>,
536    /// How long the pairing lasts; the service's default when `None`.
537    pub device_ttl: Option<Duration>,
538    /// What the device is; a remote terminal when `None`. Only the issuer sets it.
539    pub kind: Option<DeviceKind>,
540}
541
542impl IssueCode {
543    /// A code for a device acting for `owner` with `groups`, every scope, the default
544    /// pairing length and no name.
545    pub fn new(
546        owner: impl Into<String>,
547        groups: impl IntoIterator<Item = impl Into<String>>,
548    ) -> Self {
549        Self {
550            owner: owner.into(),
551            groups: groups.into_iter().map(Into::into).collect(),
552            scopes: Vec::new(),
553            name: None,
554            device_ttl: None,
555            kind: None,
556        }
557    }
558
559    /// Says what the device is (spec 3.3 §7.2): a phone, a remote terminal or a tray.
560    #[must_use]
561    pub fn with_kind(mut self, kind: DeviceKind) -> Self {
562        self.kind = Some(kind);
563        self
564    }
565
566    /// Grants `scopes` only.
567    #[must_use]
568    pub fn with_scopes(mut self, scopes: impl IntoIterator<Item = DeviceScope>) -> Self {
569        self.scopes = scopes.into_iter().collect();
570        self
571    }
572
573    /// Names the device.
574    #[must_use]
575    pub fn with_name(mut self, name: impl Into<String>) -> Self {
576        self.name = Some(name.into());
577        self
578    }
579
580    /// Sets how long the pairing lasts.
581    #[must_use]
582    pub fn with_device_ttl(mut self, ttl: Duration) -> Self {
583        self.device_ttl = Some(ttl);
584        self
585    }
586
587    /// The request as it is issued and recorded: every scope when none is named, sorted and
588    /// without repeats, and the name without control characters, at most 64 characters.
589    ///
590    /// # Example
591    ///
592    /// ```rust
593    /// use adk_kernel::pairing::{DeviceScope, IssueCode};
594    ///
595    /// let code = IssueCode::new("ana", ["operator"]).with_name("Ana's\u{7} phone").normalized();
596    /// assert_eq!(code.scopes, DeviceScope::ALL);
597    /// assert_eq!(code.name.as_deref(), Some("Ana's phone"));
598    /// ```
599    #[must_use]
600    pub fn normalized(mut self) -> Self {
601        self.scopes = if self.scopes.is_empty() {
602            DeviceScope::ALL.to_vec()
603        } else {
604            self.scopes.iter().copied().collect::<BTreeSet<_>>().into_iter().collect()
605        };
606        self.name = self
607            .name
608            .map(|name| secret::clean_name(&name, MAX_NAME_CHARS))
609            .filter(|name| !name.is_empty());
610        self
611    }
612}
613
614/// A claimed code whose device is not stored yet: the control plane records the claim
615/// first, then stores the device or puts the code back.
616pub(crate) struct PendingClaim {
617    code: PairingCode,
618    device: DeviceRecord,
619    token: String,
620}
621
622impl PendingClaim {
623    /// The device the claim pairs.
624    pub(crate) fn device(&self) -> &DeviceRecord {
625        &self.device
626    }
627}
628
629/// The marker the device guard leaves on a request it admitted, so the extractor behind it
630/// knows the request's risk was checked and recorded.
631#[derive(Debug, Clone, PartialEq, Eq)]
632pub(crate) struct DeviceAdmission {
633    pub(crate) device: String,
634}
635
636/// A code just issued (spec 3.3 §10 K2): the only time the code itself is seen.
637#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
638#[serde(rename_all = "camelCase")]
639#[non_exhaustive]
640pub struct IssuedCode {
641    /// The code, as `ABCD-EFGH-2345`.
642    pub code: String,
643    /// When it stops working.
644    pub expires_at: DateTime<Utc>,
645    /// The scopes the device will get.
646    pub scopes: Vec<DeviceScope>,
647    /// Where a phone opens its code, when the kernel knows its home's address:
648    /// `<home>/pair#code=ABCD-EFGH-2345`, the code in the fragment so no server log keeps it.
649    /// `None` for a terminal or a tray, which take the code typed.
650    #[serde(default, skip_serializing_if = "Option::is_none")]
651    pub url: Option<String>,
652    /// How long the device that claims the code stays paired, in seconds.
653    #[serde(default)]
654    pub device_ttl_secs: u64,
655}
656
657/// A device just paired (spec 3.3 §10 K2): the only time its token is seen.
658#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
659#[serde(rename_all = "camelCase")]
660#[non_exhaustive]
661pub struct ClaimedDevice {
662    /// The device.
663    pub device: DeviceView,
664    /// Its bearer token, `adkd_<id>_<secret>`; keep it secret.
665    pub token: String,
666}
667
668impl fmt::Debug for ClaimedDevice {
669    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670        f.debug_struct("ClaimedDevice").field("device", &self.device).finish_non_exhaustive()
671    }
672}
673
674/// Device pairing over a [`DeviceStore`] (spec 3.3 §10 K2, S-I7): issue and claim codes,
675/// authenticate and authorize device tokens, list and revoke devices.
676///
677/// The control plane serves it when [`ControlPlaneConfig::with_pairing`](crate::control::ControlPlaneConfig::with_pairing)
678/// sets it; see the [module documentation](self) for the flow and the scopes.
679#[derive(Clone)]
680pub struct Pairing {
681    inner: Arc<Inner>,
682}
683
684struct Inner {
685    store: Arc<dyn DeviceStore>,
686    #[cfg(feature = "channels")]
687    channels: Option<Arc<dyn crate::channels::ChannelBindingStore>>,
688    code_ttl: Duration,
689    device_ttl: Duration,
690    home_url: Option<String>,
691    clock: Arc<dyn Clock>,
692    recheck: Duration,
693    revoked: tokio::sync::broadcast::Sender<String>,
694    routes: Option<DeviceRoutes>,
695}
696
697impl fmt::Debug for Pairing {
698    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
699        f.debug_struct("Pairing")
700            .field("code_ttl", &self.inner.code_ttl)
701            .field("device_ttl", &self.inner.device_ttl)
702            .field("home_url", &self.inner.home_url)
703            .finish_non_exhaustive()
704    }
705}
706
707impl Pairing {
708    /// How long a code works by default: ten minutes.
709    pub const DEFAULT_CODE_TTL: Duration = Duration::from_secs(10 * 60);
710    /// How long a device's pairing lasts by default: ninety days.
711    pub const DEFAULT_DEVICE_TTL: Duration = Duration::from_secs(90 * 24 * 60 * 60);
712
713    /// Pairing over `store`, with the default lengths and no home address.
714    pub fn new(store: Arc<dyn DeviceStore>) -> Self {
715        Self {
716            inner: Arc::new(Inner {
717                store,
718                #[cfg(feature = "channels")]
719                channels: None,
720                code_ttl: Self::DEFAULT_CODE_TTL,
721                device_ttl: Self::DEFAULT_DEVICE_TTL,
722                home_url: None,
723                clock: Arc::new(SystemClock),
724                recheck: DEFAULT_RECHECK,
725                revoked: tokio::sync::broadcast::channel(64).0,
726                routes: None,
727            }),
728        }
729    }
730
731    fn rebuild(self, change: impl FnOnce(&mut Inner)) -> Self {
732        let inner = Arc::try_unwrap(self.inner).unwrap_or_else(|shared| Inner {
733            store: shared.store.clone(),
734            #[cfg(feature = "channels")]
735            channels: shared.channels.clone(),
736            code_ttl: shared.code_ttl,
737            device_ttl: shared.device_ttl,
738            home_url: shared.home_url.clone(),
739            clock: shared.clock.clone(),
740            recheck: shared.recheck,
741            revoked: shared.revoked.clone(),
742            routes: shared.routes.clone(),
743        });
744        let mut inner = inner;
745        change(&mut inner);
746        Self { inner: Arc::new(inner) }
747    }
748
749    /// Opens the server's own routes to devices (spec 3.3 §10 K2): `routes` names the scope
750    /// each needs, after the kernel's [`device_scope_for`]. The device token extractor and
751    /// the device guard read it from here.
752    ///
753    /// # Example
754    ///
755    /// ```rust
756    /// use std::sync::Arc;
757    /// use axum::http::Method;
758    /// use adk_kernel::pairing::{DeviceScope, InMemoryDeviceStore, Pairing};
759    ///
760    /// let pairing = Pairing::new(Arc::new(InMemoryDeviceStore::new())).with_device_routes(Arc::new(
761    ///     |method: &Method, path: &str| {
762    ///         (method == Method::GET && path.starts_with("/api/surface/")).then_some(DeviceScope::Read)
763    ///     },
764    /// ));
765    /// assert_eq!(pairing.scope_for(&Method::GET, "/api/surface/status"), Some(DeviceScope::Read));
766    /// assert_eq!(pairing.scope_for(&Method::POST, "/api/kernel/freeze"), Some(DeviceScope::Stop));
767    /// ```
768    #[must_use]
769    pub fn with_device_routes(self, routes: DeviceRoutes) -> Self {
770        self.rebuild(|inner| inner.routes = Some(routes))
771    }
772
773    /// The scope a device needs for `method` on `path`: the kernel's routes, then the
774    /// server's ([`with_device_routes`](Self::with_device_routes)); `None` when closed.
775    pub fn scope_for(&self, method: &Method, path: &str) -> Option<DeviceScope> {
776        device_scope_for(method, path)
777            .or_else(|| self.inner.routes.as_ref().and_then(|routes| routes(method, path)))
778    }
779
780    /// Codes work for `ttl`.
781    #[must_use]
782    pub fn with_code_ttl(self, ttl: Duration) -> Self {
783        self.rebuild(|inner| inner.code_ttl = ttl)
784    }
785
786    /// Devices stay paired for `ttl` unless a code says otherwise; at most a year.
787    #[must_use]
788    pub fn with_device_ttl(self, ttl: Duration) -> Self {
789        self.rebuild(|inner| inner.device_ttl = ttl.min(MAX_DEVICE_TTL))
790    }
791
792    /// The web home's address, such as `https://kernel.tail1234.ts.net`, so an issued code
793    /// carries the URL a phone opens.
794    #[must_use]
795    pub fn with_home_url(self, url: impl Into<String>) -> Self {
796        let url = url.into().trim_end_matches('/').to_string();
797        self.rebuild(|inner| inner.home_url = Some(url))
798    }
799
800    /// Reads time from `clock`.
801    #[must_use]
802    pub fn with_clock(self, clock: Arc<dyn Clock>) -> Self {
803        self.rebuild(|inner| inner.clock = clock)
804    }
805
806    /// How often an open event stream re-reads its device, for a revocation made on another
807    /// replica; a revocation made here ends it at once. Defaults to five seconds.
808    #[must_use]
809    pub fn with_revocation_check(self, interval: Duration) -> Self {
810        self.rebuild(|inner| inner.recheck = interval.max(Duration::from_millis(10)))
811    }
812
813    /// Keeps chat accounts' pairings in `store` (spec 3.3 §10 K1), so the control plane
814    /// accepts, lists and revokes them beside devices.
815    #[cfg(feature = "channels")]
816    #[must_use]
817    pub fn with_channel_bindings(
818        self,
819        store: Arc<dyn crate::channels::ChannelBindingStore>,
820    ) -> Self {
821        self.rebuild(|inner| inner.channels = Some(store))
822    }
823
824    /// The chat accounts' pairing store, when one is set.
825    #[cfg(feature = "channels")]
826    pub fn channel_bindings(&self) -> Option<&Arc<dyn crate::channels::ChannelBindingStore>> {
827        self.inner.channels.as_ref()
828    }
829
830    /// The device store.
831    pub fn store(&self) -> &Arc<dyn DeviceStore> {
832        &self.inner.store
833    }
834
835    /// The web home's address, when set.
836    pub fn home_url(&self) -> Option<&str> {
837        self.inner.home_url.as_deref()
838    }
839
840    /// The time on the service's clock.
841    pub fn now(&self) -> DateTime<Utc> {
842        self.inner.clock.now()
843    }
844
845    /// Issues a code for `request`; the store keeps its hash.
846    ///
847    /// # Errors
848    ///
849    /// Returns [`KernelError::Config`] when the owner is empty, the device's pairing would
850    /// last no time or more than 365 days, or the random number generator fails, and the
851    /// store's error.
852    pub async fn issue(&self, request: IssueCode) -> Result<IssuedCode> {
853        let device_ttl = self.check(&request)?;
854        let request = request.normalized();
855        // The link opens the phone's pairing page; a terminal or a tray takes the code typed.
856        let phone = request.kind == Some(DeviceKind::Phone);
857        let now = self.now();
858        self.inner.store.prune_codes(now).await?;
859        let code = secret::new_code()?;
860        let expires_at = now + chrono::Duration::from_std(self.inner.code_ttl).unwrap_or_default();
861        let mut stored =
862            PairingCode::new(secret::code_hash(&code), request.owner, device_ttl, now, expires_at);
863        stored.groups = request.groups;
864        stored.scopes = request.scopes.clone();
865        stored.name = request.name;
866        stored.kind = request.kind;
867        self.inner.store.put_code(stored).await?;
868        // A new code starts the count of claims again, after a lockout too.
869        self.inner.store.reset_claim_attempts().await?;
870        let url = self
871            .inner
872            .home_url
873            .as_ref()
874            .filter(|_| phone)
875            .map(|home| format!("{home}/pair#code={code}"));
876        Ok(IssuedCode {
877            code,
878            expires_at,
879            scopes: request.scopes,
880            url,
881            device_ttl_secs: device_ttl.as_secs(),
882        })
883    }
884
885    /// Checks `request` as [`issue`](Self::issue) does, before anything is recorded of it,
886    /// and returns how long its device stays paired.
887    ///
888    /// # Errors
889    ///
890    /// Returns [`KernelError::Config`] when the owner is empty or the device's pairing would
891    /// last no time or more than 365 days.
892    pub(crate) fn check(&self, request: &IssueCode) -> Result<Duration> {
893        if request.owner.trim().is_empty() {
894            return Err(KernelError::Config {
895                reason: "a pairing code needs the person the device acts for".into(),
896            });
897        }
898        let device_ttl = request.device_ttl.unwrap_or(self.inner.device_ttl);
899        if device_ttl.is_zero() || device_ttl > MAX_DEVICE_TTL {
900            return Err(KernelError::Config {
901                reason: format!(
902                    "a device stays paired for at most 365 days and longer than none, not {} \
903                     days: pass `adk-rust pair --days` between 1 and 365",
904                    device_ttl.as_secs() / 86_400
905                ),
906            });
907        }
908        Ok(device_ttl)
909    }
910
911    /// Claims `code` for a device called `name` (the name the code was issued with wins) and
912    /// returns its token, once.
913    ///
914    /// Every claim is counted in the store before its code is looked up, on every replica
915    /// over the store: after twenty claims without a success every waiting code is
916    /// cancelled, and claims are refused until the next code is issued. A claim whose device
917    /// cannot be stored puts its code back.
918    ///
919    /// # Errors
920    ///
921    /// Returns [`KernelError::Unauthorized`] for a wrong, used or expired code, or once the
922    /// claims are locked out. Returns the store's error.
923    pub async fn claim(&self, code: &str, name: Option<&str>) -> Result<ClaimedDevice> {
924        let pending = self.take_for_claim(code, name).await?;
925        self.finish_claim(pending).await
926    }
927
928    /// Takes `code` for a claim and makes its device and token, storing neither.
929    pub(crate) async fn take_for_claim(
930        &self,
931        code: &str,
932        name: Option<&str>,
933    ) -> Result<PendingClaim> {
934        let wrong = || KernelError::Unauthorized {
935            reason: "the pairing code is wrong, used or expired: run `adk-rust pair` for a new \
936                     one"
937            .into(),
938        };
939        let store = &self.inner.store;
940        let attempts = store.count_claim_attempt().await?;
941        if attempts > MAX_FAILED_CLAIMS {
942            // The count stays over the limit until the next code is issued, so every claim
943            // in flight and every later one is refused, and a failed clear refuses too.
944            let cleared = store.clear_codes().await?;
945            if cleared > 0 {
946                tracing::warn!(
947                    pairing.cleared = cleared,
948                    "too many claims without a success; every waiting code was cancelled"
949                );
950            }
951            return Err(KernelError::Unauthorized {
952                reason: "too many pairing codes were wrong, so every waiting code was \
953                         cancelled: run `adk-rust pair` for a new one"
954                    .into(),
955            });
956        }
957        let now = self.now();
958        let taken = store.take_code(&secret::code_hash(code)).await?;
959        let Some(code) = taken.filter(|code| now < code.expires_at) else {
960            return Err(wrong());
961        };
962        if let Err(error) = store.reset_claim_attempts().await {
963            tracing::warn!(error = %error, "the count of pairing claims could not be reset");
964        }
965        let id = secret::new_device_id()?;
966        let (token, token_hash) = secret::new_token(&id)?;
967        let name = code
968            .name
969            .clone()
970            .or_else(|| name.map(|name| secret::clean_name(name, MAX_NAME_CHARS)))
971            .filter(|name| !name.is_empty())
972            .unwrap_or_else(|| "Device".to_string());
973        let ttl = Duration::from_secs(code.device_ttl_secs).min(MAX_DEVICE_TTL);
974        let device = DeviceRecord::new(
975            id,
976            name,
977            code.owner.clone(),
978            token_hash,
979            now,
980            now + chrono::Duration::from_std(ttl).unwrap_or_default(),
981        )
982        .with_scopes(code.scopes.clone())
983        .with_groups(code.groups.clone());
984        // The issuer's kind; nothing the claim sends sets it.
985        let device = DeviceRecord { kind: code.kind, ..device };
986        Ok(PendingClaim { code, device, token })
987    }
988
989    /// Stores a taken claim's device and returns its token; puts the code back when the
990    /// device cannot be stored.
991    pub(crate) async fn finish_claim(&self, pending: PendingClaim) -> Result<ClaimedDevice> {
992        if let Err(error) = self.inner.store.put_device(pending.device.clone()).await {
993            self.abandon_claim(pending).await;
994            return Err(error);
995        }
996        Ok(ClaimedDevice { device: pending.device.view(self.now()), token: pending.token })
997    }
998
999    /// Puts a taken claim's code back, so it can be claimed again.
1000    pub(crate) async fn abandon_claim(&self, pending: PendingClaim) {
1001        if let Err(error) = self.inner.store.put_code(pending.code).await {
1002            tracing::error!(error = %error, "a pairing code could not be put back");
1003        }
1004    }
1005
1006    /// Resolves when device `id` stops working: when it is revoked here, at once; when a
1007    /// re-read finds it revoked on another replica or gone, each open stream re-reading the
1008    /// store every five seconds by default; or when its pairing ends. A server ends a
1009    /// device's open streams with it (spec 3.3 §10 K2, S-I7).
1010    ///
1011    /// # Example
1012    ///
1013    /// ```rust
1014    /// use std::sync::Arc;
1015    /// use adk_kernel::pairing::{InMemoryDeviceStore, IssueCode, Pairing};
1016    ///
1017    /// # #[tokio::main(flavor = "current_thread")]
1018    /// # async fn main() -> adk_kernel::Result<()> {
1019    /// let pairing = Pairing::new(Arc::new(InMemoryDeviceStore::new()));
1020    /// let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await?;
1021    /// let device = pairing.claim(&issued.code, None).await?.device;
1022    /// let ends = pairing.until_device_ends(device.id.clone());
1023    /// pairing.revoke(&device.id).await?;
1024    /// ends.await;
1025    /// # Ok(())
1026    /// # }
1027    /// ```
1028    pub fn until_device_ends(&self, id: String) -> impl Future<Output = ()> + Send + 'static {
1029        let pairing = self.clone();
1030        let mut revoked = self.inner.revoked.subscribe();
1031        async move {
1032            loop {
1033                let wait = match pairing.inner.store.get_device(&id).await {
1034                    Ok(Some(device)) if device.is_active(pairing.now()) => {
1035                        let left = (device.expires_at - pairing.now()).to_std().unwrap_or_default();
1036                        left.min(pairing.inner.recheck)
1037                    }
1038                    Ok(_) => return,
1039                    Err(error) => {
1040                        tracing::warn!(device.id = %id, error = %error, "a device could not be re-read");
1041                        pairing.inner.recheck
1042                    }
1043                };
1044                tokio::select! {
1045                    () = tokio::time::sleep(wait) => {}
1046                    message = revoked.recv() => match message {
1047                        Ok(gone) if gone == id => return,
1048                        Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
1049                        Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
1050                    },
1051                }
1052            }
1053        }
1054    }
1055
1056    /// The device `token` belongs to, when the token works.
1057    ///
1058    /// # Errors
1059    ///
1060    /// Returns [`KernelError::Unauthorized`] for an unknown, revoked or expired token, and
1061    /// the store's error.
1062    pub async fn authenticate(&self, token: &str) -> Result<DeviceRecord> {
1063        let unknown = || KernelError::Unauthorized {
1064            reason: "the device token is not one this kernel issued: pair the device again \
1065                     with `adk-rust pair`"
1066                .into(),
1067        };
1068        let (id, secret_text) = secret::parse_token(token).ok_or_else(unknown)?;
1069        let device = self.inner.store.get_device(id).await?.ok_or_else(unknown)?;
1070        if !secret::constant_time_eq(
1071            secret::digest(secret_text).as_bytes(),
1072            device.token_hash.as_bytes(),
1073        ) {
1074            return Err(unknown());
1075        }
1076        if let Some(at) = device.revoked_at {
1077            return Err(KernelError::Unauthorized {
1078                reason: format!(
1079                    "{} was removed on {}: pair it again with `adk-rust pair`",
1080                    device.name,
1081                    at.format("%Y-%m-%d")
1082                ),
1083            });
1084        }
1085        if self.now() >= device.expires_at {
1086            return Err(KernelError::Unauthorized {
1087                reason: format!(
1088                    "{}'s pairing ended on {}: pair it again with `adk-rust pair`",
1089                    device.name,
1090                    device.expires_at.format("%Y-%m-%d")
1091                ),
1092            });
1093        }
1094        Ok(device)
1095    }
1096
1097    /// The request context a device token's request runs as, when `method` and `path`
1098    /// (with or without the `/api` prefix) are a route the device's scopes open: the
1099    /// device's owner with the owner's approval groups, and the device named in
1100    /// [`DEVICE_ID_METADATA`] and [`DEVICE_NAME_METADATA`].
1101    ///
1102    /// It checks the device's scopes only: a decision's risk, which a device may answer at
1103    /// low and medium only (spec 3.3 §7.2), is checked by the device guard of the control
1104    /// plane ([`guard_devices`](crate::control::guard_devices)), which also records it.
1105    ///
1106    /// # Errors
1107    ///
1108    /// [`authenticate`](Self::authenticate)'s errors, and a `Forbidden` error coded
1109    /// `kernel.unauthorized` when the route is closed to devices or needs a scope the device
1110    /// lacks.
1111    pub async fn authorize(
1112        &self,
1113        token: &str,
1114        method: &Method,
1115        path: &str,
1116    ) -> Result<RequestContext> {
1117        let device = self.authenticate(token).await?;
1118        match self.scope_for(method, path) {
1119            Some(scope) if device.has_scope(scope) => Ok(device_context(&device)),
1120            Some(scope) => Err(forbidden(format!(
1121                "{} was paired without the `{scope}` scope, which {method} {path} needs; pair it \
1122                 again with `adk-rust pair --scope {scope}`",
1123                device.name
1124            ))),
1125            None => Err(forbidden(format!(
1126                "a paired device may not call {method} {path}: devices read, answer decisions \
1127                 and stop everything; anything else happens in the home or on the kernel's own \
1128                 terminal"
1129            ))),
1130        }
1131    }
1132
1133    /// Every paired device, oldest first.
1134    ///
1135    /// # Errors
1136    ///
1137    /// Returns the store's error.
1138    pub async fn devices(&self) -> Result<Vec<DeviceRecord>> {
1139        self.inner.store.list_devices().await
1140    }
1141
1142    /// Removes device `id`: its token stops working at once, its attachments are removed, and
1143    /// an event stream it holds open ends, at once on this kernel and at its next re-read on
1144    /// another replica (five seconds by default). Revoking a revoked device changes nothing
1145    /// but removes what is still attached.
1146    ///
1147    /// # Errors
1148    ///
1149    /// Returns [`KernelError::Core`] coded `kernel.not_found` for an unknown device, and the
1150    /// store's error.
1151    pub async fn revoke(&self, id: &str) -> Result<DeviceRecord> {
1152        let Some(mut device) = self.inner.store.get_device(id).await? else {
1153            return Err(KernelError::Core(AdkError::new(
1154                ErrorComponent::Server,
1155                ErrorCategory::NotFound,
1156                crate::error::NOT_FOUND_CODE,
1157                format!("no paired device {id}: list them with `adk-rust pair list`"),
1158            )));
1159        };
1160        if device.revoked_at.is_none() {
1161            device.revoked_at = Some(self.now());
1162            self.inner.store.put_device(device.clone()).await?;
1163        }
1164        // Its push subscription and passkey go with it; a store that keeps none has none.
1165        match self
1166            .inner
1167            .store
1168            .remove_attachments(&AttachmentHolder::Device(device.id.clone()))
1169            .await
1170        {
1171            Ok(_) => {}
1172            Err(KernelError::Core(error)) if error.category == ErrorCategory::Unsupported => {}
1173            Err(error) => return Err(error),
1174        }
1175        // Event streams the device holds open here end now; elsewhere, at their next re-read.
1176        let _ = self.inner.revoked.send(device.id.clone());
1177        Ok(device)
1178    }
1179}
1180
1181/// A `Forbidden` kernel error coded `kernel.unauthorized`, answered `403`.
1182pub(crate) fn forbidden(message: String) -> KernelError {
1183    KernelError::Core(AdkError::new(
1184        ErrorComponent::Server,
1185        ErrorCategory::Forbidden,
1186        UNAUTHORIZED_CODE,
1187        message,
1188    ))
1189}
1190
1191/// The request context of `device`'s requests.
1192fn device_context(device: &DeviceRecord) -> RequestContext {
1193    let scopes = device.scopes.iter().map(|scope| scope.as_str()).collect::<Vec<_>>().join(",");
1194    RequestContext {
1195        user_id: device.owner.clone(),
1196        scopes: device.groups.clone(),
1197        metadata: HashMap::from([
1198            (DEVICE_ID_METADATA.to_string(), device.id.clone()),
1199            (DEVICE_NAME_METADATA.to_string(), device.name.clone()),
1200            (DEVICE_SCOPES_METADATA.to_string(), scopes),
1201            (DEVICE_KIND_METADATA.to_string(), device.kind().as_str().to_string()),
1202        ]),
1203    }
1204}
1205
1206/// The scope a device needs for `method` on `path`, or `None` when the route is closed to
1207/// devices (spec 3.3 §7.2, §10 K2, S-I10). `path` may carry the `/api` prefix and a query.
1208///
1209/// # Example
1210///
1211/// ```rust
1212/// use axum::http::Method;
1213/// use adk_kernel::pairing::{DeviceScope, device_scope_for};
1214///
1215/// assert_eq!(device_scope_for(&Method::POST, "/api/approvals/a1/decide"), Some(DeviceScope::Decide));
1216/// assert_eq!(device_scope_for(&Method::GET, "/kernel/processes?limit=5"), Some(DeviceScope::Read));
1217/// assert_eq!(device_scope_for(&Method::POST, "/api/kernel/freeze"), Some(DeviceScope::Stop));
1218/// assert_eq!(device_scope_for(&Method::POST, "/api/kernel/unfreeze"), None);
1219/// assert_eq!(device_scope_for(&Method::POST, "/api/kernel/pairing"), None);
1220/// ```
1221pub fn device_scope_for(method: &Method, path: &str) -> Option<DeviceScope> {
1222    let path = path.split(['?', '#']).next().unwrap_or_default();
1223    let path = path.strip_prefix(crate::control::paths::API_PREFIX).unwrap_or(path);
1224    let segments: Vec<&str> = path.split('/').filter(|segment| !segment.is_empty()).collect();
1225    match (method.as_str(), segments.as_slice()) {
1226        ("GET", ["kernel", "health" | "processes" | "events" | "agenda"])
1227        | ("POST", ["kernel", "attach", _])
1228        // What Today and "Agent Memory and Rules" read, and the device's own place in
1229        // "While you were away" (spec 3.3 §10 K3–K5); changing a setting or a memory stays
1230        // closed to devices.
1231        | (
1232            "GET",
1233            ["kernel", "settings" | "away" | "memory" | "record" | "agents"]
1234            | ["kernel", "settings" | "agents", _]
1235            | ["kernel", "away", "lines", _]
1236            | ["kernel", "record", "check"],
1237        )
1238        | ("POST", ["kernel", "away", "seen"])
1239        | ("GET", ["approvals"] | ["approvals", _]) => Some(DeviceScope::Read),
1240        ("POST", ["approvals", id, "decide"]) if *id != "delegations" => Some(DeviceScope::Decide),
1241        ("POST", ["kernel", "freeze"]) => Some(DeviceScope::Stop),
1242        _ => None,
1243    }
1244}
1245
1246/// The tool of a take-over, as `adk-harness` asks for one (spec 3.3 §10 H2): a secret the
1247/// person types in the home or on the phone, never a yes.
1248pub(crate) const TAKE_OVER_TOOL: &str = "harness:take-over";
1249
1250/// The device token of a request, when its `Authorization` header carries one.
1251pub(crate) fn device_token(headers: &axum::http::HeaderMap) -> Option<&str> {
1252    let value = headers.get(axum::http::header::AUTHORIZATION)?.to_str().ok()?;
1253    let token = value.strip_prefix("Bearer ").or_else(|| value.strip_prefix("bearer "))?.trim();
1254    token.starts_with(secret::TOKEN_PREFIX).then_some(token)
1255}
1256
1257/// Admits device tokens as their devices (spec 3.3 §10 K2), each only to the routes its
1258/// scopes open, and every other request through `fallback`.
1259///
1260/// Mount it as the `RequestContextExtractor` of a `ServerBuilder` that serves the kernel's
1261/// routes, wrapping the extractor it had, so a device token is never mistaken for another
1262/// credential and never widened: a request that carries one is the device, on loopback too.
1263/// Layer [`guard_devices`](crate::control::guard_devices) on the built app as well: it
1264/// checks a device's decision for its risk (low and medium only, spec 3.3 §7.2) and records
1265/// it, and the extractor refuses every device decision the guard did not admit. A refused
1266/// device request answers `401` through `ServerBuilder`, whose extractor errors carry no
1267/// `403`; the guard answers `403` first.
1268///
1269/// # Example
1270///
1271/// ```rust
1272/// use std::sync::Arc;
1273/// use adk_kernel::pairing::{DeviceTokenExtractor, InMemoryDeviceStore, Pairing};
1274///
1275/// let pairing = Pairing::new(Arc::new(InMemoryDeviceStore::new()));
1276/// let extractor = DeviceTokenExtractor::new(pairing);
1277/// # let _ = extractor;
1278/// ```
1279#[derive(Clone)]
1280pub struct DeviceTokenExtractor {
1281    pairing: Pairing,
1282    fallback: Option<Arc<dyn RequestContextExtractor>>,
1283}
1284
1285impl fmt::Debug for DeviceTokenExtractor {
1286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1287        f.debug_struct("DeviceTokenExtractor")
1288            .field("pairing", &self.pairing)
1289            .field("fallback", &self.fallback.is_some())
1290            .finish()
1291    }
1292}
1293
1294impl DeviceTokenExtractor {
1295    /// Admits device tokens of `pairing` and nothing else.
1296    pub fn new(pairing: Pairing) -> Self {
1297        Self { pairing, fallback: None }
1298    }
1299
1300    /// Hands every request without a device token to `fallback`.
1301    #[must_use]
1302    pub fn with_fallback(mut self, fallback: Arc<dyn RequestContextExtractor>) -> Self {
1303        self.fallback = Some(fallback);
1304        self
1305    }
1306}
1307
1308#[async_trait]
1309impl RequestContextExtractor for DeviceTokenExtractor {
1310    async fn extract(
1311        &self,
1312        parts: &Parts,
1313    ) -> std::result::Result<RequestContext, RequestContextError> {
1314        let Some(token) = device_token(&parts.headers) else {
1315            return match &self.fallback {
1316                Some(fallback) => fallback.extract(parts).await,
1317                None => Err(RequestContextError::MissingAuth),
1318            };
1319        };
1320        let path =
1321            parts.uri.path_and_query().map_or_else(|| parts.uri.path(), |path| path.as_str());
1322        match self.pairing.authorize(token, &parts.method, path).await {
1323            // A device's decision is admitted only behind the guard, which checks its risk
1324            // and records it (spec 3.3 §7.2, §11).
1325            Ok(context)
1326                if self.pairing.scope_for(&parts.method, path) == Some(DeviceScope::Decide)
1327                    && parts.extensions.get::<DeviceAdmission>().map(|admitted| &admitted.device)
1328                        != context.metadata.get(DEVICE_ID_METADATA) =>
1329            {
1330                Err(RequestContextError::InvalidToken(
1331                    "a device's decision is admitted only behind adk_kernel::control::guard_devices, \
1332                     which checks its risk and records it; layer it on the app"
1333                        .into(),
1334                ))
1335            }
1336            Ok(context) => Ok(context),
1337            Err(error @ (KernelError::Store { .. } | KernelError::Io(_))) => {
1338                Err(RequestContextError::ExtractionFailed(error.to_string()))
1339            }
1340            Err(error) => Err(RequestContextError::InvalidToken(error.to_string())),
1341        }
1342    }
1343}
1344
1345#[cfg(test)]
1346mod tests {
1347    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
1348
1349    use super::*;
1350
1351    fn pairing() -> Pairing {
1352        Pairing::new(Arc::new(InMemoryDeviceStore::new()))
1353    }
1354
1355    /// An in-memory store that counts code lookups, can make them slow, and can fail a
1356    /// device write or a clear.
1357    #[derive(Default)]
1358    struct Faulty {
1359        inner: InMemoryDeviceStore,
1360        lookups: AtomicUsize,
1361        slow: AtomicBool,
1362        fail_put_device: AtomicBool,
1363        fail_clear: AtomicBool,
1364    }
1365
1366    fn down() -> KernelError {
1367        KernelError::Store { backend: "test", reason: "down".into() }
1368    }
1369
1370    #[async_trait]
1371    impl DeviceStore for Faulty {
1372        async fn put_code(&self, code: PairingCode) -> Result<()> {
1373            self.inner.put_code(code).await
1374        }
1375        async fn take_code(&self, code_hash: &str) -> Result<Option<PairingCode>> {
1376            self.lookups.fetch_add(1, Ordering::SeqCst);
1377            if self.slow.load(Ordering::SeqCst) {
1378                tokio::time::sleep(Duration::from_millis(20)).await;
1379            }
1380            self.inner.take_code(code_hash).await
1381        }
1382        async fn prune_codes(&self, before: DateTime<Utc>) -> Result<usize> {
1383            self.inner.prune_codes(before).await
1384        }
1385        async fn clear_codes(&self) -> Result<usize> {
1386            if self.fail_clear.load(Ordering::SeqCst) {
1387                return Err(down());
1388            }
1389            self.inner.clear_codes().await
1390        }
1391        async fn put_device(&self, device: DeviceRecord) -> Result<()> {
1392            if self.fail_put_device.swap(false, Ordering::SeqCst) {
1393                return Err(down());
1394            }
1395            self.inner.put_device(device).await
1396        }
1397        async fn get_device(&self, id: &str) -> Result<Option<DeviceRecord>> {
1398            self.inner.get_device(id).await
1399        }
1400        async fn list_devices(&self) -> Result<Vec<DeviceRecord>> {
1401            self.inner.list_devices().await
1402        }
1403        async fn count_claim_attempt(&self) -> Result<u64> {
1404            self.inner.count_claim_attempt().await
1405        }
1406        async fn reset_claim_attempts(&self) -> Result<()> {
1407            self.inner.reset_claim_attempts().await
1408        }
1409    }
1410
1411    /// The pairing link opens the phone's pairing page, so only a phone's code carries it: a
1412    /// terminal or a tray takes its code typed (spec 3.3 §5.4, §10 K2).
1413    #[tokio::test]
1414    async fn only_a_phone_s_code_carries_the_pairing_link() {
1415        let pairing = pairing().with_home_url("https://home.example/ui/");
1416        let phone = pairing
1417            .issue(IssueCode::new("ana", ["operator"]).with_kind(DeviceKind::Phone))
1418            .await
1419            .unwrap();
1420        assert_eq!(phone.url, Some(format!("https://home.example/ui/pair#code={}", phone.code)));
1421        for kind in [None, Some(DeviceKind::Terminal), Some(DeviceKind::Tray)] {
1422            let request = IssueCode::new("ana", ["operator"]);
1423            let request = match kind {
1424                Some(kind) => request.with_kind(kind),
1425                None => request,
1426            };
1427            assert_eq!(pairing.issue(request).await.unwrap().url, None, "{kind:?}");
1428        }
1429    }
1430
1431    /// Concurrent wrong claims are counted before they are checked, so no
1432    /// more than twenty reach the codes.
1433    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1434    async fn concurrent_wrong_claims_are_counted_before_they_are_checked() {
1435        let store = Arc::new(Faulty::default());
1436        store.slow.store(true, Ordering::SeqCst);
1437        let pairing = Pairing::new(store.clone());
1438        pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1439        let mut claims = Vec::new();
1440        for guess in 0..100 {
1441            let pairing = pairing.clone();
1442            claims.push(tokio::spawn(async move {
1443                pairing.claim(&format!("0000-0000-{guess:04}"), None).await.is_err()
1444            }));
1445        }
1446        for claim in claims {
1447            assert!(claim.await.unwrap());
1448        }
1449        let lookups = store.lookups.load(Ordering::SeqCst);
1450        assert!(lookups <= MAX_FAILED_CLAIMS as usize, "{lookups} guesses reached the codes");
1451    }
1452
1453    /// Replicas over one store share the count of wrong codes.
1454    #[tokio::test]
1455    async fn replicas_share_the_count_of_wrong_codes() {
1456        let store: Arc<dyn DeviceStore> = Arc::new(InMemoryDeviceStore::new());
1457        let (first, second) = (Pairing::new(store.clone()), Pairing::new(store));
1458        let issued = first.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1459        for _ in 0..MAX_FAILED_CLAIMS / 2 {
1460            assert!(first.claim("0000-0000", None).await.is_err());
1461            assert!(second.claim("0000-0000", None).await.is_err());
1462        }
1463        assert!(second.claim(&issued.code, None).await.is_err(), "the shared lockout fired");
1464    }
1465
1466    /// A lockout whose clear fails keeps refusing claims.
1467    #[tokio::test]
1468    async fn a_lockout_whose_clear_fails_keeps_refusing() {
1469        let store = Arc::new(Faulty::default());
1470        store.fail_clear.store(true, Ordering::SeqCst);
1471        let pairing = Pairing::new(store.clone());
1472        let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1473        for _ in 0..=MAX_FAILED_CLAIMS {
1474            assert!(pairing.claim("0000-0000", None).await.is_err());
1475        }
1476        assert!(pairing.claim(&issued.code, None).await.is_err(), "still locked out");
1477    }
1478
1479    /// A claim whose device cannot be stored keeps its code.
1480    #[tokio::test]
1481    async fn a_claim_whose_device_cannot_be_stored_keeps_its_code() {
1482        let store = Arc::new(Faulty::default());
1483        let pairing = Pairing::new(store.clone());
1484        let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1485        store.fail_put_device.store(true, Ordering::SeqCst);
1486        assert!(matches!(pairing.claim(&issued.code, None).await, Err(KernelError::Store { .. })));
1487        assert!(pairing.claim(&issued.code, None).await.is_ok(), "the retry pairs");
1488    }
1489
1490    /// A lockout holds until the next code is issued, which pairs.
1491    #[tokio::test]
1492    async fn a_lockout_holds_until_the_next_code() {
1493        let pairing = pairing();
1494        let first = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1495        for _ in 0..MAX_FAILED_CLAIMS {
1496            assert!(pairing.claim("0000-0000-0000", None).await.is_err());
1497        }
1498        let error = pairing.claim(&first.code, None).await.unwrap_err();
1499        assert!(error.to_string().contains("too many"), "{error}");
1500        let second = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1501        assert!(pairing.claim(&first.code, None).await.is_err(), "the first code was cancelled");
1502        assert!(pairing.claim(&second.code, None).await.is_ok(), "a new code pairs");
1503    }
1504
1505    /// The extractor alone never admits a device's decision, which only
1506    /// the guard in front of the app checks for risk and records.
1507    #[tokio::test]
1508    async fn the_extractor_alone_refuses_a_device_decision() {
1509        let pairing = pairing();
1510        let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1511        let token = pairing.claim(&issued.code, None).await.unwrap().token;
1512        let extractor = DeviceTokenExtractor::new(pairing);
1513        let request = axum::http::Request::builder()
1514            .method(Method::POST)
1515            .uri("/api/approvals/a1/decide")
1516            .header("authorization", format!("Bearer {token}"))
1517            .body(())
1518            .unwrap();
1519        let (parts, ()) = request.into_parts();
1520        assert!(extractor.extract(&parts).await.is_err(), "decide needs the guard");
1521        let request = axum::http::Request::builder()
1522            .uri("/api/approvals")
1523            .header("authorization", format!("Bearer {token}"))
1524            .body(())
1525            .unwrap();
1526        let (parts, ()) = request.into_parts();
1527        assert!(extractor.extract(&parts).await.is_ok(), "read needs no guard");
1528    }
1529
1530    #[tokio::test]
1531    async fn a_code_pairs_one_device_with_its_scopes() {
1532        let pairing = pairing();
1533        let issued = pairing
1534            .issue(IssueCode::new("ana", ["operator"]).with_scopes([DeviceScope::Read]))
1535            .await
1536            .unwrap();
1537        assert_eq!(issued.scopes, [DeviceScope::Read]);
1538        assert_eq!(issued.url, None);
1539        let claimed = pairing.claim(&issued.code.to_lowercase(), Some("Pixel")).await.unwrap();
1540        assert_eq!(claimed.device.name, "Pixel");
1541        assert_eq!(claimed.device.scopes, [DeviceScope::Read]);
1542        let device = pairing.authenticate(&claimed.token).await.unwrap();
1543        assert_eq!(
1544            (device.owner.as_str(), device.groups.as_slice()),
1545            ("ana", &["operator".to_string()][..])
1546        );
1547        assert!(pairing.claim(&issued.code, None).await.is_err());
1548    }
1549
1550    #[tokio::test]
1551    async fn the_store_never_holds_the_code_or_the_token() {
1552        let store = Arc::new(InMemoryDeviceStore::new());
1553        let pairing = Pairing::new(store.clone());
1554        let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1555        let claimed = pairing.claim(&issued.code, None).await.unwrap();
1556        let stored = serde_json::to_string(&store.list_devices().await.unwrap()).unwrap();
1557        let (_, secret) = secret::parse_token(&claimed.token).unwrap();
1558        assert!(!stored.contains(secret));
1559        assert!(!stored.contains(&issued.code));
1560    }
1561
1562    #[tokio::test]
1563    async fn revoked_and_expired_tokens_are_refused() {
1564        let clock = adk_core::ManualClock::new(Utc::now());
1565        let pairing =
1566            pairing().with_device_ttl(Duration::from_secs(60)).with_clock(Arc::new(clock.clone()));
1567        let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1568        let claimed = pairing.claim(&issued.code, None).await.unwrap();
1569        pairing.revoke(&claimed.device.id).await.unwrap();
1570        let error = pairing.authenticate(&claimed.token).await.unwrap_err();
1571        assert!(error.to_string().contains("was removed"), "{error}");
1572
1573        let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1574        let claimed = pairing.claim(&issued.code, None).await.unwrap();
1575        clock.advance(Duration::from_secs(61));
1576        let error = pairing.authenticate(&claimed.token).await.unwrap_err();
1577        assert!(error.to_string().contains("pairing ended"), "{error}");
1578        let refused = pairing
1579            .issue(IssueCode::new("ana", ["operator"]).with_device_ttl(Duration::ZERO))
1580            .await
1581            .unwrap_err();
1582        assert!(matches!(refused, KernelError::Config { .. }), "a zero-length pairing is refused");
1583    }
1584
1585    #[tokio::test]
1586    async fn a_wrong_secret_is_refused() {
1587        let pairing = pairing();
1588        let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1589        let claimed = pairing.claim(&issued.code, None).await.unwrap();
1590        let last = if claimed.token.ends_with('0') { '1' } else { '0' };
1591        let forged = format!("{}{last}", &claimed.token[..claimed.token.len() - 1]);
1592        assert!(matches!(
1593            pairing.authenticate(&forged).await,
1594            Err(KernelError::Unauthorized { .. })
1595        ));
1596    }
1597
1598    #[tokio::test]
1599    async fn twenty_wrong_codes_cancel_every_waiting_code() {
1600        let pairing = pairing();
1601        let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1602        for _ in 0..MAX_FAILED_CLAIMS {
1603            assert!(pairing.claim("0000-0000", None).await.is_err());
1604        }
1605        assert!(pairing.claim(&issued.code, None).await.is_err(), "the lockout cancelled it");
1606    }
1607
1608    #[tokio::test]
1609    async fn authorize_opens_only_the_scoped_routes() {
1610        let pairing = pairing();
1611        let issued = pairing
1612            .issue(IssueCode::new("ana", ["operator"]).with_scopes([DeviceScope::Read]))
1613            .await
1614            .unwrap();
1615        let token = pairing.claim(&issued.code, None).await.unwrap().token;
1616        let context = pairing.authorize(&token, &Method::GET, "/api/approvals").await.unwrap();
1617        assert_eq!(context.user_id, "ana");
1618        assert_eq!(context.scopes, ["operator"]);
1619        let error =
1620            pairing.authorize(&token, &Method::POST, "/api/approvals/x/decide").await.unwrap_err();
1621        assert_eq!(AdkError::from(error).category, ErrorCategory::Forbidden);
1622        let error =
1623            pairing.authorize(&token, &Method::POST, "/api/kernel/unfreeze").await.unwrap_err();
1624        assert_eq!(AdkError::from(error).category, ErrorCategory::Forbidden);
1625    }
1626}