use std::collections::{BTreeSet, HashMap};
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use adk_core::{AdkError, Clock, ErrorCategory, ErrorComponent, RequestContext, SystemClock};
use adk_server::auth_bridge::{RequestContextError, RequestContextExtractor};
use async_trait::async_trait;
use axum::http::Method;
use axum::http::request::Parts;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::error::{KernelError, Result, UNAUTHORIZED_CODE, UNSUPPORTED_CODE};
mod attachments;
mod kinds;
mod memory;
#[cfg(feature = "postgres")]
pub(crate) mod postgres;
#[cfg(feature = "redis")]
pub(crate) mod redis;
pub(crate) mod secret;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
pub(crate) mod sql;
#[cfg(feature = "sqlite")]
mod sqlite;
pub use attachments::{AttachmentHolder, DeviceAttachment};
pub use kinds::{DeviceKind, DeviceRoutes};
pub use memory::InMemoryDeviceStore;
#[cfg(feature = "postgres")]
pub use postgres::PostgresDeviceStore;
#[cfg(feature = "redis")]
pub use redis::RedisDeviceStore;
#[cfg(feature = "sqlite")]
pub use sqlite::SqliteDeviceStore;
pub const DEVICE_ID_METADATA: &str = "adk.device.id";
pub const DEVICE_NAME_METADATA: &str = "adk.device.name";
pub const DEVICE_SCOPES_METADATA: &str = "adk.device.scopes";
pub const DEVICE_KIND_METADATA: &str = "adk.device.kind";
const MAX_FAILED_CLAIMS: u64 = 20;
const DEFAULT_RECHECK: Duration = Duration::from_secs(5);
const MAX_NAME_CHARS: usize = 64;
const MAX_DEVICE_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum DeviceScope {
Decide,
Read,
Stop,
}
impl DeviceScope {
pub const ALL: [Self; 3] = [Self::Decide, Self::Read, Self::Stop];
pub fn as_str(self) -> &'static str {
match self {
Self::Decide => "decide",
Self::Read => "read",
Self::Stop => "stop",
}
}
}
impl fmt::Display for DeviceScope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl std::str::FromStr for DeviceScope {
type Err = KernelError;
fn from_str(text: &str) -> Result<Self> {
match text.trim().to_ascii_lowercase().as_str() {
"decide" => Ok(Self::Decide),
"read" => Ok(Self::Read),
"stop" => Ok(Self::Stop),
other => Err(KernelError::Config {
reason: format!("unknown device scope `{other}`: use decide, read or stop"),
}),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DeviceRecord {
pub id: String,
pub name: String,
pub owner: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub groups: Vec<String>,
pub scopes: Vec<DeviceScope>,
pub token_hash: String,
pub created_at: DateTime<Utc>,
pub expires_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revoked_at: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<DeviceKind>,
}
impl DeviceRecord {
pub fn new(
id: impl Into<String>,
name: impl Into<String>,
owner: impl Into<String>,
token_hash: impl Into<String>,
created_at: DateTime<Utc>,
expires_at: DateTime<Utc>,
) -> Self {
Self {
id: id.into(),
name: name.into(),
owner: owner.into(),
groups: Vec::new(),
scopes: DeviceScope::ALL.to_vec(),
token_hash: token_hash.into(),
created_at,
expires_at,
revoked_at: None,
kind: None,
}
}
#[must_use]
pub fn with_kind(mut self, kind: DeviceKind) -> Self {
self.kind = Some(kind);
self
}
pub fn kind(&self) -> DeviceKind {
self.kind.unwrap_or(DeviceKind::Terminal)
}
#[must_use]
pub fn with_scopes(mut self, scopes: impl IntoIterator<Item = DeviceScope>) -> Self {
self.scopes = scopes.into_iter().collect::<BTreeSet<_>>().into_iter().collect();
self
}
#[must_use]
pub fn with_groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.groups = groups.into_iter().map(Into::into).collect();
self
}
pub fn is_active(&self, now: DateTime<Utc>) -> bool {
self.revoked_at.is_none() && now < self.expires_at
}
pub fn has_scope(&self, scope: DeviceScope) -> bool {
self.scopes.contains(&scope)
}
pub fn view(&self, now: DateTime<Utc>) -> DeviceView {
let state = match (self.revoked_at, now < self.expires_at) {
(Some(_), _) => DeviceState::Revoked,
(None, true) => DeviceState::Active,
(None, false) => DeviceState::Expired,
};
DeviceView {
id: self.id.clone(),
name: self.name.clone(),
owner: self.owner.clone(),
scopes: self.scopes.clone(),
created_at: self.created_at,
expires_at: self.expires_at,
revoked_at: self.revoked_at,
state,
kind: self.kind(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum DeviceState {
Active,
Expired,
Revoked,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DeviceView {
pub id: String,
pub name: String,
pub owner: String,
pub scopes: Vec<DeviceScope>,
pub created_at: DateTime<Utc>,
pub expires_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revoked_at: Option<DateTime<Utc>>,
pub state: DeviceState,
#[serde(default = "terminal")]
pub kind: DeviceKind,
}
fn terminal() -> DeviceKind {
DeviceKind::Terminal
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PairingCode {
pub code_hash: String,
pub owner: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub groups: Vec<String>,
pub scopes: Vec<DeviceScope>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
pub device_ttl_secs: u64,
pub issued_at: DateTime<Utc>,
pub expires_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<DeviceKind>,
}
impl PairingCode {
pub fn new(
code_hash: impl Into<String>,
owner: impl Into<String>,
device_ttl: Duration,
issued_at: DateTime<Utc>,
expires_at: DateTime<Utc>,
) -> Self {
Self {
code_hash: code_hash.into(),
owner: owner.into(),
groups: Vec::new(),
scopes: DeviceScope::ALL.to_vec(),
name: None,
device_ttl_secs: device_ttl.as_secs(),
issued_at,
expires_at,
kind: None,
}
}
}
#[async_trait]
pub trait DeviceStore: Send + Sync {
async fn put_code(&self, code: PairingCode) -> Result<()>;
async fn take_code(&self, code_hash: &str) -> Result<Option<PairingCode>>;
async fn prune_codes(&self, before: DateTime<Utc>) -> Result<usize>;
async fn clear_codes(&self) -> Result<usize>;
async fn put_device(&self, device: DeviceRecord) -> Result<()>;
async fn get_device(&self, id: &str) -> Result<Option<DeviceRecord>>;
async fn list_devices(&self) -> Result<Vec<DeviceRecord>>;
async fn count_claim_attempt(&self) -> Result<u64>;
async fn reset_claim_attempts(&self) -> Result<()>;
async fn put_attachment(&self, attachment: DeviceAttachment) -> Result<()> {
let _ = attachment;
Err(no_attachments())
}
async fn put_attachment_if_absent(&self, attachment: DeviceAttachment) -> Result<bool> {
let _ = attachment;
Err(no_attachments())
}
async fn attachments(
&self,
holder: &AttachmentHolder,
kind: &str,
) -> Result<Vec<DeviceAttachment>> {
let _ = (holder, kind);
Err(no_attachments())
}
async fn remove_attachment(
&self,
holder: &AttachmentHolder,
kind: &str,
key: &str,
) -> Result<bool> {
let _ = (holder, kind, key);
Err(no_attachments())
}
async fn remove_attachments(&self, holder: &AttachmentHolder) -> Result<usize> {
let _ = holder;
Err(no_attachments())
}
}
fn no_attachments() -> KernelError {
KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::Unsupported,
UNSUPPORTED_CODE,
"this device store keeps no attachments: use the in-memory, SQLite, PostgreSQL or Redis \
device store",
))
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct IssueCode {
pub owner: String,
pub groups: Vec<String>,
pub scopes: Vec<DeviceScope>,
pub name: Option<String>,
pub device_ttl: Option<Duration>,
pub kind: Option<DeviceKind>,
}
impl IssueCode {
pub fn new(
owner: impl Into<String>,
groups: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
Self {
owner: owner.into(),
groups: groups.into_iter().map(Into::into).collect(),
scopes: Vec::new(),
name: None,
device_ttl: None,
kind: None,
}
}
#[must_use]
pub fn with_kind(mut self, kind: DeviceKind) -> Self {
self.kind = Some(kind);
self
}
#[must_use]
pub fn with_scopes(mut self, scopes: impl IntoIterator<Item = DeviceScope>) -> Self {
self.scopes = scopes.into_iter().collect();
self
}
#[must_use]
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub fn with_device_ttl(mut self, ttl: Duration) -> Self {
self.device_ttl = Some(ttl);
self
}
#[must_use]
pub fn normalized(mut self) -> Self {
self.scopes = if self.scopes.is_empty() {
DeviceScope::ALL.to_vec()
} else {
self.scopes.iter().copied().collect::<BTreeSet<_>>().into_iter().collect()
};
self.name = self
.name
.map(|name| secret::clean_name(&name, MAX_NAME_CHARS))
.filter(|name| !name.is_empty());
self
}
}
pub(crate) struct PendingClaim {
code: PairingCode,
device: DeviceRecord,
token: String,
}
impl PendingClaim {
pub(crate) fn device(&self) -> &DeviceRecord {
&self.device
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DeviceAdmission {
pub(crate) device: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct IssuedCode {
pub code: String,
pub expires_at: DateTime<Utc>,
pub scopes: Vec<DeviceScope>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(default)]
pub device_ttl_secs: u64,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ClaimedDevice {
pub device: DeviceView,
pub token: String,
}
impl fmt::Debug for ClaimedDevice {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ClaimedDevice").field("device", &self.device).finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct Pairing {
inner: Arc<Inner>,
}
struct Inner {
store: Arc<dyn DeviceStore>,
#[cfg(feature = "channels")]
channels: Option<Arc<dyn crate::channels::ChannelBindingStore>>,
code_ttl: Duration,
device_ttl: Duration,
home_url: Option<String>,
clock: Arc<dyn Clock>,
recheck: Duration,
revoked: tokio::sync::broadcast::Sender<String>,
routes: Option<DeviceRoutes>,
}
impl fmt::Debug for Pairing {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Pairing")
.field("code_ttl", &self.inner.code_ttl)
.field("device_ttl", &self.inner.device_ttl)
.field("home_url", &self.inner.home_url)
.finish_non_exhaustive()
}
}
impl Pairing {
pub const DEFAULT_CODE_TTL: Duration = Duration::from_secs(10 * 60);
pub const DEFAULT_DEVICE_TTL: Duration = Duration::from_secs(90 * 24 * 60 * 60);
pub fn new(store: Arc<dyn DeviceStore>) -> Self {
Self {
inner: Arc::new(Inner {
store,
#[cfg(feature = "channels")]
channels: None,
code_ttl: Self::DEFAULT_CODE_TTL,
device_ttl: Self::DEFAULT_DEVICE_TTL,
home_url: None,
clock: Arc::new(SystemClock),
recheck: DEFAULT_RECHECK,
revoked: tokio::sync::broadcast::channel(64).0,
routes: None,
}),
}
}
fn rebuild(self, change: impl FnOnce(&mut Inner)) -> Self {
let inner = Arc::try_unwrap(self.inner).unwrap_or_else(|shared| Inner {
store: shared.store.clone(),
#[cfg(feature = "channels")]
channels: shared.channels.clone(),
code_ttl: shared.code_ttl,
device_ttl: shared.device_ttl,
home_url: shared.home_url.clone(),
clock: shared.clock.clone(),
recheck: shared.recheck,
revoked: shared.revoked.clone(),
routes: shared.routes.clone(),
});
let mut inner = inner;
change(&mut inner);
Self { inner: Arc::new(inner) }
}
#[must_use]
pub fn with_device_routes(self, routes: DeviceRoutes) -> Self {
self.rebuild(|inner| inner.routes = Some(routes))
}
pub fn scope_for(&self, method: &Method, path: &str) -> Option<DeviceScope> {
device_scope_for(method, path)
.or_else(|| self.inner.routes.as_ref().and_then(|routes| routes(method, path)))
}
#[must_use]
pub fn with_code_ttl(self, ttl: Duration) -> Self {
self.rebuild(|inner| inner.code_ttl = ttl)
}
#[must_use]
pub fn with_device_ttl(self, ttl: Duration) -> Self {
self.rebuild(|inner| inner.device_ttl = ttl.min(MAX_DEVICE_TTL))
}
#[must_use]
pub fn with_home_url(self, url: impl Into<String>) -> Self {
let url = url.into().trim_end_matches('/').to_string();
self.rebuild(|inner| inner.home_url = Some(url))
}
#[must_use]
pub fn with_clock(self, clock: Arc<dyn Clock>) -> Self {
self.rebuild(|inner| inner.clock = clock)
}
#[must_use]
pub fn with_revocation_check(self, interval: Duration) -> Self {
self.rebuild(|inner| inner.recheck = interval.max(Duration::from_millis(10)))
}
#[cfg(feature = "channels")]
#[must_use]
pub fn with_channel_bindings(
self,
store: Arc<dyn crate::channels::ChannelBindingStore>,
) -> Self {
self.rebuild(|inner| inner.channels = Some(store))
}
#[cfg(feature = "channels")]
pub fn channel_bindings(&self) -> Option<&Arc<dyn crate::channels::ChannelBindingStore>> {
self.inner.channels.as_ref()
}
pub fn store(&self) -> &Arc<dyn DeviceStore> {
&self.inner.store
}
pub fn home_url(&self) -> Option<&str> {
self.inner.home_url.as_deref()
}
pub fn now(&self) -> DateTime<Utc> {
self.inner.clock.now()
}
pub async fn issue(&self, request: IssueCode) -> Result<IssuedCode> {
let device_ttl = self.check(&request)?;
let request = request.normalized();
let phone = request.kind == Some(DeviceKind::Phone);
let now = self.now();
self.inner.store.prune_codes(now).await?;
let code = secret::new_code()?;
let expires_at = now + chrono::Duration::from_std(self.inner.code_ttl).unwrap_or_default();
let mut stored =
PairingCode::new(secret::code_hash(&code), request.owner, device_ttl, now, expires_at);
stored.groups = request.groups;
stored.scopes = request.scopes.clone();
stored.name = request.name;
stored.kind = request.kind;
self.inner.store.put_code(stored).await?;
self.inner.store.reset_claim_attempts().await?;
let url = self
.inner
.home_url
.as_ref()
.filter(|_| phone)
.map(|home| format!("{home}/pair#code={code}"));
Ok(IssuedCode {
code,
expires_at,
scopes: request.scopes,
url,
device_ttl_secs: device_ttl.as_secs(),
})
}
pub(crate) fn check(&self, request: &IssueCode) -> Result<Duration> {
if request.owner.trim().is_empty() {
return Err(KernelError::Config {
reason: "a pairing code needs the person the device acts for".into(),
});
}
let device_ttl = request.device_ttl.unwrap_or(self.inner.device_ttl);
if device_ttl.is_zero() || device_ttl > MAX_DEVICE_TTL {
return Err(KernelError::Config {
reason: format!(
"a device stays paired for at most 365 days and longer than none, not {} \
days: pass `adk-rust pair --days` between 1 and 365",
device_ttl.as_secs() / 86_400
),
});
}
Ok(device_ttl)
}
pub async fn claim(&self, code: &str, name: Option<&str>) -> Result<ClaimedDevice> {
let pending = self.take_for_claim(code, name).await?;
self.finish_claim(pending).await
}
pub(crate) async fn take_for_claim(
&self,
code: &str,
name: Option<&str>,
) -> Result<PendingClaim> {
let wrong = || KernelError::Unauthorized {
reason: "the pairing code is wrong, used or expired: run `adk-rust pair` for a new \
one"
.into(),
};
let store = &self.inner.store;
let attempts = store.count_claim_attempt().await?;
if attempts > MAX_FAILED_CLAIMS {
let cleared = store.clear_codes().await?;
if cleared > 0 {
tracing::warn!(
pairing.cleared = cleared,
"too many claims without a success; every waiting code was cancelled"
);
}
return Err(KernelError::Unauthorized {
reason: "too many pairing codes were wrong, so every waiting code was \
cancelled: run `adk-rust pair` for a new one"
.into(),
});
}
let now = self.now();
let taken = store.take_code(&secret::code_hash(code)).await?;
let Some(code) = taken.filter(|code| now < code.expires_at) else {
return Err(wrong());
};
if let Err(error) = store.reset_claim_attempts().await {
tracing::warn!(error = %error, "the count of pairing claims could not be reset");
}
let id = secret::new_device_id()?;
let (token, token_hash) = secret::new_token(&id)?;
let name = code
.name
.clone()
.or_else(|| name.map(|name| secret::clean_name(name, MAX_NAME_CHARS)))
.filter(|name| !name.is_empty())
.unwrap_or_else(|| "Device".to_string());
let ttl = Duration::from_secs(code.device_ttl_secs).min(MAX_DEVICE_TTL);
let device = DeviceRecord::new(
id,
name,
code.owner.clone(),
token_hash,
now,
now + chrono::Duration::from_std(ttl).unwrap_or_default(),
)
.with_scopes(code.scopes.clone())
.with_groups(code.groups.clone());
let device = DeviceRecord { kind: code.kind, ..device };
Ok(PendingClaim { code, device, token })
}
pub(crate) async fn finish_claim(&self, pending: PendingClaim) -> Result<ClaimedDevice> {
if let Err(error) = self.inner.store.put_device(pending.device.clone()).await {
self.abandon_claim(pending).await;
return Err(error);
}
Ok(ClaimedDevice { device: pending.device.view(self.now()), token: pending.token })
}
pub(crate) async fn abandon_claim(&self, pending: PendingClaim) {
if let Err(error) = self.inner.store.put_code(pending.code).await {
tracing::error!(error = %error, "a pairing code could not be put back");
}
}
pub fn until_device_ends(&self, id: String) -> impl Future<Output = ()> + Send + 'static {
let pairing = self.clone();
let mut revoked = self.inner.revoked.subscribe();
async move {
loop {
let wait = match pairing.inner.store.get_device(&id).await {
Ok(Some(device)) if device.is_active(pairing.now()) => {
let left = (device.expires_at - pairing.now()).to_std().unwrap_or_default();
left.min(pairing.inner.recheck)
}
Ok(_) => return,
Err(error) => {
tracing::warn!(device.id = %id, error = %error, "a device could not be re-read");
pairing.inner.recheck
}
};
tokio::select! {
() = tokio::time::sleep(wait) => {}
message = revoked.recv() => match message {
Ok(gone) if gone == id => return,
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
},
}
}
}
}
pub async fn authenticate(&self, token: &str) -> Result<DeviceRecord> {
let unknown = || KernelError::Unauthorized {
reason: "the device token is not one this kernel issued: pair the device again \
with `adk-rust pair`"
.into(),
};
let (id, secret_text) = secret::parse_token(token).ok_or_else(unknown)?;
let device = self.inner.store.get_device(id).await?.ok_or_else(unknown)?;
if !secret::constant_time_eq(
secret::digest(secret_text).as_bytes(),
device.token_hash.as_bytes(),
) {
return Err(unknown());
}
if let Some(at) = device.revoked_at {
return Err(KernelError::Unauthorized {
reason: format!(
"{} was removed on {}: pair it again with `adk-rust pair`",
device.name,
at.format("%Y-%m-%d")
),
});
}
if self.now() >= device.expires_at {
return Err(KernelError::Unauthorized {
reason: format!(
"{}'s pairing ended on {}: pair it again with `adk-rust pair`",
device.name,
device.expires_at.format("%Y-%m-%d")
),
});
}
Ok(device)
}
pub async fn authorize(
&self,
token: &str,
method: &Method,
path: &str,
) -> Result<RequestContext> {
let device = self.authenticate(token).await?;
match self.scope_for(method, path) {
Some(scope) if device.has_scope(scope) => Ok(device_context(&device)),
Some(scope) => Err(forbidden(format!(
"{} was paired without the `{scope}` scope, which {method} {path} needs; pair it \
again with `adk-rust pair --scope {scope}`",
device.name
))),
None => Err(forbidden(format!(
"a paired device may not call {method} {path}: devices read, answer decisions \
and stop everything; anything else happens in the home or on the kernel's own \
terminal"
))),
}
}
pub async fn devices(&self) -> Result<Vec<DeviceRecord>> {
self.inner.store.list_devices().await
}
pub async fn revoke(&self, id: &str) -> Result<DeviceRecord> {
let Some(mut device) = self.inner.store.get_device(id).await? else {
return Err(KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::NotFound,
crate::error::NOT_FOUND_CODE,
format!("no paired device {id}: list them with `adk-rust pair list`"),
)));
};
if device.revoked_at.is_none() {
device.revoked_at = Some(self.now());
self.inner.store.put_device(device.clone()).await?;
}
match self
.inner
.store
.remove_attachments(&AttachmentHolder::Device(device.id.clone()))
.await
{
Ok(_) => {}
Err(KernelError::Core(error)) if error.category == ErrorCategory::Unsupported => {}
Err(error) => return Err(error),
}
let _ = self.inner.revoked.send(device.id.clone());
Ok(device)
}
}
pub(crate) fn forbidden(message: String) -> KernelError {
KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::Forbidden,
UNAUTHORIZED_CODE,
message,
))
}
fn device_context(device: &DeviceRecord) -> RequestContext {
let scopes = device.scopes.iter().map(|scope| scope.as_str()).collect::<Vec<_>>().join(",");
RequestContext {
user_id: device.owner.clone(),
scopes: device.groups.clone(),
metadata: HashMap::from([
(DEVICE_ID_METADATA.to_string(), device.id.clone()),
(DEVICE_NAME_METADATA.to_string(), device.name.clone()),
(DEVICE_SCOPES_METADATA.to_string(), scopes),
(DEVICE_KIND_METADATA.to_string(), device.kind().as_str().to_string()),
]),
}
}
pub fn device_scope_for(method: &Method, path: &str) -> Option<DeviceScope> {
let path = path.split(['?', '#']).next().unwrap_or_default();
let path = path.strip_prefix(crate::control::paths::API_PREFIX).unwrap_or(path);
let segments: Vec<&str> = path.split('/').filter(|segment| !segment.is_empty()).collect();
match (method.as_str(), segments.as_slice()) {
("GET", ["kernel", "health" | "processes" | "events" | "agenda"])
| ("POST", ["kernel", "attach", _])
| (
"GET",
["kernel", "settings" | "away" | "memory" | "record" | "agents"]
| ["kernel", "settings" | "agents", _]
| ["kernel", "away", "lines", _]
| ["kernel", "record", "check"],
)
| ("POST", ["kernel", "away", "seen"])
| ("GET", ["approvals"] | ["approvals", _]) => Some(DeviceScope::Read),
("POST", ["approvals", id, "decide"]) if *id != "delegations" => Some(DeviceScope::Decide),
("POST", ["kernel", "freeze"]) => Some(DeviceScope::Stop),
_ => None,
}
}
pub(crate) const TAKE_OVER_TOOL: &str = "harness:take-over";
pub(crate) fn device_token(headers: &axum::http::HeaderMap) -> Option<&str> {
let value = headers.get(axum::http::header::AUTHORIZATION)?.to_str().ok()?;
let token = value.strip_prefix("Bearer ").or_else(|| value.strip_prefix("bearer "))?.trim();
token.starts_with(secret::TOKEN_PREFIX).then_some(token)
}
#[derive(Clone)]
pub struct DeviceTokenExtractor {
pairing: Pairing,
fallback: Option<Arc<dyn RequestContextExtractor>>,
}
impl fmt::Debug for DeviceTokenExtractor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DeviceTokenExtractor")
.field("pairing", &self.pairing)
.field("fallback", &self.fallback.is_some())
.finish()
}
}
impl DeviceTokenExtractor {
pub fn new(pairing: Pairing) -> Self {
Self { pairing, fallback: None }
}
#[must_use]
pub fn with_fallback(mut self, fallback: Arc<dyn RequestContextExtractor>) -> Self {
self.fallback = Some(fallback);
self
}
}
#[async_trait]
impl RequestContextExtractor for DeviceTokenExtractor {
async fn extract(
&self,
parts: &Parts,
) -> std::result::Result<RequestContext, RequestContextError> {
let Some(token) = device_token(&parts.headers) else {
return match &self.fallback {
Some(fallback) => fallback.extract(parts).await,
None => Err(RequestContextError::MissingAuth),
};
};
let path =
parts.uri.path_and_query().map_or_else(|| parts.uri.path(), |path| path.as_str());
match self.pairing.authorize(token, &parts.method, path).await {
Ok(context)
if self.pairing.scope_for(&parts.method, path) == Some(DeviceScope::Decide)
&& parts.extensions.get::<DeviceAdmission>().map(|admitted| &admitted.device)
!= context.metadata.get(DEVICE_ID_METADATA) =>
{
Err(RequestContextError::InvalidToken(
"a device's decision is admitted only behind adk_kernel::control::guard_devices, \
which checks its risk and records it; layer it on the app"
.into(),
))
}
Ok(context) => Ok(context),
Err(error @ (KernelError::Store { .. } | KernelError::Io(_))) => {
Err(RequestContextError::ExtractionFailed(error.to_string()))
}
Err(error) => Err(RequestContextError::InvalidToken(error.to_string())),
}
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use super::*;
fn pairing() -> Pairing {
Pairing::new(Arc::new(InMemoryDeviceStore::new()))
}
#[derive(Default)]
struct Faulty {
inner: InMemoryDeviceStore,
lookups: AtomicUsize,
slow: AtomicBool,
fail_put_device: AtomicBool,
fail_clear: AtomicBool,
}
fn down() -> KernelError {
KernelError::Store { backend: "test", reason: "down".into() }
}
#[async_trait]
impl DeviceStore for Faulty {
async fn put_code(&self, code: PairingCode) -> Result<()> {
self.inner.put_code(code).await
}
async fn take_code(&self, code_hash: &str) -> Result<Option<PairingCode>> {
self.lookups.fetch_add(1, Ordering::SeqCst);
if self.slow.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(20)).await;
}
self.inner.take_code(code_hash).await
}
async fn prune_codes(&self, before: DateTime<Utc>) -> Result<usize> {
self.inner.prune_codes(before).await
}
async fn clear_codes(&self) -> Result<usize> {
if self.fail_clear.load(Ordering::SeqCst) {
return Err(down());
}
self.inner.clear_codes().await
}
async fn put_device(&self, device: DeviceRecord) -> Result<()> {
if self.fail_put_device.swap(false, Ordering::SeqCst) {
return Err(down());
}
self.inner.put_device(device).await
}
async fn get_device(&self, id: &str) -> Result<Option<DeviceRecord>> {
self.inner.get_device(id).await
}
async fn list_devices(&self) -> Result<Vec<DeviceRecord>> {
self.inner.list_devices().await
}
async fn count_claim_attempt(&self) -> Result<u64> {
self.inner.count_claim_attempt().await
}
async fn reset_claim_attempts(&self) -> Result<()> {
self.inner.reset_claim_attempts().await
}
}
#[tokio::test]
async fn only_a_phone_s_code_carries_the_pairing_link() {
let pairing = pairing().with_home_url("https://home.example/ui/");
let phone = pairing
.issue(IssueCode::new("ana", ["operator"]).with_kind(DeviceKind::Phone))
.await
.unwrap();
assert_eq!(phone.url, Some(format!("https://home.example/ui/pair#code={}", phone.code)));
for kind in [None, Some(DeviceKind::Terminal), Some(DeviceKind::Tray)] {
let request = IssueCode::new("ana", ["operator"]);
let request = match kind {
Some(kind) => request.with_kind(kind),
None => request,
};
assert_eq!(pairing.issue(request).await.unwrap().url, None, "{kind:?}");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_wrong_claims_are_counted_before_they_are_checked() {
let store = Arc::new(Faulty::default());
store.slow.store(true, Ordering::SeqCst);
let pairing = Pairing::new(store.clone());
pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
let mut claims = Vec::new();
for guess in 0..100 {
let pairing = pairing.clone();
claims.push(tokio::spawn(async move {
pairing.claim(&format!("0000-0000-{guess:04}"), None).await.is_err()
}));
}
for claim in claims {
assert!(claim.await.unwrap());
}
let lookups = store.lookups.load(Ordering::SeqCst);
assert!(lookups <= MAX_FAILED_CLAIMS as usize, "{lookups} guesses reached the codes");
}
#[tokio::test]
async fn replicas_share_the_count_of_wrong_codes() {
let store: Arc<dyn DeviceStore> = Arc::new(InMemoryDeviceStore::new());
let (first, second) = (Pairing::new(store.clone()), Pairing::new(store));
let issued = first.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
for _ in 0..MAX_FAILED_CLAIMS / 2 {
assert!(first.claim("0000-0000", None).await.is_err());
assert!(second.claim("0000-0000", None).await.is_err());
}
assert!(second.claim(&issued.code, None).await.is_err(), "the shared lockout fired");
}
#[tokio::test]
async fn a_lockout_whose_clear_fails_keeps_refusing() {
let store = Arc::new(Faulty::default());
store.fail_clear.store(true, Ordering::SeqCst);
let pairing = Pairing::new(store.clone());
let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
for _ in 0..=MAX_FAILED_CLAIMS {
assert!(pairing.claim("0000-0000", None).await.is_err());
}
assert!(pairing.claim(&issued.code, None).await.is_err(), "still locked out");
}
#[tokio::test]
async fn a_claim_whose_device_cannot_be_stored_keeps_its_code() {
let store = Arc::new(Faulty::default());
let pairing = Pairing::new(store.clone());
let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
store.fail_put_device.store(true, Ordering::SeqCst);
assert!(matches!(pairing.claim(&issued.code, None).await, Err(KernelError::Store { .. })));
assert!(pairing.claim(&issued.code, None).await.is_ok(), "the retry pairs");
}
#[tokio::test]
async fn a_lockout_holds_until_the_next_code() {
let pairing = pairing();
let first = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
for _ in 0..MAX_FAILED_CLAIMS {
assert!(pairing.claim("0000-0000-0000", None).await.is_err());
}
let error = pairing.claim(&first.code, None).await.unwrap_err();
assert!(error.to_string().contains("too many"), "{error}");
let second = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
assert!(pairing.claim(&first.code, None).await.is_err(), "the first code was cancelled");
assert!(pairing.claim(&second.code, None).await.is_ok(), "a new code pairs");
}
#[tokio::test]
async fn the_extractor_alone_refuses_a_device_decision() {
let pairing = pairing();
let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
let token = pairing.claim(&issued.code, None).await.unwrap().token;
let extractor = DeviceTokenExtractor::new(pairing);
let request = axum::http::Request::builder()
.method(Method::POST)
.uri("/api/approvals/a1/decide")
.header("authorization", format!("Bearer {token}"))
.body(())
.unwrap();
let (parts, ()) = request.into_parts();
assert!(extractor.extract(&parts).await.is_err(), "decide needs the guard");
let request = axum::http::Request::builder()
.uri("/api/approvals")
.header("authorization", format!("Bearer {token}"))
.body(())
.unwrap();
let (parts, ()) = request.into_parts();
assert!(extractor.extract(&parts).await.is_ok(), "read needs no guard");
}
#[tokio::test]
async fn a_code_pairs_one_device_with_its_scopes() {
let pairing = pairing();
let issued = pairing
.issue(IssueCode::new("ana", ["operator"]).with_scopes([DeviceScope::Read]))
.await
.unwrap();
assert_eq!(issued.scopes, [DeviceScope::Read]);
assert_eq!(issued.url, None);
let claimed = pairing.claim(&issued.code.to_lowercase(), Some("Pixel")).await.unwrap();
assert_eq!(claimed.device.name, "Pixel");
assert_eq!(claimed.device.scopes, [DeviceScope::Read]);
let device = pairing.authenticate(&claimed.token).await.unwrap();
assert_eq!(
(device.owner.as_str(), device.groups.as_slice()),
("ana", &["operator".to_string()][..])
);
assert!(pairing.claim(&issued.code, None).await.is_err());
}
#[tokio::test]
async fn the_store_never_holds_the_code_or_the_token() {
let store = Arc::new(InMemoryDeviceStore::new());
let pairing = Pairing::new(store.clone());
let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
let claimed = pairing.claim(&issued.code, None).await.unwrap();
let stored = serde_json::to_string(&store.list_devices().await.unwrap()).unwrap();
let (_, secret) = secret::parse_token(&claimed.token).unwrap();
assert!(!stored.contains(secret));
assert!(!stored.contains(&issued.code));
}
#[tokio::test]
async fn revoked_and_expired_tokens_are_refused() {
let clock = adk_core::ManualClock::new(Utc::now());
let pairing =
pairing().with_device_ttl(Duration::from_secs(60)).with_clock(Arc::new(clock.clone()));
let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
let claimed = pairing.claim(&issued.code, None).await.unwrap();
pairing.revoke(&claimed.device.id).await.unwrap();
let error = pairing.authenticate(&claimed.token).await.unwrap_err();
assert!(error.to_string().contains("was removed"), "{error}");
let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
let claimed = pairing.claim(&issued.code, None).await.unwrap();
clock.advance(Duration::from_secs(61));
let error = pairing.authenticate(&claimed.token).await.unwrap_err();
assert!(error.to_string().contains("pairing ended"), "{error}");
let refused = pairing
.issue(IssueCode::new("ana", ["operator"]).with_device_ttl(Duration::ZERO))
.await
.unwrap_err();
assert!(matches!(refused, KernelError::Config { .. }), "a zero-length pairing is refused");
}
#[tokio::test]
async fn a_wrong_secret_is_refused() {
let pairing = pairing();
let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
let claimed = pairing.claim(&issued.code, None).await.unwrap();
let last = if claimed.token.ends_with('0') { '1' } else { '0' };
let forged = format!("{}{last}", &claimed.token[..claimed.token.len() - 1]);
assert!(matches!(
pairing.authenticate(&forged).await,
Err(KernelError::Unauthorized { .. })
));
}
#[tokio::test]
async fn twenty_wrong_codes_cancel_every_waiting_code() {
let pairing = pairing();
let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
for _ in 0..MAX_FAILED_CLAIMS {
assert!(pairing.claim("0000-0000", None).await.is_err());
}
assert!(pairing.claim(&issued.code, None).await.is_err(), "the lockout cancelled it");
}
#[tokio::test]
async fn authorize_opens_only_the_scoped_routes() {
let pairing = pairing();
let issued = pairing
.issue(IssueCode::new("ana", ["operator"]).with_scopes([DeviceScope::Read]))
.await
.unwrap();
let token = pairing.claim(&issued.code, None).await.unwrap().token;
let context = pairing.authorize(&token, &Method::GET, "/api/approvals").await.unwrap();
assert_eq!(context.user_id, "ana");
assert_eq!(context.scopes, ["operator"]);
let error =
pairing.authorize(&token, &Method::POST, "/api/approvals/x/decide").await.unwrap_err();
assert_eq!(AdkError::from(error).category, ErrorCategory::Forbidden);
let error =
pairing.authorize(&token, &Method::POST, "/api/kernel/unfreeze").await.unwrap_err();
assert_eq!(AdkError::from(error).category, ErrorCategory::Forbidden);
}
}