Skip to main content

adk_website/
incident.rs

1//! The incident path (spec 3.5 §7.20 "Run and protect", §7.21 P1, §7.11, A-I4, A-I11, S5).
2//!
3//! | Step | What happens |
4//! |---|---|
5//! | Probe | The Guardian's probe ([`GuardianProbe`]) re-proves the domain, reads the host and the origin against the signed releases, and records `site.drift.detected` |
6//! | Incident | Drift opens one incident: the site's status becomes `incident` (`site.status.changed`) |
7//! | Read-only | The edge answers every non-read capability with 503 — the edge's status control, added with the edge |
8//! | Rollback | To the last good signed release: the Guardian runs `site_rollback` when its `protect` job's level lets the call run (a standing rule the owner created, A-I11); otherwise the rollback is a proposal the owner approves |
9//! | Alarm | One P1 alarm, repeated until a person acknowledges it |
10//! | Exit | Only a person's decision closes the incident and restores `operational` |
11//!
12//! An incident a job caused in its own area demotes that area's jobs one level (§7.11). Drift
13//! is a change no release explains — tampering from outside — so it demotes no job: the
14//! Guardian's reversal is the response, not the cause.
15
16use std::collections::BTreeMap;
17use std::sync::Arc;
18use std::sync::atomic::{AtomicU64, Ordering};
19
20use adk_auth::signed_audit::NoteVerifier;
21use adk_core::audit_log::{AuditActor, AuditRecorder, AuditTrail};
22use adk_core::principal::{SubjectKind, SubjectRef};
23use adk_core::{
24    ActingContext, AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock, ToolEffect,
25};
26use adk_harness::website::{LevelDecision, SITE_ROLLBACK, SiteRef, SiteRuntime, level_decision};
27use adk_kernel::charter::AutonomyLadder;
28use adk_site::host::SiteHost;
29use adk_site::migrate::claim::{DnsResolver, DomainClaim};
30use adk_site::migrate::http::HttpClient;
31use adk_site::migrate::probe::{Drift, DriftLocation, ProbeConfig, ProbeReport, Prober};
32use async_trait::async_trait;
33use awp_types::{AutonomyLevel, SiteState, Urgency};
34use chrono::{DateTime, Utc};
35use serde::{Deserialize, Serialize};
36use serde_json::json;
37use tokio::sync::Mutex;
38use uuid::Uuid;
39
40use crate::alarms::{Alarm, AlarmRouter};
41use crate::audit;
42
43/// The job whose level decides whether the Guardian rolls back alone (spec 3.5 §7.20).
44pub const PROTECT_JOB: &str = "protect";
45
46/// The site's status as the product last set it (spec 3.5 §7.5).
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "camelCase")]
49pub struct StatusRecord {
50    /// The state.
51    pub state: SiteState,
52    /// Since when.
53    pub since: DateTime<Utc>,
54    /// Why, as a snake_case code.
55    pub reason: String,
56    /// The release being served.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub release_seq: Option<u64>,
59}
60
61/// Where the site's status goes: the edge's signed status document serves it (spec 3.5
62/// §7.5, §7.9).
63#[async_trait]
64pub trait StatusSink: Send + Sync {
65    /// Sets the site's status.
66    ///
67    /// # Errors
68    ///
69    /// Returns the sink's error.
70    async fn set(&self, site: Uuid, status: StatusRecord) -> Result<()>;
71
72    /// The site's status.
73    ///
74    /// # Errors
75    ///
76    /// Returns the sink's error.
77    async fn get(&self, site: Uuid) -> Result<Option<StatusRecord>>;
78}
79
80/// A [`StatusSink`] in memory, until the edge's status store serves it.
81#[derive(Debug, Default)]
82pub struct InMemoryStatusBoard {
83    statuses: Mutex<BTreeMap<Uuid, StatusRecord>>,
84}
85
86impl InMemoryStatusBoard {
87    /// No statuses yet.
88    pub fn new() -> Self {
89        Self::default()
90    }
91}
92
93#[async_trait]
94impl StatusSink for InMemoryStatusBoard {
95    async fn set(&self, site: Uuid, status: StatusRecord) -> Result<()> {
96        self.statuses.lock().await.insert(site, status);
97        Ok(())
98    }
99
100    async fn get(&self, site: Uuid) -> Result<Option<StatusRecord>> {
101        Ok(self.statuses.lock().await.get(&site).cloned())
102    }
103}
104
105/// Who may roll back (spec 3.5 A-I11).
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(rename_all = "snake_case")]
108pub enum RollbackAuthority {
109    /// The `protect` job's level lets `site_rollback` run: the Guardian rolls back.
110    Standing,
111    /// The owner approves the rollback.
112    Proposal,
113}
114
115/// The rollback an incident plans.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase")]
118pub struct RollbackPlan {
119    /// The last good signed release.
120    pub to_release: u64,
121    /// Who rolls back.
122    pub authority: RollbackAuthority,
123    /// The release served after the rollback, once it ran.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub done: Option<u64>,
126}
127
128/// How an incident ended: by a person's decision.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(rename_all = "camelCase")]
131pub struct IncidentExit {
132    /// Who decided.
133    pub by: String,
134    /// The decision's id.
135    pub decision: String,
136    /// When.
137    pub at: DateTime<Utc>,
138}
139
140/// An incident (spec 3.5 §7.20).
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(rename_all = "camelCase")]
143pub struct Incident {
144    /// Its id.
145    pub id: String,
146    /// The site.
147    pub site: Uuid,
148    /// When it opened.
149    pub opened_at: DateTime<Utc>,
150    /// The drift that opened it.
151    pub drift: Vec<Drift>,
152    /// The rollback it plans.
153    pub rollback: RollbackPlan,
154    /// The area whose jobs it demoted, when a job's work caused it.
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub area: Option<String>,
157    /// The jobs it demoted.
158    #[serde(default, skip_serializing_if = "Vec::is_empty")]
159    pub demoted: Vec<String>,
160    /// The P1 alarm.
161    pub alarm: String,
162    /// How it ended.
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub closed: Option<IncidentExit>,
165}
166
167impl Incident {
168    /// The Guardian's turn for the incident: the plan in plain words, run under the
169    /// `incident` playbook.
170    pub fn guardian_turn(&self) -> String {
171        let paths: Vec<&str> = self.drift.iter().map(|d| d.path.as_str()).collect();
172        let act = match self.rollback.authority {
173            RollbackAuthority::Standing => format!(
174                "Roll the site back to signed release {} with site_rollback now.",
175                self.rollback.to_release
176            ),
177            RollbackAuthority::Proposal => format!(
178                "Your authority does not let you roll back alone: call site_rollback to \
179                 release {} so the owner decides it, and say so in one sentence.",
180                self.rollback.to_release
181            ),
182        };
183        format!(
184            "Incident {}: {} served file(s) match no signed release ({}). {act} Then report \
185             what you did. The incident stays open until a person closes it.",
186            self.id,
187            paths.len(),
188            paths.join(", ")
189        )
190    }
191}
192
193/// Opens, tracks and closes incidents (spec 3.5 §7.20, A-I11).
194pub struct IncidentPath {
195    site: SiteRef,
196    runtime: Arc<SiteRuntime>,
197    ladder: AutonomyLadder,
198    alarms: Arc<AlarmRouter>,
199    status: Arc<dyn StatusSink>,
200    clock: Arc<dyn Clock>,
201    audit: Option<AuditTrail>,
202    incidents: Mutex<BTreeMap<String, Incident>>,
203    tainted: Mutex<std::collections::BTreeSet<u64>>,
204    next: AtomicU64,
205}
206
207impl std::fmt::Debug for IncidentPath {
208    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
209        f.debug_struct("IncidentPath").field("site", &self.site).finish_non_exhaustive()
210    }
211}
212
213fn not_a_person(by: &SubjectRef) -> bool {
214    by.kind != SubjectKind::Human || adk_kernel::charter::is_agent_principal(&by.id)
215}
216
217impl IncidentPath {
218    /// The incident path of `runtime`'s site over the kernel's `ladder`, raising alarms on
219    /// `alarms` and setting the status on `status`.
220    pub fn new(
221        runtime: Arc<SiteRuntime>,
222        ladder: AutonomyLadder,
223        alarms: Arc<AlarmRouter>,
224        status: Arc<dyn StatusSink>,
225    ) -> Self {
226        Self {
227            site: runtime.site().clone(),
228            runtime,
229            ladder,
230            alarms,
231            status,
232            clock: Arc::new(SystemClock),
233            audit: None,
234            incidents: Mutex::new(BTreeMap::new()),
235            tainted: Mutex::new(std::collections::BTreeSet::new()),
236            next: AtomicU64::new(1),
237        }
238    }
239
240    /// The clock.
241    #[must_use]
242    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
243        self.clock = clock;
244        self
245    }
246
247    /// Where `site.status.changed` and `site.rollback` records go.
248    #[must_use]
249    pub fn with_audit(mut self, trail: AuditTrail) -> Self {
250        self.audit = Some(trail);
251        self
252    }
253
254    /// Who may roll back now: the Guardian when its `protect` job's level lets
255    /// `site_rollback` run, otherwise the owner (spec 3.5 §7.11, A-I11).
256    ///
257    /// # Errors
258    ///
259    /// Returns the autonomy store's error.
260    pub async fn rollback_authority(&self) -> Result<RollbackAuthority> {
261        let level = self
262            .ladder
263            .level(self.site.id, PROTECT_JOB)
264            .await
265            .map_err(|e| AdkError::config(e.to_string()))?
266            .unwrap_or(AutonomyLevel::Propose);
267        let spec = adk_harness::website::spec(SITE_ROLLBACK);
268        Ok(match level_decision(level, spec, ToolEffect::NonIdempotent) {
269            LevelDecision::Allow => RollbackAuthority::Standing,
270            _ => RollbackAuthority::Proposal,
271        })
272    }
273
274    async fn set_status(&self, state: SiteState, reason: &str, release: Option<u64>) -> Result<()> {
275        let record = StatusRecord {
276            state,
277            since: self.clock.now(),
278            reason: reason.to_string(),
279            release_seq: release,
280        };
281        self.status.set(self.site.id, record).await?;
282        tracing::info!(site.state = ?state, reason, "site.status.changed");
283        audit::record(
284            self.audit.as_ref(),
285            audit::STATUS_CHANGED,
286            AuditActor::default(),
287            json!({ "site": self.site.id, "state": state, "reason": reason, "releaseSeq": release }),
288        )
289        .await;
290        Ok(())
291    }
292
293    /// Acts on a probe (spec 3.5 §7.20, S5): no drift, nothing; drift with an incident open,
294    /// the drift joins it; otherwise a new incident — status `incident`, a rollback plan to
295    /// the last good signed release, one P1 alarm. Drift at the origin leaves the host's copy
296    /// of the current release intact, so it is the last good one; drift on the host changed
297    /// that copy, which cannot restore itself, so the last good release is the latest one
298    /// before it whose copy no probe found changed.
299    ///
300    /// # Errors
301    ///
302    /// Returns the status sink's or the autonomy store's error.
303    pub async fn on_probe(&self, report: &ProbeReport) -> Result<Option<Incident>> {
304        if !report.drift_detected() {
305            return Ok(None);
306        }
307        if let Some(open) =
308            self.incidents.lock().await.values_mut().find(|incident| incident.closed.is_none())
309        {
310            open.drift.extend(report.drift.iter().cloned());
311            return Ok(Some(open.clone()));
312        }
313        let previous = self.runtime.pipeline().previous().await.map(|p| p.manifest.seq);
314        let Some(current) = report.checkpoint.or(previous) else {
315            return Err(AdkError::new(
316                ErrorComponent::Tool,
317                ErrorCategory::NotFound,
318                "website.incident.no_release",
319                "drift was found but no signed release is known to roll back to",
320            ));
321        };
322        let on_host = report.drift.iter().any(|drift| drift.location == DriftLocation::Host);
323        let to_release = {
324            let mut tainted = self.tainted.lock().await;
325            if on_host {
326                tainted.insert(current);
327            }
328            (1..=current).rev().find(|seq| !tainted.contains(seq)).unwrap_or(current)
329        };
330        self.open(report.drift.clone(), to_release, None).await.map(Some)
331    }
332
333    /// Opens an incident for `drift` with a rollback to `to_release`; an incident a job
334    /// caused names its `area`, whose jobs it demotes one level (spec 3.5 §7.11).
335    ///
336    /// # Errors
337    ///
338    /// Returns the status sink's or the autonomy store's error.
339    #[tracing::instrument(skip_all, name = "website.job.protect", fields(website.incident = tracing::field::Empty, site.id = %self.site.id))]
340    pub async fn open(
341        &self,
342        drift: Vec<Drift>,
343        to_release: u64,
344        area: Option<&str>,
345    ) -> Result<Incident> {
346        let id = format!("incident-{}", self.next.fetch_add(1, Ordering::Relaxed));
347        tracing::Span::current().record("website.incident", id.as_str());
348        self.set_status(SiteState::Incident, "drift_detected", Some(to_release)).await?;
349        let demoted = match area {
350            Some(area) => self
351                .ladder
352                .incident(self.site.id, area, &id)
353                .await
354                .map_err(|e| AdkError::config(e.to_string()))?
355                .into_iter()
356                .map(|job| job.job)
357                .collect(),
358            None => Vec::new(),
359        };
360        let authority = self.rollback_authority().await?;
361        let act = match authority {
362            RollbackAuthority::Standing => format!("rolling back to signed release {to_release}"),
363            RollbackAuthority::Proposal => {
364                format!("approve rolling back to signed release {to_release}")
365            }
366        };
367        let now = self.clock.now();
368        let mut alarm = Alarm::new(
369            self.site.id,
370            Urgency::P1,
371            "incident",
372            format!(
373                "Incident {id}: {} file(s) on {} match no signed release; {act}.",
374                drift.len(),
375                self.site.origin
376            ),
377            now,
378        );
379        alarm.id = format!("{id}-alarm");
380        self.alarms.raise(alarm.clone()).await;
381        let incident = Incident {
382            id: id.clone(),
383            site: self.site.id,
384            opened_at: now,
385            drift,
386            rollback: RollbackPlan { to_release, authority, done: None },
387            area: area.map(str::to_string),
388            demoted,
389            alarm: alarm.id,
390            closed: None,
391        };
392        self.incidents.lock().await.insert(id, incident.clone());
393        Ok(incident)
394    }
395
396    /// Records that the rollback of incident `id` ran, as the Guardian's `site_rollback` or
397    /// the owner's approval, with the release now served.
398    ///
399    /// # Errors
400    ///
401    /// `NotFound` for an unknown incident.
402    pub async fn rolled_back(&self, id: &str, served: u64) -> Result<Incident> {
403        let mut incidents = self.incidents.lock().await;
404        let incident = incidents.get_mut(id).ok_or_else(|| unknown(id))?;
405        incident.rollback.done = Some(served);
406        audit::record(
407            self.audit.as_ref(),
408            audit::ROLLBACK,
409            AuditActor::default(),
410            json!({ "site": self.site.id, "incident": id, "toRelease": incident.rollback.to_release, "releaseSeq": served }),
411        )
412        .await;
413        Ok(incident.clone())
414    }
415
416    /// The owner approves the proposed rollback of incident `id`: it runs as the owner's act
417    /// (spec 3.5 A-I11). When the host cannot restore the planned release exactly, the
418    /// releases before it are tried in turn: the last good one is the latest that restores.
419    ///
420    /// # Errors
421    ///
422    /// `Forbidden` when `by` is not a person; `NotFound` for an unknown incident; the
423    /// pipeline's error.
424    pub async fn approve_rollback(&self, id: &str, by: &SubjectRef) -> Result<Incident> {
425        if not_a_person(by) {
426            return Err(forbidden(by, "approves a rollback"));
427        }
428        let planned = {
429            let incidents = self.incidents.lock().await;
430            incidents.get(id).ok_or_else(|| unknown(id))?.rollback.to_release
431        };
432        let mut failure = None;
433        for to in (1..=planned).rev() {
434            match self.runtime.pipeline().rollback(to).await {
435                Ok(published) => return self.rolled_back(id, published.staged.manifest.seq).await,
436                Err(error) => {
437                    tracing::warn!(website.incident = id, to_release = to, error = %error, "release does not restore; trying the one before");
438                    failure = Some(error);
439                }
440            }
441        }
442        Err(AdkError::new(
443            ErrorComponent::Tool,
444            ErrorCategory::Internal,
445            "website.incident.rollback",
446            format!(
447                "no signed release up to {planned} restores exactly: {}",
448                failure.map(|e| e.to_string()).unwrap_or_default()
449            ),
450        ))
451    }
452
453    /// Closes incident `id` by a person's decision `decision`: the status returns to
454    /// `operational` (spec 3.5 §7.20: "exit is a person's decision").
455    ///
456    /// # Errors
457    ///
458    /// `Forbidden` when `by` is not a person; `NotFound` for an unknown incident; the
459    /// status sink's error.
460    pub async fn close(&self, id: &str, by: &SubjectRef, decision: &str) -> Result<Incident> {
461        if not_a_person(by) {
462            return Err(forbidden(by, "closes an incident"));
463        }
464        let (incident, served) = {
465            let mut incidents = self.incidents.lock().await;
466            let incident = incidents.get_mut(id).ok_or_else(|| unknown(id))?;
467            incident.closed = Some(IncidentExit {
468                by: by.id.clone(),
469                decision: decision.to_string(),
470                at: self.clock.now(),
471            });
472            let served = incident.rollback.done.unwrap_or(incident.rollback.to_release);
473            (incident.clone(), served)
474        };
475        if let Err(error) = self.alarms.acknowledge(&incident.alarm, by).await {
476            tracing::debug!(error = %error, "the incident's alarm was already acknowledged");
477        }
478        self.set_status(SiteState::Operational, "incident_closed", Some(served)).await?;
479        Ok(incident)
480    }
481
482    /// Every incident, open and closed.
483    pub async fn incidents(&self) -> Vec<Incident> {
484        self.incidents.lock().await.values().cloned().collect()
485    }
486
487    /// The open incident, if any.
488    pub async fn open_incident(&self) -> Option<Incident> {
489        self.incidents.lock().await.values().find(|i| i.closed.is_none()).cloned()
490    }
491}
492
493fn unknown(id: &str) -> AdkError {
494    AdkError::new(
495        ErrorComponent::Tool,
496        ErrorCategory::NotFound,
497        "website.incident.unknown",
498        format!("no incident {id}"),
499    )
500}
501
502fn forbidden(by: &SubjectRef, act: &str) -> AdkError {
503    AdkError::new(
504        ErrorComponent::Tool,
505        ErrorCategory::Forbidden,
506        "website.incident.not_a_person",
507        format!("{} is not a person; only a person {act} (spec 3.5 §7.20)", by.id),
508    )
509}
510
511/// The Guardian's probe as a kernel process (spec 3.5 §7.20, §7.8 "Probes", A-I9): each run
512/// re-proves the domain claim — a `ProvenDomain` is never stored — probes the host and the
513/// origin, and hands the report to the incident path.
514pub struct GuardianProbe {
515    /// The owner's claim of the domain.
516    pub claim: DomainClaim,
517    /// The resolver that proves it.
518    pub resolver: Arc<dyn DnsResolver>,
519    /// The host.
520    pub host: Arc<dyn SiteHost>,
521    /// The signed, rate-limited client that reads the origin.
522    pub http: Arc<HttpClient>,
523    /// The release keys the checkpoint must verify against.
524    pub trusted: Vec<NoteVerifier>,
525    /// What to probe.
526    pub config: ProbeConfig,
527    /// Where `site.drift.detected` goes, as the Guardian.
528    pub audit: Option<(Arc<dyn AuditRecorder>, ActingContext)>,
529    /// The incident path.
530    pub incidents: Arc<IncidentPath>,
531}
532
533/// One probe's outcome.
534#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
535#[serde(rename_all = "camelCase")]
536pub struct ProbeOutcome {
537    /// The report.
538    pub report: ProbeReport,
539    /// The incident it opened or joined.
540    #[serde(default, skip_serializing_if = "Option::is_none")]
541    pub incident: Option<Incident>,
542}
543
544impl GuardianProbe {
545    /// Runs one probe (spec 3.5 §7.20).
546    ///
547    /// # Errors
548    ///
549    /// Returns the claim's refusal when the domain is no longer proven (A-I9), the prober's
550    /// error, or the incident path's.
551    #[tracing::instrument(skip_all, name = "site.probe", fields(site.domain = %self.config.domain))]
552    pub async fn run(&self) -> Result<ProbeOutcome> {
553        let migrate = |e: adk_site::migrate::MigrateError| AdkError::config(e.to_string());
554        let proven =
555            self.claim.verify_dns(self.resolver.as_ref(), Utc::now()).await.map_err(migrate)?;
556        let mut prober = Prober::new(
557            self.host.clone(),
558            self.http.clone(),
559            self.resolver.clone(),
560            self.trusted.clone(),
561            &proven,
562            self.config.clone(),
563        )
564        .map_err(migrate)?;
565        if let Some((recorder, acting)) = &self.audit {
566            prober = prober.with_audit(recorder.clone(), acting.clone());
567        }
568        let report = prober.probe().await.map_err(migrate)?;
569        let incident = self.incidents.on_probe(&report).await?;
570        Ok(ProbeOutcome { report, incident })
571    }
572}