Skip to main content

adk_server/rest/controllers/
governance.rs

1//! Admin endpoints for the organisation kill switch.
2//!
3//! Mounted by [`ServerBuilder::enable_governance_endpoints`](crate::ServerBuilder::enable_governance_endpoints)
4//! behind the server's auth middleware:
5//!
6//! - `POST /api/admin/freeze` — freezes execution; on a mirrored control the freeze is
7//!   written to the shared governance store and reaches every replica. Running durable
8//!   runs are asked to cancel through the run store, or parked by a [`FreezeDelegate`]
9//!   when one is registered (spec 3.2 §10 S4).
10//! - `POST /api/admin/unfreeze` — lifts the freeze.
11//! - `GET /api/admin/governance` — reports the current state, including what a freeze does
12//!   with running runs (`runningRuns`: `park` under a delegate, `cancel` otherwise).
13//!
14//! A freeze or an unfreeze needs an administrator: a caller whose scopes include the admin
15//! scope ([`SecurityConfig::admin_scope`](crate::SecurityConfig::admin_scope), `"admin"` by
16//! default). A request with no caller — a server without a `RequestContextExtractor` — is
17//! refused with `401` (`governance.unauthenticated`), and an authenticated caller without the
18//! scope with `403` (`governance.forbidden`); either leaves the control as it was. The status
19//! is open to every caller the auth middleware admits.
20//!
21//! When the control has an audit trail attached
22//! ([`GovernanceControl::attach_audit`]), both changes are recorded with the calling
23//! user as the actor. A freeze takes effect even when its record fails, and answers
24//! `503`; an unfreeze that cannot be recorded under `AuditFailureMode::Block` is refused
25//! with `503` and execution stays frozen. The `503` status's `error` follows
26//! [`SecurityConfig::expose_error_details`](crate::SecurityConfig::expose_error_details).
27
28use std::sync::Arc;
29
30use adk_core::audit_log::AuditActor;
31use adk_core::principal::SubjectRef;
32use adk_core::{
33    AdkError, DurableRunStore, ErrorCategory, ErrorComponent, GovernanceControl, RequestContext,
34    RunFilter, RunState,
35};
36use async_trait::async_trait;
37use axum::{
38    Extension, Json,
39    extract::State,
40    http::StatusCode,
41    response::{IntoResponse, Response},
42};
43use serde::{Deserialize, Serialize};
44
45use super::error_details;
46
47/// What a freeze does with the runs that were running (spec 3.2 §10 S4), as
48/// `GET /api/admin/governance` reports it in `runningRuns`.
49///
50/// # Example
51///
52/// ```rust
53/// use adk_server::rest::RunningRuns;
54///
55/// assert_eq!(serde_json::to_value(RunningRuns::Park).unwrap(), "park");
56/// assert_eq!(serde_json::to_value(RunningRuns::Cancel).unwrap(), "cancel");
57/// ```
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "lowercase")]
60pub enum RunningRuns {
61    /// Running runs are parked `Waiting` at their next checkpoint and resume on unfreeze.
62    Park,
63    /// Running runs are asked to cancel and cannot resume.
64    Cancel,
65}
66
67/// What a [`FreezeDelegate`]'s freeze did with the runs that were running.
68///
69/// # Example
70///
71/// ```rust
72/// use adk_server::rest::FreezeReport;
73///
74/// let report = FreezeReport { parked_runs: 6, cancelled_runs: 0 };
75/// assert_eq!(report.parked_runs + report.cancelled_runs, 6);
76/// ```
77#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
78pub struct FreezeReport {
79    /// Runs parked `Waiting`, to resume on unfreeze.
80    pub parked_runs: usize,
81    /// Runs asked to cancel.
82    pub cancelled_runs: usize,
83}
84
85/// Freezes and unfreezes on behalf of the admin endpoints, in place of the controller's own
86/// freeze (spec 3.2 §10 S4): a kernel registers one so `POST /api/admin/freeze` parks its
87/// running processes instead of cancelling them, and `POST /api/admin/unfreeze` wakes them.
88///
89/// The delegate owns the whole change: it writes the control, with
90/// [`GovernanceControl::freeze_recorded`] and [`unfreeze_recorded`], records the audit
91/// records, and stops or resumes the runs. The endpoints report what it returns.
92///
93/// [`unfreeze_recorded`]: GovernanceControl::unfreeze_recorded
94///
95/// # Example
96///
97/// ```rust
98/// use adk_core::GovernanceControl;
99/// use adk_core::audit_log::AuditActor;
100/// use adk_server::rest::{FreezeDelegate, FreezeReport};
101/// use async_trait::async_trait;
102///
103/// struct ParkEverything(GovernanceControl);
104///
105/// #[async_trait]
106/// impl FreezeDelegate for ParkEverything {
107///     async fn freeze(&self, reason: &str, by: AuditActor) -> adk_core::Result<FreezeReport> {
108///         self.0.freeze_recorded(reason, by).await?;
109///         // ... suspend every running process at its next checkpoint ...
110///         Ok(FreezeReport { parked_runs: 0, cancelled_runs: 0 })
111///     }
112///
113///     async fn unfreeze(&self, by: AuditActor) -> adk_core::Result<()> {
114///         self.0.unfreeze_recorded(by).await
115///         // ... then wake what the freeze parked ...
116///     }
117/// }
118/// ```
119#[async_trait]
120pub trait FreezeDelegate: Send + Sync {
121    /// Freezes execution for `reason` as `by`, stops the running runs, and reports what
122    /// happened to them.
123    ///
124    /// # Errors
125    ///
126    /// Returns the control's or the store's error; the endpoint answers `503` with it, and
127    /// the delegate is expected to have frozen this replica regardless.
128    async fn freeze(&self, reason: &str, by: AuditActor) -> adk_core::Result<FreezeReport>;
129
130    /// Lifts the freeze as `by` and resumes what the freeze stopped.
131    ///
132    /// # Errors
133    ///
134    /// Returns the control's or the store's error; the endpoint answers `503` with it, and
135    /// execution stays frozen.
136    async fn unfreeze(&self, by: AuditActor) -> adk_core::Result<()>;
137
138    /// What a freeze does with running runs, reported as `runningRuns`. A delegate parks.
139    fn running_runs(&self) -> RunningRuns {
140        RunningRuns::Park
141    }
142}
143
144/// State for the governance admin endpoints.
145#[derive(Clone)]
146pub struct GovernanceController {
147    control: GovernanceControl,
148    run_stores: Vec<Arc<dyn DurableRunStore>>,
149    delegate: Option<Arc<dyn FreezeDelegate>>,
150    expose_error_details: bool,
151    admin_scope: String,
152}
153
154impl std::fmt::Debug for GovernanceController {
155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156        f.debug_struct("GovernanceController")
157            .field("control", &self.control)
158            .field("run_stores", &self.run_stores.len())
159            .field("delegate", &self.delegate.is_some())
160            .field("expose_error_details", &self.expose_error_details)
161            .field("admin_scope", &self.admin_scope)
162            .finish()
163    }
164}
165
166impl GovernanceController {
167    /// Endpoints over `control`, whose freeze and unfreeze admit callers with the
168    /// [`ADMIN_SCOPE`](crate::ADMIN_SCOPE).
169    pub fn new(control: GovernanceControl) -> Self {
170        Self {
171            control,
172            run_stores: Vec::new(),
173            delegate: None,
174            expose_error_details: false,
175            admin_scope: crate::ADMIN_SCOPE.to_string(),
176        }
177    }
178
179    /// Whether a `503`'s `error` carries the store's or the delegate's own message (default:
180    /// `false`); see [`SecurityConfig::expose_error_details`](crate::SecurityConfig::expose_error_details).
181    /// `ServerBuilder::enable_governance_endpoints` sets it from the server's
182    /// [`SecurityConfig`](crate::SecurityConfig).
183    ///
184    /// # Example
185    ///
186    /// ```rust
187    /// use adk_core::GovernanceControl;
188    /// use adk_server::GovernanceController;
189    ///
190    /// let controller = GovernanceController::new(GovernanceControl::new()).with_error_details(true);
191    /// ```
192    #[must_use]
193    pub fn with_error_details(mut self, expose: bool) -> Self {
194        self.expose_error_details = expose;
195        self
196    }
197
198    /// Admits to the freeze and the unfreeze only callers whose scopes include `scope`.
199    /// [`ServerBuilder`](crate::ServerBuilder) sets the server's
200    /// [`SecurityConfig::admin_scope`](crate::SecurityConfig::admin_scope).
201    ///
202    /// # Example
203    ///
204    /// ```rust
205    /// use adk_core::GovernanceControl;
206    /// use adk_server::GovernanceController;
207    ///
208    /// let controller = GovernanceController::new(GovernanceControl::new()).with_admin_scope("ops");
209    /// # let _ = controller;
210    /// ```
211    pub fn with_admin_scope(mut self, scope: impl Into<String>) -> Self {
212        self.admin_scope = scope.into();
213        self
214    }
215
216    /// A freeze also requests cancellation of every running run in `store`, unless a
217    /// [`FreezeDelegate`] handles the freeze.
218    pub fn with_run_store(mut self, store: Arc<dyn DurableRunStore>) -> Self {
219        if !self.run_stores.iter().any(|existing| Arc::ptr_eq(existing, &store)) {
220            self.run_stores.push(store);
221        }
222        self
223    }
224
225    /// Hands freezes and unfreezes to `delegate` (spec 3.2 §10 S4), so a freeze parks the
226    /// running runs the delegate supervises instead of cancelling the run stores' runs.
227    ///
228    /// # Example
229    ///
230    /// ```rust,ignore
231    /// let controller = GovernanceController::new(control).with_freeze_delegate(kernel);
232    /// ```
233    pub fn with_freeze_delegate(mut self, delegate: Arc<dyn FreezeDelegate>) -> Self {
234        self.delegate = Some(delegate);
235        self
236    }
237
238    /// What a freeze does with running runs.
239    pub fn running_runs(&self) -> RunningRuns {
240        self.delegate.as_ref().map_or(RunningRuns::Cancel, |delegate| delegate.running_runs())
241    }
242
243    fn status(&self) -> GovernanceStatus {
244        GovernanceStatus {
245            frozen: self.control.is_frozen(),
246            reason: self.control.reason(),
247            mirrored: self.control.is_mirrored(),
248            stale: self.control.is_stale(),
249            running_runs: self.running_runs(),
250            parked_runs: None,
251            cancelled_runs: None,
252            error: None,
253        }
254    }
255
256    /// Asks every running run in the run stores to cancel and returns how many were asked.
257    async fn cancel_running(&self) -> usize {
258        let mut cancelled = 0;
259        for store in &self.run_stores {
260            let running = store.list(RunFilter::default().states([RunState::Running])).await;
261            match running {
262                Ok(runs) => {
263                    for run in runs {
264                        match store.request_cancel(&run.run_id).await {
265                            Ok(()) => cancelled += 1,
266                            Err(error) => {
267                                tracing::error!(run.id = %run.run_id, error = %error, "could not request cancellation of a running run")
268                            }
269                        }
270                    }
271                }
272                Err(error) => {
273                    tracing::error!(error = %error, "could not list running runs to cancel")
274                }
275            }
276        }
277        cancelled
278    }
279}
280
281/// `POST /api/admin/freeze` request body.
282#[derive(Debug, Default, Deserialize)]
283#[serde(rename_all = "camelCase")]
284pub struct FreezeRequest {
285    /// Why execution is frozen; carried in every error a frozen run returns.
286    #[serde(default)]
287    pub reason: Option<String>,
288}
289
290/// The kill switch's current state.
291///
292/// # Example
293///
294/// ```rust
295/// use adk_server::rest::{GovernanceStatus, RunningRuns};
296///
297/// let status = GovernanceStatus {
298///     frozen: true,
299///     reason: Some("incident 7".into()),
300///     mirrored: false,
301///     stale: false,
302///     running_runs: RunningRuns::Park,
303///     parked_runs: Some(6),
304///     cancelled_runs: Some(0),
305///     error: None,
306/// };
307/// let json = serde_json::to_value(&status).unwrap();
308/// assert_eq!(json["runningRuns"], "park");
309/// assert_eq!(json["parkedRuns"], 6);
310/// ```
311#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
312#[serde(rename_all = "camelCase")]
313pub struct GovernanceStatus {
314    /// Whether execution is frozen.
315    pub frozen: bool,
316    /// The freeze reason, while frozen.
317    #[serde(skip_serializing_if = "Option::is_none")]
318    pub reason: Option<String>,
319    /// Whether the control mirrors a shared governance store.
320    pub mirrored: bool,
321    /// Whether a mirrored control has gone past its staleness limit.
322    pub stale: bool,
323    /// What a freeze does with running runs: `park` under a [`FreezeDelegate`], else `cancel`.
324    pub running_runs: RunningRuns,
325    /// Running durable runs this freeze parked, to resume on unfreeze.
326    #[serde(skip_serializing_if = "Option::is_none")]
327    pub parked_runs: Option<usize>,
328    /// Running durable runs asked to cancel by this freeze.
329    #[serde(skip_serializing_if = "Option::is_none")]
330    pub cancelled_runs: Option<usize>,
331    /// Why the shared store could not be written, as `{component}.{category}: {message}`. The
332    /// message is the generic one for its category unless
333    /// [`SecurityConfig::expose_error_details`](crate::SecurityConfig::expose_error_details) is
334    /// set or the server wrote it.
335    #[serde(skip_serializing_if = "Option::is_none")]
336    pub error: Option<String>,
337}
338
339/// The audit actor for an administrator's request: the authenticated user, who is also
340/// the issuer written to the shared store.
341fn admin_actor(caller: &RequestContext) -> AuditActor {
342    AuditActor {
343        on_behalf_of: Some(SubjectRef::human(caller.user_id.clone())),
344        ..AuditActor::default()
345    }
346}
347
348/// The caller of a freeze or an unfreeze when they are an administrator; otherwise the
349/// refusal: `401` without a caller, `403` without the admin scope.
350fn administrator(
351    controller: &GovernanceController,
352    caller: Option<RequestContext>,
353    action: &str,
354) -> Result<RequestContext, Response> {
355    let scope = &controller.admin_scope;
356    let refusal = |category, code, message: String| {
357        let error = AdkError::new(ErrorComponent::Server, category, code, message);
358        let status = StatusCode::from_u16(error.http_status_code())
359            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
360        (status, Json(error.to_problem_json())).into_response()
361    };
362    let Some(caller) = caller else {
363        tracing::warn!(governance.action = action, "governance change refused: no caller");
364        return Err(refusal(
365            ErrorCategory::Unauthorized,
366            "governance.unauthenticated",
367            format!(
368                "{action} needs an authenticated administrator; configure a \
369                 RequestContextExtractor that grants the `{scope}` scope"
370            ),
371        ));
372    };
373    if !caller.scopes.iter().any(|granted| granted == scope) {
374        tracing::warn!(
375            caller.user_id = %caller.user_id,
376            governance.action = action,
377            "governance change refused: the caller is not an administrator"
378        );
379        return Err(refusal(
380            ErrorCategory::Forbidden,
381            "governance.forbidden",
382            format!("{} may not {action}: it needs the `{scope}` scope", caller.user_id),
383        ));
384    }
385    Ok(caller)
386}
387
388/// `POST /api/admin/freeze`
389///
390/// Responds `401` without a caller and `403` to a caller without the admin scope, and
391/// leaves the control as it was.
392///
393/// Responds `503` with the status when the shared store could not be written; this
394/// replica is frozen regardless.
395pub async fn freeze(
396    State(controller): State<GovernanceController>,
397    Extension(caller): Extension<Option<RequestContext>>,
398    Json(request): Json<FreezeRequest>,
399) -> Response {
400    let caller = match administrator(&controller, caller, "freeze") {
401        Ok(caller) => caller,
402        Err(refusal) => return refusal,
403    };
404    let reason = request.reason.unwrap_or_else(|| "frozen by an administrator".to_string());
405    tracing::warn!(
406        caller.user_id = %caller.user_id,
407        governance.reason = %reason,
408        "governance freeze requested"
409    );
410    let actor = admin_actor(&caller);
411    let mut status = controller.status();
412    let written = match &controller.delegate {
413        Some(delegate) => match delegate.freeze(&reason, actor).await {
414            Ok(report) => {
415                status.parked_runs = Some(report.parked_runs);
416                status.cancelled_runs = Some(report.cancelled_runs);
417                tracing::warn!(
418                    runs.parked = report.parked_runs,
419                    runs.cancel_requested = report.cancelled_runs,
420                    "governance freeze applied by the delegate"
421                );
422                Ok(())
423            }
424            Err(error) => Err(error),
425        },
426        None => {
427            let written = controller.control.freeze_recorded(reason, actor).await;
428            let cancelled = controller.cancel_running().await;
429            tracing::warn!(runs.cancel_requested = cancelled, "governance freeze applied");
430            status.parked_runs = Some(0);
431            status.cancelled_runs = Some(cancelled);
432            written
433        }
434    };
435    // Read again, so the status carries the state the freeze left.
436    let current = controller.status();
437    status.frozen = current.frozen;
438    status.reason = current.reason;
439    status.stale = current.stale;
440    match written {
441        Ok(()) => Json(status).into_response(),
442        Err(error) => {
443            status.error = Some(error_details::display(&error, controller.expose_error_details));
444            (StatusCode::SERVICE_UNAVAILABLE, Json(status)).into_response()
445        }
446    }
447}
448
449/// `POST /api/admin/unfreeze`
450///
451/// Responds `401` without a caller and `403` to a caller without the admin scope, and
452/// leaves the freeze in force.
453///
454/// Responds `503` with the status when the shared store could not be written; the
455/// freeze then stays in force.
456pub async fn unfreeze(
457    State(controller): State<GovernanceController>,
458    Extension(caller): Extension<Option<RequestContext>>,
459) -> Response {
460    let caller = match administrator(&controller, caller, "unfreeze") {
461        Ok(caller) => caller,
462        Err(refusal) => return refusal,
463    };
464    tracing::warn!(caller.user_id = %caller.user_id, "governance unfreeze requested");
465    let actor = admin_actor(&caller);
466    let lifted = match &controller.delegate {
467        Some(delegate) => delegate.unfreeze(actor).await,
468        None => controller.control.unfreeze_recorded(actor).await,
469    };
470    match lifted {
471        Ok(()) => Json(controller.status()).into_response(),
472        Err(error) => {
473            let mut status = controller.status();
474            status.error = Some(error_details::display(&error, controller.expose_error_details));
475            (StatusCode::SERVICE_UNAVAILABLE, Json(status)).into_response()
476        }
477    }
478}
479
480/// `GET /api/admin/governance`
481pub async fn status(State(controller): State<GovernanceController>) -> Json<GovernanceStatus> {
482    Json(controller.status())
483}