adk_kernel/charter/store.rs
1//! The charter store and approval chains (spec 3.5 §7.6, §7.11, A-I23).
2
3use std::collections::BTreeMap;
4use std::fmt;
5
6use adk_core::principal::{SubjectKind, SubjectRef};
7use async_trait::async_trait;
8use awp_types::{
9 ActionClass, ApprovalChain, Charter, Governance, OwnerSignature, Role, RoleHolder,
10};
11use chrono::{DateTime, Utc};
12use serde::{Deserialize, Serialize};
13use uuid::Uuid;
14
15use crate::error::{KernelError, Result};
16
17/// The action class of a charter change in a charter's approval chains (spec 3.5 §7.6): a
18/// commit needs every role of the chain with this action, or one owner when the charter
19/// names no such chain.
20pub const CHARTER_ACTION: ActionClass = ActionClass::CharterChange;
21
22/// One approval of a decision by a person holding a role (spec 3.5 §7.6, A-I23).
23///
24/// # Example
25///
26/// ```rust
27/// use adk_core::principal::SubjectRef;
28/// use adk_kernel::charter::RoleApproval;
29/// use awp_types::Role;
30///
31/// let approval = RoleApproval::new(Role::Owner, SubjectRef::human("amina"), chrono::Utc::now());
32/// assert_eq!(serde_json::to_value(&approval).unwrap()["principal"]["id"], "amina");
33/// ```
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "camelCase")]
36#[non_exhaustive]
37pub struct RoleApproval {
38 /// The role the approver acts in.
39 pub role: Role,
40 /// Who approved.
41 pub principal: SubjectRef,
42 /// When.
43 pub at: DateTime<Utc>,
44}
45
46impl RoleApproval {
47 /// An approval by `principal` acting as `role` at `at`.
48 pub fn new(role: Role, principal: SubjectRef, at: DateTime<Utc>) -> Self {
49 Self { role, principal, at }
50 }
51}
52
53/// The decision that commits a charter version (spec 3.5 §7.6, §7.11): its id, the approvals
54/// of its chain, and the signed note that seals it in the audit log.
55///
56/// # Example
57///
58/// ```rust
59/// use adk_core::principal::SubjectRef;
60/// use adk_kernel::charter::{CommitDecision, RoleApproval};
61/// use awp_types::Role;
62///
63/// let now = chrono::Utc::now();
64/// let decision = CommitDecision::new("decision-1", now)
65/// .with_approval(RoleApproval::new(Role::Owner, SubjectRef::human("amina"), now))
66/// .with_signed_note("note:sha256:ab12");
67/// assert_eq!(decision.approvals.len(), 1);
68/// ```
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(rename_all = "camelCase")]
71#[non_exhaustive]
72pub struct CommitDecision {
73 /// The decision's id.
74 pub decision_id: String,
75 /// The approvals of the charter's approval chain, one per role it requires.
76 pub approvals: Vec<RoleApproval>,
77 /// The signed note sealing the commit in the audit log (`adk-auth`'s signed audit), by
78 /// reference.
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub signed_note: Option<String>,
81 /// When the decision was made.
82 pub decided_at: DateTime<Utc>,
83}
84
85impl CommitDecision {
86 /// A decision with no approvals and no signed note yet.
87 pub fn new(decision_id: impl Into<String>, decided_at: DateTime<Utc>) -> Self {
88 Self {
89 decision_id: decision_id.into(),
90 approvals: Vec::new(),
91 signed_note: None,
92 decided_at,
93 }
94 }
95
96 /// Adds an approval.
97 #[must_use]
98 pub fn with_approval(mut self, approval: RoleApproval) -> Self {
99 self.approvals.push(approval);
100 self
101 }
102
103 /// Sets the signed note's reference.
104 #[must_use]
105 pub fn with_signed_note(mut self, note: impl Into<String>) -> Self {
106 self.signed_note = Some(note.into());
107 self
108 }
109}
110
111/// One committed charter version with the decision that committed it (spec 3.5 §7.11).
112///
113/// # Example
114///
115/// ```rust,ignore
116/// let version = store.current(site).await?.expect("a committed charter");
117/// assert_eq!(version.version(), version.charter.version);
118/// ```
119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
120#[serde(rename_all = "camelCase")]
121#[non_exhaustive]
122pub struct CharterVersion {
123 /// The charter, with its version and owner signature as committed.
124 pub charter: Charter,
125 /// The committing decision.
126 pub decision: CommitDecision,
127 /// When it took effect.
128 pub committed_at: DateTime<Utc>,
129}
130
131impl CharterVersion {
132 /// A committed version of `charter`.
133 pub fn new(charter: Charter, decision: CommitDecision, committed_at: DateTime<Utc>) -> Self {
134 Self { charter, decision, committed_at }
135 }
136
137 /// The site.
138 pub fn site(&self) -> Uuid {
139 self.charter.site_id
140 }
141
142 /// The version number.
143 pub fn version(&self) -> u32 {
144 self.charter.version
145 }
146}
147
148/// Why an approval chain is not satisfied (A-I23).
149///
150/// # Example
151///
152/// ```rust
153/// use adk_kernel::charter::ChainRefusal;
154///
155/// let refusal = ChainRefusal::new("charter", "owner needs an approval");
156/// assert!(refusal.to_string().contains("charter"));
157/// ```
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(rename_all = "camelCase")]
160#[non_exhaustive]
161pub struct ChainRefusal {
162 /// The action class.
163 pub action: String,
164 /// What is missing or wrong.
165 pub reason: String,
166}
167
168impl ChainRefusal {
169 /// A refusal of `action`'s chain for `reason`.
170 pub fn new(action: impl Into<String>, reason: impl Into<String>) -> Self {
171 Self { action: action.into(), reason: reason.into() }
172 }
173}
174
175impl fmt::Display for ChainRefusal {
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 write!(f, "the `{}` approval chain is not satisfied: {}", self.action, self.reason)
178 }
179}
180
181/// Whether `id` names an agent rather than a person: an `urn:adk:agent:` URN or a SPIFFE
182/// id, the forms of `adk_core::principal::AgentId` (spec 3.5 §7.6: no agent holds a role).
183///
184/// # Example
185///
186/// ```rust
187/// use adk_kernel::charter::is_agent_principal;
188///
189/// assert!(is_agent_principal("urn:adk:agent:example/steward"));
190/// assert!(!is_agent_principal("amina@example.com"));
191/// ```
192pub fn is_agent_principal(id: &str) -> bool {
193 let id = id.trim().to_ascii_lowercase();
194 id.starts_with("urn:adk:agent:") || id.starts_with("spiffe://")
195}
196
197/// Checks that `approvals` satisfy the approval chain `governance` names for `action`
198/// (spec 3.5 §7.6, A-I23): every role the chain lists has an approval by a person holding
199/// that role, each role's approval by a different person, none by `proposer`. A role the
200/// chain lists twice needs two people. A charter that names no chain for `action` needs one
201/// owner.
202///
203/// An approval by an agent (a subject of kind `Agent` or `Service`, or an agent identity
204/// such as `urn:adk:agent:…`) is refused outright: no agent holds a role.
205///
206/// # Example
207///
208/// ```rust
209/// use adk_core::principal::SubjectRef;
210/// use adk_kernel::charter::{RoleApproval, check_chain};
211/// use awp_types::{ActionClass, ApprovalChain, Governance, Role, RoleHolder};
212///
213/// let governance = Governance {
214/// roles: vec![
215/// RoleHolder { principal: "eva".into(), roles: vec![Role::Editor, Role::Publisher] },
216/// RoleHolder { principal: "paul".into(), roles: vec![Role::Publisher] },
217/// RoleHolder { principal: "amina".into(), roles: vec![Role::Owner] },
218/// ],
219/// approval_chains: vec![ApprovalChain { action: ActionClass::Publish, roles: vec![Role::Editor, Role::Publisher] }],
220/// };
221/// let now = chrono::Utc::now();
222/// let by = |role, who: &str| RoleApproval::new(role, SubjectRef::human(who), now);
223/// let publish = ActionClass::Publish;
224/// // One person cannot fill both roles.
225/// assert!(check_chain(&governance, &publish, &[by(Role::Editor, "eva"), by(Role::Publisher, "eva")], None).is_err());
226/// assert!(check_chain(&governance, &publish, &[by(Role::Editor, "eva"), by(Role::Publisher, "paul")], None).is_ok());
227/// // The proposer cannot approve.
228/// assert!(check_chain(&governance, &publish, &[by(Role::Editor, "eva"), by(Role::Publisher, "paul")], Some("paul")).is_err());
229/// ```
230///
231/// # Errors
232///
233/// Returns the [`ChainRefusal`] naming the first fault found.
234pub fn check_chain(
235 governance: &Governance,
236 action: &ActionClass,
237 approvals: &[RoleApproval],
238 proposer: Option<&str>,
239) -> std::result::Result<(), ChainRefusal> {
240 let refuse = |reason: String| Err(ChainRefusal::new(action.as_str(), reason));
241 let chain = governance
242 .approval_chains
243 .iter()
244 .find(|chain| &chain.action == action)
245 .cloned()
246 .unwrap_or_else(|| ApprovalChain { action: action.clone(), roles: vec![Role::Owner] });
247 if chain.roles.is_empty() {
248 return refuse("the chain lists no role, so nobody can satisfy it".into());
249 }
250 // Who approved in which of the roles they hold.
251 let mut acted: BTreeMap<&str, Vec<Role>> = BTreeMap::new();
252 for approval in approvals {
253 let who = &approval.principal;
254 if who.kind != SubjectKind::Human || is_agent_principal(&who.id) {
255 return refuse(format!(
256 "{} is not a person, and no agent holds a role (spec 3.5 §7.6)",
257 who.id
258 ));
259 }
260 if !governance.holds(&who.id, approval.role) {
261 return refuse(format!("{} does not hold the {:?} role", who.id, approval.role));
262 }
263 if proposer.is_some_and(|proposer| proposer == who.id) {
264 return refuse(format!("{} proposed it, so cannot also approve it", who.id));
265 }
266 acted.entry(who.id.as_str()).or_default().push(approval.role);
267 }
268 // The chain's roles go to distinct people, each in a role they approved in: the AWP
269 // chain's own matching over the roles acted in, so the order of approvals is irrelevant.
270 let acting = Governance {
271 roles: acted
272 .iter()
273 .map(|(who, roles)| RoleHolder { principal: (*who).to_string(), roles: roles.clone() })
274 .collect(),
275 approval_chains: Vec::new(),
276 };
277 let people: Vec<&str> = acted.keys().copied().collect();
278 if !chain.is_satisfied_by(&acting, &people) {
279 return refuse(format!(
280 "it needs {} approvals, one per role of {:?}, each by a different person acting in \
281 a role they hold",
282 chain.roles.len(),
283 chain.roles
284 ));
285 }
286 Ok(())
287}
288
289/// Every committed version of every site's charter (spec 3.5 §7.11), append-only, on
290/// in-memory, SQLite, PostgreSQL and Redis.
291///
292/// [`commit`](Self::commit) is the only way a version takes effect; it checks the draft and
293/// the decision and calls [`append`](Self::append), which backends implement as a
294/// compare-and-set on the site's latest version.
295///
296/// # Example
297///
298/// ```rust,ignore
299/// let committed = store.commit(draft, decision).await?;
300/// assert_eq!(store.current(committed.site()).await?.unwrap().version(), committed.version());
301/// ```
302#[async_trait]
303pub trait CharterStore: Send + Sync {
304 /// Appends `version` when its number is one past the site's latest committed version
305 /// (1 for a site with none); `false`, writing nothing, otherwise.
306 ///
307 /// # Errors
308 ///
309 /// Returns [`KernelError::Store`] when the backend fails.
310 async fn append(&self, version: CharterVersion) -> Result<bool>;
311
312 /// The site's version in force: its latest, or `None` before the first commit.
313 ///
314 /// # Errors
315 ///
316 /// Returns [`KernelError::Store`] when the backend fails.
317 async fn current(&self, site: Uuid) -> Result<Option<CharterVersion>>;
318
319 /// Every committed version of the site, oldest first.
320 ///
321 /// # Errors
322 ///
323 /// Returns [`KernelError::Store`] when the backend fails.
324 async fn history(&self, site: Uuid) -> Result<Vec<CharterVersion>>;
325
326 /// Version `version` of the site, or `None`.
327 ///
328 /// # Errors
329 ///
330 /// Returns [`KernelError::Store`] when the backend fails.
331 async fn get(&self, site: Uuid, version: u32) -> Result<Option<CharterVersion>>;
332
333 /// Commits `draft` by `decision` as the site's next version (spec 3.5 §7.6, A-I23).
334 ///
335 /// The draft must pass `Charter::validate()` (A-I14: no target without a baseline), and
336 /// no role in its governance may be held by an agent. The decision must satisfy the
337 /// approval chain for [`CHARTER_ACTION`] of the charter in force — or, for a site's first
338 /// charter, of the draft — by distinct people ([`check_chain`]), so a draft cannot
339 /// loosen the chain that approves it. The committed version is the next number, signed
340 /// with the decision: its id, the first owner's approval, the signed note and the time.
341 ///
342 /// # Errors
343 ///
344 /// Returns [`KernelError::Config`] for a draft that fails validation or names another
345 /// site, [`KernelError::Unauthorized`] for a decision that does not satisfy the chain,
346 /// an [`AdkError`](adk_core::AdkError) conflict when another commit took the version
347 /// first, or a store error.
348 async fn commit(&self, draft: Charter, decision: CommitDecision) -> Result<CharterVersion> {
349 let site = draft.site_id;
350 draft.validate().map_err(|error| KernelError::Config {
351 reason: format!("the charter draft for site {site} is invalid: {error}"),
352 })?;
353 if let Some(agent) = draft
354 .governance
355 .roles
356 .iter()
357 .find(|held| !held.roles.is_empty() && is_agent_principal(&held.principal))
358 {
359 return Err(KernelError::Config {
360 reason: format!(
361 "the charter draft gives {} the {:?} roles, but no agent holds a role (spec \
362 3.5 §7.6); name a person",
363 agent.principal, agent.roles
364 ),
365 });
366 }
367 let current = self.current(site).await?;
368 let governing = current.as_ref().map_or(&draft.governance, |c| &c.charter.governance);
369 check_chain(governing, &CHARTER_ACTION, &decision.approvals, None)
370 .map_err(|refusal| KernelError::Unauthorized { reason: refusal.to_string() })?;
371 let owner = decision
372 .approvals
373 .iter()
374 .find(|approval| approval.role == Role::Owner)
375 .or_else(|| decision.approvals.first())
376 .map(|approval| approval.principal.id.clone())
377 .unwrap_or_default();
378 let mut charter = draft;
379 charter.version = current.as_ref().map_or(1, |c| c.version() + 1);
380 charter.signed = Some(OwnerSignature {
381 decision: decision.decision_id.clone(),
382 principal: owner,
383 note: decision.signed_note.clone().unwrap_or_default(),
384 signed_at: decision.decided_at,
385 });
386 let version = CharterVersion::new(charter, decision, Utc::now());
387 if !self.append(version.clone()).await? {
388 return Err(KernelError::Core(adk_core::AdkError::new(
389 adk_core::ErrorComponent::Server,
390 adk_core::ErrorCategory::Conflict,
391 CHARTER_CONFLICT_CODE,
392 format!(
393 "another commit took version {} of site {site}'s charter first; read the \
394 current charter and commit again",
395 version.version()
396 ),
397 )));
398 }
399 Ok(version)
400 }
401}
402
403/// The error code of a commit another commit beat to its version.
404pub(crate) const CHARTER_CONFLICT_CODE: &str = "website.charter.conflict";
405
406/// Commits `draft` by `decision` on `store` as [`CharterStore::commit`] does, and records the
407/// outcome on `trail` (spec 3.5 §9.3): `website.approval_chain.satisfied` and
408/// `website.charter.committed` for a commit, `website.approval_chain.refused` for a decision
409/// whose chain is not satisfied. The records name the approvers and the decision, never the
410/// charter's text.
411///
412/// # Example
413///
414/// ```rust,ignore
415/// let version = commit_audited(store.as_ref(), draft, decision, Some(&trail)).await?;
416/// ```
417///
418/// # Errors
419///
420/// As [`CharterStore::commit`].
421pub async fn commit_audited(
422 store: &dyn CharterStore,
423 draft: Charter,
424 decision: CommitDecision,
425 trail: Option<&adk_core::audit_log::AuditTrail>,
426) -> Result<CharterVersion> {
427 use adk_core::audit_log::AuditActor;
428
429 let site = draft.site_id;
430 let decision_id = decision.decision_id.clone();
431 let approvers: Vec<String> =
432 decision.approvals.iter().map(|approval| approval.principal.id.clone()).collect();
433 let actor = || match decision.approvals.first() {
434 Some(approval) => AuditActor::subject(approval.principal.clone()),
435 None => AuditActor::default(),
436 };
437 let actor = actor();
438 let kind = super::WEBSITE_AUDIT_KIND;
439 match store.commit(draft, decision).await {
440 Ok(version) => {
441 let fields = serde_json::json!({
442 "site": site,
443 "action": CHARTER_ACTION.as_str(),
444 "decision": decision_id,
445 "approvers": approvers,
446 "charterVersion": version.version(),
447 "signedNote": version.decision.signed_note,
448 });
449 super::record(
450 trail,
451 kind,
452 super::audit::APPROVAL_CHAIN_SATISFIED,
453 actor.clone(),
454 fields.clone(),
455 )
456 .await;
457 super::record(trail, kind, super::audit::CHARTER_COMMITTED, actor, fields).await;
458 Ok(version)
459 }
460 Err(KernelError::Unauthorized { reason }) => {
461 let fields = serde_json::json!({
462 "site": site,
463 "action": CHARTER_ACTION.as_str(),
464 "decision": decision_id,
465 "approvers": approvers,
466 "reason": reason,
467 });
468 super::record(trail, kind, super::audit::APPROVAL_CHAIN_REFUSED, actor, fields).await;
469 Err(KernelError::Unauthorized { reason })
470 }
471 Err(error) => Err(error),
472 }
473}