use std::collections::BTreeMap;
use std::sync::Arc;
use adk_core::audit_log::{AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind};
use adk_core::principal::SubjectRef;
use adk_core::{
AdkError, ApprovalAction, ApprovalRequest, ApprovalRisk, ApprovalState, ErrorCategory,
ErrorComponent,
};
use async_trait::async_trait;
use axum::Json;
use axum::Router;
use axum::extract::{Extension, Path as UrlPath, State};
use axum::http::Method;
use axum::routing::{get, post};
use serde::{Deserialize, Serialize};
use serde_json::json;
use super::client::encode;
use super::routes::{Caller, ControlBackend, record};
use super::server::PeerProcess;
use super::settings::require_owner;
use super::{ControlTransport, paths};
use crate::error::{
CONFIG_CODE, FROZEN_CODE, INVALID_STATE_CODE, KernelError, NOT_FOUND_CODE, Result,
};
const RECORDED_ARGS: usize = 200;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CommandInfo {
pub name: String,
pub description: String,
}
impl CommandInfo {
pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
Self { name: name.into(), description: description.into() }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CommandReach {
pub transport: ControlTransport,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub device: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub peer_pid: Option<u32>,
}
impl CommandReach {
pub fn new(transport: ControlTransport) -> Self {
Self { transport, device: None, peer_pid: None }
}
#[must_use]
pub fn with_device(mut self, device: impl Into<String>) -> Self {
self.device = Some(device.into());
self
}
#[must_use]
pub fn with_peer_pid(mut self, pid: u32) -> Self {
self.peer_pid = Some(pid);
self
}
pub fn is_local(&self) -> bool {
matches!(self.transport, ControlTransport::Socket | ControlTransport::Pipe)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CommandCall {
pub user: String,
pub session: String,
pub name: String,
pub args: String,
pub reach: CommandReach,
}
impl CommandCall {
pub fn new(
user: impl Into<String>,
session: impl Into<String>,
name: impl Into<String>,
args: impl Into<String>,
reach: CommandReach,
) -> Self {
Self {
user: user.into(),
session: session.into(),
name: name.into(),
args: args.into(),
reach,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandsResponse {
pub commands: Vec<CommandInfo>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RunCommandRequest {
pub name: String,
#[serde(default)]
pub args: String,
pub session_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RunCommandResponse {
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlwaysAllowResponse {
pub label: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionModeResponse {
pub mode: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SurfaceRecord {
pub kind: AuditRecordKind,
pub action: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub decision: Option<AuditDecision>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub ext: BTreeMap<String, serde_json::Value>,
}
impl SurfaceRecord {
pub fn new(kind: AuditRecordKind, action: impl Into<String>) -> Self {
Self { kind, action: action.into(), decision: None, ext: BTreeMap::new() }
}
#[must_use]
pub fn with_decision(mut self, decision: AuditDecision) -> Self {
self.decision = Some(decision);
self
}
#[must_use]
pub fn with_ext(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
self.ext.insert(key.into(), value);
self
}
}
const SURFACE_ACTIONS: &str = "surface.";
const KERNEL_FIELDS: &[&str] = &["transport", "device", "deviceName", "presence"];
#[async_trait]
pub trait CommandHost: Send + Sync {
fn commands(&self) -> Vec<CommandInfo>;
fn changes(&self, name: &str, args: &str) -> bool;
async fn tightens(&self, call: &CommandCall) -> Result<bool> {
let _ = call;
Ok(false)
}
async fn session_mode(&self, user: &str, session: &str) -> Result<Option<String>> {
let _ = (user, session);
Ok(None)
}
async fn run(&self, call: &CommandCall) -> Result<String>;
async fn always_allow_offer(&self, request: &ApprovalRequest) -> Result<Option<String>> {
let _ = request;
Ok(None)
}
async fn prepare_always_allow(
&self,
request: &ApprovalRequest,
by: &SubjectRef,
) -> Result<String> {
let _ = (request, by);
Err(no_rules())
}
async fn grant_always_allow(&self, request: &ApprovalRequest) -> Result<()> {
let _ = request;
Err(no_rules())
}
}
fn no_rules() -> KernelError {
KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::InvalidInput,
CONFIG_CODE,
"this kernel makes no standing rules from a decision: allow it once",
))
}
type Backend = State<Arc<dyn ControlBackend>>;
pub(super) fn routes() -> Router<Arc<dyn ControlBackend>> {
Router::new()
.route(paths::COMMANDS, get(list))
.route(paths::COMMAND_RUN, post(run))
.route(paths::ALWAYS_ALLOW, get(offer))
.route(paths::ALWAYS_ALLOW_PREPARE, post(prepare))
.route(paths::ALWAYS_ALLOW_GRANT, post(grant))
.route(paths::SESSION_MODE, get(session_mode))
.route(paths::SURFACE_RECORDS, post(surface_record))
}
fn host_of(backend: &dyn ControlBackend) -> Result<Arc<dyn CommandHost>> {
backend.kernel().and_then(|kernel| kernel.config().control.commands.clone()).ok_or_else(|| {
KernelError::Config {
reason: "this kernel offers no commands: set ControlPlaneConfig::with_commands, as \
`adk-rust up` does"
.into(),
}
})
}
async fn list(State(backend): Backend, caller: Caller) -> Result<Json<CommandsResponse>> {
require_owner(&caller, "use the REPL's commands")?;
Ok(Json(CommandsResponse { commands: host_of(backend.as_ref())?.commands() }))
}
async fn run(
State(backend): Backend,
caller: Caller,
peer: Option<Extension<PeerProcess>>,
Json(request): Json<RunCommandRequest>,
) -> Result<Json<RunCommandResponse>> {
require_owner(&caller, "run the REPL's commands")?;
let host = host_of(backend.as_ref())?;
let RunCommandRequest { name, args, session_id } = request;
let args = args.trim().to_string();
if !host.commands().iter().any(|command| command.name == name) {
return Err(KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::NotFound,
NOT_FOUND_CODE,
format!("no command /{name} on this kernel; /help lists them"),
)));
}
let changes = host.changes(&name, &args);
let mut reach = CommandReach::new(caller.transport);
if let Some(device) = caller.context.metadata.get(crate::pairing::DEVICE_ID_METADATA) {
reach = reach.with_device(device.clone());
}
if let Some(Extension(PeerProcess(pid))) = peer {
reach = reach.with_peer_pid(pid);
}
let recorded: String = args.chars().take(RECORDED_ARGS).collect();
let call = CommandCall::new(caller.context.user_id.clone(), &session_id, &name, args, reach);
let governance = backend.governance();
if changes && governance.is_frozen() && !host.tightens(&call).await? {
let reason = governance.reason().unwrap_or_default();
return Err(KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::Conflict,
FROZEN_CODE,
format!(
"everything is stopped ({reason}), so /{name} cannot let the agents do more \
until you resume all; what makes them do less still runs"
),
)));
}
let extra = [
("session", json!(session_id)),
("args", json!(recorded)),
("changes", json!(changes)),
("reach", json!(call.reach)),
];
record(backend.as_ref(), &caller, "commands.run", Some(&name), &extra).await?;
let text = host.run(&call).await?;
Ok(Json(RunCommandResponse { text }))
}
async fn owned_request(
backend: &dyn ControlBackend,
caller: &Caller,
id: &str,
) -> Result<ApprovalRequest> {
let approvals = backend.approvals().ok_or_else(|| KernelError::Config {
reason: "this kernel has no approvals inbox; start it with an approval service".into(),
})?;
approvals
.get(id)
.await?
.filter(|request| request.scope.user_id == caller.context.user_id)
.ok_or_else(|| {
KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::NotFound,
NOT_FOUND_CODE,
format!("no decision {id} of yours"),
))
})
}
async fn waiting(
backend: &dyn ControlBackend,
caller: &Caller,
id: &str,
) -> Result<ApprovalRequest> {
let request = owned_request(backend, caller, id).await?;
if request.state != ApprovalState::Pending {
return Err(KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::Conflict,
INVALID_STATE_CODE,
format!("decision {id} is no longer waiting"),
)));
}
Ok(request)
}
fn high_risk(backend: &dyn ControlBackend, request: &ApprovalRequest) -> bool {
request.risk >= ApprovalRisk::High || super::pairing::rated_high(backend.kernel(), request)
}
fn no_rule_applies() -> KernelError {
KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::NotFound,
NOT_FOUND_CODE,
"no standing rule applies to this call; allow it once",
))
}
async fn offer(
State(backend): Backend,
caller: Caller,
UrlPath(id): UrlPath<String>,
) -> Result<Json<AlwaysAllowResponse>> {
require_owner(&caller, "see what Always allow creates")?;
let host = host_of(backend.as_ref())?;
let request = waiting(backend.as_ref(), &caller, &id).await?;
if high_risk(backend.as_ref(), &request) {
return Err(no_rule_applies());
}
match host.always_allow_offer(&request).await? {
Some(label) => Ok(Json(AlwaysAllowResponse { label })),
None => Err(no_rule_applies()),
}
}
async fn prepare(
State(backend): Backend,
caller: Caller,
UrlPath(id): UrlPath<String>,
) -> Result<Json<AlwaysAllowResponse>> {
require_owner(&caller, "create a standing rule")?;
let host = host_of(backend.as_ref())?;
let request = waiting(backend.as_ref(), &caller, &id).await?;
if high_risk(backend.as_ref(), &request) {
return Err(crate::pairing::forbidden(format!(
"decision {id} is high risk: no standing rule is ever made of it; allow it once"
)));
}
let label = host.prepare_always_allow(&request, &caller.subject()).await?;
Ok(Json(AlwaysAllowResponse { label }))
}
async fn grant(
State(backend): Backend,
caller: Caller,
UrlPath(id): UrlPath<String>,
) -> Result<Json<serde_json::Value>> {
require_owner(&caller, "create a standing rule")?;
let host = host_of(backend.as_ref())?;
let request = owned_request(backend.as_ref(), &caller, &id).await?;
let own_yes = request.decisions.last().is_some_and(|decision| {
decision.kind == ApprovalAction::Approve && decision.approver.id == caller.context.user_id
});
if request.state != ApprovalState::Approved || !own_yes || high_risk(backend.as_ref(), &request)
{
return Err(KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::Conflict,
INVALID_STATE_CODE,
format!("decision {id} was not allowed by your yes, so no rule is made from it"),
)));
}
record(backend.as_ref(), &caller, "rules.always_allow", Some(&id), &[]).await?;
host.grant_always_allow(&request).await?;
Ok(Json(json!({ "granted": id })))
}
async fn session_mode(
State(backend): Backend,
caller: Caller,
UrlPath(session): UrlPath<String>,
) -> Result<Json<SessionModeResponse>> {
require_owner(&caller, "read a session's mode")?;
let host = host_of(backend.as_ref())?;
match host.session_mode(&caller.context.user_id, &session).await? {
Some(mode) => Ok(Json(SessionModeResponse { mode })),
None => Err(KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::NotFound,
NOT_FOUND_CODE,
"this kernel keeps no mode for its sessions",
))),
}
}
async fn surface_record(
State(backend): Backend,
caller: Caller,
Json(record): Json<SurfaceRecord>,
) -> Result<Json<serde_json::Value>> {
require_owner(&caller, "write a surface's records")?;
let SurfaceRecord { kind, action, decision, ext } = record;
let kinds = [
AuditRecordKind::Approval,
AuditRecordKind::Governance,
AuditRecordKind::Configuration,
AuditRecordKind::Other("surface".into()),
];
if !action.starts_with(SURFACE_ACTIONS) || !kinds.contains(&kind) {
return Err(KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::InvalidInput,
CONFIG_CODE,
format!("only a surface's records (`surface.…`) are written here, not `{action}`"),
)));
}
if let Some(id) = ext.get("approvalId") {
let id = id.as_str().unwrap_or_default();
owned_request(backend.as_ref(), &caller, id).await?;
}
let Some(trail) = backend.audit_trail() else {
return Ok(Json(json!({ "recorded": false })));
};
let mut draft =
AuditRecordDraft::new(kind, action).actor(AuditActor::subject(caller.subject()));
if let Some(decision) = decision {
draft = draft.decision(decision);
}
for (key, value) in ext {
if !KERNEL_FIELDS.contains(&key.as_str()) {
draft = draft.ext(key, value);
}
}
draft = draft.ext("transport", json!(caller.transport));
trail.record(draft).await?;
Ok(Json(json!({ "recorded": true })))
}
impl super::ControlClient {
pub async fn commands(&self) -> Result<Vec<CommandInfo>> {
let answer: CommandsResponse =
self.call(Method::GET, paths::COMMANDS.to_string(), None::<&()>).await?;
Ok(answer.commands)
}
pub async fn run_command(&self, name: &str, args: &str, session: &str) -> Result<String> {
let body = RunCommandRequest {
name: name.to_string(),
args: args.to_string(),
session_id: session.to_string(),
};
let answer: RunCommandResponse =
self.call(Method::POST, paths::COMMAND_RUN.to_string(), Some(&body)).await?;
Ok(answer.text)
}
pub async fn always_allow_offer(&self, id: &str) -> Result<Option<String>> {
let path = paths::ALWAYS_ALLOW.replace("{id}", &encode(id));
match self.call::<AlwaysAllowResponse>(Method::GET, path, None::<&()>).await {
Ok(answer) => Ok(Some(answer.label)),
Err(error) if error.category() == ErrorCategory::NotFound => Ok(None),
Err(error) => Err(error),
}
}
pub async fn prepare_always_allow(&self, id: &str) -> Result<String> {
let path = paths::ALWAYS_ALLOW_PREPARE.replace("{id}", &encode(id));
let answer: AlwaysAllowResponse = self.call(Method::POST, path, Some(&())).await?;
Ok(answer.label)
}
pub async fn grant_always_allow(&self, id: &str) -> Result<()> {
let path = paths::ALWAYS_ALLOW_GRANT.replace("{id}", &encode(id));
let _: serde_json::Value = self.call(Method::POST, path, Some(&())).await?;
Ok(())
}
pub async fn session_mode(&self, session: &str) -> Result<Option<String>> {
let path = paths::SESSION_MODE.replace("{session}", &encode(session));
match self.call::<SessionModeResponse>(Method::GET, path, None::<&()>).await {
Ok(answer) => Ok(Some(answer.mode)),
Err(error) if error.category() == ErrorCategory::NotFound => Ok(None),
Err(error) => Err(error),
}
}
pub async fn record_surface(&self, record: &SurfaceRecord) -> Result<()> {
let path = paths::SURFACE_RECORDS.to_string();
let _: serde_json::Value = self.call(Method::POST, path, Some(record)).await?;
Ok(())
}
}