Skip to main content

dekopon_policy/
lib.rs

1//! ```
2//! use dekopon_core::{CapabilityId, PrincipalId, ProviderId};
3//! use dekopon_policy::{PolicyContext, PolicyEngine, PolicyRequest, PolicyTarget, PolicyWorld};
4//! use dekopon_capability::EffectKind;
5//! use dekopon_core::RiskLevel;
6//!
7//! let world = PolicyWorld::new(
8//!     ["alice".parse::<PrincipalId>()?],
9//!     [(
10//!         "cli-probe.upper".parse::<CapabilityId>()?,
11//!         "cli-probe".parse::<ProviderId>()?,
12//!     )],
13//! )?;
14//! let engine = PolicyEngine::new(
15//!     r#"@id("alice-may-cli-probe-upper")
16//!        permit(principal == Dekopon::Principal::"alice",
17//!               action == Dekopon::Action::"cli-probe.upper",
18//!               resource == Dekopon::Provider::"cli-probe");"#,
19//!     &world,
20//! )?;
21//! let decision = engine.authorize(PolicyRequest {
22//!     principal: "alice".parse()?,
23//!     target: PolicyTarget::Capability {
24//!         capability: "cli-probe.upper".parse()?,
25//!         provider: "cli-probe".parse()?,
26//!         effect: EffectKind::ReadOnly,
27//!         risk: RiskLevel::Low,
28//!     },
29//!     context: PolicyContext {
30//!         via: Some("dekopon-gatewayd".to_owned()),
31//!         agent: Some("reviewer".to_owned()),
32//!         ..PolicyContext::default()
33//!     },
34//! });
35//! assert!(decision.allowed);
36//! # Ok::<(), Box<dyn std::error::Error>>(())
37//! ```
38
39#![forbid(unsafe_code)]
40#![cfg_attr(test, allow(clippy::unwrap_used))]
41#![cfg_attr(
42    test,
43    allow(
44        clippy::disallowed_methods,
45        clippy::disallowed_types,
46        reason = "tests spawn, join and drain freely; production sites carry their own expectation"
47    )
48)]
49use std::{
50    collections::{BTreeMap, BTreeSet, HashSet},
51    fmt,
52    str::FromStr as _,
53};
54
55use cedar_policy::{
56    ActionConstraint, Authorizer, Context, Decision, Effect, Entities, Entity, EntityId,
57    EntityTypeName, EntityUid, PolicyId, PolicySet, RestrictedExpression, Schema, ValidationMode,
58    Validator,
59};
60use dekopon_capability::EffectKind;
61use dekopon_core::{
62    AgentId, CapabilityId, GroupId, IdentifierError, PrincipalId, PrincipalKind, ProviderId,
63    RiskLevel, SecretDrn, SecretSinkKind, Subject,
64};
65use serde_json::json;
66use sha2::{Digest as _, Sha256};
67use thiserror::Error;
68
69mod continuity;
70mod github;
71mod request;
72pub use continuity::RequestOutcome;
73pub use request::{HttpRequestFacts, OpaqueBody, RequestBody};
74
75pub const NAMESPACE: &str = "Dekopon";
76pub const AGENT_PROMPT_ACTION: &str = "agent.prompt";
77pub const SECRET_USE_ACTION: &str = "secret.use";
78pub const MAX_POLICY_BYTES: usize = 1024 * 1024;
79pub const MAX_POLICIES: usize = 1_024;
80pub const MAX_POLICY_ID_BYTES: usize = 128;
81pub const RESERVED_POLICY_ID_PREFIX: &str = "dekopon-broker-";
82pub const DEFAULT_SECRET_USE_POLICY_ID: &str = "dekopon-broker-default-secret-use";
83const DEFAULT_SECRET_USE_POLICY: &str = r#"@id("dekopon-broker-default-secret-use")
84permit(principal, action == Dekopon::Action::"secret.use", resource)
85when { context.selection == "default" };"#;
86
87const PRINCIPAL_TYPE: &str = "Dekopon::Principal";
88const PROVIDER_TYPE: &str = "Dekopon::Provider";
89const AGENT_TYPE: &str = "Dekopon::Agent";
90const SECRET_TYPE: &str = "Dekopon::Secret";
91const ACTION_TYPE: &str = "Dekopon::Action";
92const GROUP_TYPE: &str = "Dekopon::Group";
93const PROVIDER_GROUP_SUFFIX: &str = ":*";
94const READ_ONLY_GROUP_SUFFIX: &str = ":read-only";
95const DIGEST_DOMAIN: &[u8] = b"dekopon-policy-v1\0";
96
97#[derive(Clone, Debug, Default, Eq, PartialEq)]
98pub struct PolicyWorld {
99    principals: BTreeSet<PrincipalId>,
100    memberships: BTreeMap<PrincipalId, BTreeSet<GroupId>>,
101    subjects: BTreeMap<Subject, PrincipalId>,
102    providers: BTreeSet<ProviderId>,
103    capabilities: BTreeMap<CapabilityId, ProviderId>,
104    read_only: BTreeSet<CapabilityId>,
105    secrets: BTreeSet<SecretDrn>,
106    phantom_capabilities: BTreeSet<CapabilityId>,
107    phantom_providers: BTreeSet<ProviderId>,
108    phantom_action_groups: BTreeSet<String>,
109}
110
111impl PolicyWorld {
112    pub fn new(
113        principals: impl IntoIterator<Item = PrincipalId>,
114        capabilities: impl IntoIterator<Item = (CapabilityId, ProviderId)>,
115    ) -> Result<Self, PolicyBuildError> {
116        let mut world = Self::default();
117        for principal in principals {
118            world.principals.insert(principal);
119        }
120        let mut reserved = BTreeSet::new();
121        let mut duplicates = BTreeSet::new();
122        for (capability, provider) in capabilities {
123            if matches!(capability.as_str(), AGENT_PROMPT_ACTION | SECRET_USE_ACTION) {
124                reserved.insert(capability.clone());
125            }
126            world.providers.insert(provider.clone());
127            if world
128                .capabilities
129                .insert(capability.clone(), provider)
130                .is_some()
131            {
132                duplicates.insert(capability);
133            }
134        }
135        if !reserved.is_empty() || !duplicates.is_empty() {
136            return Err(PolicyBuildError::WorldConflicts {
137                reserved: reserved.into_iter().collect(),
138                duplicates: duplicates.into_iter().collect(),
139            });
140        }
141        Ok(world)
142    }
143
144    pub fn principals(&self) -> impl Iterator<Item = &PrincipalId> {
145        self.principals.iter()
146    }
147
148    pub fn providers(&self) -> impl Iterator<Item = &ProviderId> {
149        self.providers.iter()
150    }
151
152    pub fn capabilities(&self) -> impl Iterator<Item = (&CapabilityId, &ProviderId)> {
153        self.capabilities.iter()
154    }
155
156    #[must_use]
157    pub fn with_secrets(mut self, secrets: impl IntoIterator<Item = SecretDrn>) -> Self {
158        self.secrets.extend(secrets);
159        self
160    }
161
162    pub fn secrets(&self) -> impl Iterator<Item = &SecretDrn> {
163        self.secrets.iter()
164    }
165
166    #[must_use]
167    pub fn with_group_members(
168        mut self,
169        members: impl IntoIterator<Item = (PrincipalId, GroupId)>,
170    ) -> Self {
171        for (principal, group) in members {
172            self.principals.insert(principal.clone());
173            self.memberships.entry(principal).or_default().insert(group);
174        }
175        self
176    }
177
178    #[must_use]
179    pub fn with_read_only(mut self, capabilities: impl IntoIterator<Item = CapabilityId>) -> Self {
180        self.read_only.extend(capabilities);
181        self
182    }
183
184    fn groups(&self) -> BTreeSet<&GroupId> {
185        self.memberships.values().flatten().collect()
186    }
187
188    fn action_groups_of(&self, capability: &CapabilityId, provider: &ProviderId) -> Vec<String> {
189        let mut groups = vec![format!("{provider}{PROVIDER_GROUP_SUFFIX}")];
190        if self.read_only.contains(capability) {
191            groups.push(format!("{provider}{READ_ONLY_GROUP_SUFFIX}"));
192        }
193        groups
194    }
195
196    fn action_groups(&self) -> BTreeMap<String, BTreeSet<&CapabilityId>> {
197        let mut groups = BTreeMap::<String, BTreeSet<&CapabilityId>>::new();
198        for (capability, provider) in &self.capabilities {
199            for group in self.action_groups_of(capability, provider) {
200                groups.entry(group).or_default().insert(capability);
201            }
202        }
203        for phantom in &self.phantom_action_groups {
204            groups.entry(phantom.clone()).or_default();
205        }
206        groups
207    }
208
209    #[must_use]
210    fn with_phantoms(&self, unresolved: &[UnresolvedName]) -> Self {
211        let mut world = self.clone();
212        for entry in unresolved {
213            match entry.kind {
214                UnresolvedKind::Capability => {
215                    if let Ok(capability) = entry.name.parse::<CapabilityId>() {
216                        world.phantom_capabilities.insert(capability);
217                    }
218                }
219                UnresolvedKind::Provider => {
220                    if let Ok(provider) = entry.name.parse::<ProviderId>() {
221                        world.phantom_providers.insert(provider);
222                    }
223                }
224                UnresolvedKind::ActionGroup => {
225                    world.phantom_action_groups.insert(entry.name.clone());
226                }
227            }
228        }
229        world
230    }
231
232    #[must_use]
233    pub fn with_subjects(
234        mut self,
235        subjects: impl IntoIterator<Item = (Subject, PrincipalId)>,
236    ) -> Self {
237        self.subjects.extend(subjects);
238        self
239    }
240
241    #[must_use]
242    pub fn principal_kind(&self, principal: &PrincipalId) -> PrincipalKind {
243        self.subjects
244            .iter()
245            .find_map(|(subject, mapped)| (mapped == principal).then(|| subject.principal_kind()))
246            .unwrap_or(PrincipalKind::Service)
247    }
248
249    #[must_use]
250    pub fn identity_digest(&self) -> String {
251        let mut hasher = Sha256::new();
252        hasher.update(b"dekopon-identity-v1\0");
253        hasher.update(b"subjects\0");
254        for (subject, principal) in &self.subjects {
255            hasher.update(subject.canonical().as_bytes());
256            hasher.update([0]);
257            hasher.update(principal.as_str().as_bytes());
258            hasher.update([0]);
259        }
260        hasher.update(b"memberships\0");
261        for principal in &self.principals {
262            hasher.update(b"principal\0");
263            hasher.update(principal.as_str().as_bytes());
264            hasher.update([0]);
265            for group in self.memberships.get(principal).into_iter().flatten() {
266                hasher.update(b"group\0");
267                hasher.update(group.as_str().as_bytes());
268                hasher.update([0]);
269            }
270        }
271        finish_digest(hasher)
272    }
273
274    fn schema_json(&self) -> serde_json::Value {
275        // Every routing attribute must be declared optional in the schema, or Cedar's strict
276        // validator rejects any policy referencing an absent one.
277        const ROUTING: [&str; 5] = [
278            "subject",
279            "transportKind",
280            "transport",
281            "trigger",
282            "startedBy",
283        ];
284        let mut routing_attributes = serde_json::Map::from_iter(ROUTING.map(|name| {
285            (
286                name.to_owned(),
287                json!({ "type": "String", "required": false }),
288            )
289        }));
290        // Conversation is a nested record, not flat strings, so a policy reading container must
291        // guard with has first or Cedar's strict validator refuses it at load time.
292        routing_attributes.insert(
293            "conversation".to_owned(),
294            json!({
295                "type": "Record",
296                "required": false,
297                "attributes": {
298                    "kind": { "type": "String" },
299                    "container": { "type": "String", "required": false },
300                    "id": { "type": "String" },
301                    "thread": { "type": "String", "required": false },
302                },
303            }),
304        );
305        routing_attributes.insert("github".to_owned(), github::schema());
306        // Fields added here must be schema-required only if the broker always stamps them on the
307        // request, or Cedar evaluation can fail.
308        let context = |required: &[&str]| {
309            let mut attributes = routing_attributes.clone();
310            attributes.extend(
311                ["via", "agent"].map(|name| (name.to_owned(), json!({ "type": "String" }))),
312            );
313            attributes.extend(
314                required
315                    .iter()
316                    .map(|name| ((*name).to_owned(), json!({ "type": "String" }))),
317            );
318            json!({ "type": "Record", "attributes": attributes })
319        };
320
321        let entity_shape = json!({ "shape": { "type": "Record", "attributes": {} } });
322        let capability_context = context(&["effect", "risk"]);
323        let prompt_context = context(&[]);
324        // Capability, provider and sink are required together on secret.use so a request cannot
325        // satisfy policy via a binding different from the one it is actually trusted for.
326        let secret_context = context(&["capability", "provider", "sink", "selection"]);
327
328        let mut actions = serde_json::Map::new();
329        for (capability, groups) in self
330            .capabilities
331            .iter()
332            .map(|(capability, provider)| (capability, self.action_groups_of(capability, provider)))
333            .chain(
334                self.phantom_capabilities
335                    .iter()
336                    .map(|capability| (capability, Vec::new())),
337            )
338        {
339            let member_of = groups
340                .into_iter()
341                .map(|group| json!({ "id": group }))
342                .collect::<Vec<_>>();
343            actions.insert(
344                capability.as_str().to_owned(),
345                json!({
346                    "memberOf": member_of,
347                    "appliesTo": {
348                        "principalTypes": ["Principal"],
349                        "resourceTypes": ["Provider"],
350                        "context": capability_context,
351                    }
352                }),
353            );
354        }
355        for group in self.action_groups().into_keys() {
356            actions.insert(group, json!({}));
357        }
358        actions.insert(
359            AGENT_PROMPT_ACTION.to_owned(),
360            json!({
361                "appliesTo": {
362                    "principalTypes": ["Principal"],
363                    "resourceTypes": ["Agent"],
364                    "context": prompt_context,
365                }
366            }),
367        );
368        let mut entity_types = serde_json::Map::from_iter([
369            (
370                "Principal".to_owned(),
371                json!({ "memberOfTypes": ["Group"], "shape": { "type": "Record", "attributes": { "kind": { "type": "String" } } } }),
372            ),
373            ("Group".to_owned(), entity_shape.clone()),
374            ("Provider".to_owned(), entity_shape.clone()),
375            ("Agent".to_owned(), entity_shape),
376        ]);
377        actions.insert(
378            SECRET_USE_ACTION.to_owned(),
379            json!({
380                "appliesTo": {
381                    "principalTypes": ["Principal"],
382                    "resourceTypes": ["Secret"],
383                    "context": secret_context,
384                }
385            }),
386        );
387        entity_types.insert(
388            "Secret".to_owned(),
389            json!({ "shape": { "type": "Record", "attributes": {} } }),
390        );
391
392        json!({
393            NAMESPACE: {
394                "entityTypes": entity_types,
395                "actions": actions,
396            }
397        })
398    }
399}
400
401#[derive(Clone, Debug, Eq, PartialEq)]
402pub enum PolicyTarget {
403    Capability {
404        capability: CapabilityId,
405        provider: ProviderId,
406        effect: EffectKind,
407        risk: RiskLevel,
408    },
409    AgentPrompt {
410        agent: AgentId,
411    },
412    SecretUse {
413        secret: SecretDrn,
414        capability: CapabilityId,
415        provider: ProviderId,
416        sink: SecretSinkKind,
417        selection: SecretSelection,
418    },
419}
420
421#[derive(Clone, Copy, Debug, Eq, PartialEq)]
422pub enum SecretSelection {
423    Default,
424    Proposed,
425}
426
427impl SecretSelection {
428    #[must_use]
429    pub const fn as_str(self) -> &'static str {
430        match self {
431            Self::Default => "default",
432            Self::Proposed => "proposed",
433        }
434    }
435}
436
437impl PolicyTarget {
438    #[must_use]
439    pub fn action(&self) -> &str {
440        match self {
441            Self::Capability { capability, .. } => capability.as_str(),
442            Self::AgentPrompt { .. } => AGENT_PROMPT_ACTION,
443            Self::SecretUse { .. } => SECRET_USE_ACTION,
444        }
445    }
446}
447
448#[derive(Clone, Debug, Default, Eq, PartialEq)]
449pub struct PolicyContext {
450    pub via: Option<String>,
451    pub subject: Option<String>,
452    pub agent: Option<String>,
453    pub transport_kind: Option<String>,
454    pub transport: Option<String>,
455    pub trigger: Option<String>,
456    pub started_by: Option<String>,
457    pub conversation: Option<PolicyConversation>,
458    pub github: Option<serde_json::Value>,
459}
460
461#[derive(Clone, Debug, Eq, PartialEq)]
462pub struct PolicyConversation {
463    pub kind: String,
464    pub container: Option<String>,
465    pub id: String,
466    pub thread: Option<String>,
467}
468
469#[derive(Clone, Debug, Eq, PartialEq)]
470pub struct PolicyRequest {
471    pub principal: PrincipalId,
472    pub target: PolicyTarget,
473    pub context: PolicyContext,
474}
475
476#[derive(Clone, Debug, Default, Eq, PartialEq)]
477pub struct PolicyDecision {
478    pub allowed: bool,
479    pub determining_policy_ids: Vec<String>,
480    pub erroring_policy_ids: Vec<String>,
481    pub errors_present: bool,
482    pub refusal: Option<String>,
483    pub opaque_body: Option<OpaqueBody>,
484}
485
486impl PolicyDecision {
487    fn refused(error: &RequestError) -> Self {
488        Self {
489            allowed: false,
490            determining_policy_ids: Vec::new(),
491            erroring_policy_ids: Vec::new(),
492            errors_present: true,
493            refusal: Some(error.to_string()),
494            opaque_body: None,
495        }
496    }
497}
498
499#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
500pub enum UnresolvedKind {
501    Capability,
502    Provider,
503    ActionGroup,
504}
505
506impl UnresolvedKind {
507    #[must_use]
508    pub const fn label(self) -> &'static str {
509        match self {
510            Self::Capability => "capability",
511            Self::Provider => "provider",
512            Self::ActionGroup => "action group",
513        }
514    }
515}
516
517#[derive(Clone, Debug, Eq, PartialEq)]
518pub struct UnresolvedName {
519    pub policy: String,
520    pub name: String,
521    pub kind: UnresolvedKind,
522}
523
524#[derive(Clone, Copy, Debug, Eq, PartialEq)]
525enum Handling {
526    Refuse,
527    Tolerate,
528}
529
530pub struct PolicyEngine {
531    policies: PolicySet,
532    schema: Schema,
533    entities: Entities,
534    entity_types: EntityTypes,
535    authorizer: Authorizer,
536    referenced_capabilities: BTreeSet<CapabilityId>,
537    permit_reach: PermitReach,
538    policy_count: usize,
539    digest: String,
540}
541
542enum PermitReach {
543    AnyAction,
544    Named(BTreeSet<CapabilityId>),
545}
546
547#[derive(Debug)]
548struct EntityTypes {
549    principal: EntityTypeName,
550    action: EntityTypeName,
551    provider: EntityTypeName,
552    agent: EntityTypeName,
553    secret: EntityTypeName,
554}
555
556impl EntityTypes {
557    fn parse() -> Result<Self, PolicyBuildError> {
558        Ok(Self {
559            principal: entity_type_name(PRINCIPAL_TYPE)?,
560            action: entity_type_name(ACTION_TYPE)?,
561            provider: entity_type_name(PROVIDER_TYPE)?,
562            agent: entity_type_name(AGENT_TYPE)?,
563            secret: entity_type_name(SECRET_TYPE)?,
564        })
565    }
566}
567
568impl fmt::Debug for PolicyEngine {
569    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
570        formatter
571            .debug_struct("PolicyEngine")
572            .field("digest", &self.digest)
573            .field("policies", &self.policy_count)
574            .field(
575                "referenced_capabilities",
576                &self.referenced_capabilities.len(),
577            )
578            .finish()
579    }
580}
581
582impl PolicyEngine {
583    pub fn new(policy_text: &str, world: &PolicyWorld) -> Result<Self, PolicyBuildError> {
584        let (engine, unresolved) = Self::build(policy_text, world, Handling::Refuse)?;
585        debug_assert!(
586            unresolved.is_empty(),
587            "Handling::Refuse returns an error rather than tolerating a name"
588        );
589        Ok(engine)
590    }
591
592    pub fn new_lenient(
593        policy_text: &str,
594        world: &PolicyWorld,
595    ) -> Result<(Self, Vec<UnresolvedName>), PolicyBuildError> {
596        Self::build(policy_text, world, Handling::Tolerate)
597    }
598
599    fn build(
600        policy_text: &str,
601        world: &PolicyWorld,
602        handling: Handling,
603    ) -> Result<(Self, Vec<UnresolvedName>), PolicyBuildError> {
604        if policy_text.len() > MAX_POLICY_BYTES {
605            return Err(PolicyBuildError::PolicyTooLarge {
606                length: policy_text.len(),
607                maximum: MAX_POLICY_BYTES,
608            });
609        }
610        let policies = if policy_text.trim().is_empty() {
611            PolicySet::new()
612        } else {
613            PolicySet::from_str(policy_text).map_err(|source| PolicyBuildError::Parse {
614                messages: source.iter().map(ToString::to_string).collect(),
615            })?
616        };
617        if policies.num_of_templates() > 0 {
618            return Err(PolicyBuildError::TemplateUnsupported);
619        }
620        if policies.num_of_policies() > MAX_POLICIES {
621            return Err(PolicyBuildError::TooManyPolicies {
622                count: policies.num_of_policies(),
623                maximum: MAX_POLICIES,
624            });
625        }
626        let mut policies = apply_annotated_ids(&policies)?;
627        refuse_non_canonical_literals(&policies)?;
628        let policy_count = policies.num_of_policies();
629        add_default_secret_use_permit(&mut policies)?;
630        let (ordinary_policies, invalid_request_shapes) = inspect_request_shapes(&policies)?;
631        if !invalid_request_shapes.is_empty() {
632            return Err(PolicyBuildError::InvalidRequestShapes {
633                policies: invalid_request_shapes,
634            });
635        }
636
637        // Classification must run before schema generation; a tolerated name needs to already be in
638        // the schema before Cedar's strict validator runs.
639        let (referenced_capabilities, unresolved) = classify_policies(&policies, world, handling)?;
640        let permit_reach = permit_reach(&policies, world);
641        let effective = world.with_phantoms(&unresolved);
642
643        let schema = Schema::from_json_value(effective.schema_json()).map_err(|source| {
644            PolicyBuildError::Schema {
645                message: source.to_string(),
646            }
647        })?;
648        let validation =
649            Validator::new(schema.clone()).validate(&ordinary_policies, ValidationMode::Strict);
650        if !validation.validation_passed() {
651            let mut messages = validation
652                .validation_errors()
653                .map(ToString::to_string)
654                .collect::<Vec<_>>();
655            messages.sort();
656            return Err(PolicyBuildError::Validation { messages });
657        }
658
659        let entities = build_entities(&effective, &schema)?;
660        let digest = policy_digest(&policies, world, &unresolved)?;
661
662        Ok((
663            Self {
664                policy_count,
665                policies,
666                schema,
667                entities,
668                entity_types: EntityTypes::parse()?,
669                authorizer: Authorizer::new(),
670                referenced_capabilities,
671                permit_reach,
672                digest,
673            },
674            unresolved,
675        ))
676    }
677
678    #[must_use]
679    pub fn authorize(&self, request: PolicyRequest) -> PolicyDecision {
680        self.authorize_with_facts(request, None)
681    }
682
683    #[must_use]
684    pub fn authorize_http(
685        &self,
686        request: PolicyRequest,
687        facts: HttpRequestFacts,
688    ) -> PolicyDecision {
689        self.authorize_with_facts(request, Some(facts))
690    }
691
692    fn authorize_with_facts(
693        &self,
694        request: PolicyRequest,
695        facts: Option<HttpRequestFacts>,
696    ) -> PolicyDecision {
697        let facts = facts.map_or(RequestFacts::Absent, RequestFacts::Known);
698        let (cedar_request, opaque_body) = match self.build_request(request, facts) {
699            Ok(built) => built,
700            Err(error) => return PolicyDecision::refused(&error),
701        };
702        let response =
703            self.authorizer
704                .is_authorized(&cedar_request, &self.policies, &self.entities);
705        let mut erroring_policy_ids = response
706            .diagnostics()
707            .errors()
708            .map(|error| match error {
709                cedar_policy::AuthorizationError::PolicyEvaluationError(error) => {
710                    error.policy_id().to_string()
711                }
712            })
713            .collect::<Vec<_>>();
714        erroring_policy_ids.sort();
715        erroring_policy_ids.dedup();
716        let errors_present = !erroring_policy_ids.is_empty();
717        let mut determining_policy_ids = response
718            .diagnostics()
719            .reason()
720            .map(ToString::to_string)
721            .collect::<Vec<_>>();
722        determining_policy_ids.sort();
723        determining_policy_ids.dedup();
724        PolicyDecision {
725            allowed: matches!(response.decision(), Decision::Allow) && !errors_present,
726            determining_policy_ids,
727            erroring_policy_ids,
728            errors_present,
729            refusal: None,
730            opaque_body,
731        }
732    }
733
734    #[must_use]
735    pub fn request_outcome(&self, request: PolicyRequest) -> RequestOutcome {
736        match self.build_request(request, RequestFacts::Unknown) {
737            Ok((request, _)) => RequestOutcome::from_partial(
738                &self
739                    .authorizer
740                    .is_authorized_partial(&request, &self.policies, &self.entities),
741                &self.entities,
742            ),
743            Err(_) => RequestOutcome::Denied,
744        }
745    }
746
747    #[must_use]
748    pub fn routing_dependent_policies(&self) -> Vec<String> {
749        continuity::routing_dependent_policies(&self.policies)
750    }
751
752    pub fn referenced_capabilities(&self) -> impl Iterator<Item = &CapabilityId> {
753        self.referenced_capabilities.iter()
754    }
755
756    #[must_use]
757    pub fn names_in_a_permit(&self, capability: &CapabilityId) -> bool {
758        match &self.permit_reach {
759            PermitReach::AnyAction => true,
760            PermitReach::Named(named) => named.contains(capability),
761        }
762    }
763
764    #[must_use]
765    pub fn policy_count(&self) -> usize {
766        self.policy_count
767    }
768
769    #[must_use]
770    pub fn digest(&self) -> &str {
771        &self.digest
772    }
773
774    fn build_request(
775        &self,
776        request: PolicyRequest,
777        request_facts: RequestFacts,
778    ) -> Result<(cedar_policy::Request, Option<OpaqueBody>), RequestError> {
779        let PolicyRequest {
780            principal,
781            target,
782            context,
783        } = request;
784        let has_request = match request_facts {
785            RequestFacts::Absent => false,
786            RequestFacts::Known(_) | RequestFacts::Unknown => true,
787        };
788        let action = entity_uid(&self.entity_types.action, target.action());
789        let principal = entity_uid(&self.entity_types.principal, principal.as_str());
790        let (resource, mut attributes) = match target {
791            PolicyTarget::Capability {
792                provider,
793                effect,
794                risk,
795                ..
796            } => (
797                entity_uid(&self.entity_types.provider, provider.as_str()),
798                serde_json::Map::from_iter([
799                    ("effect".to_owned(), json!(effect.to_string())),
800                    ("risk".to_owned(), json!(risk.to_string())),
801                ]),
802            ),
803            PolicyTarget::AgentPrompt { agent } => (
804                entity_uid(&self.entity_types.agent, agent.as_str()),
805                serde_json::Map::new(),
806            ),
807            PolicyTarget::SecretUse {
808                secret,
809                capability,
810                provider,
811                sink,
812                selection,
813            } => (
814                entity_uid(&self.entity_types.secret, secret.as_str()),
815                serde_json::Map::from_iter([
816                    ("capability".to_owned(), json!(capability.to_string())),
817                    ("provider".to_owned(), json!(provider.to_string())),
818                    ("sink".to_owned(), json!(sink.to_string())),
819                    ("selection".to_owned(), json!(selection.as_str())),
820                ]),
821            ),
822        };
823        for (name, value) in [
824            ("via", context.via),
825            ("subject", context.subject),
826            ("agent", context.agent),
827            ("transportKind", context.transport_kind),
828            ("transport", context.transport),
829            ("trigger", context.trigger),
830            ("startedBy", context.started_by),
831        ] {
832            if let Some(value) = value {
833                attributes.insert(name.to_owned(), json!(value));
834            }
835        }
836        if let Some(conversation) = context.conversation {
837            let mut fields = serde_json::Map::from_iter([
838                ("kind".to_owned(), json!(conversation.kind)),
839                ("id".to_owned(), json!(conversation.id)),
840            ]);
841            if let Some(container) = conversation.container {
842                fields.insert("container".to_owned(), json!(container));
843            }
844            if let Some(thread) = conversation.thread {
845                fields.insert("thread".to_owned(), json!(thread));
846            }
847            attributes.insert("conversation".to_owned(), fields.into());
848        }
849        let github_schema = if let Some(github) = context.github {
850            attributes.insert("github".to_owned(), github);
851            Some((&self.schema, &action))
852        } else {
853            None
854        };
855        let context =
856            Context::from_json_value(attributes.into(), github_schema).map_err(|source| {
857                RequestError::Context {
858                    message: source.to_string(),
859                }
860            })?;
861        let merge_error = |source: cedar_policy::ContextCreationError| RequestError::Context {
862            message: source.to_string(),
863        };
864        let (context, opaque_body) = match request_facts {
865            RequestFacts::Known(facts) => {
866                let (request, opaque_body) = facts.context()?;
867                (context.merge(request).map_err(merge_error)?, opaque_body)
868            }
869            RequestFacts::Unknown => (
870                context
871                    .merge([(
872                        "request".to_owned(),
873                        RestrictedExpression::new_unknown("request"),
874                    )])
875                    .map_err(merge_error)?,
876                None,
877            ),
878            RequestFacts::Absent => (context, None),
879        };
880        let schema = if has_request {
881            None
882        } else {
883            Some(&self.schema)
884        };
885        cedar_policy::Request::new(principal, action, resource, context, schema)
886            .map(|request| (request, opaque_body))
887            .map_err(|source| RequestError::Schema {
888                message: source.to_string(),
889            })
890    }
891}
892
893enum RequestFacts {
894    Absent,
895    Known(HttpRequestFacts),
896    Unknown,
897}
898
899#[derive(Clone, Debug, Eq, Error, PartialEq)]
900enum RequestError {
901    #[error("trusted routing context could not be assembled: {message}")]
902    Context { message: String },
903    #[error("request does not validate against the policy schema: {message}")]
904    Schema { message: String },
905}
906
907fn apply_annotated_ids(policies: &PolicySet) -> Result<PolicySet, PolicyBuildError> {
908    let mut renamed = PolicySet::new();
909    let mut seen = BTreeSet::new();
910    for policy in policies.policies() {
911        let id = match policy.annotation("id") {
912            Some(annotation) => {
913                if annotation.is_empty()
914                    || annotation.len() > MAX_POLICY_ID_BYTES
915                    || !annotation.bytes().all(|byte| {
916                        byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')
917                    })
918                {
919                    return Err(PolicyBuildError::InvalidPolicyId {
920                        policy: policy.id().to_string(),
921                    });
922                }
923                PolicyId::new(annotation)
924            }
925            None => {
926                return Err(PolicyBuildError::MissingPolicyId {
927                    policy: policy.id().to_string(),
928                });
929            }
930        };
931        if !seen.insert(id.to_string()) {
932            return Err(PolicyBuildError::DuplicatePolicyId {
933                policy: id.to_string(),
934            });
935        }
936        renamed
937            .add(policy.new_id(id))
938            .map_err(|source| PolicyBuildError::Parse {
939                messages: vec![source.to_string()],
940            })?;
941    }
942    Ok(renamed)
943}
944
945fn add_default_secret_use_permit(policies: &mut PolicySet) -> Result<(), PolicyBuildError> {
946    if let Some(policy) = policies.policies().find(|policy| {
947        policy
948            .id()
949            .to_string()
950            .starts_with(RESERVED_POLICY_ID_PREFIX)
951    }) {
952        return Err(PolicyBuildError::ReservedPolicyId {
953            policy: policy.id().to_string(),
954        });
955    }
956    let parse = |messages: Vec<String>| PolicyBuildError::Parse { messages };
957    let builtin = PolicySet::from_str(DEFAULT_SECRET_USE_POLICY)
958        .map_err(|source| parse(source.iter().map(ToString::to_string).collect()))?;
959    for policy in apply_annotated_ids(&builtin)?.policies() {
960        policies
961            .add(policy.clone())
962            .map_err(|source| parse(vec![source.to_string()]))?;
963    }
964    Ok(())
965}
966
967fn inspect_request_shapes(
968    policies: &PolicySet,
969) -> Result<(PolicySet, Vec<String>), PolicyBuildError> {
970    let mut ordinary = PolicySet::new();
971    let mut invalid = Vec::new();
972    for policy in policies.policies() {
973        let est = policy.to_json().map_err(|source| PolicyBuildError::Parse {
974            messages: vec![source.to_string()],
975        })?;
976        if !references_request(&est) {
977            ordinary
978                .add(policy.clone())
979                .map_err(|source| PolicyBuildError::Parse {
980                    messages: vec![source.to_string()],
981                })?;
982            continue;
983        }
984        let guard = json!({"kind": "when", "body": {"has": {
985            "left": {"Var": "context"}, "attr": "request"
986        }}});
987        if policy.effect() != Effect::Forbid || est["conditions"][0] != guard {
988            invalid.push(policy.id().to_string());
989        }
990    }
991    invalid.sort();
992    Ok((ordinary, invalid))
993}
994
995fn references_request(value: &serde_json::Value) -> bool {
996    match value {
997        serde_json::Value::Object(fields) => {
998            let refers = [".", "has"].into_iter().any(|op| {
999                fields.get(op).is_some_and(|expr| {
1000                    expr.get("left") == Some(&json!({"Var": "context"}))
1001                        && (expr.get("attr") == Some(&json!("request"))
1002                            || expr
1003                                .get("attr")
1004                                .and_then(serde_json::Value::as_array)
1005                                .and_then(|path| path.first())
1006                                == Some(&json!("request")))
1007                })
1008            });
1009            refers || fields.values().any(references_request)
1010        }
1011        serde_json::Value::Array(values) => values.iter().any(references_request),
1012        serde_json::Value::Null
1013        | serde_json::Value::Bool(_)
1014        | serde_json::Value::Number(_)
1015        | serde_json::Value::String(_) => false,
1016    }
1017}
1018
1019fn refuse_non_canonical_literals(policies: &PolicySet) -> Result<(), PolicyBuildError> {
1020    for policy in policies.policies() {
1021        let est = policy.to_json().map_err(|source| PolicyBuildError::Parse {
1022            messages: vec![source.to_string()],
1023        })?;
1024        let id = policy.id().to_string();
1025        literal_walk(&est, &id)?;
1026    }
1027    Ok(())
1028}
1029
1030fn literal_walk(value: &serde_json::Value, policy: &str) -> Result<(), PolicyBuildError> {
1031    let serde_json::Value::Object(fields) = value else {
1032        if let serde_json::Value::Array(values) = value {
1033            for value in values {
1034                literal_walk(value, policy)?;
1035            }
1036        }
1037        return Ok(());
1038    };
1039    if let Some(serde_json::Value::String(literal)) = fields.get("Value")
1040        && is_drn_text(literal)
1041        && literal.bytes().any(|byte| byte.is_ascii_uppercase())
1042    {
1043        return Err(non_canonical_drn(policy, literal));
1044    }
1045    if let Some(like) = fields.get("like") {
1046        // The EST may hold a literal run as one piece per character, so runs are rejoined.
1047        let mut pieces = vec![String::new()];
1048        for piece in like
1049            .get("pattern")
1050            .and_then(serde_json::Value::as_array)
1051            .into_iter()
1052            .flatten()
1053        {
1054            match (
1055                piece.get("Literal").and_then(serde_json::Value::as_str),
1056                pieces.last_mut(),
1057            ) {
1058                (Some(literal), Some(run)) => run.push_str(literal),
1059                (Some(_), None) | (None, _) => pieces.push(String::new()),
1060            }
1061        }
1062        let checked = is_context_subject(like.get("left"))
1063            || pieces.iter().any(|piece| is_drn_text_anywhere(piece));
1064        if checked
1065            && pieces
1066                .iter()
1067                .any(|piece| piece.bytes().any(|byte| byte.is_ascii_uppercase()))
1068        {
1069            return Err(PolicyBuildError::NonCanonicalPattern {
1070                policy: policy.to_owned(),
1071            });
1072        }
1073    }
1074    for operator in ["==", "!=", "contains", "containsAny", "containsAll"] {
1075        let Some(operands) = fields.get(operator) else {
1076            continue;
1077        };
1078        let (left, right) = (operands.get("left"), operands.get("right"));
1079        for (subject, other) in [(left, right), (right, left)] {
1080            if mentions_context_subject(subject) {
1081                subject_literals(other, policy)?;
1082            }
1083        }
1084    }
1085    for value in fields.values() {
1086        literal_walk(value, policy)?;
1087    }
1088    Ok(())
1089}
1090
1091fn is_drn_text(value: &str) -> bool {
1092    value
1093        .get(..4)
1094        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("drn:"))
1095}
1096
1097fn is_drn_text_anywhere(value: &str) -> bool {
1098    value.to_ascii_lowercase().contains("drn:")
1099}
1100
1101fn is_context_subject(value: Option<&serde_json::Value>) -> bool {
1102    value.is_some_and(|value| {
1103        value.get(".") == Some(&json!({"left": {"Var": "context"}, "attr": "subject"}))
1104    })
1105}
1106
1107fn mentions_context_subject(value: Option<&serde_json::Value>) -> bool {
1108    is_context_subject(value)
1109        || value
1110            .and_then(|value| value.get("Set"))
1111            .and_then(serde_json::Value::as_array)
1112            .is_some_and(|elements| {
1113                elements
1114                    .iter()
1115                    .any(|element| is_context_subject(Some(element)))
1116            })
1117}
1118
1119fn subject_literals(
1120    value: Option<&serde_json::Value>,
1121    policy: &str,
1122) -> Result<(), PolicyBuildError> {
1123    let Some(value) = value else {
1124        return Ok(());
1125    };
1126    let elements = value
1127        .get("Set")
1128        .and_then(serde_json::Value::as_array)
1129        .map_or_else(|| std::slice::from_ref(value), Vec::as_slice);
1130    for element in elements {
1131        let Some(literal) = element.get("Value").and_then(serde_json::Value::as_str) else {
1132            continue;
1133        };
1134        match literal.parse::<Subject>() {
1135            Ok(subject) if subject.canonical() != literal => {
1136                return Err(non_canonical_drn(policy, literal));
1137            }
1138            Ok(subject) if subject.kind().is_id_form() => {
1139                return Err(PolicyBuildError::IdFormSubject {
1140                    policy: policy.to_owned(),
1141                    value: literal.to_owned(),
1142                });
1143            }
1144            Ok(_) => {}
1145            Err(_) => return Err(non_canonical_drn(policy, literal)),
1146        }
1147    }
1148    Ok(())
1149}
1150
1151fn non_canonical_drn(policy: &str, value: &str) -> PolicyBuildError {
1152    PolicyBuildError::NonCanonicalDrn {
1153        policy: policy.to_owned(),
1154        value: value.to_owned(),
1155    }
1156}
1157
1158fn entity_type_name(type_name: &str) -> Result<EntityTypeName, PolicyBuildError> {
1159    EntityTypeName::from_str(type_name).map_err(|source| PolicyBuildError::Entities {
1160        message: format!("could not parse entity type {type_name}: {source}"),
1161    })
1162}
1163
1164fn entity_uid(type_name: &EntityTypeName, id: &str) -> EntityUid {
1165    EntityUid::from_type_name_and_id(type_name.clone(), EntityId::new(id))
1166}
1167
1168fn classify_policies(
1169    policies: &PolicySet,
1170    world: &PolicyWorld,
1171    handling: Handling,
1172) -> Result<(BTreeSet<CapabilityId>, Vec<UnresolvedName>), PolicyBuildError> {
1173    let mut referenced_capabilities = BTreeSet::new();
1174    let mut unresolved = Vec::new();
1175    let action_groups = world.action_groups();
1176    for policy in policies.policies() {
1177        let id = policy.id().to_string();
1178        for uid in policy.entity_literals() {
1179            let type_name = uid.type_name().to_string();
1180            let value = uid.id().unescaped().to_owned();
1181            match type_name.as_str() {
1182                PRINCIPAL_TYPE => {
1183                    let principal = value.parse::<PrincipalId>().map_err(|source| {
1184                        PolicyBuildError::MalformedPrincipal {
1185                            policy: id.clone(),
1186                            principal: value.clone(),
1187                            source,
1188                        }
1189                    })?;
1190                    if !world.principals.contains(&principal) {
1191                        return Err(PolicyBuildError::UnknownPrincipal {
1192                            policy: id.clone(),
1193                            principal: value,
1194                        });
1195                    }
1196                }
1197                PROVIDER_TYPE => {
1198                    let parsed = value.parse::<ProviderId>().ok();
1199                    let declared = parsed
1200                        .as_ref()
1201                        .is_some_and(|provider| world.providers.contains(provider));
1202                    if !declared {
1203                        // A literal outside the identifier grammar is treated as a typo, not
1204                        // tolerated, since tolerating it would drop it from the phantom set and
1205                        // surface as an unexplained raw Cedar failure.
1206                        if parsed.is_none() || handling == Handling::Refuse {
1207                            return Err(PolicyBuildError::UnknownProvider {
1208                                policy: id.clone(),
1209                                provider: value,
1210                            });
1211                        }
1212                        unresolved.push(UnresolvedName {
1213                            policy: id.clone(),
1214                            name: value,
1215                            kind: UnresolvedKind::Provider,
1216                        });
1217                    }
1218                }
1219                GROUP_TYPE => {
1220                    let group = value.parse::<GroupId>().map_err(|source| {
1221                        PolicyBuildError::MalformedGroup {
1222                            policy: id.clone(),
1223                            group: value.clone(),
1224                            source,
1225                        }
1226                    })?;
1227                    if !world.groups().contains(&group) {
1228                        return Err(PolicyBuildError::UnknownGroup {
1229                            policy: id.clone(),
1230                            group: value,
1231                        });
1232                    }
1233                }
1234                SECRET_TYPE => {
1235                    let secret = value.parse::<SecretDrn>().map_err(|source| {
1236                        PolicyBuildError::MalformedSecret {
1237                            policy: id.clone(),
1238                            secret: value.clone(),
1239                            source,
1240                        }
1241                    })?;
1242                    if secret.as_str() != value {
1243                        return Err(PolicyBuildError::NonCanonicalSecret {
1244                            policy: id.clone(),
1245                            secret: value,
1246                        });
1247                    }
1248                    if !world.secrets.contains(&secret) {
1249                        return Err(PolicyBuildError::UnknownSecret {
1250                            policy: id.clone(),
1251                            secret: value,
1252                        });
1253                    }
1254                }
1255                ACTION_TYPE => {
1256                    if matches!(value.as_str(), AGENT_PROMPT_ACTION | SECRET_USE_ACTION) {
1257                        continue;
1258                    }
1259                    if action_group_provider(&value).is_some() {
1260                        if action_groups.contains_key(&value) {
1261                            continue;
1262                        }
1263                        if handling == Handling::Refuse {
1264                            return Err(PolicyBuildError::UnknownAction {
1265                                policy: id.clone(),
1266                                action: value,
1267                            });
1268                        }
1269                        unresolved.push(UnresolvedName {
1270                            policy: id.clone(),
1271                            name: value,
1272                            kind: UnresolvedKind::ActionGroup,
1273                        });
1274                        continue;
1275                    }
1276                    let parsed = value.parse::<CapabilityId>().ok();
1277                    match parsed
1278                        .clone()
1279                        .filter(|capability| world.capabilities.contains_key(capability))
1280                    {
1281                        Some(capability) => {
1282                            referenced_capabilities.insert(capability);
1283                        }
1284                        None => {
1285                            if parsed.is_none() || handling == Handling::Refuse {
1286                                return Err(PolicyBuildError::UnknownAction {
1287                                    policy: id.clone(),
1288                                    action: value,
1289                                });
1290                            }
1291                            unresolved.push(UnresolvedName {
1292                                policy: id.clone(),
1293                                name: value,
1294                                kind: UnresolvedKind::Capability,
1295                            });
1296                        }
1297                    }
1298                }
1299                AGENT_TYPE => {}
1300                other => {
1301                    return Err(PolicyBuildError::UnknownEntityType {
1302                        policy: id.clone(),
1303                        entity_type: other.to_owned(),
1304                    });
1305                }
1306            }
1307        }
1308    }
1309    Ok((referenced_capabilities, unresolved))
1310}
1311
1312fn permit_reach(policies: &PolicySet, world: &PolicyWorld) -> PermitReach {
1313    let groups = world.action_groups();
1314    let mut named = BTreeSet::new();
1315    for policy in policies.policies() {
1316        match policy.effect() {
1317            Effect::Permit => {}
1318            Effect::Forbid => continue,
1319        }
1320        match policy.action_constraint() {
1321            ActionConstraint::Any => return PermitReach::AnyAction,
1322            ActionConstraint::In(_) | ActionConstraint::Eq(_) => {}
1323        }
1324        for uid in policy.entity_literals() {
1325            if uid.type_name().to_string() != ACTION_TYPE {
1326                continue;
1327            }
1328            let value = uid.id().unescaped();
1329            if let Some(members) = groups.get(value) {
1330                named.extend(members.iter().map(|&capability| capability.clone()));
1331            } else if let Ok(capability) = value.parse::<CapabilityId>()
1332                && world.capabilities.contains_key(&capability)
1333            {
1334                named.insert(capability);
1335            }
1336        }
1337    }
1338    PermitReach::Named(named)
1339}
1340
1341fn action_group_provider(value: &str) -> Option<ProviderId> {
1342    value
1343        .strip_suffix(PROVIDER_GROUP_SUFFIX)
1344        .or_else(|| value.strip_suffix(READ_ONLY_GROUP_SUFFIX))?
1345        .parse()
1346        .ok()
1347}
1348
1349fn build_entities(world: &PolicyWorld, schema: &Schema) -> Result<Entities, PolicyBuildError> {
1350    let principal_type = entity_type_name(PRINCIPAL_TYPE)?;
1351    let group_type = entity_type_name(GROUP_TYPE)?;
1352    let mut entities = Vec::new();
1353    for principal in &world.principals {
1354        let parents = world
1355            .memberships
1356            .get(principal)
1357            .into_iter()
1358            .flatten()
1359            .map(|group| entity_uid(&group_type, group.as_str()))
1360            .collect::<HashSet<_>>();
1361        entities.push(
1362            Entity::new(
1363                entity_uid(&principal_type, principal.as_str()),
1364                [(
1365                    "kind".to_owned(),
1366                    RestrictedExpression::new_string(
1367                        world.principal_kind(principal).as_str().to_owned(),
1368                    ),
1369                )]
1370                .into_iter()
1371                .collect(),
1372                parents,
1373            )
1374            .map_err(|source| PolicyBuildError::Entities {
1375                message: source.to_string(),
1376            })?,
1377        );
1378    }
1379    for group in world.groups() {
1380        entities.push(Entity::new_no_attrs(
1381            entity_uid(&group_type, group.as_str()),
1382            HashSet::new(),
1383        ));
1384    }
1385    for (type_name, ids) in [
1386        (
1387            PROVIDER_TYPE,
1388            world
1389                .providers
1390                .iter()
1391                .chain(world.phantom_providers.iter())
1392                .map(ProviderId::as_str)
1393                .collect::<Vec<_>>(),
1394        ),
1395        (
1396            SECRET_TYPE,
1397            world
1398                .secrets
1399                .iter()
1400                .map(SecretDrn::as_str)
1401                .collect::<Vec<_>>(),
1402        ),
1403    ] {
1404        let type_name = entity_type_name(type_name)?;
1405        for id in ids {
1406            entities.push(Entity::new_no_attrs(
1407                entity_uid(&type_name, id),
1408                HashSet::new(),
1409            ));
1410        }
1411    }
1412    let actions = schema
1413        .action_entities()
1414        .map_err(|source| PolicyBuildError::Entities {
1415            message: source.to_string(),
1416        })?;
1417    Entities::from_entities(entities.into_iter().chain(actions), Some(schema)).map_err(|source| {
1418        PolicyBuildError::Entities {
1419            message: source.to_string(),
1420        }
1421    })
1422}
1423
1424fn policy_digest(
1425    policies: &PolicySet,
1426    world: &PolicyWorld,
1427    unresolved: &[UnresolvedName],
1428) -> Result<String, PolicyBuildError> {
1429    let canonical = policies
1430        .policies()
1431        .map(|policy| {
1432            let json = policy
1433                .to_json()
1434                .map_err(|source| PolicyBuildError::Digest {
1435                    policy: policy.id().to_string(),
1436                    message: source.to_string(),
1437                })?
1438                .to_string();
1439            Ok((policy.id().to_string(), json))
1440        })
1441        .collect::<Result<BTreeMap<_, _>, PolicyBuildError>>()?;
1442
1443    let mut hasher = Sha256::new();
1444    hasher.update(DIGEST_DOMAIN);
1445    hasher.update(b"policies\0");
1446    for (id, text) in &canonical {
1447        hasher.update(id.as_bytes());
1448        hasher.update([0]);
1449        hasher.update(text.as_bytes());
1450        hasher.update([0]);
1451    }
1452    hasher.update(b"entities\0");
1453    for principal in &world.principals {
1454        hasher.update(format!("{PRINCIPAL_TYPE}::{:?}", principal.as_str()).as_bytes());
1455        hasher.update([0]);
1456        hasher.update(world.principal_kind(principal).as_str().as_bytes());
1457        hasher.update([0]);
1458        for group in world.memberships.get(principal).into_iter().flatten() {
1459            hasher.update(format!("in {GROUP_TYPE}::{:?}", group.as_str()).as_bytes());
1460            hasher.update([0]);
1461        }
1462    }
1463    for provider in &world.providers {
1464        hasher.update(format!("{PROVIDER_TYPE}::{:?}", provider.as_str()).as_bytes());
1465        hasher.update([0]);
1466    }
1467    for secret in &world.secrets {
1468        hasher.update(format!("{SECRET_TYPE}::{:?}", secret.as_str()).as_bytes());
1469        hasher.update([0]);
1470    }
1471    hasher.update(b"actions\0");
1472    let mut actions = world
1473        .capabilities
1474        .keys()
1475        .map(|capability| capability.as_str())
1476        .collect::<Vec<_>>();
1477    actions.push(AGENT_PROMPT_ACTION);
1478    if !world.secrets.is_empty() {
1479        actions.push(SECRET_USE_ACTION);
1480    }
1481    actions.sort_unstable();
1482    for action in actions {
1483        hasher.update(action.as_bytes());
1484        hasher.update([0]);
1485    }
1486    hasher.update(b"action-groups\0");
1487    for (group, members) in world.action_groups() {
1488        hasher.update(group.as_bytes());
1489        hasher.update([0]);
1490        for member in members {
1491            hasher.update(member.as_str().as_bytes());
1492            hasher.update([0]);
1493        }
1494    }
1495
1496    hasher.update(b"phantoms\0");
1497    let mut phantoms = unresolved
1498        .iter()
1499        .map(|entry| format!("{}::{}", entry.kind.label(), entry.name))
1500        .collect::<Vec<_>>();
1501    phantoms.sort_unstable();
1502    phantoms.dedup();
1503    for phantom in phantoms {
1504        hasher.update(phantom.as_bytes());
1505        hasher.update([0]);
1506    }
1507
1508    Ok(finish_digest(hasher))
1509}
1510
1511fn finish_digest(hasher: Sha256) -> String {
1512    let mut hex = String::with_capacity(64 + 7);
1513    hex.push_str("sha256:");
1514    for byte in hasher.finalize() {
1515        const HEX: &[u8; 16] = b"0123456789abcdef";
1516        hex.push(char::from(HEX[usize::from(byte >> 4)]));
1517        hex.push(char::from(HEX[usize::from(byte & 0x0f)]));
1518    }
1519    hex
1520}
1521
1522#[derive(Clone, Debug, Eq, Error, PartialEq)]
1523pub enum PolicyBuildError {
1524    #[error("policy source is {length} bytes; maximum is {maximum}")]
1525    PolicyTooLarge { length: usize, maximum: usize },
1526    #[error("policy set contains {count} policies; maximum is {maximum}")]
1527    TooManyPolicies { count: usize, maximum: usize },
1528    #[error("policy source could not be parsed: {}", messages.join("; "))]
1529    Parse { messages: Vec<String> },
1530    #[error("policy templates are not supported; write static policies instead")]
1531    TemplateUnsupported,
1532    #[error("policy schema could not be generated: {message}")]
1533    Schema { message: String },
1534    #[error("policy set failed strict validation: {}", messages.join("; "))]
1535    Validation { messages: Vec<String> },
1536    #[error("request policy shape invalid for IDs: {}", policies.join(", "))]
1537    InvalidRequestShapes { policies: Vec<String> },
1538    #[error("policy {policy} names undeclared principal {principal:?}")]
1539    UnknownPrincipal { policy: String, principal: String },
1540    #[error("policy {policy} names malformed principal {principal:?}")]
1541    MalformedPrincipal {
1542        policy: String,
1543        principal: String,
1544        #[source]
1545        source: IdentifierError,
1546    },
1547    #[error("policy {policy} names undeclared secret {secret:?}")]
1548    UnknownSecret { policy: String, secret: String },
1549    #[error("policy {policy} names malformed secret DRN {secret:?}")]
1550    MalformedSecret {
1551        policy: String,
1552        secret: String,
1553        #[source]
1554        source: dekopon_core::SecretDrnError,
1555    },
1556    #[error("policy {policy} names group {group:?}, which no principal belongs to")]
1557    UnknownGroup { policy: String, group: String },
1558    #[error("policy {policy} names malformed group {group:?}")]
1559    MalformedGroup {
1560        policy: String,
1561        group: String,
1562        #[source]
1563        source: IdentifierError,
1564    },
1565    #[error("policy {policy} names undeclared provider {provider:?}")]
1566    UnknownProvider { policy: String, provider: String },
1567    #[error("policy {policy} names undeclared action {action:?}")]
1568    UnknownAction { policy: String, action: String },
1569    #[error("policy {policy} compares a DRN that is not canonical lowercase: {value:?}")]
1570    NonCanonicalDrn { policy: String, value: String },
1571    #[error("policy {policy} has a DRN `like` pattern that is not canonical lowercase")]
1572    NonCanonicalPattern { policy: String },
1573    #[error("policy {policy} names secret {secret:?}, which is not canonical lowercase")]
1574    NonCanonicalSecret { policy: String, secret: String },
1575    #[error(
1576        "policy {policy} compares context.subject with the id form {value:?}; context.subject is \
1577         always the name form, so the comparison never matches"
1578    )]
1579    IdFormSubject { policy: String, value: String },
1580    #[error("policy identifier {policy:?} uses the prefix reserved for the broker's own policies")]
1581    ReservedPolicyId { policy: String },
1582    #[error("policy {policy} names unknown entity type {entity_type}")]
1583    UnknownEntityType { policy: String, entity_type: String },
1584    #[error("policy {policy} has an @id annotation that is not a bounded portable identifier")]
1585    InvalidPolicyId { policy: String },
1586    #[error(
1587        "policy {policy} has no @id annotation; every statement needs one so audit records name it \
1588         stably"
1589    )]
1590    MissingPolicyId { policy: String },
1591    #[error("policy identifier {policy:?} is used by more than one policy")]
1592    DuplicatePolicyId { policy: String },
1593    #[error(
1594        "policy world conflicts: reserved actions {reserved:?}; duplicate capabilities {duplicates:?}"
1595    )]
1596    WorldConflicts {
1597        reserved: Vec<CapabilityId>,
1598        duplicates: Vec<CapabilityId>,
1599    },
1600    #[error("policy entity store could not be built: {message}")]
1601    Entities { message: String },
1602    #[error("policy {policy} could not be canonicalized for the policy digest: {message}")]
1603    Digest { policy: String, message: String },
1604}
1605
1606#[cfg(test)]
1607mod github_fixture_tests;
1608#[cfg(test)]
1609mod tests;