use std::collections::BTreeMap;
use std::fmt;
use adk_core::principal::{SubjectKind, SubjectRef};
use async_trait::async_trait;
use awp_types::{
ActionClass, ApprovalChain, Charter, Governance, OwnerSignature, Role, RoleHolder,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::error::{KernelError, Result};
pub const CHARTER_ACTION: ActionClass = ActionClass::CharterChange;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RoleApproval {
pub role: Role,
pub principal: SubjectRef,
pub at: DateTime<Utc>,
}
impl RoleApproval {
pub fn new(role: Role, principal: SubjectRef, at: DateTime<Utc>) -> Self {
Self { role, principal, at }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CommitDecision {
pub decision_id: String,
pub approvals: Vec<RoleApproval>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signed_note: Option<String>,
pub decided_at: DateTime<Utc>,
}
impl CommitDecision {
pub fn new(decision_id: impl Into<String>, decided_at: DateTime<Utc>) -> Self {
Self {
decision_id: decision_id.into(),
approvals: Vec::new(),
signed_note: None,
decided_at,
}
}
#[must_use]
pub fn with_approval(mut self, approval: RoleApproval) -> Self {
self.approvals.push(approval);
self
}
#[must_use]
pub fn with_signed_note(mut self, note: impl Into<String>) -> Self {
self.signed_note = Some(note.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CharterVersion {
pub charter: Charter,
pub decision: CommitDecision,
pub committed_at: DateTime<Utc>,
}
impl CharterVersion {
pub fn new(charter: Charter, decision: CommitDecision, committed_at: DateTime<Utc>) -> Self {
Self { charter, decision, committed_at }
}
pub fn site(&self) -> Uuid {
self.charter.site_id
}
pub fn version(&self) -> u32 {
self.charter.version
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ChainRefusal {
pub action: String,
pub reason: String,
}
impl ChainRefusal {
pub fn new(action: impl Into<String>, reason: impl Into<String>) -> Self {
Self { action: action.into(), reason: reason.into() }
}
}
impl fmt::Display for ChainRefusal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "the `{}` approval chain is not satisfied: {}", self.action, self.reason)
}
}
pub fn is_agent_principal(id: &str) -> bool {
let id = id.trim().to_ascii_lowercase();
id.starts_with("urn:adk:agent:") || id.starts_with("spiffe://")
}
pub fn check_chain(
governance: &Governance,
action: &ActionClass,
approvals: &[RoleApproval],
proposer: Option<&str>,
) -> std::result::Result<(), ChainRefusal> {
let refuse = |reason: String| Err(ChainRefusal::new(action.as_str(), reason));
let chain = governance
.approval_chains
.iter()
.find(|chain| &chain.action == action)
.cloned()
.unwrap_or_else(|| ApprovalChain { action: action.clone(), roles: vec![Role::Owner] });
if chain.roles.is_empty() {
return refuse("the chain lists no role, so nobody can satisfy it".into());
}
let mut acted: BTreeMap<&str, Vec<Role>> = BTreeMap::new();
for approval in approvals {
let who = &approval.principal;
if who.kind != SubjectKind::Human || is_agent_principal(&who.id) {
return refuse(format!(
"{} is not a person, and no agent holds a role (spec 3.5 §7.6)",
who.id
));
}
if !governance.holds(&who.id, approval.role) {
return refuse(format!("{} does not hold the {:?} role", who.id, approval.role));
}
if proposer.is_some_and(|proposer| proposer == who.id) {
return refuse(format!("{} proposed it, so cannot also approve it", who.id));
}
acted.entry(who.id.as_str()).or_default().push(approval.role);
}
let acting = Governance {
roles: acted
.iter()
.map(|(who, roles)| RoleHolder { principal: (*who).to_string(), roles: roles.clone() })
.collect(),
approval_chains: Vec::new(),
};
let people: Vec<&str> = acted.keys().copied().collect();
if !chain.is_satisfied_by(&acting, &people) {
return refuse(format!(
"it needs {} approvals, one per role of {:?}, each by a different person acting in \
a role they hold",
chain.roles.len(),
chain.roles
));
}
Ok(())
}
#[async_trait]
pub trait CharterStore: Send + Sync {
async fn append(&self, version: CharterVersion) -> Result<bool>;
async fn current(&self, site: Uuid) -> Result<Option<CharterVersion>>;
async fn history(&self, site: Uuid) -> Result<Vec<CharterVersion>>;
async fn get(&self, site: Uuid, version: u32) -> Result<Option<CharterVersion>>;
async fn commit(&self, draft: Charter, decision: CommitDecision) -> Result<CharterVersion> {
let site = draft.site_id;
draft.validate().map_err(|error| KernelError::Config {
reason: format!("the charter draft for site {site} is invalid: {error}"),
})?;
if let Some(agent) = draft
.governance
.roles
.iter()
.find(|held| !held.roles.is_empty() && is_agent_principal(&held.principal))
{
return Err(KernelError::Config {
reason: format!(
"the charter draft gives {} the {:?} roles, but no agent holds a role (spec \
3.5 §7.6); name a person",
agent.principal, agent.roles
),
});
}
let current = self.current(site).await?;
let governing = current.as_ref().map_or(&draft.governance, |c| &c.charter.governance);
check_chain(governing, &CHARTER_ACTION, &decision.approvals, None)
.map_err(|refusal| KernelError::Unauthorized { reason: refusal.to_string() })?;
let owner = decision
.approvals
.iter()
.find(|approval| approval.role == Role::Owner)
.or_else(|| decision.approvals.first())
.map(|approval| approval.principal.id.clone())
.unwrap_or_default();
let mut charter = draft;
charter.version = current.as_ref().map_or(1, |c| c.version() + 1);
charter.signed = Some(OwnerSignature {
decision: decision.decision_id.clone(),
principal: owner,
note: decision.signed_note.clone().unwrap_or_default(),
signed_at: decision.decided_at,
});
let version = CharterVersion::new(charter, decision, Utc::now());
if !self.append(version.clone()).await? {
return Err(KernelError::Core(adk_core::AdkError::new(
adk_core::ErrorComponent::Server,
adk_core::ErrorCategory::Conflict,
CHARTER_CONFLICT_CODE,
format!(
"another commit took version {} of site {site}'s charter first; read the \
current charter and commit again",
version.version()
),
)));
}
Ok(version)
}
}
pub(crate) const CHARTER_CONFLICT_CODE: &str = "website.charter.conflict";
pub async fn commit_audited(
store: &dyn CharterStore,
draft: Charter,
decision: CommitDecision,
trail: Option<&adk_core::audit_log::AuditTrail>,
) -> Result<CharterVersion> {
use adk_core::audit_log::AuditActor;
let site = draft.site_id;
let decision_id = decision.decision_id.clone();
let approvers: Vec<String> =
decision.approvals.iter().map(|approval| approval.principal.id.clone()).collect();
let actor = || match decision.approvals.first() {
Some(approval) => AuditActor::subject(approval.principal.clone()),
None => AuditActor::default(),
};
let actor = actor();
let kind = super::WEBSITE_AUDIT_KIND;
match store.commit(draft, decision).await {
Ok(version) => {
let fields = serde_json::json!({
"site": site,
"action": CHARTER_ACTION.as_str(),
"decision": decision_id,
"approvers": approvers,
"charterVersion": version.version(),
"signedNote": version.decision.signed_note,
});
super::record(
trail,
kind,
super::audit::APPROVAL_CHAIN_SATISFIED,
actor.clone(),
fields.clone(),
)
.await;
super::record(trail, kind, super::audit::CHARTER_COMMITTED, actor, fields).await;
Ok(version)
}
Err(KernelError::Unauthorized { reason }) => {
let fields = serde_json::json!({
"site": site,
"action": CHARTER_ACTION.as_str(),
"decision": decision_id,
"approvers": approvers,
"reason": reason,
});
super::record(trail, kind, super::audit::APPROVAL_CHAIN_REFUSED, actor, fields).await;
Err(KernelError::Unauthorized { reason })
}
Err(error) => Err(error),
}
}