adk_kernel/charter/directory.rs
1//! The charter as the approval service's directory (spec 3.5 §7.6, A-I23): who holds which
2//! role is what the charter in force says, never what a surface asserts.
3
4use std::sync::Arc;
5
6use adk_core::principal::{SubjectKind, SubjectRef};
7use adk_core::{AdkError, ApprovalPolicy, ApprovalRequest, ApproverDirectory, ApproverSelector};
8use async_trait::async_trait;
9use awp_types::{ActionClass, Governance, Role};
10use uuid::Uuid;
11
12use super::store::{CharterStore, is_agent_principal};
13
14/// The approver group of `role`: `role:{role}`, such as `role:publisher`.
15///
16/// # Example
17///
18/// ```rust
19/// use adk_kernel::charter::{group_role, role_group};
20/// use awp_types::Role;
21///
22/// assert_eq!(role_group(Role::Publisher), "role:publisher");
23/// assert_eq!(group_role("role:publisher"), Some(Role::Publisher));
24/// ```
25pub fn role_group(role: Role) -> String {
26 let name = serde_json::to_value(role)
27 .ok()
28 .and_then(|value| value.as_str().map(str::to_owned))
29 .unwrap_or_default();
30 format!("role:{name}")
31}
32
33/// The role a `role:{role}` group names; `None` for any other group.
34pub fn group_role(group: &str) -> Option<Role> {
35 let name = group.strip_prefix("role:")?;
36 serde_json::from_value(serde_json::Value::String(name.to_string())).ok()
37}
38
39/// The approval policy of `action`'s chain under `governance` (spec 3.5 §7.6, A-I23): one
40/// slot per role of the chain, `role:{role}`, each filled by a distinct person who holds the
41/// role, none of them the requester. A charter that names no chain for `action` needs one
42/// owner, as [`check_chain`](super::check_chain) does.
43///
44/// # Example
45///
46/// ```rust
47/// use adk_core::ApproverSelector;
48/// use adk_kernel::charter::chain_policy;
49/// use awp_types::{ActionClass, ApprovalChain, Governance, Role};
50///
51/// let governance = Governance {
52/// roles: Vec::new(),
53/// approval_chains: vec![ApprovalChain {
54/// action: ActionClass::Publish,
55/// roles: vec![Role::Editor, Role::Publisher],
56/// }],
57/// };
58/// let policy = chain_policy(&governance, &ActionClass::Publish);
59/// assert_eq!(
60/// policy.slots,
61/// [ApproverSelector::group("role:editor"), ApproverSelector::group("role:publisher")]
62/// );
63/// assert_eq!(policy.quorum, 2);
64/// assert!(policy.forbid_self_approval);
65/// let charter = chain_policy(&governance, &ActionClass::CharterChange);
66/// assert_eq!(charter.slots, [ApproverSelector::group("role:owner")]);
67/// ```
68pub fn chain_policy(governance: &Governance, action: &ActionClass) -> ApprovalPolicy {
69 let roles = governance
70 .approval_chains
71 .iter()
72 .find(|chain| &chain.action == action)
73 .map_or_else(|| vec![Role::Owner], |chain| chain.roles.clone());
74 ApprovalPolicy::for_slots(
75 roles.into_iter().map(|role| ApproverSelector::group(role_group(role))),
76 )
77}
78
79/// The approval service's [`ApproverDirectory`] over the site charters in a
80/// [`CharterStore`] (spec 3.5 §7.6, A-I23): a person's groups are `role:{role}` for every
81/// role their site's charter in force gives them, so a release chain, a charter signature or
82/// a promotion is decided only by the people the charter names, whichever surface they
83/// decide on. An agent holds no role. The directory governs the `role:` groups only: a
84/// caller's claim to one is ignored, while other groups, such as an operator scope, stay as
85/// the caller's authentication asserted them.
86///
87/// A request names its site in `args_redacted.site`; one that names none belongs to the
88/// site set with [`for_site`](Self::for_site), so one directory serves every site of an
89/// agency's kernel.
90///
91/// | Request | `role:` groups come from |
92/// |---|---|
93/// | its site has a charter in force | that charter's governance |
94/// | no charter in force, and the request carries the charter it would commit (`args_redacted.charter`) | that charter's governance: the first charter's own signers sign it |
95/// | otherwise, or no site | none |
96///
97/// # Example
98///
99/// ```rust
100/// use std::sync::Arc;
101/// use adk_core::{ApproverDirectory, InMemoryApprovalStore, StoreApprovalService};
102/// use adk_kernel::charter::{CharterDirectory, InMemoryCharterStore};
103///
104/// let site = uuid::Uuid::new_v4();
105/// let directory = CharterDirectory::new(Arc::new(InMemoryCharterStore::new())).for_site(site);
106/// assert!(directory.governs("role:publisher"));
107/// assert!(!directory.governs("operator"));
108/// let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
109/// .with_directory(Arc::new(directory));
110/// # let _ = service;
111/// ```
112pub struct CharterDirectory {
113 charters: Arc<dyn CharterStore>,
114 site: Option<Uuid>,
115}
116
117impl std::fmt::Debug for CharterDirectory {
118 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119 f.debug_struct("CharterDirectory").field("site", &self.site).finish_non_exhaustive()
120 }
121}
122
123impl CharterDirectory {
124 /// The directory of every site whose charters `charters` keeps.
125 pub fn new(charters: Arc<dyn CharterStore>) -> Self {
126 Self { charters, site: None }
127 }
128
129 /// Reads a request that names no site as `site`'s.
130 #[must_use]
131 pub fn for_site(mut self, site: Uuid) -> Self {
132 self.site = Some(site);
133 self
134 }
135}
136
137#[async_trait]
138impl ApproverDirectory for CharterDirectory {
139 async fn groups(
140 &self,
141 subject: &SubjectRef,
142 request: &ApprovalRequest,
143 ) -> adk_core::Result<Vec<String>> {
144 if subject.kind != SubjectKind::Human || is_agent_principal(&subject.id) {
145 return Ok(Vec::new());
146 }
147 let named = request.args_redacted.get("site").and_then(serde_json::Value::as_str);
148 let site = match named {
149 Some(named) => named.parse::<Uuid>().ok(),
150 None => self.site,
151 };
152 let Some(site) = site else { return Ok(Vec::new()) };
153 let current = self.charters.current(site).await.map_err(|error| {
154 AdkError::new(
155 adk_core::ErrorComponent::Agent,
156 adk_core::ErrorCategory::Unavailable,
157 "charter.directory.unavailable",
158 format!("the charter store cannot say who holds which role: {error}"),
159 )
160 })?;
161 let proposed = || request.args_redacted.get("charter")?.get("governance").cloned();
162 let governance = match current {
163 Some(version) => version.charter.governance,
164 None => match proposed() {
165 Some(proposed) => {
166 serde_json::from_value::<Governance>(proposed).unwrap_or_default()
167 }
168 None => return Ok(Vec::new()),
169 },
170 };
171 Ok(governance
172 .roles
173 .iter()
174 .filter(|holder| holder.principal == subject.id)
175 .flat_map(|holder| holder.roles.iter().copied())
176 .map(role_group)
177 .collect())
178 }
179
180 fn governs(&self, group: &str) -> bool {
181 group.starts_with("role:")
182 }
183}