Skip to main content

trustee_api/
xagent.rs

1//! 16F: per-agent dispatch surface — `/xagent/{name}/api/v1/...`
2//!
3//! Closes the THQ dispatch gap: torpi's proxy forwards
4//! `/thq/api/agents/{id}/...` to `{endpoint}/api/v1/...` with the CALLER's
5//! Bearer injected, so until now THQ-dispatched sessions ran under the
6//! CALLER's identity (the owner), not the agent's. This module exposes the
7//! same handler surface under a per-agent path prefix and re-keys every
8//! request to the agent-user the THQ entry represents.
9//!
10//! Mechanism (impersonation by Bearer swap — zero handler duplication):
11//! 1. `{name}` resolves through the boot-time dispatch table
12//!    (`ServerState.thq_dispatch`, populated by 16E discovery) to the
13//!    agent-user's stable key (= its Kanidm `sub`, per the 16E pin).
14//! 2. The OUTER caller is gate-checked: human admin only
15//!    ([`crate::auth::check_dispatch_admin`]). Agents can never dispatch
16//!    agents; open mode follows the same open posture as `check_auth`.
17//! 3. The agent's service token (captured from its per-user `.env` at boot)
18//!    is exchanged for a short-lived `role=agent` access token (RFC 8693,
19//!    expiry-buffered cache). Open mode passes through unauthenticated,
20//!    matching `check_auth`'s open posture.
21//! 4. The inner request is rebuilt with `Authorization: Bearer <agent>` and
22//!    the caller's cookie STRIPPED, then the STANDARD handler runs: `check_auth`
23//!    authenticates the AGENT, Cedar applies the per-action agent matrix
24//!    (working set minus DeleteSession), `user_key` resolves to the agent's
25//!    sub, and session bucket / per-user home / MCP loader all resolve to the
26//!    agent's own namespace — her own fame, never the caller's tools.
27//!
28//! THQ-side wiring: set each agent-user's `[thq].advertise_url` to
29//! `https://<host>:<port>/xagent/<agent_name>` — torpi appends
30//! `/api/v1/...` to the advertised origin, landing here.
31
32use axum::extract::ws::WebSocketUpgrade;
33use axum::extract::{Path, State};
34use axum::http::{header, HeaderMap, StatusCode};
35use axum::response::{IntoResponse, Response};
36use axum::Json;
37
38use crate::routes;
39use crate::state::ServerState;
40
41/// Minimum identity for dispatched sessions whose create body carries none.
42/// Charters replace this per agent once drafted (owner-approved content);
43/// until then the agent at least knows its own name.
44fn default_identity(agent: &str) -> String {
45    format!("You are {agent}, an agent on the Tanbal platform.")
46}
47
48/// Resolve the dispatch target and rebuild the inner request headers with
49/// the AGENT's Bearer (cookie stripped). Shared prelude of every wrapper.
50async fn dispatch_context(
51    state: &ServerState,
52    agent: &str,
53    headers: &HeaderMap,
54) -> Result<HeaderMap, (StatusCode, String)> {
55    let Some(entry) = state.thq_dispatch.get(agent).map(|e| e.clone()) else {
56        return Err((StatusCode::NOT_FOUND, format!("unknown agent: {agent}")));
57    };
58    if entry.user_key.is_empty() {
59        return Err((
60            StatusCode::NOT_FOUND,
61            format!("agent {agent} has no owner_id — not dispatchable"),
62        ));
63    }
64
65    // Outer gate: human admin (open mode allowed, same posture as check_auth).
66    crate::auth::check_dispatch_admin(&state.auth, headers)
67        .await
68        .map_err(|s| {
69            (
70                s,
71                "xagent dispatch requires an admin Bearer token".to_string(),
72            )
73        })?;
74
75    // Inner identity: the agent's own short-lived Bearer.
76    let mut inner = headers.clone();
77
78    let Some(auth) = state.auth.as_ref() else {
79        // Open mode: no IdP to mint from — run the inner call unauthenticated,
80        // which check_auth resolves as the open-mode "default" user.
81        inner.remove(header::AUTHORIZATION);
82        inner.remove(header::COOKIE);
83        return Ok(inner);
84    };
85
86    let Some(ref service_token) = entry.service_token else {
87        return Err((
88            StatusCode::BAD_GATEWAY,
89            format!(
90                "agent {agent} has no service token provisioned (per-user .env) — cannot impersonate"
91            ),
92        ));
93    };
94
95    // Cache: (token, expires_at) with a 60s safety buffer (pep 0.5.6 lesson).
96    if let Some(kv) = state.agent_dispatch_tokens.get(&entry.user_key) {
97        let (tok, exp) = kv.value();
98        if std::time::Instant::now() < *exp {
99            inner.insert(
100                header::AUTHORIZATION,
101                format!("Bearer {tok}").parse().map_err(|_| {
102                    (
103                        StatusCode::INTERNAL_SERVER_ERROR,
104                        "header build".to_string(),
105                    )
106                })?,
107            );
108            inner.remove(header::COOKIE);
109            return Ok(inner);
110        }
111    }
112
113    let (token, expires_in) = auth
114        .exchange_agent_token(service_token)
115        .await
116        .map_err(|s| (s, "agent token exchange failed".to_string()))?;
117    let buffered = std::time::Duration::from_secs(expires_in.saturating_sub(60))
118        .max(std::time::Duration::from_secs(30));
119    state.agent_dispatch_tokens.insert(
120        entry.user_key.clone(),
121        (token.clone(), std::time::Instant::now() + buffered),
122    );
123
124    inner.insert(
125        header::AUTHORIZATION,
126        format!("Bearer {token}").parse().map_err(|_| {
127            (
128                StatusCode::INTERNAL_SERVER_ERROR,
129                "header build".to_string(),
130            )
131        })?,
132    );
133    inner.remove(header::COOKIE);
134    Ok(inner)
135}
136
137/// THQ polls `{advertise_url}/api/v1/health` for liveness — resolve the agent
138/// (unknown → 404 → THQ marks it offline) then answer with the shared health.
139pub async fn x_health(State(state): State<ServerState>, Path(agent): Path<String>) -> Response {
140    if !state.thq_dispatch.contains_key(&agent) {
141        return (StatusCode::NOT_FOUND, format!("unknown agent: {agent}")).into_response();
142    }
143    routes::health().await.into_response()
144}
145
146pub async fn x_list_sessions(
147    State(state): State<ServerState>,
148    Path(agent): Path<String>,
149    headers: HeaderMap,
150) -> Result<Response, (StatusCode, String)> {
151    let inner = dispatch_context(&state, &agent, &headers).await?;
152    routes::list_sessions(State(state), inner).await
153}
154
155pub async fn x_create_session(
156    State(state): State<ServerState>,
157    Path(agent): Path<String>,
158    headers: HeaderMap,
159    Json(mut req): Json<routes::CreateSessionRequest>,
160) -> Result<Response, (StatusCode, String)> {
161    let inner = dispatch_context(&state, &agent, &headers).await?;
162    if req.identity.is_none() {
163        req.identity = Some(default_identity(&agent));
164    }
165    routes::create_session(State(state), inner, Json(req)).await
166}
167
168pub async fn x_list_live_sessions(
169    State(state): State<ServerState>,
170    Path(agent): Path<String>,
171    headers: HeaderMap,
172) -> Result<Response, (StatusCode, String)> {
173    let inner = dispatch_context(&state, &agent, &headers).await?;
174    routes::list_live_sessions(State(state), inner).await
175}
176
177pub async fn x_get_session_detail(
178    State(state): State<ServerState>,
179    Path((agent, session_id)): Path<(String, String)>,
180    headers: HeaderMap,
181) -> Result<Response, (StatusCode, String)> {
182    let inner = dispatch_context(&state, &agent, &headers).await?;
183    routes::get_session_detail(State(state), Path(session_id), inner).await
184}
185
186pub async fn x_destroy_session(
187    State(state): State<ServerState>,
188    Path((agent, session_id)): Path<(String, String)>,
189    headers: HeaderMap,
190) -> Result<Response, (StatusCode, String)> {
191    let inner = dispatch_context(&state, &agent, &headers).await?;
192    routes::destroy_session(State(state), inner, Path(session_id)).await
193}
194
195pub async fn x_get_live_session(
196    State(state): State<ServerState>,
197    Path((agent, session_id)): Path<(String, String)>,
198    headers: HeaderMap,
199) -> Result<Response, (StatusCode, String)> {
200    let inner = dispatch_context(&state, &agent, &headers).await?;
201    routes::get_live_session(State(state), inner, Path(session_id)).await
202}
203
204pub async fn x_resume_session(
205    State(state): State<ServerState>,
206    Path((agent, checkpoint_session_id)): Path<(String, String)>,
207    headers: HeaderMap,
208    body: Option<Json<routes::ResumeRequestBody>>,
209) -> Result<Response, (StatusCode, String)> {
210    let inner = dispatch_context(&state, &agent, &headers).await?;
211    routes::resume_session(State(state), Path(checkpoint_session_id), inner, body).await
212}
213
214pub async fn x_get_session_history(
215    State(state): State<ServerState>,
216    Path((agent, session_id)): Path<(String, String)>,
217    headers: HeaderMap,
218) -> Result<Response, (StatusCode, String)> {
219    let inner = dispatch_context(&state, &agent, &headers).await?;
220    routes::get_session_history(State(state), Path(session_id), inner).await
221}
222
223pub async fn x_post_command_session(
224    State(state): State<ServerState>,
225    Path((agent, session_id)): Path<(String, String)>,
226    headers: HeaderMap,
227    Json(req): Json<routes::CommandRequest>,
228) -> Result<Response, (StatusCode, String)> {
229    let inner = dispatch_context(&state, &agent, &headers).await?;
230    routes::post_command_session(State(state), inner, Path(session_id), Json(req)).await
231}
232
233pub async fn x_post_cancel_session(
234    State(state): State<ServerState>,
235    Path((agent, session_id)): Path<(String, String)>,
236    headers: HeaderMap,
237) -> Result<Response, (StatusCode, String)> {
238    let inner = dispatch_context(&state, &agent, &headers).await?;
239    routes::post_cancel_session(State(state), inner, Path(session_id)).await
240}
241
242pub async fn x_post_handoff_session(
243    State(state): State<ServerState>,
244    Path((agent, session_id)): Path<(String, String)>,
245    headers: HeaderMap,
246) -> Result<Response, (StatusCode, String)> {
247    let inner = dispatch_context(&state, &agent, &headers).await?;
248    routes::post_handoff_session(State(state), inner, Path(session_id)).await
249}
250
251pub async fn x_ws_session_handler(
252    ws: WebSocketUpgrade,
253    State(state): State<ServerState>,
254    Path((agent, session_id)): Path<(String, String)>,
255    headers: HeaderMap,
256) -> Result<Response, StatusCode> {
257    let inner = dispatch_context(&state, &agent, &headers)
258        .await
259        .map_err(|(s, _)| s)?;
260    routes::ws_session_handler(ws, State(state), inner, Path(session_id)).await
261}
262
263pub async fn x_list_models(
264    State(state): State<ServerState>,
265    Path(agent): Path<String>,
266    headers: HeaderMap,
267) -> Result<Response, (StatusCode, String)> {
268    let inner = dispatch_context(&state, &agent, &headers).await?;
269    routes::list_models(State(state), inner).await
270}
271
272/// The `/xagent/{agent}/api/v1` route tree — merged into the main router.
273pub fn router() -> axum::Router<ServerState> {
274    use axum::routing::{get, post};
275    axum::Router::new()
276        .route("/xagent/{agent}/api/v1/health", get(x_health))
277        .route(
278            "/xagent/{agent}/api/v1/sessions",
279            get(x_list_sessions).post(x_create_session),
280        )
281        .route(
282            "/xagent/{agent}/api/v1/sessions/live",
283            get(x_list_live_sessions),
284        )
285        .route(
286            "/xagent/{agent}/api/v1/sessions/{id}",
287            get(x_get_session_detail).delete(x_destroy_session),
288        )
289        .route(
290            "/xagent/{agent}/api/v1/sessions/{id}/live",
291            get(x_get_live_session),
292        )
293        .route(
294            "/xagent/{agent}/api/v1/sessions/{id}/resume",
295            post(x_resume_session),
296        )
297        .route(
298            "/xagent/{agent}/api/v1/sessions/{id}/history",
299            get(x_get_session_history),
300        )
301        .route(
302            "/xagent/{agent}/api/v1/sessions/{id}/command",
303            post(x_post_command_session),
304        )
305        .route(
306            "/xagent/{agent}/api/v1/sessions/{id}/cancel",
307            post(x_post_cancel_session),
308        )
309        .route(
310            "/xagent/{agent}/api/v1/sessions/{id}/handoff",
311            post(x_post_handoff_session),
312        )
313        .route(
314            "/xagent/{agent}/api/v1/sessions/{id}/stream",
315            get(x_ws_session_handler),
316        )
317        .route("/xagent/{agent}/api/v1/models", get(x_list_models))
318}
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323    use crate::state::ThqDispatchEntry;
324    use std::collections::HashMap;
325
326    fn open_state() -> ServerState {
327        let (session, _rx) = trustee_core::session::Session::new();
328        let (ws_tx, _ws_rx) = tokio::sync::broadcast::channel::<String>(16);
329        ServerState::new(session, ws_tx, None)
330    }
331
332    fn hdrs(pairs: &[(&str, &str)]) -> HeaderMap {
333        let mut h = HeaderMap::new();
334        for (k, v) in pairs {
335            h.insert(
336                header::HeaderName::from_bytes(k.as_bytes()).unwrap(),
337                header::HeaderValue::from_str(v).unwrap(),
338            );
339        }
340        h
341    }
342
343    #[test]
344    fn default_identity_names_the_agent() {
345        assert_eq!(
346            default_identity("saman"),
347            "You are saman, an agent on the Tanbal platform."
348        );
349    }
350
351    #[tokio::test]
352    async fn dispatch_unknown_agent_is_404() {
353        let state = open_state();
354        let err = dispatch_context(&state, "nobody", &hdrs(&[]))
355            .await
356            .unwrap_err();
357        assert_eq!(err.0, StatusCode::NOT_FOUND);
358        assert!(err.1.contains("unknown agent"));
359    }
360
361    #[tokio::test]
362    async fn dispatch_entry_without_owner_id_is_not_dispatchable() {
363        let state = open_state();
364        state.thq_dispatch.insert(
365            "ghost".to_string(),
366            ThqDispatchEntry {
367                user_key: String::new(),
368                service_token: None,
369            },
370        );
371        let err = dispatch_context(&state, "ghost", &hdrs(&[]))
372            .await
373            .unwrap_err();
374        assert_eq!(err.0, StatusCode::NOT_FOUND);
375        assert!(err.1.contains("not dispatchable"));
376    }
377
378    #[tokio::test]
379    async fn open_mode_dispatch_strips_auth_and_cookie() {
380        // Open mode (auth=None): the inner request must carry NO caller
381        // credentials — the inner check_auth resolves the open "default" user.
382        let state = open_state();
383        state.thq_dispatch.insert(
384            "saman".to_string(),
385            ThqDispatchEntry {
386                user_key: "f27de518-a647-4ea2-85ec-8ecc4d61e658".to_string(),
387                service_token: None,
388            },
389        );
390        let inner = dispatch_context(
391            &state,
392            "saman",
393            &hdrs(&[
394                ("Authorization", "Bearer caller-jwt"),
395                ("Cookie", "trustee_token=owner-session"),
396            ]),
397        )
398        .await
399        .unwrap();
400        assert!(
401            inner.get(header::AUTHORIZATION).is_none(),
402            "caller Bearer stripped"
403        );
404        assert!(
405            inner.get(header::COOKIE).is_none(),
406            "caller cookie stripped"
407        );
408    }
409
410    #[tokio::test]
411    async fn dispatch_table_missing_service_token_still_resolves_context_in_open_mode() {
412        // Open mode never mints (no IdP) — a None service_token is fine there.
413        let state = open_state();
414        state.thq_dispatch.insert(
415            "ravand".to_string(),
416            ThqDispatchEntry {
417                user_key: "1a71c077-b3b3-4581-b605-925c3f276f30".to_string(),
418                service_token: None,
419            },
420        );
421        let inner = dispatch_context(&state, "ravand", &hdrs(&[]))
422            .await
423            .unwrap();
424        assert!(inner.get(header::AUTHORIZATION).is_none());
425    }
426
427    // ── admin decision core (no IdP needed) ─────────────────────────────
428
429    #[test]
430    fn dispatch_allowed_only_for_human_admins() {
431        use crate::auth::{dispatch_allowed, PrincipalKind};
432        assert!(dispatch_allowed(PrincipalKind::Human, Some("admin")));
433        assert!(!dispatch_allowed(PrincipalKind::Human, Some("user")));
434        assert!(
435            !dispatch_allowed(PrincipalKind::Agent, Some("admin")),
436            "agents never dispatch agents"
437        );
438        assert!(!dispatch_allowed(PrincipalKind::Human, None));
439        assert!(
440            !dispatch_allowed(PrincipalKind::Human, Some("Admin")),
441            "case-sensitive"
442        );
443    }
444
445    #[test]
446    fn secrets_map_is_unused_but_type_stable() {
447        // Guards the merge-secrets typing used by ServerState::with_secrets —
448        // xagent must never need per-user secrets for impersonation (the
449        // service token travels in the dispatch entry, not the secrets map).
450        let _m: HashMap<String, String> = HashMap::new();
451    }
452}