use std::sync::Arc;
use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind};
use adk_core::principal::SubjectRef;
use adk_core::{ApprovalRequest, ApprovalRisk, RequestContext};
use axum::body::Body;
use axum::extract::{Path as UrlPath, State};
use axum::http::{Method, Request};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::json;
use super::routes::{Caller, ControlBackend, record};
use super::{ControlTransport, paths};
use crate::audit;
use crate::error::{KernelError, Result};
use crate::pairing::{
ClaimedDevice, DEVICE_ID_METADATA, DEVICE_NAME_METADATA, DeviceAdmission, DeviceKind,
DeviceScope, DeviceView, IssueCode, IssuedCode, Pairing, device_scope_for, device_token,
};
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IssueRequest {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub scopes: Vec<DeviceScope>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_in_days: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<DeviceKind>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClaimRequest {
pub code: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DevicesResponse {
pub devices: Vec<DeviceView>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeviceResponse {
pub device: DeviceView,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AcceptChannelRequest {
pub code: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum ChannelAccountState {
Active,
Revoked,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ChannelAccountView {
pub id: String,
pub channel: String,
pub account: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
pub user_id: String,
pub paired_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revoked_at: Option<DateTime<Utc>>,
pub state: ChannelAccountState,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ChannelPairingView {
pub id: String,
pub channel: String,
pub account: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
pub requested_at: DateTime<Utc>,
pub expires_at: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChannelAccountsResponse {
pub accounts: Vec<ChannelAccountView>,
pub waiting: Vec<ChannelPairingView>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChannelPairingResponse {
pub waiting: ChannelPairingView,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChannelAccountResponse {
pub account: ChannelAccountView,
}
type Backend = State<Arc<dyn ControlBackend>>;
pub(super) fn routes(backend: Arc<dyn ControlBackend>) -> Router {
Router::new()
.route(paths::PAIRING, post(issue))
.route(paths::DEVICES, get(devices))
.route(paths::DEVICE_REVOKE, post(revoke))
.route(paths::CHANNELS, get(channels::list))
.route(paths::CHANNEL_PAIR, post(channels::accept))
.route(paths::CHANNEL_REVOKE, post(channels::revoke))
.route(paths::CHANNEL_DISMISS, post(channels::dismiss))
.with_state(backend)
}
pub(super) fn claim_routes(backend: Arc<dyn ControlBackend>) -> Router {
Router::new()
.route(&format!("{}{}", paths::API_PREFIX, paths::PAIRING_CLAIM), post(claim))
.with_state(backend)
}
fn pairing_of(backend: &dyn ControlBackend) -> Result<Pairing> {
backend.pairing().ok_or_else(|| KernelError::Config {
reason: "this kernel pairs no devices: set ControlPlaneConfig::with_pairing, as \
`adk-rust up` does"
.into(),
})
}
async fn issue(
State(backend): Backend,
caller: Caller,
Json(request): Json<IssueRequest>,
) -> Result<Json<IssuedCode>> {
caller.require_operator("issue a pairing code")?;
let pairing = pairing_of(backend.as_ref())?;
let mut code = IssueCode::new(caller.context.user_id.clone(), caller.context.scopes.clone())
.with_scopes(request.scopes.iter().copied());
if let Some(name) = &request.name {
code = code.with_name(name);
}
if let Some(days) = request.expires_in_days {
code = code.with_device_ttl(std::time::Duration::from_secs(u64::from(days) * 86_400));
}
if let Some(kind) = request.kind {
code = code.with_kind(kind);
}
let code = code.normalized();
pairing.check(&code)?;
let (surface, how) = operator_surface(caller.transport);
let extra = [
("surface", json!(surface)),
("how", json!(how)),
("scopes", json!(code.scopes)),
("name", json!(code.name)),
("expiresInDays", json!(request.expires_in_days)),
("kind", json!(code.kind.unwrap_or(DeviceKind::Terminal))),
];
record(backend.as_ref(), &caller, "pairing.issue", None, &extra).await?;
Ok(Json(pairing.issue(code).await?))
}
async fn claim(
State(backend): Backend,
Json(request): Json<ClaimRequest>,
) -> Result<Json<ClaimedDevice>> {
let pairing = pairing_of(backend.as_ref())?;
let pending = pairing.take_for_claim(&request.code, request.name.as_deref()).await?;
let device = pending.device();
let (surface, how) = kind_surface(Some(device.kind().as_str()));
let extra = [
("surface", json!(surface)),
("how", json!(how)),
("device", json!(device.id)),
("name", json!(device.name)),
("scopes", json!(device.scopes)),
];
let recorded = record_as(
backend.as_ref(),
SubjectRef::human(device.owner.clone()),
ControlTransport::Http,
"pairing.claim",
Some(&device.id),
&extra,
)
.await;
if let Err(error) = recorded {
pairing.abandon_claim(pending).await;
return Err(error);
}
Ok(Json(pairing.finish_claim(pending).await?))
}
async fn devices(State(backend): Backend, caller: Caller) -> Result<Json<DevicesResponse>> {
caller.require_operator("list the paired devices")?;
let pairing = pairing_of(backend.as_ref())?;
let now = pairing.now();
let devices = pairing.devices().await?.iter().map(|device| device.view(now)).collect();
Ok(Json(DevicesResponse { devices }))
}
async fn revoke(
State(backend): Backend,
caller: Caller,
UrlPath(id): UrlPath<String>,
) -> Result<Json<DeviceResponse>> {
caller.require_operator("remove a paired device")?;
let pairing = pairing_of(backend.as_ref())?;
record(backend.as_ref(), &caller, "devices.revoke", Some(&id), &[]).await?;
let device = pairing.revoke(&id).await?;
Ok(Json(DeviceResponse { device: device.view(pairing.now()) }))
}
pub(super) async fn record_as(
backend: &dyn ControlBackend,
subject: SubjectRef,
transport: ControlTransport,
action: &str,
target: Option<&str>,
extra: &[(&str, serde_json::Value)],
) -> Result<()> {
tracing::info!(
control.action = action,
control.subject = %subject.id,
control.transport = ?transport,
control.target = target.unwrap_or_default(),
"kernel control action"
);
let Some(trail) = backend.audit_trail() else {
return Ok(());
};
let draft = AuditRecordDraft::new(
AuditRecordKind::Other(audit::KERNEL_AUDIT_KIND.into()),
audit::CONTROL,
)
.actor(AuditActor::subject(subject.clone()))
.ext("subject", json!(subject))
.ext("transport", json!(transport))
.ext("action", json!(action))
.ext("target", json!(target));
let draft = extra.iter().fold(draft, |draft, (key, value)| draft.ext(*key, value.clone()));
trail.record(draft).await.map_err(KernelError::from)
}
const MAX_DECIDE_BODY: usize = 2 * 1024 * 1024;
pub(crate) fn rated_high(
kernel: Option<&crate::kernel::Kernel>,
request: &ApprovalRequest,
) -> bool {
#[cfg(feature = "drivers")]
if let Some(drivers) = kernel.and_then(crate::kernel::Kernel::drivers) {
return drivers
.mounted()
.iter()
.filter_map(|id| drivers.record(id))
.any(|record| record.manifest.class_of(&request.tool_name).is_never_auto_allowed());
}
let _ = (kernel, request);
false
}
pub(super) async fn admit_device(
backend: &dyn ControlBackend,
pairing: &Pairing,
token: &str,
method: &Method,
path: &str,
answer: Option<&str>,
) -> std::result::Result<RequestContext, Response> {
let context =
pairing.authorize(token, method, path).await.map_err(IntoResponse::into_response)?;
if device_scope_for(method, path) != Some(DeviceScope::Decide) {
return Ok(context);
}
let segments: Vec<&str> = path.split('/').filter(|segment| !segment.is_empty()).collect();
let id = percent_decode(segments.iter().rev().nth(1).copied().unwrap_or_default());
let Some(approvals) = backend.approvals() else {
return Err(crate::pairing::forbidden(
"this kernel cannot check a decision's risk for a device: decide it in the home".into(),
)
.into_response());
};
match approvals.get(&id).await {
Ok(Some(request))
if request.risk >= ApprovalRisk::High || rated_high(backend.kernel(), &request) =>
{
return Err(crate::pairing::forbidden(
"this decision is high risk: confirm it's you and approve it in the home".into(),
)
.into_response());
}
Ok(Some(request))
if request.tool_name == crate::pairing::TAKE_OVER_TOOL && answer != Some("reject") =>
{
return Err(crate::pairing::forbidden(
"this decision asks you to type a secret: take over in the home".into(),
)
.into_response());
}
Ok(_) => {}
Err(error) => return Err(KernelError::Core(error).into_response()),
}
let device = context.metadata.get(DEVICE_ID_METADATA).cloned();
let name = context.metadata.get(DEVICE_NAME_METADATA).cloned();
let (surface, how) = device_surface(&context);
let extra = [
("surface", json!(surface)),
("how", json!(how)),
("device", json!(device)),
("deviceName", json!(name)),
("answer", json!(answer)),
];
record_as(
backend,
SubjectRef::human(context.user_id.clone()),
ControlTransport::Http,
"approvals.decide",
Some(&id),
&extra,
)
.await
.map_err(IntoResponse::into_response)?;
Ok(context)
}
fn device_surface(context: &RequestContext) -> (&'static str, &'static str) {
kind_surface(context.metadata.get(crate::pairing::DEVICE_KIND_METADATA).map(String::as_str))
}
fn kind_surface(kind: Option<&str>) -> (&'static str, &'static str) {
match kind {
Some("phone") => ("phone", "touch"),
Some("tray") => ("tray", "pointer"),
_ => ("terminal", "keyboard"),
}
}
fn operator_surface(transport: ControlTransport) -> (&'static str, &'static str) {
match transport {
ControlTransport::Socket | ControlTransport::Pipe => ("terminal", "keyboard"),
ControlTransport::Http => ("api", "api"),
}
}
pub(super) async fn read_answer(
request: Request<Body>,
) -> std::result::Result<(Request<Body>, Option<String>), Response> {
if device_scope_for(request.method(), request.uri().path()) != Some(DeviceScope::Decide) {
return Ok((request, None));
}
let (parts, body) = request.into_parts();
let Ok(bytes) = axum::body::to_bytes(body, MAX_DECIDE_BODY).await else {
return Err(axum::http::StatusCode::PAYLOAD_TOO_LARGE.into_response());
};
let answer = serde_json::from_slice::<serde_json::Value>(&bytes)
.ok()
.and_then(|body| body.get("action")?.as_str().map(str::to_string));
Ok((Request::from_parts(parts, Body::from(bytes)), answer))
}
fn percent_decode(segment: &str) -> String {
let bytes = segment.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
let hex = |at: usize| bytes.get(at).and_then(|byte| (*byte as char).to_digit(16));
match (bytes[index], hex(index + 1), hex(index + 2)) {
(b'%', Some(high), Some(low)) => {
out.push(u8::try_from(high * 16 + low).unwrap_or_default());
index += 3;
}
(byte, _, _) => {
out.push(byte);
index += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}
fn is_claim(method: &Method, path: &str) -> bool {
*method == Method::POST
&& path.strip_prefix(paths::API_PREFIX).unwrap_or(path) == paths::PAIRING_CLAIM
}
pub(super) fn guard(backend: Arc<dyn ControlBackend>, router: Router) -> Router {
router.layer(middleware::from_fn(move |request: Request<Body>, next: Next| {
let backend = backend.clone();
async move {
let Some(pairing) = backend.pairing() else {
return next.run(request).await;
};
let Some(token) = device_token(request.headers()).map(str::to_string) else {
return next.run(request).await;
};
let method = request.method().clone();
let path = request.uri().path().to_string();
if is_claim(&method, &path) {
return next.run(request).await;
}
let (request, answer) = match read_answer(request).await {
Ok(read) => read,
Err(response) => return response,
};
match admit_device(
backend.as_ref(),
&pairing,
&token,
&method,
&path,
answer.as_deref(),
)
.await
{
Ok(context) => {
let mut request = request;
if let Some(device) = context.metadata.get(DEVICE_ID_METADATA) {
request.extensions_mut().insert(DeviceAdmission { device: device.clone() });
}
next.run(request).await
}
Err(response) => response,
}
}
}))
}
mod channels {
use axum::Json;
use axum::extract::{Path as UrlPath, State};
use super::{
AcceptChannelRequest, Backend, Caller, ChannelAccountResponse, ChannelAccountsResponse,
ChannelPairingResponse,
};
use crate::error::{KernelError, Result};
fn no_account(id: &str) -> KernelError {
KernelError::Core(adk_core::AdkError::new(
adk_core::ErrorComponent::Server,
adk_core::ErrorCategory::NotFound,
crate::error::NOT_FOUND_CODE,
format!("no chat account {id}: list them with `adk-rust pair list`"),
))
}
#[cfg(feature = "channels")]
fn bindings(
backend: &dyn super::ControlBackend,
) -> Option<(crate::pairing::Pairing, std::sync::Arc<dyn crate::channels::ChannelBindingStore>)>
{
let pairing = backend.pairing()?;
let store = pairing.channel_bindings().cloned()?;
Some((pairing, store))
}
pub(super) async fn list(
State(backend): Backend,
caller: Caller,
) -> Result<Json<ChannelAccountsResponse>> {
caller.require_operator("list the paired chat accounts")?;
let empty = ChannelAccountsResponse { accounts: Vec::new(), waiting: Vec::new() };
#[cfg(feature = "channels")]
if let Some((pairing, store)) = bindings(backend.as_ref()) {
let now = pairing.now();
let accounts =
store.list_bindings().await?.iter().map(|binding| binding.view()).collect();
let waiting = store
.list_requests()
.await?
.iter()
.filter(|request| !request.dismissed && request.expires_at > now)
.map(|request| request.view())
.collect();
return Ok(Json(ChannelAccountsResponse { accounts, waiting }));
}
let _ = backend;
Ok(Json(empty))
}
pub(super) async fn accept(
State(backend): Backend,
caller: Caller,
Json(request): Json<AcceptChannelRequest>,
) -> Result<Json<ChannelAccountResponse>> {
caller.require_operator("pair a chat account")?;
#[cfg(feature = "channels")]
{
let (pairing, store) =
bindings(backend.as_ref()).ok_or_else(|| KernelError::Config {
reason: "this kernel pairs no chat accounts: no chat channel is connected to \
it (Pairing::with_channel_bindings)"
.into(),
})?;
let now = pairing.now();
let waiting = crate::channels::take_pairing(store.as_ref(), &request.code, now).await?;
let binding = crate::channels::binding_for(
&waiting,
&caller.context.user_id,
&caller.context.scopes,
now,
);
let extra = [
("channel", serde_json::json!(binding.channel)),
("account", serde_json::json!(binding.account)),
];
let recorded = super::record(
backend.as_ref(),
&caller,
"channels.pair",
Some(&binding.id),
&extra,
)
.await;
if let Err(error) = recorded {
crate::channels::restore_pairing(store.as_ref(), waiting).await;
return Err(error);
}
if let Err(error) = store.put_binding(binding.clone()).await {
crate::channels::restore_pairing(store.as_ref(), waiting).await;
return Err(error);
}
Ok(Json(ChannelAccountResponse { account: binding.view() }))
}
#[cfg(not(feature = "channels"))]
{
let _ = (backend, request);
Err(KernelError::Config {
reason: "this kernel has no chat channels: it was built without adk-kernel's \
`channels` feature, so no chat account can be paired with it"
.into(),
})
}
}
pub(super) async fn revoke(
State(backend): Backend,
caller: Caller,
UrlPath(id): UrlPath<String>,
) -> Result<Json<ChannelAccountResponse>> {
caller.require_operator("remove a chat account")?;
#[cfg(feature = "channels")]
if let Some((pairing, store)) = bindings(backend.as_ref())
&& store.get_binding(&id).await?.is_some()
{
super::record(backend.as_ref(), &caller, "channels.revoke", Some(&id), &[]).await?;
let binding =
crate::channels::revoke_binding(store.as_ref(), &id, pairing.now()).await?;
if let Some(kernel) = backend.kernel() {
crate::channels::stop_account_turns(kernel, &binding.channel, &binding.account)
.await;
}
return Ok(Json(ChannelAccountResponse { account: binding.view() }));
}
let _ = backend;
Err(no_account(&id))
}
pub(super) async fn dismiss(
State(backend): Backend,
caller: Caller,
UrlPath(id): UrlPath<String>,
) -> Result<Json<ChannelPairingResponse>> {
caller.require_operator("dismiss a chat account waiting to be paired")?;
#[cfg(feature = "channels")]
if let Some((pairing, store)) = bindings(backend.as_ref())
&& let Some(waiting) = crate::channels::waiting_request(store.as_ref(), &id).await?
{
super::record(backend.as_ref(), &caller, "channels.dismiss", Some(&id), &[]).await?;
crate::channels::dismiss_request(store.as_ref(), &waiting, pairing.now()).await?;
return Ok(Json(ChannelPairingResponse { waiting: waiting.view() }));
}
let _ = backend;
Err(no_account(&id))
}
}
#[cfg(test)]
mod tests {
use super::percent_decode;
#[test]
fn path_segments_decode_as_the_router_decodes_them() {
assert_eq!(percent_decode("apr_1f"), "apr_1f");
assert_eq!(percent_decode("a%2Fb%20c"), "a/b c");
assert_eq!(percent_decode("bad%2"), "bad%2");
assert_eq!(percent_decode("%E6%97%A5"), "日");
}
}