Skip to main content

qualia_cooperative_core/authoring/delegation/
policy.rs

1use super::*;
2use crate::{
3    agency_delegation::{delegation_permits, AccessRequest, ConsentState},
4    agency_domain::{agency_domain_taxonomy, ids::AI_PROXY},
5    authority_type::ids,
6    taxonomy::Sphere,
7    trigger::TriggerContext,
8};
9use qualia_app_contract::{delegation::DelegationMode, effects::CommandEffect};
10use std::io::Write;
11
12fn text(value: &str) -> bool {
13    !value.trim().is_empty() && value.len() <= 4096
14}
15
16struct ByteCount(usize);
17impl Write for ByteCount {
18    fn write(&mut self, value: &[u8]) -> std::io::Result<usize> {
19        self.0 = self
20            .0
21            .checked_add(value.len())
22            .filter(|n| *n <= MAX_AUTHORING_DELEGATION_BYTES)
23            .ok_or_else(|| std::io::Error::other("delegation byte budget exceeded"))?;
24        Ok(value.len())
25    }
26    fn flush(&mut self) -> std::io::Result<()> {
27        Ok(())
28    }
29}
30
31/// Structural/policy validation only. The native owner must verify every
32/// signature, qualified association and root adoption separately.
33pub fn validate_delegation(d: &AuthoringDelegation, now: u64) -> Result<(), DelegationError> {
34    let a = &d.agency;
35    let t = &d.task;
36    if d.actions.is_empty()
37        || d.actions.len() > 10
38        || a.agent_dids.len() != 1
39        || a.scope.len() > 12
40        || t.allowed_command_ids.is_empty()
41        || t.allowed_command_ids.len() > 32
42        || t.allowed_effects.is_empty()
43        || t.allowed_effects.len() > 8
44        || d.remaining_depth as usize >= MAX_AUTHORING_DELEGATION_DEPTH
45        || a.trigger.is_some()
46        || !a.transfer_schedule.is_empty()
47    {
48        return Err(DelegationError::Bounds);
49    }
50    for value in [
51        &d.root_subject,
52        &d.project_id,
53        &d.document_id,
54        &d.source_id,
55        &d.grantor_subject,
56        &d.grantee_subject,
57        &a.id,
58        &a.principal_did,
59        &a.agent_dids[0],
60        &a.values_anchor,
61        &t.delegation_id,
62        &t.principal_id,
63        &t.actor_id,
64        &t.goal,
65    ] {
66        if !text(value) {
67            return Err(DelegationError::Binding);
68        }
69    }
70    if d.version != 1
71        || d.root_adoption_digest == [0; 32]
72        || d.grantor_subject == d.grantee_subject
73        || d.grantor_controller == [0; 32]
74        || d.grantee_controller == [0; 32]
75        || t.principal_id != d.root_subject
76        || t.actor_id != d.grantee_subject
77        || t.app_id.as_str() != "poet"
78        || t.delegation_id != a.id
79        || a.evidence_ref.as_deref().is_none_or(|s| !text(s))
80        || d.actions
81            .iter()
82            .enumerate()
83            .any(|(i, v)| d.actions[..i].contains(v))
84        || t.allowed_effects
85            .iter()
86            .enumerate()
87            .any(|(i, v)| t.allowed_effects[..i].contains(v))
88        || t.allowed_command_ids
89            .iter()
90            .enumerate()
91            .any(|(i, v)| !text(v) || t.allowed_command_ids[..i].contains(v))
92    {
93        return Err(DelegationError::Binding);
94    }
95    // The first native adapter supports explicit automated agency only. Other
96    // profiles/triggers/jurisdictions remain retained data, never silently ignored.
97    if a.domain != AI_PROXY
98        || a.jurisdiction.is_some()
99        || a.authority.modality.as_deref() != Some(ids::MOD_AUTOMATED)
100        || a.authority.trigger.as_deref() != Some(ids::TRIG_PERSISTENT)
101        || a.authority.accountability.as_deref() != Some(ids::ACCT_VALUES_BOUND)
102        || !a.authority.flags.is_empty()
103    {
104        return Err(DelegationError::UnsupportedPolicy);
105    }
106    if a.consent != ConsentState::Granted {
107        return Err(DelegationError::Consent);
108    }
109    let end = a.valid_to_unix.ok_or(DelegationError::Binding)? as u64;
110    if a.revoked
111        || a.valid_from_unix as u64 >= end
112        || now < a.valid_from_unix as u64
113        || now >= end
114        || !t.is_active()
115        || now
116            .checked_mul(1000)
117            .is_none_or(|ms| ms >= t.expiry_timestamp_ms.get())
118        || t.expiry_timestamp_ms.get() > end * 1000
119    {
120        return Err(DelegationError::ExpiredOrRevoked);
121    }
122    if t.budgets.max_steps == 0
123        || t.budgets.max_cpu_time_ms == 0
124        || t.budgets.max_memory_bytes == 0
125        || t.budgets.external_cost_minor_units.is_some_and(|n| n != 0)
126        || t.allowed_effects.contains(&CommandEffect::ExternalCharge)
127    {
128        return Err(DelegationError::Budget);
129    }
130    // No inferred network/provider/device authority in this bounded adapter.
131    if t.allowed_effects.iter().any(|e| {
132        matches!(
133            e,
134            CommandEffect::NetworkDisclosure | CommandEffect::DeviceCapture
135        )
136    }) {
137        return Err(DelegationError::UnsupportedPolicy);
138    }
139    if a.scope.iter().any(|(k, v)| {
140        !text(k) || !text(v) || !matches!(k.as_str(), "purpose" | "action" | "data_class")
141    }) || a
142        .scope
143        .iter()
144        .enumerate()
145        .any(|(i, v)| a.scope[..i].contains(v))
146        || !a.scope.iter().any(|(k, v)| k == "purpose" && v == &t.goal)
147        || !a
148            .scope
149            .iter()
150            .any(|(k, v)| k == "data_class" && v == AUTHORING_DATA_CLASS)
151        || d.actions.iter().any(|action| {
152            !a.scope
153                .iter()
154                .any(|(k, v)| k == "action" && v == action_name(*action))
155        })
156    {
157        return Err(DelegationError::Scope);
158    }
159    serde_json::to_writer(&mut ByteCount(0), d).map_err(|_| DelegationError::Bounds)?;
160    Ok(())
161}
162
163pub fn action_name(action: super::super::AuthoringAction) -> &'static str {
164    use super::super::AuthoringAction::*;
165    match action {
166        ReadSource => "read_source",
167        ExecuteSource => "execute_source",
168        MaterialEdit => "material_edit",
169        Undo => "undo",
170        Redo => "redo",
171        Rebuild => "rebuild",
172        SaveCheckpoint => "save_checkpoint",
173        ReopenCheckpoint => "reopen_checkpoint",
174        ContributionRecord => "contribution_record",
175        ReviewDecision => "review_decision",
176    }
177}
178
179/// Check the operation against one already admitted edge. This returns no
180/// reusable permit and consumes no budget; the locked host must do both.
181pub fn check_delegated_operation(
182    d: &AuthoringDelegation,
183    op: &DelegatedOperation<'_>,
184) -> Result<(), DelegationError> {
185    validate_delegation(d, op.now_unix)?;
186    if op.actor_subject != d.grantee_subject
187        || op.actor_controller != &d.grantee_controller
188        || op.target.project_id != d.project_id
189        || op.target.document_id != d.document_id
190        || op.target.source_id != d.source_id
191        || op.purpose != d.task.goal
192        || !d.actions.contains(&op.action)
193        || !d
194            .task
195            .allowed_command_ids
196            .iter()
197            .any(|v| v == op.command_id)
198        || op.effects.is_empty()
199        || op
200            .effects
201            .iter()
202            .any(|effect| !d.task.is_effect_allowed(effect))
203    {
204        return Err(DelegationError::Scope);
205    }
206    use super::super::AuthoringAction::*;
207    let required_effect = match op.action {
208        ReadSource => CommandEffect::Read,
209        SaveCheckpoint => CommandEffect::FilesystemWrite,
210        ContributionRecord | ReviewDecision => CommandEffect::WorkspaceMutation,
211        _ => CommandEffect::DocumentMutation,
212    };
213    if !op.effects.contains(&required_effect) {
214        return Err(DelegationError::Scope);
215    }
216    match d.task.mode {
217        DelegationMode::Observe
218            if op.action == super::super::AuthoringAction::ReadSource
219                && op.effects == [CommandEffect::Read] => {}
220        DelegationMode::BoundedDelegation => {}
221        _ => return Err(DelegationError::UnsupportedPolicy),
222    }
223    let req = AccessRequest {
224        domain: d.agency.domain.clone(),
225        data_class: AUTHORING_DATA_CLASS.into(),
226        action: match op.action {
227            super::super::AuthoringAction::ReadSource => "read",
228            super::super::AuthoringAction::ReviewDecision => "decide",
229            _ => "write",
230        }
231        .into(),
232        sphere: Sphere::Personhood,
233        jurisdiction: None,
234        provenance: None,
235    };
236    // Native action/purpose/data constraints are checked above; reuse the
237    // existing agency evaluator for its consent/domain/selfhood semantics.
238    let now = u32::try_from(op.now_unix).map_err(|_| DelegationError::ExpiredOrRevoked)?;
239    if !delegation_permits(
240        &d.agency,
241        &agency_domain_taxonomy(),
242        &req,
243        &TriggerContext::at(now),
244    )
245    .is_permit()
246    {
247        return Err(DelegationError::Scope);
248    }
249    Ok(())
250}
251
252/// Parent hash/signature matching is performed by the native verifier. This
253/// compares all policy-bearing fields without inferring wildcard authority.
254pub fn check_parent_attenuation(
255    p: &AuthoringDelegation,
256    c: &AuthoringDelegation,
257) -> Result<(), DelegationError> {
258    let pb = &p.task.budgets;
259    let cb = &c.task.budgets;
260    if p.remaining_depth == 0
261        || c.remaining_depth >= p.remaining_depth
262        || c.root_subject != p.root_subject
263        || c.root_adoption_digest != p.root_adoption_digest
264        || c.project_id != p.project_id
265        || c.document_id != p.document_id
266        || c.source_id != p.source_id
267        || c.grantor_subject != p.grantee_subject
268        || c.grantor_controller != p.grantee_controller
269        || c.agency.principal_did != p.agency.principal_did
270        || c.agency.domain != p.agency.domain
271        || c.agency.authority != p.agency.authority
272        || c.agency.values_anchor != p.agency.values_anchor
273        || c.agency.jurisdiction != p.agency.jurisdiction
274        || c.agency.precedence != p.agency.precedence
275        || c.agency.valid_from_unix < p.agency.valid_from_unix
276        || c.agency.valid_to_unix > p.agency.valid_to_unix
277        || c.task.expiry_timestamp_ms > p.task.expiry_timestamp_ms
278        || c.task.goal != p.task.goal
279        || c.task.app_id != p.task.app_id
280        || c.task.mode != p.task.mode
281        || c.actions.iter().any(|v| !p.actions.contains(v))
282        || c.agency.scope.iter().any(|v| !p.agency.scope.contains(v))
283        || c.task
284            .allowed_effects
285            .iter()
286            .any(|v| !p.task.allowed_effects.contains(v))
287        || c.task
288            .allowed_command_ids
289            .iter()
290            .any(|v| !p.task.allowed_command_ids.contains(v))
291        || cb.max_steps > pb.max_steps
292        || cb.max_cpu_time_ms > pb.max_cpu_time_ms
293        || cb.max_memory_bytes > pb.max_memory_bytes
294        || cb.external_cost_minor_units != pb.external_cost_minor_units
295    {
296        return Err(DelegationError::Attenuation);
297    }
298    Ok(())
299}