Skip to main content

adk_kernel/control/
pairing.rs

1//! The pairing routes of the control plane (spec 3.3 §10 K1, K2, §11 S-I6, S-I7): issue and
2//! claim device codes, list and revoke devices, accept, list and revoke chat accounts, and
3//! the admission of device tokens.
4//!
5//! | Route (under `/api`) | Caller | Effect |
6//! |---|---|---|
7//! | `POST /kernel/pairing` | operator | Issues a pairing code ([`IssueRequest`] → [`IssuedCode`]) |
8//! | `POST /kernel/pairing/claim` | anyone holding a code | Claims it ([`ClaimRequest`] → [`ClaimedDevice`], the token shown once) |
9//! | `GET /kernel/devices` | operator | Every paired device ([`DevicesResponse`]) |
10//! | `POST /kernel/devices/{id}/revoke` | operator | Removes a device ([`DeviceResponse`]) |
11//! | `POST /kernel/channels/pair` (feature `channels`) | operator | Accepts the code a chat account was sent ([`AcceptChannelRequest`] → [`ChannelAccountResponse`]) |
12//! | `GET /kernel/channels` (feature `channels`) | operator | Paired chat accounts and the ones waiting ([`ChannelAccountsResponse`]) |
13//! | `POST /kernel/channels/{id}/revoke` (feature `channels`) | operator | Removes a chat account and stops its turns that have not finished ([`ChannelAccountResponse`]) |
14//! | `POST /kernel/channels/waiting/{id}/dismiss` (feature `channels`) | operator | Dismisses a chat account waiting to be paired: its code stops working and it gets no new one for a day ([`ChannelPairingResponse`]) |
15//!
16//! The operator routes are mounted on every kernel: one that pairs no devices, or has no
17//! chat channels, answers `400` naming what it lacks, and lists no chat accounts.
18//!
19//! Each route that changes something writes a `kernel.control` record before it takes
20//! effect: `pairing.issue`, `pairing.claim` (the device's owner as the subject, since the
21//! caller has no credentials but the code), `devices.revoke`, `channels.pair`,
22//! `channels.revoke` and `channels.dismiss`. A claim or an acceptance takes its code first
23//! and puts it back when the record cannot be written, so nothing is paired unrecorded and
24//! the code still works. A device's own actions carry `device` in their record, and a
25//! decision a device answers is recorded as `approvals.decide`, with the device's name and
26//! its answer, before it reaches the inbox.
27
28use std::sync::Arc;
29
30use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind};
31use adk_core::principal::SubjectRef;
32use adk_core::{ApprovalRequest, ApprovalRisk, RequestContext};
33use axum::body::Body;
34use axum::extract::{Path as UrlPath, State};
35use axum::http::{Method, Request};
36use axum::middleware::{self, Next};
37use axum::response::{IntoResponse, Response};
38use axum::routing::{get, post};
39use axum::{Json, Router};
40use chrono::{DateTime, Utc};
41use serde::{Deserialize, Serialize};
42use serde_json::json;
43
44use super::routes::{Caller, ControlBackend, record};
45use super::{ControlTransport, paths};
46use crate::audit;
47use crate::error::{KernelError, Result};
48use crate::pairing::{
49    ClaimedDevice, DEVICE_ID_METADATA, DEVICE_NAME_METADATA, DeviceAdmission, DeviceKind,
50    DeviceScope, DeviceView, IssueCode, IssuedCode, Pairing, device_scope_for, device_token,
51};
52
53/// `POST /kernel/pairing` body: `adk-rust pair [--name] [--scope] [--days] [--kind]` (spec
54/// 3.3 §10 K2).
55///
56/// # Example
57///
58/// ```rust
59/// use adk_kernel::control::api::IssueRequest;
60/// use adk_kernel::pairing::{DeviceKind, DeviceScope};
61///
62/// let body = IssueRequest {
63///     name: Some("Ana's phone".into()),
64///     scopes: vec![DeviceScope::Decide],
65///     expires_in_days: Some(30),
66///     kind: Some(DeviceKind::Phone),
67/// };
68/// assert_eq!(serde_json::to_value(&body).unwrap()["kind"], "phone");
69/// ```
70#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "camelCase")]
72pub struct IssueRequest {
73    /// What the person calls the device.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub name: Option<String>,
76    /// The scopes; every scope when empty.
77    #[serde(default, skip_serializing_if = "Vec::is_empty")]
78    pub scopes: Vec<DeviceScope>,
79    /// How many days the device stays paired; the kernel's default (90) when absent, at most
80    /// 365.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub expires_in_days: Option<u32>,
83    /// What the device is (spec 3.3 §7.2): a phone, a remote terminal or a tray; a terminal
84    /// when absent. The claim never changes it.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub kind: Option<DeviceKind>,
87}
88
89/// `POST /kernel/pairing/claim` body (spec 3.3 §10 K2).
90#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "camelCase")]
92pub struct ClaimRequest {
93    /// The code, as shown or typed.
94    pub code: String,
95    /// What the device calls itself, used when the code was issued without a name.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub name: Option<String>,
98}
99
100/// `GET /kernel/devices` answer (spec 3.3 §10 K2).
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(rename_all = "camelCase")]
103pub struct DevicesResponse {
104    /// Every paired device, oldest first, revoked and expired ones included.
105    pub devices: Vec<DeviceView>,
106}
107
108/// The answer of a device action: the device after it.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub struct DeviceResponse {
112    /// The device.
113    pub device: DeviceView,
114}
115
116/// `POST /kernel/channels/pair` body (spec 3.3 §10 K1): the code a chat account was sent.
117#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
118#[serde(rename_all = "camelCase")]
119pub struct AcceptChannelRequest {
120    /// The code, as the chat account received it.
121    pub code: String,
122}
123
124/// Whether a chat account reaches the agents (spec 3.3 §10 K1).
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
126#[serde(rename_all = "camelCase")]
127#[non_exhaustive]
128pub enum ChannelAccountState {
129    /// Its messages start turns and its answers decide.
130    Active,
131    /// It was removed.
132    Revoked,
133}
134
135/// A paired chat account as the control plane lists it (spec 3.3 §10 K1).
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "camelCase")]
138#[non_exhaustive]
139pub struct ChannelAccountView {
140    /// The pairing's id.
141    pub id: String,
142    /// The channel, such as `telegram`.
143    pub channel: String,
144    /// The account on that channel.
145    pub account: String,
146    /// The account's display name, as the platform gave it.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub display_name: Option<String>,
149    /// The person it acts for.
150    pub user_id: String,
151    /// When it was paired.
152    pub paired_at: DateTime<Utc>,
153    /// When it was removed.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub revoked_at: Option<DateTime<Utc>>,
156    /// Whether it reaches the agents now.
157    pub state: ChannelAccountState,
158}
159
160/// A chat account that asked to pair and has not been accepted (spec 3.3 §10 K1).
161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
162#[serde(rename_all = "camelCase")]
163#[non_exhaustive]
164pub struct ChannelPairingView {
165    /// The id the account gets once paired, which dismisses it while it waits.
166    pub id: String,
167    /// The channel.
168    pub channel: String,
169    /// The account.
170    pub account: String,
171    /// The account's display name.
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub display_name: Option<String>,
174    /// When it asked.
175    pub requested_at: DateTime<Utc>,
176    /// When its code stops working.
177    pub expires_at: DateTime<Utc>,
178}
179
180/// `GET /kernel/channels` answer (spec 3.3 §10 K1).
181#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
182#[serde(rename_all = "camelCase")]
183pub struct ChannelAccountsResponse {
184    /// Every paired chat account, oldest first, removed ones included.
185    pub accounts: Vec<ChannelAccountView>,
186    /// The accounts waiting for their code to be accepted.
187    pub waiting: Vec<ChannelPairingView>,
188}
189
190/// The answer of `POST /kernel/channels/waiting/{id}/dismiss`: the request it dismissed.
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
192#[serde(rename_all = "camelCase")]
193pub struct ChannelPairingResponse {
194    /// The dismissed request.
195    pub waiting: ChannelPairingView,
196}
197
198/// The answer of a chat-account action: the account after it.
199#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
200#[serde(rename_all = "camelCase")]
201pub struct ChannelAccountResponse {
202    /// The account.
203    pub account: ChannelAccountView,
204}
205
206type Backend = State<Arc<dyn ControlBackend>>;
207
208/// The operator routes of `backend`'s pairing, relative to `/api`; mounted on every kernel,
209/// so one that pairs nothing answers with what to set rather than an empty `404`.
210pub(super) fn routes(backend: Arc<dyn ControlBackend>) -> Router {
211    Router::new()
212        .route(paths::PAIRING, post(issue))
213        .route(paths::DEVICES, get(devices))
214        .route(paths::DEVICE_REVOKE, post(revoke))
215        .route(paths::CHANNELS, get(channels::list))
216        .route(paths::CHANNEL_PAIR, post(channels::accept))
217        .route(paths::CHANNEL_REVOKE, post(channels::revoke))
218        .route(paths::CHANNEL_DISMISS, post(channels::dismiss))
219        .with_state(backend)
220}
221
222/// The claim route under `/api`, which needs no caller: the code is the credential.
223pub(super) fn claim_routes(backend: Arc<dyn ControlBackend>) -> Router {
224    Router::new()
225        .route(&format!("{}{}", paths::API_PREFIX, paths::PAIRING_CLAIM), post(claim))
226        .with_state(backend)
227}
228
229/// `backend`'s pairing, or a `Config` error naming why there is none.
230fn pairing_of(backend: &dyn ControlBackend) -> Result<Pairing> {
231    backend.pairing().ok_or_else(|| KernelError::Config {
232        reason: "this kernel pairs no devices: set ControlPlaneConfig::with_pairing, as \
233                 `adk-rust up` does"
234            .into(),
235    })
236}
237
238async fn issue(
239    State(backend): Backend,
240    caller: Caller,
241    Json(request): Json<IssueRequest>,
242) -> Result<Json<IssuedCode>> {
243    caller.require_operator("issue a pairing code")?;
244    let pairing = pairing_of(backend.as_ref())?;
245    let mut code = IssueCode::new(caller.context.user_id.clone(), caller.context.scopes.clone())
246        .with_scopes(request.scopes.iter().copied());
247    if let Some(name) = &request.name {
248        code = code.with_name(name);
249    }
250    if let Some(days) = request.expires_in_days {
251        code = code.with_device_ttl(std::time::Duration::from_secs(u64::from(days) * 86_400));
252    }
253    if let Some(kind) = request.kind {
254        code = code.with_kind(kind);
255    }
256    // The record names what the code grants: every scope when none was named, and the
257    // name as it is stored; a request the pairing refuses records nothing.
258    let code = code.normalized();
259    pairing.check(&code)?;
260    // Where the code was issued from, so the record says how the pairing began (spec 3.3 §11).
261    let (surface, how) = operator_surface(caller.transport);
262    let extra = [
263        ("surface", json!(surface)),
264        ("how", json!(how)),
265        ("scopes", json!(code.scopes)),
266        ("name", json!(code.name)),
267        ("expiresInDays", json!(request.expires_in_days)),
268        ("kind", json!(code.kind.unwrap_or(DeviceKind::Terminal))),
269    ];
270    record(backend.as_ref(), &caller, "pairing.issue", None, &extra).await?;
271    Ok(Json(pairing.issue(code).await?))
272}
273
274async fn claim(
275    State(backend): Backend,
276    Json(request): Json<ClaimRequest>,
277) -> Result<Json<ClaimedDevice>> {
278    let pairing = pairing_of(backend.as_ref())?;
279    // The code is taken, then the claim recorded, then the device stored: a claim nobody
280    // recorded pairs nothing and leaves its code to be claimed again.
281    let pending = pairing.take_for_claim(&request.code, request.name.as_deref()).await?;
282    let device = pending.device();
283    // The device claims its code from its own surface (spec 3.3 §11).
284    let (surface, how) = kind_surface(Some(device.kind().as_str()));
285    let extra = [
286        ("surface", json!(surface)),
287        ("how", json!(how)),
288        ("device", json!(device.id)),
289        ("name", json!(device.name)),
290        ("scopes", json!(device.scopes)),
291    ];
292    let recorded = record_as(
293        backend.as_ref(),
294        SubjectRef::human(device.owner.clone()),
295        ControlTransport::Http,
296        "pairing.claim",
297        Some(&device.id),
298        &extra,
299    )
300    .await;
301    if let Err(error) = recorded {
302        pairing.abandon_claim(pending).await;
303        return Err(error);
304    }
305    Ok(Json(pairing.finish_claim(pending).await?))
306}
307
308async fn devices(State(backend): Backend, caller: Caller) -> Result<Json<DevicesResponse>> {
309    caller.require_operator("list the paired devices")?;
310    let pairing = pairing_of(backend.as_ref())?;
311    let now = pairing.now();
312    let devices = pairing.devices().await?.iter().map(|device| device.view(now)).collect();
313    Ok(Json(DevicesResponse { devices }))
314}
315
316async fn revoke(
317    State(backend): Backend,
318    caller: Caller,
319    UrlPath(id): UrlPath<String>,
320) -> Result<Json<DeviceResponse>> {
321    caller.require_operator("remove a paired device")?;
322    let pairing = pairing_of(backend.as_ref())?;
323    record(backend.as_ref(), &caller, "devices.revoke", Some(&id), &[]).await?;
324    let device = pairing.revoke(&id).await?;
325    Ok(Json(DeviceResponse { device: device.view(pairing.now()) }))
326}
327
328/// Writes a `kernel.control` record of `action` by `subject`, for a caller that carries no
329/// request context (spec 3.2 §9.3).
330pub(super) async fn record_as(
331    backend: &dyn ControlBackend,
332    subject: SubjectRef,
333    transport: ControlTransport,
334    action: &str,
335    target: Option<&str>,
336    extra: &[(&str, serde_json::Value)],
337) -> Result<()> {
338    tracing::info!(
339        control.action = action,
340        control.subject = %subject.id,
341        control.transport = ?transport,
342        control.target = target.unwrap_or_default(),
343        "kernel control action"
344    );
345    let Some(trail) = backend.audit_trail() else {
346        return Ok(());
347    };
348    let draft = AuditRecordDraft::new(
349        AuditRecordKind::Other(audit::KERNEL_AUDIT_KIND.into()),
350        audit::CONTROL,
351    )
352    .actor(AuditActor::subject(subject.clone()))
353    .ext("subject", json!(subject))
354    .ext("transport", json!(transport))
355    .ext("action", json!(action))
356    .ext("target", json!(target));
357    let draft = extra.iter().fold(draft, |draft, (key, value)| draft.ext(*key, value.clone()));
358    trail.record(draft).await.map_err(KernelError::from)
359}
360
361/// The largest decision a device sends: a decision's edited arguments included.
362const MAX_DECIDE_BODY: usize = 2 * 1024 * 1024;
363
364/// Whether `kernel` rates `request`'s call high risk whatever the request says: a tool a
365/// mounted driver declares of a class nothing may allow without a person, `publish_public`
366/// or `financial` (spec 3.2 K-I9). Chat and paired devices, which decide no high-risk call,
367/// send it to the home (spec 3.3 §7.2, S-I6).
368pub(crate) fn rated_high(
369    kernel: Option<&crate::kernel::Kernel>,
370    request: &ApprovalRequest,
371) -> bool {
372    #[cfg(feature = "drivers")]
373    if let Some(drivers) = kernel.and_then(crate::kernel::Kernel::drivers) {
374        return drivers
375            .mounted()
376            .iter()
377            .filter_map(|id| drivers.record(id))
378            .any(|record| record.manifest.class_of(&request.tool_name).is_never_auto_allowed());
379    }
380    let _ = (kernel, request);
381    false
382}
383
384/// Admits a request carrying device `token` (spec 3.3 §10 K2): the device's context when
385/// its scopes open the route, the kernel's own and the server's
386/// ([`Pairing::with_device_routes`]); a decision it answers on the kernel's decide route
387/// (`answer`, the body's `action`) recorded and limited to low and medium risk, never a yes to
388/// a take-over; or the refusal as a response. A decide route of the server's map is admitted
389/// as it is: the server's engine applies what each surface may decide and records it.
390pub(super) async fn admit_device(
391    backend: &dyn ControlBackend,
392    pairing: &Pairing,
393    token: &str,
394    method: &Method,
395    path: &str,
396    answer: Option<&str>,
397) -> std::result::Result<RequestContext, Response> {
398    let context =
399        pairing.authorize(token, method, path).await.map_err(IntoResponse::into_response)?;
400    if device_scope_for(method, path) != Some(DeviceScope::Decide) {
401        return Ok(context);
402    }
403    let segments: Vec<&str> = path.split('/').filter(|segment| !segment.is_empty()).collect();
404    let id = percent_decode(segments.iter().rev().nth(1).copied().unwrap_or_default());
405    // §7.2: a phone approves a high-risk call only after confirming it is the person, which
406    // a device token alone does not show; a risk the kernel cannot read is refused too.
407    let Some(approvals) = backend.approvals() else {
408        return Err(crate::pairing::forbidden(
409            "this kernel cannot check a decision's risk for a device: decide it in the home".into(),
410        )
411        .into_response());
412    };
413    match approvals.get(&id).await {
414        Ok(Some(request))
415            if request.risk >= ApprovalRisk::High || rated_high(backend.kernel(), &request) =>
416        {
417            return Err(crate::pairing::forbidden(
418                "this decision is high risk: confirm it's you and approve it in the home".into(),
419            )
420            .into_response());
421        }
422        // A take-over is done by typing the secret; a yes delivers nothing (spec 3.3 §8.2).
423        Ok(Some(request))
424            if request.tool_name == crate::pairing::TAKE_OVER_TOOL && answer != Some("reject") =>
425        {
426            return Err(crate::pairing::forbidden(
427                "this decision asks you to type a secret: take over in the home".into(),
428            )
429            .into_response());
430        }
431        Ok(_) => {}
432        Err(error) => return Err(KernelError::Core(error).into_response()),
433    }
434    let device = context.metadata.get(DEVICE_ID_METADATA).cloned();
435    let name = context.metadata.get(DEVICE_NAME_METADATA).cloned();
436    // The surface is the device's kind, as the issuer of its code set it (spec 3.3 §11).
437    let (surface, how) = device_surface(&context);
438    let extra = [
439        ("surface", json!(surface)),
440        ("how", json!(how)),
441        ("device", json!(device)),
442        ("deviceName", json!(name)),
443        ("answer", json!(answer)),
444    ];
445    record_as(
446        backend,
447        SubjectRef::human(context.user_id.clone()),
448        ControlTransport::Http,
449        "approvals.decide",
450        Some(&id),
451        &extra,
452    )
453    .await
454    .map_err(IntoResponse::into_response)?;
455    Ok(context)
456}
457
458/// The surface and how of a device's context: its kind (spec 3.3 §7.2, §11).
459fn device_surface(context: &RequestContext) -> (&'static str, &'static str) {
460    kind_surface(context.metadata.get(crate::pairing::DEVICE_KIND_METADATA).map(String::as_str))
461}
462
463/// The surface and how of a device of `kind`: a phone by touch, a tray by pointer, anything
464/// else a terminal by keyboard (spec 3.3 §7.2, §11).
465fn kind_surface(kind: Option<&str>) -> (&'static str, &'static str) {
466    match kind {
467        Some("phone") => ("phone", "touch"),
468        Some("tray") => ("tray", "pointer"),
469        _ => ("terminal", "keyboard"),
470    }
471}
472
473/// The surface and how of an operator over `transport`: the kernel's socket or pipe is its
474/// own terminal, typed; HTTP is an operator client, `api` (spec 3.3 §11).
475fn operator_surface(transport: ControlTransport) -> (&'static str, &'static str) {
476    match transport {
477        ControlTransport::Socket | ControlTransport::Pipe => ("terminal", "keyboard"),
478        ControlTransport::Http => ("api", "api"),
479    }
480}
481
482/// `request` with its body read when it is a device's decision, and the `action` the body
483/// carries: the decision's record says what the device answered.
484pub(super) async fn read_answer(
485    request: Request<Body>,
486) -> std::result::Result<(Request<Body>, Option<String>), Response> {
487    if device_scope_for(request.method(), request.uri().path()) != Some(DeviceScope::Decide) {
488        return Ok((request, None));
489    }
490    let (parts, body) = request.into_parts();
491    let Ok(bytes) = axum::body::to_bytes(body, MAX_DECIDE_BODY).await else {
492        return Err(axum::http::StatusCode::PAYLOAD_TOO_LARGE.into_response());
493    };
494    let answer = serde_json::from_slice::<serde_json::Value>(&bytes)
495        .ok()
496        .and_then(|body| body.get("action")?.as_str().map(str::to_string));
497    Ok((Request::from_parts(parts, Body::from(bytes)), answer))
498}
499
500/// `segment` with its `%XX` escapes decoded, as the router decodes a path parameter.
501fn percent_decode(segment: &str) -> String {
502    let bytes = segment.as_bytes();
503    let mut out = Vec::with_capacity(bytes.len());
504    let mut index = 0;
505    while index < bytes.len() {
506        let hex = |at: usize| bytes.get(at).and_then(|byte| (*byte as char).to_digit(16));
507        match (bytes[index], hex(index + 1), hex(index + 2)) {
508            (b'%', Some(high), Some(low)) => {
509                out.push(u8::try_from(high * 16 + low).unwrap_or_default());
510                index += 3;
511            }
512            (byte, _, _) => {
513                out.push(byte);
514                index += 1;
515            }
516        }
517    }
518    String::from_utf8_lossy(&out).into_owned()
519}
520
521/// Whether `method` and `path` are the claim route, which needs no caller.
522fn is_claim(method: &Method, path: &str) -> bool {
523    *method == Method::POST
524        && path.strip_prefix(paths::API_PREFIX).unwrap_or(path) == paths::PAIRING_CLAIM
525}
526
527/// Checks every request that carries a device token against `backend`'s pairing before it
528/// reaches `router` (spec 3.3 §10 K2), so a device reaches only the routes its scopes open:
529/// `401` for an unknown, expired or revoked token, `403` for a route it may not call. The
530/// claim route passes untouched, since it needs no caller.
531pub(super) fn guard(backend: Arc<dyn ControlBackend>, router: Router) -> Router {
532    router.layer(middleware::from_fn(move |request: Request<Body>, next: Next| {
533        let backend = backend.clone();
534        async move {
535            let Some(pairing) = backend.pairing() else {
536                return next.run(request).await;
537            };
538            let Some(token) = device_token(request.headers()).map(str::to_string) else {
539                return next.run(request).await;
540            };
541            let method = request.method().clone();
542            let path = request.uri().path().to_string();
543            // The claim needs no caller: a client still holding an old token re-pairs.
544            if is_claim(&method, &path) {
545                return next.run(request).await;
546            }
547            let (request, answer) = match read_answer(request).await {
548                Ok(read) => read,
549                Err(response) => return response,
550            };
551            match admit_device(
552                backend.as_ref(),
553                &pairing,
554                &token,
555                &method,
556                &path,
557                answer.as_deref(),
558            )
559            .await
560            {
561                Ok(context) => {
562                    // The extractor behind the guard admits only the decisions it checked.
563                    let mut request = request;
564                    if let Some(device) = context.metadata.get(DEVICE_ID_METADATA) {
565                        request.extensions_mut().insert(DeviceAdmission { device: device.clone() });
566                    }
567                    next.run(request).await
568                }
569                Err(response) => response,
570            }
571        }
572    }))
573}
574
575/// The chat-account routes (spec 3.3 §10 K1), mounted on every kernel: one without chat
576/// channels lists none and answers the others with what it lacks.
577mod channels {
578    use axum::Json;
579    use axum::extract::{Path as UrlPath, State};
580
581    use super::{
582        AcceptChannelRequest, Backend, Caller, ChannelAccountResponse, ChannelAccountsResponse,
583        ChannelPairingResponse,
584    };
585    use crate::error::{KernelError, Result};
586
587    /// A chat account or waiting request `id` this kernel does not have.
588    fn no_account(id: &str) -> KernelError {
589        KernelError::Core(adk_core::AdkError::new(
590            adk_core::ErrorComponent::Server,
591            adk_core::ErrorCategory::NotFound,
592            crate::error::NOT_FOUND_CODE,
593            format!("no chat account {id}: list them with `adk-rust pair list`"),
594        ))
595    }
596
597    #[cfg(feature = "channels")]
598    fn bindings(
599        backend: &dyn super::ControlBackend,
600    ) -> Option<(crate::pairing::Pairing, std::sync::Arc<dyn crate::channels::ChannelBindingStore>)>
601    {
602        let pairing = backend.pairing()?;
603        let store = pairing.channel_bindings().cloned()?;
604        Some((pairing, store))
605    }
606
607    pub(super) async fn list(
608        State(backend): Backend,
609        caller: Caller,
610    ) -> Result<Json<ChannelAccountsResponse>> {
611        caller.require_operator("list the paired chat accounts")?;
612        let empty = ChannelAccountsResponse { accounts: Vec::new(), waiting: Vec::new() };
613        #[cfg(feature = "channels")]
614        if let Some((pairing, store)) = bindings(backend.as_ref()) {
615            let now = pairing.now();
616            let accounts =
617                store.list_bindings().await?.iter().map(|binding| binding.view()).collect();
618            let waiting = store
619                .list_requests()
620                .await?
621                .iter()
622                .filter(|request| !request.dismissed && request.expires_at > now)
623                .map(|request| request.view())
624                .collect();
625            return Ok(Json(ChannelAccountsResponse { accounts, waiting }));
626        }
627        let _ = backend;
628        // A kernel without chat channels has none to list.
629        Ok(Json(empty))
630    }
631
632    pub(super) async fn accept(
633        State(backend): Backend,
634        caller: Caller,
635        Json(request): Json<AcceptChannelRequest>,
636    ) -> Result<Json<ChannelAccountResponse>> {
637        caller.require_operator("pair a chat account")?;
638        #[cfg(feature = "channels")]
639        {
640            let (pairing, store) =
641                bindings(backend.as_ref()).ok_or_else(|| KernelError::Config {
642                    reason: "this kernel pairs no chat accounts: no chat channel is connected to \
643                         it (Pairing::with_channel_bindings)"
644                        .into(),
645                })?;
646            let now = pairing.now();
647            // The code is taken, then the pairing recorded, then the account stored: an
648            // account nobody recorded pairing is not paired, and its code still works.
649            let waiting = crate::channels::take_pairing(store.as_ref(), &request.code, now).await?;
650            let binding = crate::channels::binding_for(
651                &waiting,
652                &caller.context.user_id,
653                &caller.context.scopes,
654                now,
655            );
656            let extra = [
657                ("channel", serde_json::json!(binding.channel)),
658                ("account", serde_json::json!(binding.account)),
659            ];
660            let recorded = super::record(
661                backend.as_ref(),
662                &caller,
663                "channels.pair",
664                Some(&binding.id),
665                &extra,
666            )
667            .await;
668            if let Err(error) = recorded {
669                crate::channels::restore_pairing(store.as_ref(), waiting).await;
670                return Err(error);
671            }
672            if let Err(error) = store.put_binding(binding.clone()).await {
673                crate::channels::restore_pairing(store.as_ref(), waiting).await;
674                return Err(error);
675            }
676            Ok(Json(ChannelAccountResponse { account: binding.view() }))
677        }
678        #[cfg(not(feature = "channels"))]
679        {
680            let _ = (backend, request);
681            Err(KernelError::Config {
682                reason: "this kernel has no chat channels: it was built without adk-kernel's \
683                         `channels` feature, so no chat account can be paired with it"
684                    .into(),
685            })
686        }
687    }
688
689    pub(super) async fn revoke(
690        State(backend): Backend,
691        caller: Caller,
692        UrlPath(id): UrlPath<String>,
693    ) -> Result<Json<ChannelAccountResponse>> {
694        caller.require_operator("remove a chat account")?;
695        #[cfg(feature = "channels")]
696        if let Some((pairing, store)) = bindings(backend.as_ref())
697            && store.get_binding(&id).await?.is_some()
698        {
699            super::record(backend.as_ref(), &caller, "channels.revoke", Some(&id), &[]).await?;
700            let binding =
701                crate::channels::revoke_binding(store.as_ref(), &id, pairing.now()).await?;
702            // Its turns that have not finished stop too: they would run as the person.
703            if let Some(kernel) = backend.kernel() {
704                crate::channels::stop_account_turns(kernel, &binding.channel, &binding.account)
705                    .await;
706            }
707            return Ok(Json(ChannelAccountResponse { account: binding.view() }));
708        }
709        let _ = backend;
710        Err(no_account(&id))
711    }
712
713    /// Dismisses the waiting chat account `id`: its code stops working, its place in the
714    /// queue is freed, and it gets no new code for a day.
715    pub(super) async fn dismiss(
716        State(backend): Backend,
717        caller: Caller,
718        UrlPath(id): UrlPath<String>,
719    ) -> Result<Json<ChannelPairingResponse>> {
720        caller.require_operator("dismiss a chat account waiting to be paired")?;
721        #[cfg(feature = "channels")]
722        if let Some((pairing, store)) = bindings(backend.as_ref())
723            && let Some(waiting) = crate::channels::waiting_request(store.as_ref(), &id).await?
724        {
725            super::record(backend.as_ref(), &caller, "channels.dismiss", Some(&id), &[]).await?;
726            crate::channels::dismiss_request(store.as_ref(), &waiting, pairing.now()).await?;
727            return Ok(Json(ChannelPairingResponse { waiting: waiting.view() }));
728        }
729        let _ = backend;
730        Err(no_account(&id))
731    }
732}
733
734#[cfg(test)]
735mod tests {
736    use super::percent_decode;
737
738    #[test]
739    fn path_segments_decode_as_the_router_decodes_them() {
740        assert_eq!(percent_decode("apr_1f"), "apr_1f");
741        assert_eq!(percent_decode("a%2Fb%20c"), "a/b c");
742        assert_eq!(percent_decode("bad%2"), "bad%2");
743        assert_eq!(percent_decode("%E6%97%A5"), "日");
744    }
745}