Skip to main content

agentmux_srv/server/app_api/
aws_grants.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The AWS grants a host shares with its container agents, as the broker has them: `GET /api/v1/aws/grants` lists each
5//! grant with whether it is in force, when it was added and by which recorded change, and `POST
6//! /api/v1/aws/grants/decide` answers a grant that is new or wider than what was allowed (`identity::aws_broker::record`).
7//!
8//! Any agent may read the list. Only a native agent may answer: a container agent is the one a grant is for, so it
9//! cannot allow its own. The answer needs a reason, is recorded under the agent's name in the Audit view and in the
10//! record, and takes effect on the next request for credentials.
11
12use axum::extract::{Extension, State};
13use axum::http::StatusCode;
14use axum::response::{IntoResponse, Response};
15use axum::Json;
16use serde::Deserialize;
17use serde_json::json;
18
19use super::AppState;
20use crate::identity::aws_broker::{policy, record};
21use crate::server::caller::Caller;
22
23#[derive(Debug, Deserialize)]
24pub(crate) struct DecideRequest {
25    pub(crate) grant: String,
26    /// The change the answerer read in the list; an answer to a grant that has changed since is refused.
27    pub(crate) change: String,
28    /// `allow` or `remove`.
29    pub(crate) decision: String,
30    pub(crate) reason: String,
31}
32
33fn refuse(status: StatusCode, message: impl Into<String>) -> Response {
34    (status, Json(json!({ "error": message.into() }))).into_response()
35}
36
37/// The agent the token was minted for, and whether it runs in a container.
38async fn agent_of(state: &AppState, caller: Option<&Caller>) -> Result<(String, bool), Response> {
39    let Some(uid) = caller.and_then(Caller::uid).map(str::to_string) else {
40        return Err(refuse(StatusCode::UNAUTHORIZED, "no agent token: the AWS grants are for an agent to read and answer"));
41    };
42    let mstore = state.mstore.clone();
43    match tokio::task::spawn_blocking(move || mstore.agent_def_get(&uid)).await {
44        Ok(Ok(Some(def))) => Ok((def.slug.clone(), def.runtime().is_container())),
45        Ok(Ok(None)) => Err(refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine")),
46        _ => Err(refuse(StatusCode::INTERNAL_SERVER_ERROR, "couldn't read the agent")),
47    }
48}
49
50/// `GET /api/v1/aws/grants`
51pub(crate) async fn handle_aws_grants(State(state): State<AppState>, caller: Option<Extension<Caller>>) -> Response {
52    if let Err(r) = agent_of(&state, caller.as_ref().map(|Extension(c)| c)).await {
53        return r;
54    }
55    match tokio::task::spawn_blocking(policy::view).await {
56        Ok(Ok(view)) => Json(view).into_response(),
57        Ok(Err(e)) => refuse(StatusCode::SERVICE_UNAVAILABLE, e),
58        Err(e) => refuse(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
59    }
60}
61
62/// `POST /api/v1/aws/grants/decide`
63pub(crate) async fn handle_aws_grant_decide(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<DecideRequest>) -> Response {
64    let (slug, container) = match agent_of(&state, caller.as_ref().map(|Extension(c)| c)).await {
65        Ok(who) => who,
66        Err(r) => return r,
67    };
68    if container {
69        return refuse(StatusCode::FORBIDDEN, "A container agent can't answer for the grants it may use: a native agent (a leader or the host's steward) answers, saying why.");
70    }
71    let allow = match req.decision.trim() {
72        "allow" => true,
73        "remove" => false,
74        other => return refuse(StatusCode::BAD_REQUEST, format!("decision {other:?} is not allow or remove")),
75    };
76    let result = tokio::task::spawn_blocking(move || {
77        policy::decide(&record::Decision { grant: req.grant.trim(), change: req.change.trim(), allow, by: &slug, reason: &req.reason })
78    })
79    .await;
80    match result {
81        Ok(Ok(event)) => Json(json!({ "ok": true, "change": event.id, "grant": event.grant, "text": event.text })).into_response(),
82        Ok(Err(e)) => refuse(StatusCode::BAD_REQUEST, e),
83        Err(e) => refuse(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
84    }
85}
86
87#[cfg(test)]
88#[path = "tests/aws_grants_tests.rs"]
89mod tests;