1use super::{
2 bound, collection, nonempty, sorted_unique, EnvelopeError, EnvelopeResult, UnsupportedRight,
3 MAX_RECORD_BYTES,
4};
5use khive_types::Timestamp;
6use lion_core::{Right, Rights};
7use std::collections::BTreeMap;
8use uuid::Uuid;
9
10#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
11#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
12pub struct Principal {
13 pub kind: String,
14 pub id: String,
15 pub leg: Option<String>,
16}
17impl Principal {
18 pub fn validate(&self) -> EnvelopeResult<()> {
19 nonempty(&self.kind)?;
20 nonempty(&self.id)?;
21 if let Some(leg) = &self.leg {
22 let bytes = leg.as_bytes();
23 if bytes.is_empty()
24 || bytes.len() > 64
25 || !bytes[0].is_ascii_alphanumeric()
26 || !bytes[bytes.len() - 1].is_ascii_alphanumeric()
27 || bytes
28 .iter()
29 .any(|b| !b.is_ascii_lowercase() && !b.is_ascii_digit() && *b != b'-')
30 {
31 return Err(EnvelopeError::InvalidInput("invalid structural leg label"));
32 }
33 }
34 Ok(())
35 }
36 pub fn parent(&self) -> Self {
37 Self {
38 kind: self.kind.clone(),
39 id: self.id.clone(),
40 leg: None,
41 }
42 }
43}
44
45#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
46#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
47pub struct ContractDigest(pub [u8; 32]);
48impl ContractDigest {
49 pub fn blake3(bytes: &[u8]) -> Self {
50 Self(*blake3::hash(bytes).as_bytes())
51 }
52}
53#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
54#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
55pub struct ContractRef {
56 pub name: String,
57 pub version: u32,
58 pub digest: ContractDigest,
59}
60impl ContractRef {
61 fn validate(&self) -> EnvelopeResult<()> {
62 nonempty(&self.name)
63 }
64}
65#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
66#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
67pub struct ExactBytes(pub Vec<u8>);
68impl ExactBytes {
69 fn validate(&self) -> EnvelopeResult<()> {
70 bound("reference bytes", self.0.len(), MAX_RECORD_BYTES)?;
71 if self.0.is_empty() {
72 return Err(EnvelopeError::InvalidInput("empty exact reference"));
73 }
74 Ok(())
75 }
76}
77#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
78#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
79pub struct RepositoryIdentity {
80 pub forge: String,
81 pub immutable_id: ExactBytes,
82}
83impl RepositoryIdentity {
84 fn validate(&self) -> EnvelopeResult<()> {
85 nonempty(&self.forge)?;
86 self.immutable_id.validate()
87 }
88}
89#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
90#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
91pub struct Validity {
92 pub not_before: Timestamp,
93 pub expires_at: Option<Timestamp>,
94}
95impl Validity {
96 pub fn validate(&self) -> EnvelopeResult<()> {
97 if self.expires_at.is_some_and(|end| end <= self.not_before) {
98 return Err(EnvelopeError::InvalidInput("expiry must follow not_before"));
99 }
100 Ok(())
101 }
102 pub fn contains(&self, now: Timestamp) -> bool {
103 now >= self.not_before && self.expires_at.is_none_or(|end| now < end)
104 }
105 pub fn covers(&self, child: &Self) -> bool {
106 self.not_before <= child.not_before
107 && match (self.expires_at, child.expires_at) {
108 (None, _) => true,
109 (Some(_), None) => false,
110 (Some(a), Some(b)) => b <= a,
111 }
112 }
113}
114#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
115#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
116pub struct RunRef(pub Uuid);
117impl RunRef {
118 pub fn parse(value: &str) -> EnvelopeResult<Self> {
119 let id =
120 Uuid::parse_str(value).map_err(|_| EnvelopeError::InvalidInput("invalid run UUID"))?;
121 if id.to_string() != value {
122 return Err(EnvelopeError::InvalidInput("noncanonical run UUID"));
123 }
124 Ok(Self(id))
125 }
126}
127#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
128#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
129pub struct PhaseVisit {
130 pub phase_id: String,
131 pub round: i64,
132}
133#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
134#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
135pub struct ActionOccurrence {
136 pub visit: PhaseVisit,
137 pub action_name: String,
138}
139#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
140#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
141pub enum ArgumentValue {
142 String(String),
143 Integer(i64),
144 Duration(i64),
145 Bool(bool),
146 Word(String),
147}
148#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
149#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
150pub enum ArgumentType {
151 String,
152 Integer,
153 Duration,
154 Bool,
155 Word,
156}
157impl ArgumentValue {
158 fn kind(&self) -> ArgumentType {
159 match self {
160 Self::String(_) => ArgumentType::String,
161 Self::Integer(_) => ArgumentType::Integer,
162 Self::Duration(_) => ArgumentType::Duration,
163 Self::Bool(_) => ArgumentType::Bool,
164 Self::Word(_) => ArgumentType::Word,
165 }
166 }
167}
168#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
169#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
170pub struct ArgumentBinding {
171 pub name: String,
172 pub value: ArgumentValue,
173}
174#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
175#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
176pub struct ExactArguments(pub Vec<ArgumentBinding>);
177#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
178#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
179pub struct ArgumentSpec {
180 pub name: String,
181 pub kind: ArgumentType,
182}
183#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
184#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
185pub enum ProducerClass {
186 Actor,
187 Instrument,
188 Platform,
189 System,
190}
191#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
192#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
193pub enum SubmissionChannel {
194 Observe,
195 Sample,
196 Internal,
197}
198#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
199#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
200pub enum SubjectSelector {
201 Exact(Vec<ExactBytes>),
202 Repositories(Vec<RepositoryIdentity>),
203 AllSubjectsOfKind,
204}
205#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
206#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
207pub struct SubjectScope {
208 pub kind: ContractRef,
209 pub selector: SubjectSelector,
210}
211#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
212#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
213pub struct SourceBinding {
214 pub contract: ContractRef,
215 pub identities: Vec<ExactBytes>,
216 pub arguments: Vec<ExactArguments>,
217}
218#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
219#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
220pub enum ReportingBinding {
221 Role(String),
222 Initiator(Principal),
223}
224#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
225#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
226pub enum SubmissionBinding {
227 ActorReport {
228 run: RunRef,
229 definition: ContractDigest,
230 role: String,
231 },
232 ActionResult {
233 run: RunRef,
234 definition: ContractDigest,
235 occurrence: ActionOccurrence,
236 reporter: ReportingBinding,
237 arguments: ExactArguments,
238 },
239 Instrument(SourceBinding),
240 PlatformRelay {
241 source: SourceBinding,
242 response_contract: ContractRef,
243 },
244 ClaimTimePlatformBundle,
245}
246#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
247#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
248pub struct ObservationPermission {
249 pub policy_domain: String,
250 pub entry: ContractRef,
251 pub producer_class: ProducerClass,
252 pub channel: SubmissionChannel,
253 pub subject: SubjectScope,
254 pub binding: SubmissionBinding,
255}
256#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
257#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
258pub struct ObservationScope {
259 pub permissions: Vec<ObservationPermission>,
260}
261#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
262#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
263pub enum AdminTarget {
264 Read,
265 Create,
266 Write,
267 Delete,
268 Send,
269 RecordObservation(ObservationScope),
270}
271#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
272#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
273pub struct AdminScope {
274 pub namespace: String,
275 pub target: AdminTarget,
276}
277#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
278#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
279pub enum RightSpec {
280 Read,
281 Create,
282 Write,
283 Delete,
284 Send,
285 RecordObservation(ObservationScope),
286 GrantAdmin(AdminScope),
287}
288
289#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
290#[derive(Clone, Copy, Debug, PartialEq, Eq)]
291pub enum ReferenceFormat {
292 Opaque,
293 CanonicalUuid,
294}
295#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
296#[derive(Clone, Debug)]
297pub struct SubjectContract {
298 pub identity: ContractRef,
299 pub reference_format: ReferenceFormat,
300 pub repository_independent: bool,
301 pub repositories: Vec<RepositoryIdentity>,
302 pub membership: Vec<(ExactBytes, RepositoryIdentity)>,
303}
304#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
305#[derive(Clone, Debug)]
306pub struct SourceContract {
307 pub identity: ContractRef,
308 pub reference_format: ReferenceFormat,
309 pub identities: Vec<ExactBytes>,
310}
311#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
312#[derive(Clone, Debug)]
313pub struct EntryContract {
314 pub identity: ContractRef,
315 pub class: ProducerClass,
316 pub subject_kind: ContractRef,
317 pub source_contract: Option<ContractRef>,
318 pub response_contract: Option<ContractRef>,
319 pub authority_arguments: Vec<ArgumentSpec>,
320}
321#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
322#[derive(Clone, Debug)]
323pub struct DeclaredAction {
324 pub entry: ContractRef,
325 pub phase_id: String,
326 pub action_name: String,
327 pub by: Option<String>,
328 pub phase_owner: Option<String>,
329}
330#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
331#[derive(Clone, Debug)]
332pub struct DefinitionContract {
333 pub digest: ContractDigest,
334 pub reporting_roles: Vec<(ContractRef, String)>,
335 pub actions: Vec<DeclaredAction>,
336}
337#[cfg_attr(feature = "authority-store", derive(serde::Serialize))]
338#[derive(Clone, Debug)]
339pub struct RunContract {
340 pub policy_domain: String,
341 pub id: RunRef,
342 pub definition: ContractDigest,
343 pub bindings: Vec<(String, Principal)>,
344 pub initiating_principal: Principal,
345 pub subject_kind: ContractRef,
346 pub subject: ExactBytes,
347}
348
349#[derive(Clone, Debug)]
353pub struct ClosedCatalog {
354 subjects: BTreeMap<ContractRef, SubjectContract>,
355 sources: BTreeMap<ContractRef, SourceContract>,
356 entries: BTreeMap<ContractRef, EntryContract>,
357 definitions: BTreeMap<ContractDigest, DefinitionContract>,
358 runs: BTreeMap<RunRef, RunContract>,
359}
360impl ClosedCatalog {
361 pub fn provision(
362 subjects: Vec<SubjectContract>,
363 sources: Vec<SourceContract>,
364 entries: Vec<EntryContract>,
365 definitions: Vec<DefinitionContract>,
366 runs: Vec<RunContract>,
367 ) -> EnvelopeResult<Self> {
368 collection(&subjects, false)?;
369 collection(&sources, false)?;
370 collection(&entries, true)?;
371 collection(&definitions, false)?;
372 collection(&runs, false)?;
373 let mut catalog = Self {
374 subjects: BTreeMap::new(),
375 sources: BTreeMap::new(),
376 entries: BTreeMap::new(),
377 definitions: BTreeMap::new(),
378 runs: BTreeMap::new(),
379 };
380 for subject in subjects {
381 subject.identity.validate()?;
382 sorted_unique(&subject.repositories, false)?;
383 collection(&subject.membership, false)?;
384 if subject.repository_independent
385 && (!subject.repositories.is_empty() || !subject.membership.is_empty())
386 {
387 return Err(EnvelopeError::InvalidInput(
388 "repository-independent contract has repository bindings",
389 ));
390 }
391 for repository in &subject.repositories {
392 repository.validate()?;
393 }
394 let mut members = BTreeMap::new();
395 for (reference, repository) in &subject.membership {
396 validate_reference(reference, subject.reference_format)?;
397 if !subject.repositories.contains(repository)
398 || members.insert(reference, repository).is_some()
399 {
400 return Err(EnvelopeError::InvalidInput(
401 "ambiguous or unknown repository membership",
402 ));
403 }
404 }
405 if catalog
406 .subjects
407 .insert(subject.identity.clone(), subject)
408 .is_some()
409 {
410 return Err(EnvelopeError::InvalidInput("duplicate subject contract"));
411 }
412 }
413 for source in sources {
414 source.identity.validate()?;
415 sorted_unique(&source.identities, true)?;
416 for reference in &source.identities {
417 validate_reference(reference, source.reference_format)?;
418 }
419 if catalog
420 .sources
421 .insert(source.identity.clone(), source)
422 .is_some()
423 {
424 return Err(EnvelopeError::InvalidInput("duplicate source contract"));
425 }
426 }
427 for entry in entries {
428 entry.identity.validate()?;
429 sorted_unique(&entry.authority_arguments, false)?;
430 if entry
431 .authority_arguments
432 .windows(2)
433 .any(|p| p[0].name == p[1].name)
434 {
435 return Err(EnvelopeError::InvalidInput("duplicate argument name"));
436 }
437 for arg in &entry.authority_arguments {
438 nonempty(&arg.name)?;
439 }
440 if !catalog.subjects.contains_key(&entry.subject_kind) {
441 return Err(EnvelopeError::InvalidInput(
442 "unknown entry subject contract",
443 ));
444 }
445 if let Some(source) = &entry.source_contract {
446 if !catalog.sources.contains_key(source) {
447 return Err(EnvelopeError::InvalidInput("unknown entry source contract"));
448 }
449 }
450 if entry.class == ProducerClass::Platform {
451 entry
452 .response_contract
453 .as_ref()
454 .ok_or(EnvelopeError::InvalidInput(
455 "platform entry lacks response contract",
456 ))?
457 .validate()?;
458 } else if entry.response_contract.is_some() {
459 return Err(EnvelopeError::InvalidInput(
460 "non-platform response contract",
461 ));
462 }
463 if catalog
464 .entries
465 .insert(entry.identity.clone(), entry)
466 .is_some()
467 {
468 return Err(EnvelopeError::InvalidInput("duplicate entry contract"));
469 }
470 }
471 for definition in definitions {
472 collection(&definition.reporting_roles, false)?;
473 collection(&definition.actions, false)?;
474 for (entry, role) in &definition.reporting_roles {
475 if !catalog.entries.contains_key(entry) {
476 return Err(EnvelopeError::InvalidInput(
477 "unknown reporting entry contract",
478 ));
479 }
480 nonempty(role)?;
481 }
482 for action in &definition.actions {
483 if !catalog.entries.contains_key(&action.entry) {
484 return Err(EnvelopeError::InvalidInput("unknown action entry"));
485 }
486 nonempty(&action.phase_id)?;
487 nonempty(&action.action_name)?;
488 if let Some(role) = &action.by {
489 nonempty(role)?;
490 }
491 if let Some(role) = &action.phase_owner {
492 nonempty(role)?;
493 }
494 }
495 if catalog
496 .definitions
497 .insert(definition.digest, definition)
498 .is_some()
499 {
500 return Err(EnvelopeError::InvalidInput("duplicate definition contract"));
501 }
502 }
503 for run in runs {
504 nonempty(&run.policy_domain)?;
505 collection(&run.bindings, false)?;
506 run.initiating_principal.validate()?;
507 if !catalog.definitions.contains_key(&run.definition) {
508 return Err(EnvelopeError::InvalidInput("unknown run definition"));
509 }
510 let subject = catalog
511 .subjects
512 .get(&run.subject_kind)
513 .ok_or(EnvelopeError::InvalidInput("unknown run subject kind"))?;
514 validate_reference(&run.subject, subject.reference_format)?;
515 let mut roles = BTreeMap::new();
516 for (role, principal) in &run.bindings {
517 nonempty(role)?;
518 principal.validate()?;
519 if roles.insert(role, principal).is_some() {
520 return Err(EnvelopeError::InvalidInput("duplicate run role"));
521 }
522 }
523 if catalog.runs.insert(run.id, run).is_some() {
524 return Err(EnvelopeError::InvalidInput("duplicate run contract"));
525 }
526 }
527 Ok(catalog)
528 }
529
530 pub fn validate_rights(
531 &self,
532 rights: &[RightSpec],
533 namespace: &str,
534 grantee: &Principal,
535 ) -> EnvelopeResult<Rights> {
536 self.validate_rights_inner(rights, namespace, grantee, true)
537 }
538 pub(crate) fn validate_source_rights(
541 &self,
542 rights: &[RightSpec],
543 namespace: &str,
544 owner: &Principal,
545 ) -> EnvelopeResult<Rights> {
546 self.validate_rights_inner(rights, namespace, owner, false)
547 }
548 fn validate_rights_inner(
549 &self,
550 rights: &[RightSpec],
551 namespace: &str,
552 grantee: &Principal,
553 bind_producer: bool,
554 ) -> EnvelopeResult<Rights> {
555 nonempty(namespace)?;
556 grantee.validate()?;
557 sorted_unique(rights, true)?;
558 let mut carriers = Rights::empty();
559 for right in rights {
560 let scope = match right {
561 RightSpec::RecordObservation(scope) => {
562 carriers = carriers.with(Right::Execute);
563 scope
564 }
565 RightSpec::GrantAdmin(admin) => {
566 if grantee.leg.is_some() {
567 return Err(EnvelopeError::InvalidInput(
568 "subactor cannot hold administration",
569 ));
570 }
571 if admin.namespace != namespace {
572 return Err(EnvelopeError::InvalidInput(
573 "admin namespace differs from grant",
574 ));
575 }
576 let AdminTarget::RecordObservation(scope) = &admin.target else {
577 return Err(EnvelopeError::RightNotSupported(
578 UnsupportedRight::OrdinaryNamespace,
579 ));
580 };
581 carriers = carriers.with(Right::Delegate);
582 scope
583 }
584 _ => {
585 return Err(EnvelopeError::RightNotSupported(
586 UnsupportedRight::OrdinaryNamespace,
587 ))
588 }
589 };
590 collection(&scope.permissions, true)?;
591 for (index, permission) in scope.permissions.iter().enumerate() {
592 if scope.permissions[..index].contains(permission) {
593 return Err(EnvelopeError::InvalidInput(
594 "duplicate observation permission",
595 ));
596 }
597 self.validate_permission(
598 permission,
599 if bind_producer && matches!(right, RightSpec::RecordObservation(_)) {
600 Some(grantee)
601 } else {
602 None
603 },
604 )?;
605 }
606 }
607 Ok(carriers)
608 }
609
610 #[cfg(feature = "authority-store")]
611 pub(crate) fn covers_observation_permission(
612 &self,
613 held: &ObservationPermission,
614 wanted: &ObservationPermission,
615 ) -> bool {
616 held.policy_domain == wanted.policy_domain
617 && held.entry == wanted.entry
618 && held.producer_class == wanted.producer_class
619 && held.channel == wanted.channel
620 && self.covers_subject(&held.subject, &wanted.subject)
621 && binding_covers(&held.binding, &wanted.binding)
622 }
623
624 pub fn covers_rights(&self, parent: &[RightSpec], requested: &[RightSpec]) -> bool {
625 requested.iter().all(|child| {
626 parent.iter().any(|held| match (held, child) {
627 (RightSpec::RecordObservation(a), RightSpec::RecordObservation(b)) => {
628 self.covers_scope(a, b)
629 }
630 (RightSpec::GrantAdmin(a), RightSpec::GrantAdmin(b))
631 if a.namespace == b.namespace =>
632 {
633 match (&a.target, &b.target) {
634 (AdminTarget::RecordObservation(a), AdminTarget::RecordObservation(b)) => {
635 self.covers_scope(a, b)
636 }
637 _ => false,
638 }
639 }
640 _ => false,
641 })
642 })
643 }
644 fn covers_scope(&self, parent: &ObservationScope, child: &ObservationScope) -> bool {
645 child.permissions.iter().all(|wanted| {
646 parent.permissions.iter().any(|held| {
647 held.policy_domain == wanted.policy_domain
648 && held.entry == wanted.entry
649 && held.producer_class == wanted.producer_class
650 && held.channel == wanted.channel
651 && self.covers_subject(&held.subject, &wanted.subject)
652 && binding_covers(&held.binding, &wanted.binding)
653 })
654 })
655 }
656 fn validate_permission(
657 &self,
658 p: &ObservationPermission,
659 grantee: Option<&Principal>,
660 ) -> EnvelopeResult<()> {
661 nonempty(&p.policy_domain)?;
662 if matches!(p.binding, SubmissionBinding::ClaimTimePlatformBundle) {
663 return Err(EnvelopeError::RightNotSupported(
664 UnsupportedRight::ClaimTimePlatformBundleInM1,
665 ));
666 }
667 if p.channel != SubmissionChannel::Observe || p.producer_class == ProducerClass::System {
668 return Err(EnvelopeError::RightNotSupported(
669 UnsupportedRight::InternalProducer,
670 ));
671 }
672 let entry = self
673 .entries
674 .get(&p.entry)
675 .ok_or(EnvelopeError::InvalidInput("unknown entry contract"))?;
676 if p.producer_class != entry.class || p.subject.kind != entry.subject_kind {
677 return Err(EnvelopeError::InvalidInput(
678 "entry class or subject contract mismatch",
679 ));
680 }
681 self.validate_subject(&p.subject)?;
682 match &p.binding {
683 SubmissionBinding::Instrument(source)
684 | SubmissionBinding::PlatformRelay { source, .. } => {
685 if let SubmissionBinding::PlatformRelay {
686 response_contract, ..
687 } = &p.binding
688 {
689 if entry.response_contract.as_ref() != Some(response_contract) {
690 return Err(EnvelopeError::InvalidInput(
691 "platform response contract mismatch",
692 ));
693 }
694 }
695 let class = if matches!(p.binding, SubmissionBinding::Instrument(_)) {
696 ProducerClass::Instrument
697 } else {
698 ProducerClass::Platform
699 };
700 if p.producer_class != class
701 || entry.source_contract.as_ref() != Some(&source.contract)
702 {
703 return Err(EnvelopeError::InvalidInput(
704 "source binding contract mismatch",
705 ));
706 }
707 let known = self
708 .sources
709 .get(&source.contract)
710 .ok_or(EnvelopeError::InvalidInput("unknown source contract"))?;
711 sorted_unique(&source.identities, true)?;
712 sorted_unique(&source.arguments, true)?;
713 for identity in &source.identities {
714 validate_reference(identity, known.reference_format)?;
715 if !known.identities.contains(identity) {
716 return Err(EnvelopeError::InvalidInput("unknown source identity"));
717 }
718 }
719 for args in &source.arguments {
720 validate_arguments(args, &entry.authority_arguments)?;
721 }
722 }
723 SubmissionBinding::ActorReport {
724 run,
725 definition,
726 role,
727 } => {
728 let (run, def) = self.actor_context(p, *run, *definition)?;
729 let roles: Vec<_> = def
730 .reporting_roles
731 .iter()
732 .filter(|(identity, _)| identity == &p.entry)
733 .collect();
734 if roles.len() != 1
735 || roles[0].1 != *role
736 || grantee.is_some_and(|p| resolve_role(run, role).ok() != Some(p))
737 {
738 return Err(EnvelopeError::InvalidInput(
739 "reporting role does not resolve to grantee",
740 ));
741 }
742 resolve_role(run, role)?;
743 if !entry.authority_arguments.is_empty() {
744 return Err(EnvelopeError::InvalidInput(
745 "actor report lacks required argument binding",
746 ));
747 }
748 }
749 SubmissionBinding::ActionResult {
750 run,
751 definition,
752 occurrence,
753 reporter,
754 arguments,
755 } => {
756 let (run, def) = self.actor_context(p, *run, *definition)?;
757 nonempty(&occurrence.visit.phase_id)?;
758 nonempty(&occurrence.action_name)?;
759 if occurrence.visit.round < 1 {
760 return Err(EnvelopeError::InvalidInput(
761 "round zero is not a phase visit",
762 ));
763 }
764 let actions: Vec<_> = def
765 .actions
766 .iter()
767 .filter(|a| {
768 a.phase_id == occurrence.visit.phase_id
769 && a.action_name == occurrence.action_name
770 })
771 .collect();
772 if actions.len() != 1 {
773 return Err(EnvelopeError::InvalidInput(
774 "ambiguous or unknown action occurrence",
775 ));
776 }
777 let action = actions[0];
778 if action.entry != p.entry {
779 return Err(EnvelopeError::InvalidInput(
780 "action entry differs from permission",
781 ));
782 }
783 let expected = match action.by.as_ref().or(action.phase_owner.as_ref()) {
784 Some(role) => {
785 if grantee.is_some_and(|p| resolve_role(run, role).ok() != Some(p)) {
786 return Err(EnvelopeError::InvalidInput(
787 "action reporter does not resolve to grantee",
788 ));
789 }
790 {
791 resolve_role(run, role)?;
792 ReportingBinding::Role(role.clone())
793 }
794 }
795 None => ReportingBinding::Initiator(run.initiating_principal.clone()),
796 };
797 if &expected != reporter
798 || (matches!(expected, ReportingBinding::Initiator(_))
799 && grantee.is_some_and(|p| &run.initiating_principal != p))
800 {
801 return Err(EnvelopeError::InvalidInput(
802 "action reporting binding mismatch",
803 ));
804 }
805 validate_arguments(arguments, &entry.authority_arguments)?;
806 }
807 SubmissionBinding::ClaimTimePlatformBundle => unreachable!(),
808 }
809 Ok(())
810 }
811 fn actor_context(
812 &self,
813 p: &ObservationPermission,
814 id: RunRef,
815 digest: ContractDigest,
816 ) -> EnvelopeResult<(&RunContract, &DefinitionContract)> {
817 if p.producer_class != ProducerClass::Actor {
818 return Err(EnvelopeError::InvalidInput(
819 "actor binding has non-actor class",
820 ));
821 }
822 let run = self
823 .runs
824 .get(&id)
825 .ok_or(EnvelopeError::InvalidInput("unknown named run"))?;
826 let definition = self
827 .definitions
828 .get(&digest)
829 .ok_or(EnvelopeError::InvalidInput("unknown pinned definition"))?;
830 if run.policy_domain != p.policy_domain
831 || run.definition != digest
832 || run.subject_kind != p.subject.kind
833 || !self.subject_contains(&p.subject, &run.subject)
834 {
835 return Err(EnvelopeError::InvalidInput(
836 "run subject or definition mismatch",
837 ));
838 }
839 Ok((run, definition))
840 }
841 fn validate_subject(&self, scope: &SubjectScope) -> EnvelopeResult<()> {
842 let contract = self
843 .subjects
844 .get(&scope.kind)
845 .ok_or(EnvelopeError::InvalidInput("unknown subject kind"))?;
846 match &scope.selector {
847 SubjectSelector::Exact(refs) => {
848 sorted_unique(refs, true)?;
849 for reference in refs {
850 validate_reference(reference, contract.reference_format)?;
851 }
852 }
853 SubjectSelector::Repositories(repositories) => {
854 sorted_unique(repositories, true)?;
855 if contract.repository_independent
856 || repositories
857 .iter()
858 .any(|r| !contract.repositories.contains(r))
859 {
860 return Err(EnvelopeError::InvalidInput(
861 "unknown or unsupported repository selector",
862 ));
863 }
864 }
865 SubjectSelector::AllSubjectsOfKind if !contract.repository_independent => {
866 return Err(EnvelopeError::InvalidInput(
867 "repository-bearing subject cannot use all-subjects",
868 ))
869 }
870 SubjectSelector::AllSubjectsOfKind => {}
871 }
872 Ok(())
873 }
874 fn subject_contains(&self, scope: &SubjectScope, reference: &ExactBytes) -> bool {
875 let Some(contract) = self.subjects.get(&scope.kind) else {
876 return false;
877 };
878 match &scope.selector {
879 SubjectSelector::Exact(refs) => refs.contains(reference),
880 SubjectSelector::AllSubjectsOfKind => contract.repository_independent,
881 SubjectSelector::Repositories(repos) => contract
882 .membership
883 .iter()
884 .any(|(r, repo)| r == reference && repos.contains(repo)),
885 }
886 }
887 fn covers_subject(&self, parent: &SubjectScope, child: &SubjectScope) -> bool {
888 if parent.kind != child.kind {
889 return false;
890 }
891 match (&parent.selector, &child.selector) {
892 (_, SubjectSelector::Exact(refs)) => {
893 refs.iter().all(|r| self.subject_contains(parent, r))
894 }
895 (SubjectSelector::Repositories(a), SubjectSelector::Repositories(b)) => {
896 b.iter().all(|r| a.contains(r))
897 }
898 (SubjectSelector::AllSubjectsOfKind, SubjectSelector::AllSubjectsOfKind) => self
899 .subjects
900 .get(&parent.kind)
901 .is_some_and(|s| s.repository_independent),
902 _ => false,
903 }
904 }
905}
906fn resolve_role<'a>(run: &'a RunContract, role: &str) -> EnvelopeResult<&'a Principal> {
907 run.bindings
908 .iter()
909 .find(|(name, _)| name == role)
910 .map(|(_, p)| p)
911 .ok_or(EnvelopeError::InvalidInput(
912 "explicit reporting role is unbound",
913 ))
914}
915fn validate_reference(reference: &ExactBytes, format: ReferenceFormat) -> EnvelopeResult<()> {
916 reference.validate()?;
917 if format == ReferenceFormat::CanonicalUuid {
918 RunRef::parse(
919 std::str::from_utf8(&reference.0)
920 .map_err(|_| EnvelopeError::InvalidInput("non-UTF8 UUID reference"))?,
921 )?;
922 }
923 Ok(())
924}
925fn validate_arguments(arguments: &ExactArguments, schema: &[ArgumentSpec]) -> EnvelopeResult<()> {
926 collection(&arguments.0, false)?;
927 if arguments.0.len() != schema.len() {
928 return Err(EnvelopeError::InvalidInput("incomplete argument tuple"));
929 }
930 for (arg, expected) in arguments.0.iter().zip(schema) {
931 if arg.name != expected.name || arg.value.kind() != expected.kind {
932 return Err(EnvelopeError::InvalidInput(
933 "argument name or type mismatch",
934 ));
935 }
936 if let ArgumentValue::String(text) | ArgumentValue::Word(text) = &arg.value {
937 bound("argument text", text.len(), MAX_RECORD_BYTES)?;
938 }
939 }
940 Ok(())
941}
942fn binding_covers(parent: &SubmissionBinding, child: &SubmissionBinding) -> bool {
943 match (parent, child) {
944 (SubmissionBinding::Instrument(a), SubmissionBinding::Instrument(b)) => source_covers(a, b),
945 (
946 SubmissionBinding::PlatformRelay {
947 source: a,
948 response_contract: ar,
949 },
950 SubmissionBinding::PlatformRelay {
951 source: b,
952 response_contract: br,
953 },
954 ) => ar == br && source_covers(a, b),
955 _ => parent == child,
956 }
957}
958
959fn source_covers(a: &SourceBinding, b: &SourceBinding) -> bool {
960 a.contract == b.contract
961 && b.identities.iter().all(|i| a.identities.contains(i))
962 && b.arguments.iter().all(|args| a.arguments.contains(args))
963}