Skip to main content

vela_protocol/kernel/
principal_capability.rs

1//! Stable principals and retained short-lived capability claims.
2//!
3//! Runtime OAuth, OIDC, SciTokens, GitHub App, or local credentials are
4//! adapters. Their bearer bytes never enter canonical Vela history. This
5//! module defines only the closed, independently replayable claims retained by
6//! an authority record.
7
8use std::collections::BTreeSet;
9
10use chrono::{DateTime, SecondsFormat};
11use serde::{Deserialize, Serialize};
12
13use crate::canonical::sha256_canonical;
14
15pub const PRINCIPAL_SCHEMA_V1: &str = "vela.principal.v1";
16pub const CAPABILITY_SCHEMA_V1: &str = "vela.capability-grant.v1";
17pub const VERIFIED_CAPABILITY_CLAIM_SCHEMA_V1: &str = "vela.verified-capability-claim.v1";
18pub const CAPABILITY_AUDIENCE_V1: &str = "vela.repository-authority.v1";
19pub const MAX_CAPABILITY_LIFETIME_SECONDS: i64 = 24 * 60 * 60;
20pub const MAX_CAPABILITY_DELEGATION_DEPTH: u8 = 1;
21pub const HUMAN_ONLY_AUTHORITY_ACTIONS_V1: &[&str] = &[
22    "authority_initialize",
23    "authority_close",
24    "authority_revoke",
25    "authority_rotate",
26    "bulk_correct",
27    "destroy",
28    "membership_manage",
29    "policy_activate",
30    "policy_revoke",
31    "policy_rotate",
32    "quorum_manage",
33    "recovery_approve",
34    "review_accept",
35    "review_reject",
36];
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40pub enum PrincipalClass {
41    Human,
42    Agent,
43    Workload,
44    Service,
45    Institution,
46}
47
48pub fn principal_class_may_request(principal_class: PrincipalClass, action: &str) -> bool {
49    !matches!(
50        principal_class,
51        PrincipalClass::Agent | PrincipalClass::Workload
52    ) || !HUMAN_ONLY_AUTHORITY_ACTIONS_V1.contains(&action)
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum ExternalAccountKind {
58    Local,
59    Oidc,
60    Orcid,
61    Spiffe,
62    GithubApp,
63}
64
65impl ExternalAccountKind {
66    fn prefix(self) -> &'static str {
67        match self {
68            Self::Local => "local",
69            Self::Oidc => "oidc",
70            Self::Orcid => "orcid",
71            Self::Spiffe => "spiffe",
72            Self::GithubApp => "github-app",
73        }
74    }
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
78#[serde(deny_unknown_fields)]
79pub struct ExternalAccountLinkV1 {
80    pub kind: ExternalAccountKind,
81    pub issuer: String,
82    pub subject: String,
83    pub linked_at: String,
84    pub revoked_at: Option<String>,
85}
86
87impl ExternalAccountLinkV1 {
88    pub fn principal_identifier(&self) -> String {
89        format!("{}:{}|{}", self.kind.prefix(), self.issuer, self.subject)
90    }
91
92    fn validate(&self) -> Result<(), String> {
93        require_bounded_text("account issuer", &self.issuer, 1024)?;
94        require_bounded_text("account subject", &self.subject, 1024)?;
95        let linked_at = parse_canonical_time("account linked_at", &self.linked_at)?;
96        if let Some(revoked_at) = &self.revoked_at
97            && parse_canonical_time("account revoked_at", revoked_at)? < linked_at
98        {
99            return Err("account revocation precedes account linkage".into());
100        }
101        Ok(())
102    }
103}
104
105/// A stable principal record. Display name and affiliation are readable
106/// snapshots only; authorization uses `principal_id`, class, current account
107/// links, roles, and capabilities.
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(deny_unknown_fields)]
110pub struct PrincipalV1 {
111    pub schema: String,
112    pub principal_id: String,
113    pub principal_class: PrincipalClass,
114    pub display_name: Option<String>,
115    pub affiliation: Option<String>,
116    pub account_links: Vec<ExternalAccountLinkV1>,
117}
118
119impl PrincipalV1 {
120    pub fn validate(&self) -> Result<(), String> {
121        if self.schema != PRINCIPAL_SCHEMA_V1 {
122            return Err(format!("principal schema must be {PRINCIPAL_SCHEMA_V1}"));
123        }
124        require_bounded_text("principal_id", &self.principal_id, 2048)?;
125        if let Some(display_name) = &self.display_name {
126            require_bounded_text("display_name", display_name, 512)?;
127        }
128        if let Some(affiliation) = &self.affiliation {
129            require_bounded_text("affiliation", affiliation, 512)?;
130        }
131
132        let mut links = BTreeSet::new();
133        let mut link_identifiers = BTreeSet::new();
134        for link in &self.account_links {
135            link.validate()?;
136            if !links.insert(link) || !link_identifiers.insert(link.principal_identifier()) {
137                return Err("principal contains a duplicate account link".into());
138            }
139        }
140        if self.account_links.windows(2).any(|pair| pair[0] >= pair[1]) {
141            return Err("principal account links must be strictly sorted".into());
142        }
143
144        match self.principal_class {
145            PrincipalClass::Human => {
146                if self.account_links.is_empty()
147                    || !self
148                        .account_links
149                        .iter()
150                        .any(|link| link.principal_identifier() == self.principal_id)
151                {
152                    return Err(
153                        "human principal_id must equal one retained issuer-subject link".into(),
154                    );
155                }
156                if self.account_links.iter().any(|link| {
157                    !matches!(
158                        link.kind,
159                        ExternalAccountKind::Local
160                            | ExternalAccountKind::Oidc
161                            | ExternalAccountKind::Orcid
162                    )
163                }) {
164                    return Err("human principals may use only local, OIDC, or ORCID links".into());
165                }
166            }
167            PrincipalClass::Agent => {
168                require_prefix("agent principal", &self.principal_id, "agent:")?
169            }
170            PrincipalClass::Workload => {
171                require_one_prefix(
172                    "workload principal",
173                    &self.principal_id,
174                    &["workload:", "oidc:", "spiffe:", "github-app:"],
175                )?;
176            }
177            PrincipalClass::Service => {
178                require_prefix("service principal", &self.principal_id, "service:")?;
179            }
180            PrincipalClass::Institution => {
181                require_prefix("institution principal", &self.principal_id, "institution:")?;
182            }
183        }
184        Ok(())
185    }
186
187    pub fn root(&self) -> Result<String, String> {
188        self.validate()?;
189        Ok(format!("sha256:{}", sha256_canonical(self)?))
190    }
191}
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
194#[serde(rename_all = "snake_case")]
195pub enum CapabilityAction {
196    ArtifactRegister,
197    ArtifactRetractOwn,
198    ProposalCreate,
199    ProposalWithdrawOwn,
200    ReceiptLand,
201    VerifierAttach,
202    WorkClaim,
203}
204
205#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
206#[serde(rename_all = "snake_case")]
207pub enum ConsequenceCeiling {
208    PendingReview,
209    PolicyRouted,
210}
211
212#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
213#[serde(deny_unknown_fields)]
214pub struct CapabilityResourceBindingV1 {
215    pub resource_type: String,
216    pub resource_id: String,
217    pub resource_root: String,
218}
219
220impl CapabilityResourceBindingV1 {
221    fn validate(&self) -> Result<(), String> {
222        require_bounded_text("capability resource_type", &self.resource_type, 128)?;
223        require_bounded_text("capability resource_id", &self.resource_id, 1024)?;
224        require_sha256("capability resource_root", &self.resource_root)
225    }
226}
227
228#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
229#[serde(deny_unknown_fields)]
230pub struct CapabilityExecutionBindingV1 {
231    pub binding_type: String,
232    pub binding_root: String,
233}
234
235impl CapabilityExecutionBindingV1 {
236    fn validate(&self) -> Result<(), String> {
237        require_bounded_text("execution binding_type", &self.binding_type, 128)?;
238        require_sha256("execution binding_root", &self.binding_root)
239    }
240}
241
242/// Canonical grant identity. A JWT/CWT or provider token may carry equivalent
243/// runtime claims, but the bearer token is never serialized here.
244#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
245#[serde(deny_unknown_fields)]
246pub struct CapabilityGrantV1 {
247    pub schema: String,
248    pub capability_id: String,
249    pub issuer_principal_id: String,
250    pub subject_principal_id: String,
251    pub subject_class: PrincipalClass,
252    pub current_actor_principal_id: String,
253    pub actor_chain: Vec<String>,
254    pub parent_capability_root: Option<String>,
255    pub delegation_depth: u8,
256    pub maximum_delegation_depth: u8,
257    pub audience: String,
258    pub frontier_id: String,
259    pub actions: Vec<CapabilityAction>,
260    pub resources: Vec<CapabilityResourceBindingV1>,
261    pub execution_bindings: Vec<CapabilityExecutionBindingV1>,
262    pub consequence_ceiling: ConsequenceCeiling,
263    pub issued_at: String,
264    pub not_before: String,
265    pub expires_at: String,
266    pub token_id: String,
267    pub revocation_ref: Option<String>,
268}
269
270impl CapabilityGrantV1 {
271    pub fn new(
272        issuer_principal_id: String,
273        subject_principal_id: String,
274        subject_class: PrincipalClass,
275        current_actor_principal_id: String,
276        actor_chain: Vec<String>,
277        parent_capability_root: Option<String>,
278        delegation_depth: u8,
279        maximum_delegation_depth: u8,
280        audience: String,
281        frontier_id: String,
282        actions: Vec<CapabilityAction>,
283        resources: Vec<CapabilityResourceBindingV1>,
284        execution_bindings: Vec<CapabilityExecutionBindingV1>,
285        consequence_ceiling: ConsequenceCeiling,
286        issued_at: String,
287        not_before: String,
288        expires_at: String,
289        token_id: String,
290        revocation_ref: Option<String>,
291    ) -> Result<Self, String> {
292        let mut grant = Self {
293            schema: CAPABILITY_SCHEMA_V1.into(),
294            capability_id: String::new(),
295            issuer_principal_id,
296            subject_principal_id,
297            subject_class,
298            current_actor_principal_id,
299            actor_chain,
300            parent_capability_root,
301            delegation_depth,
302            maximum_delegation_depth,
303            audience,
304            frontier_id,
305            actions,
306            resources,
307            execution_bindings,
308            consequence_ceiling,
309            issued_at,
310            not_before,
311            expires_at,
312            token_id,
313            revocation_ref,
314        };
315        grant.capability_id = grant.derive_id()?;
316        grant.validate()?;
317        Ok(grant)
318    }
319
320    pub fn derive_id(&self) -> Result<String, String> {
321        let mut content = self.clone();
322        content.capability_id.clear();
323        let digest = sha256_canonical(&content)?;
324        Ok(format!("vcap_{}", &digest[..32]))
325    }
326
327    pub fn root(&self) -> Result<String, String> {
328        self.validate()?;
329        Ok(format!("sha256:{}", sha256_canonical(self)?))
330    }
331
332    pub fn validate(&self) -> Result<(), String> {
333        if self.schema != CAPABILITY_SCHEMA_V1 || self.capability_id != self.derive_id()? {
334            return Err("capability schema or content address is invalid".into());
335        }
336        if !matches!(
337            self.subject_class,
338            PrincipalClass::Agent | PrincipalClass::Workload
339        ) {
340            return Err("runtime capabilities are only for agent or workload principals".into());
341        }
342        match self.subject_class {
343            PrincipalClass::Agent => {
344                require_prefix(
345                    "capability agent subject",
346                    &self.subject_principal_id,
347                    "agent:",
348                )?;
349            }
350            PrincipalClass::Workload => {
351                require_one_prefix(
352                    "capability workload subject",
353                    &self.subject_principal_id,
354                    &["workload:", "oidc:", "spiffe:", "github-app:"],
355                )?;
356            }
357            _ => unreachable!("subject class was restricted above"),
358        }
359        for (name, value) in [
360            ("capability issuer", self.issuer_principal_id.as_str()),
361            ("capability subject", self.subject_principal_id.as_str()),
362            (
363                "capability current actor",
364                self.current_actor_principal_id.as_str(),
365            ),
366            ("capability token_id", self.token_id.as_str()),
367        ] {
368            require_bounded_text(name, value, 2048)?;
369        }
370        if self.issuer_principal_id == self.subject_principal_id
371            || self.current_actor_principal_id != self.subject_principal_id
372        {
373            return Err("capability issuer, subject, or current actor is invalid".into());
374        }
375        if self.actor_chain.is_empty()
376            || self.actor_chain.len() < 2
377            || self.actor_chain.get(self.actor_chain.len() - 2) != Some(&self.issuer_principal_id)
378            || self.actor_chain.last() != Some(&self.current_actor_principal_id)
379            || self.actor_chain.iter().any(String::is_empty)
380        {
381            return Err("capability actor chain does not connect issuer to current actor".into());
382        }
383        let unique_actors = self.actor_chain.iter().collect::<BTreeSet<_>>();
384        if unique_actors.len() != self.actor_chain.len() {
385            return Err("capability actor chain contains a cycle".into());
386        }
387        if self.audience != CAPABILITY_AUDIENCE_V1 || !self.frontier_id.starts_with("vfr_") {
388            return Err("capability audience or Frontier is invalid".into());
389        }
390        if self.maximum_delegation_depth > MAX_CAPABILITY_DELEGATION_DEPTH
391            || self.delegation_depth > self.maximum_delegation_depth
392            || (self.delegation_depth == 0) != self.parent_capability_root.is_none()
393        {
394            return Err("capability delegation depth or parent is invalid".into());
395        }
396        if let Some(parent) = &self.parent_capability_root {
397            require_sha256("parent_capability_root", parent)?;
398        }
399        if let Some(revocation_ref) = &self.revocation_ref {
400            require_sha256("capability revocation_ref", revocation_ref)?;
401        }
402        require_strictly_sorted("capability actions", &self.actions)?;
403        require_strictly_sorted("capability resources", &self.resources)?;
404        require_strictly_sorted("capability execution bindings", &self.execution_bindings)?;
405        if self.actions.is_empty()
406            || self.resources.is_empty()
407            || self.execution_bindings.is_empty()
408        {
409            return Err(
410                "capability must bind at least one action, resource, and execution input".into(),
411            );
412        }
413        for resource in &self.resources {
414            resource.validate()?;
415        }
416        let resource_identities = self
417            .resources
418            .iter()
419            .map(|resource| (&resource.resource_type, &resource.resource_id))
420            .collect::<BTreeSet<_>>();
421        if resource_identities.len() != self.resources.len() {
422            return Err("capability contains an ambiguous resource identity".into());
423        }
424        for binding in &self.execution_bindings {
425            binding.validate()?;
426        }
427
428        let issued_at = parse_canonical_time("capability issued_at", &self.issued_at)?;
429        let not_before = parse_canonical_time("capability not_before", &self.not_before)?;
430        let expires_at = parse_canonical_time("capability expires_at", &self.expires_at)?;
431        if not_before < issued_at
432            || expires_at <= not_before
433            || (expires_at - issued_at).num_seconds() > MAX_CAPABILITY_LIFETIME_SECONDS
434        {
435            return Err("capability validity window is invalid or exceeds 24 hours".into());
436        }
437        Ok(())
438    }
439
440    pub fn validate_at(
441        &self,
442        observed_at: &str,
443        revoked_capability_roots: &BTreeSet<String>,
444    ) -> Result<(), String> {
445        self.validate()?;
446        let observed_at = parse_canonical_time("capability observed_at", observed_at)?;
447        let not_before = parse_canonical_time("capability not_before", &self.not_before)?;
448        let expires_at = parse_canonical_time("capability expires_at", &self.expires_at)?;
449        if observed_at < not_before || observed_at >= expires_at {
450            return Err("capability is not active at the recorded observation time".into());
451        }
452        if revoked_capability_roots.contains(&self.root()?) {
453            return Err("capability was revoked before use".into());
454        }
455        Ok(())
456    }
457
458    pub fn validate_delegation_from(&self, parent: &Self) -> Result<(), String> {
459        self.validate()?;
460        parent.validate()?;
461        if self.parent_capability_root.as_deref() != Some(parent.root()?.as_str())
462            || self.issuer_principal_id != parent.subject_principal_id
463            || self.frontier_id != parent.frontier_id
464            || self.audience != parent.audience
465            || self.delegation_depth != parent.delegation_depth + 1
466            || self.maximum_delegation_depth > parent.maximum_delegation_depth
467        {
468            return Err("child capability does not form an attenuating delegation".into());
469        }
470        if !is_subset(&self.actions, &parent.actions)
471            || !is_subset(&self.resources, &parent.resources)
472            || !is_subset(&self.execution_bindings, &parent.execution_bindings)
473            || self.consequence_ceiling > parent.consequence_ceiling
474        {
475            return Err("child capability broadens its parent".into());
476        }
477        let child_not_before = parse_canonical_time("child not_before", &self.not_before)?;
478        let child_expires = parse_canonical_time("child expires_at", &self.expires_at)?;
479        let child_issued = parse_canonical_time("child issued_at", &self.issued_at)?;
480        let parent_not_before = parse_canonical_time("parent not_before", &parent.not_before)?;
481        let parent_expires = parse_canonical_time("parent expires_at", &parent.expires_at)?;
482        let parent_issued = parse_canonical_time("parent issued_at", &parent.issued_at)?;
483        if child_issued < parent_issued
484            || child_not_before < parent_not_before
485            || child_expires > parent_expires
486        {
487            return Err("child capability widens its parent's validity window".into());
488        }
489        let expected_chain = parent
490            .actor_chain
491            .iter()
492            .cloned()
493            .chain(std::iter::once(self.subject_principal_id.clone()))
494            .collect::<Vec<_>>();
495        if self.actor_chain != expected_chain {
496            return Err("child capability actor chain is not the parent's act chain".into());
497        }
498        Ok(())
499    }
500}
501
502/// The claim retained in an authority record after the runtime credential has
503/// been validated. It deliberately contains no bearer token or token bytes.
504#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
505#[serde(deny_unknown_fields)]
506pub struct VerifiedCapabilityClaimV1 {
507    pub schema: String,
508    pub capability_id: String,
509    pub capability_root: String,
510    pub issuer_principal_id: String,
511    pub subject_principal_id: String,
512    pub subject_class: PrincipalClass,
513    pub current_actor_principal_id: String,
514    pub actor_chain: Vec<String>,
515    pub audience: String,
516    pub frontier_id: String,
517    pub actions: Vec<CapabilityAction>,
518    pub resource_roots: Vec<String>,
519    pub execution_binding_roots: Vec<String>,
520    pub consequence_ceiling: ConsequenceCeiling,
521    pub issued_at: String,
522    pub expires_at: String,
523    pub token_id: String,
524    pub revocation_ref: Option<String>,
525    pub verified_at: String,
526}
527
528impl VerifiedCapabilityClaimV1 {
529    pub fn validate(&self) -> Result<(), String> {
530        if self.schema != VERIFIED_CAPABILITY_CLAIM_SCHEMA_V1
531            || !self.capability_id.starts_with("vcap_")
532        {
533            return Err("verified capability schema or ID is invalid".into());
534        }
535        require_sha256("verified capability_root", &self.capability_root)?;
536        if !matches!(
537            self.subject_class,
538            PrincipalClass::Agent | PrincipalClass::Workload
539        ) || self.issuer_principal_id.is_empty()
540            || self.subject_principal_id.is_empty()
541            || self.current_actor_principal_id != self.subject_principal_id
542            || self.actor_chain.len() < 2
543            || self.actor_chain.get(self.actor_chain.len() - 2) != Some(&self.issuer_principal_id)
544            || self.actor_chain.last() != Some(&self.current_actor_principal_id)
545            || self.audience != CAPABILITY_AUDIENCE_V1
546            || !self.frontier_id.starts_with("vfr_")
547            || self.token_id.is_empty()
548        {
549            return Err("verified capability attribution or scope is invalid".into());
550        }
551        if self.actor_chain.iter().collect::<BTreeSet<_>>().len() != self.actor_chain.len() {
552            return Err("verified capability actor chain contains a cycle".into());
553        }
554        require_strictly_sorted("verified capability actions", &self.actions)?;
555        require_strictly_sorted("verified capability resources", &self.resource_roots)?;
556        require_strictly_sorted(
557            "verified capability execution bindings",
558            &self.execution_binding_roots,
559        )?;
560        if self.actions.is_empty()
561            || self.resource_roots.is_empty()
562            || self.execution_binding_roots.is_empty()
563        {
564            return Err("verified capability scope is empty".into());
565        }
566        for root in self
567            .resource_roots
568            .iter()
569            .chain(self.execution_binding_roots.iter())
570        {
571            require_sha256("verified capability binding", root)?;
572        }
573        if let Some(revocation_ref) = &self.revocation_ref {
574            require_sha256("verified capability revocation_ref", revocation_ref)?;
575        }
576        let issued_at = parse_canonical_time("verified capability issued_at", &self.issued_at)?;
577        let expires_at = parse_canonical_time("verified capability expires_at", &self.expires_at)?;
578        let verified_at =
579            parse_canonical_time("verified capability verified_at", &self.verified_at)?;
580        if expires_at <= issued_at
581            || (expires_at - issued_at).num_seconds() > MAX_CAPABILITY_LIFETIME_SECONDS
582            || verified_at < issued_at
583            || verified_at >= expires_at
584        {
585            return Err("verified capability time claim is invalid".into());
586        }
587        Ok(())
588    }
589
590    pub fn root(&self) -> Result<String, String> {
591        self.validate()?;
592        Ok(format!("sha256:{}", sha256_canonical(self)?))
593    }
594}
595
596fn require_sha256(name: &str, value: &str) -> Result<(), String> {
597    let Some(hex) = value.strip_prefix("sha256:") else {
598        return Err(format!("{name} must use a full sha256: digest"));
599    };
600    if hex.len() != 64
601        || !hex
602            .bytes()
603            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
604    {
605        return Err(format!(
606            "{name} must contain 64 lowercase hexadecimal characters"
607        ));
608    }
609    Ok(())
610}
611
612fn parse_canonical_time(name: &str, value: &str) -> Result<DateTime<chrono::FixedOffset>, String> {
613    let parsed = DateTime::parse_from_rfc3339(value)
614        .map_err(|error| format!("{name} is not RFC3339: {error}"))?;
615    if parsed.to_rfc3339_opts(SecondsFormat::Secs, true) != value {
616        return Err(format!(
617            "{name} must use canonical whole-second UTC RFC3339"
618        ));
619    }
620    Ok(parsed)
621}
622
623fn require_bounded_text(name: &str, value: &str, maximum: usize) -> Result<(), String> {
624    if value.is_empty()
625        || value.len() > maximum
626        || value.chars().any(|character| character.is_control())
627    {
628        return Err(format!(
629            "{name} is empty, oversized, or contains control text"
630        ));
631    }
632    Ok(())
633}
634
635fn require_prefix(name: &str, value: &str, prefix: &str) -> Result<(), String> {
636    if value.len() <= prefix.len() || !value.starts_with(prefix) {
637        return Err(format!("{name} must start with {prefix}"));
638    }
639    Ok(())
640}
641
642fn require_one_prefix(name: &str, value: &str, prefixes: &[&str]) -> Result<(), String> {
643    if prefixes
644        .iter()
645        .any(|prefix| value.len() > prefix.len() && value.starts_with(prefix))
646    {
647        Ok(())
648    } else {
649        Err(format!("{name} has no supported identity namespace"))
650    }
651}
652
653fn require_strictly_sorted<T: Ord>(name: &str, values: &[T]) -> Result<(), String> {
654    if values.windows(2).any(|pair| pair[0] >= pair[1]) {
655        Err(format!("{name} must be strictly sorted and unique"))
656    } else {
657        Ok(())
658    }
659}
660
661fn is_subset<T: Ord>(candidate: &[T], parent: &[T]) -> bool {
662    let parent = parent.iter().collect::<BTreeSet<_>>();
663    candidate.iter().all(|value| parent.contains(value))
664}
665
666#[cfg(test)]
667mod tests {
668    use std::path::PathBuf;
669
670    use serde_json::json;
671
672    use super::*;
673
674    fn root(character: char) -> String {
675        format!("sha256:{}", character.to_string().repeat(64))
676    }
677
678    fn resource(character: char) -> CapabilityResourceBindingV1 {
679        CapabilityResourceBindingV1 {
680            resource_type: "target".into(),
681            resource_id: format!("erdos:{character}"),
682            resource_root: root(character),
683        }
684    }
685
686    fn execution(character: char) -> CapabilityExecutionBindingV1 {
687        CapabilityExecutionBindingV1 {
688            binding_type: "packet".into(),
689            binding_root: root(character),
690        }
691    }
692
693    fn grant() -> CapabilityGrantV1 {
694        CapabilityGrantV1::new(
695            "service:local-authority".into(),
696            "agent:codex:fixture:run-1".into(),
697            PrincipalClass::Agent,
698            "agent:codex:fixture:run-1".into(),
699            vec![
700                "service:local-authority".into(),
701                "agent:codex:fixture:run-1".into(),
702            ],
703            None,
704            0,
705            1,
706            CAPABILITY_AUDIENCE_V1.into(),
707            "vfr_0123456789abcdef".into(),
708            vec![CapabilityAction::ReceiptLand, CapabilityAction::WorkClaim],
709            vec![resource('a'), resource('b')],
710            vec![execution('c')],
711            ConsequenceCeiling::PendingReview,
712            "2026-07-24T12:00:00Z".into(),
713            "2026-07-24T12:00:00Z".into(),
714            "2026-07-24T13:00:00Z".into(),
715            "jti-fixture-1".into(),
716            Some(root('d')),
717        )
718        .unwrap()
719    }
720
721    fn human_principal() -> PrincipalV1 {
722        PrincipalV1 {
723            schema: PRINCIPAL_SCHEMA_V1.into(),
724            principal_id: "oidc:https://github.com|1234567".into(),
725            principal_class: PrincipalClass::Human,
726            display_name: Some("Fixture reviewer".into()),
727            affiliation: None,
728            account_links: vec![ExternalAccountLinkV1 {
729                kind: ExternalAccountKind::Oidc,
730                issuer: "https://github.com".into(),
731                subject: "1234567".into(),
732                linked_at: "2026-07-24T12:00:00Z".into(),
733                revoked_at: None,
734            }],
735        }
736    }
737
738    fn child_grant(parent: &CapabilityGrantV1) -> CapabilityGrantV1 {
739        CapabilityGrantV1::new(
740            parent.subject_principal_id.clone(),
741            "workload:local|worker-2".into(),
742            PrincipalClass::Workload,
743            "workload:local|worker-2".into(),
744            vec![
745                "service:local-authority".into(),
746                "agent:codex:fixture:run-1".into(),
747                "workload:local|worker-2".into(),
748            ],
749            Some(parent.root().unwrap()),
750            1,
751            1,
752            parent.audience.clone(),
753            parent.frontier_id.clone(),
754            vec![CapabilityAction::ReceiptLand],
755            vec![resource('a')],
756            vec![execution('c')],
757            ConsequenceCeiling::PendingReview,
758            "2026-07-24T12:10:00Z".into(),
759            "2026-07-24T12:10:00Z".into(),
760            "2026-07-24T12:50:00Z".into(),
761            "jti-fixture-2".into(),
762            Some(root('d')),
763        )
764        .unwrap()
765    }
766
767    fn verified_claim(grant: &CapabilityGrantV1) -> VerifiedCapabilityClaimV1 {
768        VerifiedCapabilityClaimV1 {
769            schema: VERIFIED_CAPABILITY_CLAIM_SCHEMA_V1.into(),
770            capability_id: grant.capability_id.clone(),
771            capability_root: grant.root().unwrap(),
772            issuer_principal_id: grant.issuer_principal_id.clone(),
773            subject_principal_id: grant.subject_principal_id.clone(),
774            subject_class: grant.subject_class,
775            current_actor_principal_id: grant.current_actor_principal_id.clone(),
776            actor_chain: grant.actor_chain.clone(),
777            audience: grant.audience.clone(),
778            frontier_id: grant.frontier_id.clone(),
779            actions: grant.actions.clone(),
780            resource_roots: grant
781                .resources
782                .iter()
783                .map(|resource| resource.resource_root.clone())
784                .collect(),
785            execution_binding_roots: grant
786                .execution_bindings
787                .iter()
788                .map(|binding| binding.binding_root.clone())
789                .collect(),
790            consequence_ceiling: grant.consequence_ceiling,
791            issued_at: grant.issued_at.clone(),
792            expires_at: grant.expires_at.clone(),
793            token_id: grant.token_id.clone(),
794            revocation_ref: grant.revocation_ref.clone(),
795            verified_at: "2026-07-24T12:30:00Z".into(),
796        }
797    }
798
799    #[test]
800    fn human_principal_uses_an_exact_namespaced_account_link() {
801        let principal = human_principal();
802        assert!(principal.root().unwrap().starts_with("sha256:"));
803
804        let mut inferred = principal.clone();
805        inferred.principal_id = "fixture@example.com".into();
806        assert!(inferred.validate().is_err());
807    }
808
809    #[test]
810    fn every_human_governance_action_is_structurally_forbidden_to_machines() {
811        for action in HUMAN_ONLY_AUTHORITY_ACTIONS_V1 {
812            assert!(!principal_class_may_request(PrincipalClass::Agent, action));
813            assert!(!principal_class_may_request(
814                PrincipalClass::Workload,
815                action
816            ));
817            assert!(principal_class_may_request(PrincipalClass::Human, action));
818        }
819        assert!(principal_class_may_request(
820            PrincipalClass::Agent,
821            "submission_register"
822        ));
823    }
824
825    #[test]
826    fn capability_is_content_addressed_scoped_and_time_bounded() {
827        let grant = grant();
828        assert!(grant.capability_id.starts_with("vcap_"));
829        assert!(
830            grant
831                .validate_at("2026-07-24T12:30:00Z", &BTreeSet::new())
832                .is_ok()
833        );
834        assert!(
835            grant
836                .validate_at("2026-07-24T13:00:00Z", &BTreeSet::new())
837                .is_err()
838        );
839
840        let mut long_lived = grant.clone();
841        long_lived.expires_at = "2026-07-26T12:00:00Z".into();
842        long_lived.capability_id = long_lived.derive_id().unwrap();
843        assert!(long_lived.validate().is_err());
844    }
845
846    #[test]
847    fn capability_rejects_human_subjects_unsorted_scope_and_revocation() {
848        let mut human = grant();
849        human.subject_class = PrincipalClass::Human;
850        human.capability_id = human.derive_id().unwrap();
851        assert!(human.validate().is_err());
852
853        let mut unsorted = grant();
854        unsorted.actions.reverse();
855        unsorted.capability_id = unsorted.derive_id().unwrap();
856        assert!(unsorted.validate().is_err());
857
858        let grant = grant();
859        assert!(
860            grant
861                .validate_at(
862                    "2026-07-24T12:30:00Z",
863                    &BTreeSet::from([grant.root().unwrap()])
864                )
865                .is_err()
866        );
867    }
868
869    #[test]
870    fn child_capability_can_only_attenuate_its_parent() {
871        let parent = grant();
872        let child = child_grant(&parent);
873        child.validate_delegation_from(&parent).unwrap();
874
875        let mut broadened = child.clone();
876        broadened.actions.push(CapabilityAction::VerifierAttach);
877        broadened.actions.sort();
878        broadened.capability_id = broadened.derive_id().unwrap();
879        assert!(broadened.validate_delegation_from(&parent).is_err());
880    }
881
882    #[test]
883    fn verified_claim_retains_no_bearer_token_and_fails_on_time_drift() {
884        let grant = grant();
885        let claim = verified_claim(&grant);
886        claim.validate().unwrap();
887        let encoded = serde_json::to_string(&claim).unwrap();
888        assert!(!encoded.contains("bearer"));
889        assert!(!encoded.contains("token_bytes"));
890
891        let mut expired = claim;
892        expired.verified_at = expired.expires_at.clone();
893        assert!(expired.validate().is_err());
894    }
895
896    #[test]
897    fn principal_capability_cross_implementation_fixture_is_exact() {
898        let principal = human_principal();
899        let parent = grant();
900        let child = child_grant(&parent);
901        let claim = verified_claim(&parent);
902        let mut fixture = json!({
903            "schema": "vela.principal-capability-conformance.v1",
904            "principal": principal,
905            "parent_capability": parent,
906            "child_capability": child,
907            "verified_claim": claim,
908            "expected": {
909                "principal_root": principal.root().unwrap(),
910                "parent_capability_id": parent.capability_id,
911                "parent_capability_root": parent.root().unwrap(),
912                "child_capability_id": child.capability_id,
913                "child_capability_root": child.root().unwrap(),
914                "verified_claim_root": claim.root().unwrap(),
915            },
916        });
917        let fixture_root = format!("sha256:{}", sha256_canonical(&fixture).unwrap());
918        fixture
919            .as_object_mut()
920            .unwrap()
921            .insert("fixture_root".into(), json!(fixture_root));
922        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
923            .join("../../conformance/fixtures/principal-capability-v1.json");
924        let retained: serde_json::Value =
925            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
926        assert_eq!(
927            crate::canonical::to_canonical_bytes(&retained).unwrap(),
928            crate::canonical::to_canonical_bytes(&fixture).unwrap()
929        );
930    }
931}