1use std::{error::Error as StdError, fmt, sync::Arc};
7
8use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
9use serde::{Deserialize, Deserializer, Serialize, de};
10use thiserror::Error;
11
12use crate::{
13 BoxFuture, CapabilityIdentity, Digest, DurationMillis, RunId, SkillActingWindowId,
14 SkillActivationApprovalId, TenantId, ThreadId, Timestamp,
15};
16
17const APPROVAL_DIGEST_DOMAIN: &[u8] = b"stateknot.skill-activation-approval.v1\0";
18const WINDOW_DIGEST_DOMAIN: &[u8] = b"stateknot.skill-acting-window.v1\0";
19const REVOCATION_DIGEST_DOMAIN: &[u8] = b"stateknot.skill-acting-window-revocation.v1\0";
20const SUBJECT_DIGEST_DOMAIN: &[u8] = b"stateknot.skill-authorization-subject.v1\0";
21const ACTING_WINDOW_DURATION_PATTERN: &str =
22 "^(?:[1-9][0-9]{3,6}|[1-7][0-9]{7}|8[0-5][0-9]{6}|86[0-3][0-9]{5}|86400000)$";
23const MAX_PROTOCOL_BYTES: usize = 32;
24const MAX_ORIGIN_BYTES: usize = 128;
25const MAX_URI_BYTES: usize = 4096;
26
27#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
29#[serde(deny_unknown_fields)]
30#[allow(clippy::struct_field_names)]
31pub struct SkillActivationScope {
32 tenant_id: TenantId,
33 run_id: RunId,
34 thread_id: ThreadId,
35}
36
37impl SkillActivationScope {
38 #[must_use]
40 pub const fn new(tenant_id: TenantId, run_id: RunId, thread_id: ThreadId) -> Self {
41 Self {
42 tenant_id,
43 run_id,
44 thread_id,
45 }
46 }
47
48 #[must_use]
50 pub const fn tenant_id(&self) -> &TenantId {
51 &self.tenant_id
52 }
53
54 #[must_use]
56 pub const fn run_id(&self) -> RunId {
57 self.run_id
58 }
59
60 #[must_use]
62 pub const fn thread_id(&self) -> ThreadId {
63 self.thread_id
64 }
65}
66
67#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
69#[serde(deny_unknown_fields)]
70pub struct SkillAuthorizationSubject {
71 protocol: Box<str>,
72 origin: Box<str>,
73 uri: Box<str>,
74 manifest_digest: Digest,
75}
76
77impl SkillAuthorizationSubject {
78 pub fn new(
80 protocol: impl Into<String>,
81 origin: impl Into<String>,
82 uri: impl Into<String>,
83 manifest_digest: Digest,
84 ) -> Result<Self, SkillAuthorizationSubjectError> {
85 let protocol = protocol.into();
86 let origin = origin.into();
87 let uri = uri.into();
88 validate_label(&protocol, MAX_PROTOCOL_BYTES, true)?;
89 validate_label(&origin, MAX_ORIGIN_BYTES, false)?;
90 validate_label(&uri, MAX_URI_BYTES, false)?;
91 Ok(Self {
92 protocol: protocol.into_boxed_str(),
93 origin: origin.into_boxed_str(),
94 uri: uri.into_boxed_str(),
95 manifest_digest,
96 })
97 }
98
99 #[must_use]
101 pub fn protocol(&self) -> &str {
102 &self.protocol
103 }
104
105 #[must_use]
107 pub fn origin(&self) -> &str {
108 &self.origin
109 }
110
111 #[must_use]
113 pub fn uri(&self) -> &str {
114 &self.uri
115 }
116
117 #[must_use]
119 pub const fn manifest_digest(&self) -> Digest {
120 self.manifest_digest
121 }
122
123 #[must_use]
125 pub fn subject_digest(&self) -> Digest {
126 digest_canonical(SUBJECT_DIGEST_DOMAIN, self)
127 .expect("validated Skill subject canonicalizes")
128 }
129}
130
131impl<'de> Deserialize<'de> for SkillAuthorizationSubject {
132 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
133 where
134 D: Deserializer<'de>,
135 {
136 #[derive(Deserialize)]
137 #[serde(deny_unknown_fields)]
138 struct Wire {
139 protocol: String,
140 origin: String,
141 uri: String,
142 manifest_digest: Digest,
143 }
144 let wire = Wire::deserialize(deserializer)?;
145 Self::new(wire.protocol, wire.origin, wire.uri, wire.manifest_digest)
146 .map_err(de::Error::custom)
147 }
148}
149
150#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
152#[non_exhaustive]
153pub enum SkillAuthorizationSubjectError {
154 #[error("Skill authorization subject contains an empty label")]
156 Empty,
157 #[error("Skill authorization subject label is too long")]
159 TooLong,
160 #[error("Skill authorization subject label is not canonical")]
162 NonCanonical,
163 #[error("Skill authorization protocol is invalid")]
165 InvalidProtocol,
166}
167
168fn validate_label(
169 value: &str,
170 maximum: usize,
171 protocol: bool,
172) -> Result<(), SkillAuthorizationSubjectError> {
173 if value.is_empty() {
174 return Err(SkillAuthorizationSubjectError::Empty);
175 }
176 if value.len() > maximum {
177 return Err(SkillAuthorizationSubjectError::TooLong);
178 }
179 if value.trim() != value || value.chars().any(char::is_control) {
180 return Err(SkillAuthorizationSubjectError::NonCanonical);
181 }
182 if protocol
183 && !value.bytes().all(|byte| {
184 byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'.' | b'-')
185 })
186 {
187 return Err(SkillAuthorizationSubjectError::InvalidProtocol);
188 }
189 Ok(())
190}
191
192#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
194#[serde(rename_all = "snake_case", tag = "kind", deny_unknown_fields)]
195#[non_exhaustive]
196pub enum SkillActivationSource {
197 Direct,
199 Nested {
201 parent_window_id: SkillActingWindowId,
203 },
204}
205
206impl<'de> Deserialize<'de> for SkillActivationSource {
207 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
208 where
209 D: Deserializer<'de>,
210 {
211 #[derive(Deserialize)]
212 #[serde(rename_all = "snake_case")]
213 enum Kind {
214 Direct,
215 Nested,
216 }
217
218 #[derive(Deserialize)]
219 #[serde(deny_unknown_fields)]
220 struct Wire {
221 kind: Kind,
222 #[serde(default)]
223 parent_window_id: Option<SkillActingWindowId>,
224 }
225
226 let wire = Wire::deserialize(deserializer)?;
227 match (wire.kind, wire.parent_window_id) {
228 (Kind::Direct, None) => Ok(Self::Direct),
229 (Kind::Nested, Some(parent_window_id)) => Ok(Self::Nested { parent_window_id }),
230 (Kind::Direct, Some(_)) => Err(de::Error::custom(
231 "direct Skill activation source cannot contain a parent window",
232 )),
233 (Kind::Nested, None) => Err(de::Error::missing_field("parent_window_id")),
234 }
235 }
236}
237
238#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
240#[serde(transparent)]
241pub struct SkillActingWindowDuration(DurationMillis);
242
243impl SkillActingWindowDuration {
244 pub const MIN_MILLIS: i64 = 1_000;
246 pub const MAX_MILLIS: i64 = 86_400_000;
248
249 pub const fn new(value: DurationMillis) -> Result<Self, SkillActingWindowError> {
251 if value.as_i64() < Self::MIN_MILLIS || value.as_i64() > Self::MAX_MILLIS {
252 return Err(SkillActingWindowError::InvalidDuration);
253 }
254 Ok(Self(value))
255 }
256
257 #[must_use]
259 pub const fn duration(self) -> DurationMillis {
260 self.0
261 }
262}
263
264impl<'de> Deserialize<'de> for SkillActingWindowDuration {
265 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
266 where
267 D: Deserializer<'de>,
268 {
269 let duration = DurationMillis::deserialize(deserializer)?;
270 Self::new(duration).map_err(de::Error::custom)
271 }
272}
273
274impl JsonSchema for SkillActingWindowDuration {
275 fn schema_name() -> std::borrow::Cow<'static, str> {
276 "SkillActingWindowDuration".into()
277 }
278
279 fn schema_id() -> std::borrow::Cow<'static, str> {
280 concat!(module_path!(), "::SkillActingWindowDuration").into()
281 }
282
283 fn json_schema(_: &mut SchemaGenerator) -> Schema {
284 json_schema!({
285 "type": "string",
286 "minLength": 4,
287 "maxLength": 8,
288 "pattern": ACTING_WINDOW_DURATION_PATTERN
289 })
290 }
291
292 fn inline_schema() -> bool {
293 true
294 }
295}
296
297#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
299#[serde(deny_unknown_fields)]
300pub struct SkillActivationApproval {
301 approval_id: SkillActivationApprovalId,
302 scope: SkillActivationScope,
303 subject: SkillAuthorizationSubject,
304 source: SkillActivationSource,
305 policy: CapabilityIdentity,
306 policy_digest: Digest,
307 decision_digest: Digest,
308 requested_duration: SkillActingWindowDuration,
309 approval_digest: Digest,
310}
311
312impl SkillActivationApproval {
313 #[allow(clippy::too_many_arguments)]
315 pub fn new(
316 approval_id: SkillActivationApprovalId,
317 scope: SkillActivationScope,
318 subject: SkillAuthorizationSubject,
319 source: SkillActivationSource,
320 policy: CapabilityIdentity,
321 policy_digest: Digest,
322 decision_digest: Digest,
323 requested_duration: SkillActingWindowDuration,
324 ) -> Result<Self, SkillActingWindowError> {
325 let mut value = Self {
326 approval_id,
327 scope,
328 subject,
329 source,
330 policy,
331 policy_digest,
332 decision_digest,
333 requested_duration,
334 approval_digest: Digest::sha256(b""),
335 };
336 value.approval_digest = value.compute_digest()?;
337 Ok(value)
338 }
339
340 #[must_use]
342 pub const fn approval_id(&self) -> SkillActivationApprovalId {
343 self.approval_id
344 }
345
346 #[must_use]
348 pub const fn scope(&self) -> &SkillActivationScope {
349 &self.scope
350 }
351
352 #[must_use]
354 pub const fn subject(&self) -> &SkillAuthorizationSubject {
355 &self.subject
356 }
357
358 #[must_use]
360 pub const fn source(&self) -> &SkillActivationSource {
361 &self.source
362 }
363
364 #[must_use]
366 pub const fn policy(&self) -> &CapabilityIdentity {
367 &self.policy
368 }
369
370 #[must_use]
372 pub const fn policy_digest(&self) -> Digest {
373 self.policy_digest
374 }
375
376 #[must_use]
378 pub const fn decision_digest(&self) -> Digest {
379 self.decision_digest
380 }
381
382 #[must_use]
384 pub const fn requested_duration(&self) -> SkillActingWindowDuration {
385 self.requested_duration
386 }
387
388 #[must_use]
390 pub const fn approval_digest(&self) -> Digest {
391 self.approval_digest
392 }
393
394 fn compute_digest(&self) -> Result<Digest, SkillActingWindowError> {
395 #[derive(Serialize)]
396 struct Preimage<'a> {
397 approval_id: SkillActivationApprovalId,
398 scope: &'a SkillActivationScope,
399 subject: &'a SkillAuthorizationSubject,
400 source: &'a SkillActivationSource,
401 policy: &'a CapabilityIdentity,
402 policy_digest: Digest,
403 decision_digest: Digest,
404 requested_duration: SkillActingWindowDuration,
405 }
406 digest_canonical(
407 APPROVAL_DIGEST_DOMAIN,
408 &Preimage {
409 approval_id: self.approval_id,
410 scope: &self.scope,
411 subject: &self.subject,
412 source: &self.source,
413 policy: &self.policy,
414 policy_digest: self.policy_digest,
415 decision_digest: self.decision_digest,
416 requested_duration: self.requested_duration,
417 },
418 )
419 }
420}
421
422impl fmt::Debug for SkillActivationApproval {
423 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
424 formatter
425 .debug_struct("SkillActivationApproval")
426 .field("approval_id", &self.approval_id)
427 .field("scope", &self.scope)
428 .field("subject", &self.subject)
429 .field("source", &self.source)
430 .field("policy", &self.policy)
431 .field("policy_digest", &self.policy_digest)
432 .field("decision_digest", &self.decision_digest)
433 .field("requested_duration", &self.requested_duration)
434 .field("approval_digest", &self.approval_digest)
435 .finish_non_exhaustive()
436 }
437}
438
439impl<'de> Deserialize<'de> for SkillActivationApproval {
440 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
441 where
442 D: Deserializer<'de>,
443 {
444 #[derive(Deserialize)]
445 #[serde(deny_unknown_fields)]
446 struct Wire {
447 approval_id: SkillActivationApprovalId,
448 scope: SkillActivationScope,
449 subject: SkillAuthorizationSubject,
450 source: SkillActivationSource,
451 policy: CapabilityIdentity,
452 policy_digest: Digest,
453 decision_digest: Digest,
454 requested_duration: SkillActingWindowDuration,
455 approval_digest: Digest,
456 }
457 let wire = Wire::deserialize(deserializer)?;
458 let value = Self::new(
459 wire.approval_id,
460 wire.scope,
461 wire.subject,
462 wire.source,
463 wire.policy,
464 wire.policy_digest,
465 wire.decision_digest,
466 wire.requested_duration,
467 )
468 .map_err(de::Error::custom)?;
469 if value.approval_digest != wire.approval_digest {
470 return Err(de::Error::custom(SkillActingWindowError::DigestMismatch));
471 }
472 Ok(value)
473 }
474}
475
476#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
478#[serde(deny_unknown_fields)]
479pub struct SkillActingWindowOpenRequest {
480 window_id: SkillActingWindowId,
481 approval: SkillActivationApproval,
482}
483
484impl SkillActingWindowOpenRequest {
485 #[must_use]
487 pub const fn new(window_id: SkillActingWindowId, approval: SkillActivationApproval) -> Self {
488 Self {
489 window_id,
490 approval,
491 }
492 }
493
494 #[must_use]
496 pub const fn window_id(&self) -> SkillActingWindowId {
497 self.window_id
498 }
499
500 #[must_use]
502 pub const fn approval(&self) -> &SkillActivationApproval {
503 &self.approval
504 }
505}
506
507#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
509#[serde(deny_unknown_fields)]
510pub struct SkillActingWindow {
511 window_id: SkillActingWindowId,
512 approval: SkillActivationApproval,
513 opened_at: Timestamp,
514 expires_at: Timestamp,
515 window_digest: Digest,
516}
517
518impl SkillActingWindow {
519 pub fn new(
521 window_id: SkillActingWindowId,
522 approval: SkillActivationApproval,
523 opened_at: Timestamp,
524 expires_at: Timestamp,
525 ) -> Result<Self, SkillActingWindowError> {
526 let requested_micros = approval
527 .requested_duration()
528 .duration()
529 .as_i64()
530 .checked_mul(1_000)
531 .ok_or(SkillActingWindowError::InvalidClock)?;
532 let expected = opened_at
533 .unix_micros()
534 .checked_add(requested_micros)
535 .ok_or(SkillActingWindowError::InvalidClock)?;
536 if expires_at.unix_micros() != expected {
537 return Err(SkillActingWindowError::InvalidClock);
538 }
539 let mut value = Self {
540 window_id,
541 approval,
542 opened_at,
543 expires_at,
544 window_digest: Digest::sha256(b""),
545 };
546 value.window_digest = value.compute_digest()?;
547 Ok(value)
548 }
549
550 #[must_use]
552 pub const fn window_id(&self) -> SkillActingWindowId {
553 self.window_id
554 }
555
556 #[must_use]
558 pub const fn approval(&self) -> &SkillActivationApproval {
559 &self.approval
560 }
561
562 #[must_use]
564 pub const fn opened_at(&self) -> Timestamp {
565 self.opened_at
566 }
567
568 #[must_use]
570 pub const fn expires_at(&self) -> Timestamp {
571 self.expires_at
572 }
573
574 #[must_use]
576 pub const fn window_digest(&self) -> Digest {
577 self.window_digest
578 }
579
580 fn compute_digest(&self) -> Result<Digest, SkillActingWindowError> {
581 #[derive(Serialize)]
582 struct Preimage<'a> {
583 window_id: SkillActingWindowId,
584 approval: &'a SkillActivationApproval,
585 opened_at: Timestamp,
586 expires_at: Timestamp,
587 }
588 digest_canonical(
589 WINDOW_DIGEST_DOMAIN,
590 &Preimage {
591 window_id: self.window_id,
592 approval: &self.approval,
593 opened_at: self.opened_at,
594 expires_at: self.expires_at,
595 },
596 )
597 }
598}
599
600impl fmt::Debug for SkillActingWindow {
601 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
602 formatter
603 .debug_struct("SkillActingWindow")
604 .field("window_id", &self.window_id)
605 .field("approval", &self.approval)
606 .field("opened_at", &self.opened_at)
607 .field("expires_at", &self.expires_at)
608 .field("window_digest", &self.window_digest)
609 .finish_non_exhaustive()
610 }
611}
612
613impl<'de> Deserialize<'de> for SkillActingWindow {
614 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
615 where
616 D: Deserializer<'de>,
617 {
618 #[derive(Deserialize)]
619 #[serde(deny_unknown_fields)]
620 struct Wire {
621 window_id: SkillActingWindowId,
622 approval: SkillActivationApproval,
623 opened_at: Timestamp,
624 expires_at: Timestamp,
625 window_digest: Digest,
626 }
627 let wire = Wire::deserialize(deserializer)?;
628 let value = Self::new(
629 wire.window_id,
630 wire.approval,
631 wire.opened_at,
632 wire.expires_at,
633 )
634 .map_err(de::Error::custom)?;
635 if value.window_digest != wire.window_digest {
636 return Err(de::Error::custom(SkillActingWindowError::DigestMismatch));
637 }
638 Ok(value)
639 }
640}
641
642#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
644#[serde(rename_all = "snake_case")]
645#[non_exhaustive]
646pub enum SkillActingWindowRevocationReason {
647 User,
649 Policy,
651 Compromised,
653 Superseded,
655 Administrative,
657}
658
659#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
661#[serde(deny_unknown_fields)]
662pub struct SkillActingWindowRevocation {
663 tenant_id: TenantId,
664 window_id: SkillActingWindowId,
665 reason: SkillActingWindowRevocationReason,
666 revoked_at: Timestamp,
667 revocation_digest: Digest,
668}
669
670impl SkillActingWindowRevocation {
671 pub fn new(
673 tenant_id: TenantId,
674 window_id: SkillActingWindowId,
675 reason: SkillActingWindowRevocationReason,
676 revoked_at: Timestamp,
677 ) -> Result<Self, SkillActingWindowError> {
678 let mut value = Self {
679 tenant_id,
680 window_id,
681 reason,
682 revoked_at,
683 revocation_digest: Digest::sha256(b""),
684 };
685 value.revocation_digest = digest_canonical(
686 REVOCATION_DIGEST_DOMAIN,
687 &(
688 &value.tenant_id,
689 value.window_id,
690 value.reason,
691 value.revoked_at,
692 ),
693 )?;
694 Ok(value)
695 }
696
697 #[must_use]
699 pub const fn tenant_id(&self) -> &TenantId {
700 &self.tenant_id
701 }
702
703 #[must_use]
705 pub const fn window_id(&self) -> SkillActingWindowId {
706 self.window_id
707 }
708
709 #[must_use]
711 pub const fn reason(&self) -> SkillActingWindowRevocationReason {
712 self.reason
713 }
714
715 #[must_use]
717 pub const fn revoked_at(&self) -> Timestamp {
718 self.revoked_at
719 }
720
721 #[must_use]
723 pub const fn revocation_digest(&self) -> Digest {
724 self.revocation_digest
725 }
726}
727
728impl<'de> Deserialize<'de> for SkillActingWindowRevocation {
729 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
730 where
731 D: Deserializer<'de>,
732 {
733 #[derive(Deserialize)]
734 #[serde(deny_unknown_fields)]
735 struct Wire {
736 tenant_id: TenantId,
737 window_id: SkillActingWindowId,
738 reason: SkillActingWindowRevocationReason,
739 revoked_at: Timestamp,
740 revocation_digest: Digest,
741 }
742 let wire = Wire::deserialize(deserializer)?;
743 let value = Self::new(wire.tenant_id, wire.window_id, wire.reason, wire.revoked_at)
744 .map_err(de::Error::custom)?;
745 if value.revocation_digest != wire.revocation_digest {
746 return Err(de::Error::custom(SkillActingWindowError::DigestMismatch));
747 }
748 Ok(value)
749 }
750}
751
752#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
754#[non_exhaustive]
755pub enum SkillActingWindowError {
756 #[error("Skill acting-window duration is outside the supported range")]
758 InvalidDuration,
759 #[error("Skill acting-window clock evidence is invalid")]
761 InvalidClock,
762 #[error("Skill acting-window canonical encoding failed")]
764 Encoding,
765 #[error("Skill acting-window digest does not match its fields")]
767 DigestMismatch,
768}
769
770fn digest_canonical<T: Serialize>(
771 domain: &[u8],
772 value: &T,
773) -> Result<Digest, SkillActingWindowError> {
774 let canonical =
775 serde_json_canonicalizer::to_vec(value).map_err(|_| SkillActingWindowError::Encoding)?;
776 let mut bytes = Vec::with_capacity(domain.len() + 8 + canonical.len());
777 bytes.extend_from_slice(domain);
778 bytes.extend_from_slice(
779 &u64::try_from(canonical.len())
780 .expect("Skill authorization evidence length fits u64")
781 .to_be_bytes(),
782 );
783 bytes.extend_from_slice(&canonical);
784 Ok(Digest::sha256(bytes))
785}
786
787#[derive(Clone, Copy, Debug, Eq, PartialEq)]
789#[non_exhaustive]
790pub enum SkillActivationStoreFailure {
791 Unavailable,
793 NotFound,
795 Inactive,
797 Rejected,
799}
800
801pub struct SkillActivationStoreError {
803 failure: SkillActivationStoreFailure,
804 source: Arc<dyn StdError + Send + Sync + 'static>,
805}
806
807impl SkillActivationStoreError {
808 #[must_use]
810 pub fn new<E>(failure: SkillActivationStoreFailure, source: E) -> Self
811 where
812 E: StdError + Send + Sync + 'static,
813 {
814 Self {
815 failure,
816 source: Arc::new(source),
817 }
818 }
819
820 #[must_use]
822 pub const fn failure(&self) -> SkillActivationStoreFailure {
823 self.failure
824 }
825
826 #[must_use]
828 pub fn private_source(&self) -> &(dyn StdError + Send + Sync + 'static) {
829 self.source.as_ref()
830 }
831}
832
833impl fmt::Debug for SkillActivationStoreError {
834 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
835 formatter
836 .debug_struct("SkillActivationStoreError")
837 .field("failure", &self.failure)
838 .field("has_private_source", &true)
839 .finish_non_exhaustive()
840 }
841}
842
843impl fmt::Display for SkillActivationStoreError {
844 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
845 formatter.write_str("Skill activation store failed")
846 }
847}
848
849impl StdError for SkillActivationStoreError {
850 fn source(&self) -> Option<&(dyn StdError + 'static)> {
851 Some(self.source.as_ref())
852 }
853}
854
855pub trait SkillActivationStore: Send + Sync + 'static {
857 fn open(
859 &self,
860 request: SkillActingWindowOpenRequest,
861 ) -> BoxFuture<'_, Result<SkillActingWindow, SkillActivationStoreError>>;
862
863 fn load_active(
865 &self,
866 tenant_id: TenantId,
867 window_id: SkillActingWindowId,
868 ) -> BoxFuture<'_, Result<SkillActingWindow, SkillActivationStoreError>>;
869
870 fn assert_active(
872 &self,
873 window: SkillActingWindow,
874 ) -> BoxFuture<'_, Result<(), SkillActivationStoreError>>;
875
876 fn revoke(
878 &self,
879 window: SkillActingWindow,
880 reason: SkillActingWindowRevocationReason,
881 ) -> BoxFuture<'_, Result<SkillActingWindowRevocation, SkillActivationStoreError>>;
882}
883
884#[cfg(test)]
885mod tests {
886 use super::*;
887 use crate::{
888 CapabilityName, CapabilityReference, IssuerId, PrincipalIdentity, SubjectId, Version,
889 };
890
891 fn policy() -> CapabilityIdentity {
892 CapabilityIdentity::new(
893 PrincipalIdentity::new(
894 "https://issuer.example.com".parse::<IssuerId>().unwrap(),
895 "policy".parse::<SubjectId>().unwrap(),
896 ),
897 CapabilityReference::new(
898 "skill-activation".parse::<CapabilityName>().unwrap(),
899 Version::new(1, 0, 0),
900 ),
901 )
902 }
903
904 fn approval() -> SkillActivationApproval {
905 SkillActivationApproval::new(
906 "018f1f65-45d3-7a2e-8a19-4de38b783450".parse().unwrap(),
907 SkillActivationScope::new(
908 "tenant-a".parse().unwrap(),
909 "018f1f65-45d3-7a2e-8a19-4de38b783451".parse().unwrap(),
910 "018f1f65-45d3-7a2e-8a19-4de38b783452".parse().unwrap(),
911 ),
912 SkillAuthorizationSubject::new(
913 "mcp",
914 "production",
915 "skill://review/SKILL.md",
916 Digest::sha256(b"manifest"),
917 )
918 .unwrap(),
919 SkillActivationSource::Direct,
920 policy(),
921 Digest::sha256(b"policy"),
922 Digest::sha256(b"decision"),
923 SkillActingWindowDuration::new(DurationMillis::new(60_000).unwrap()).unwrap(),
924 )
925 .unwrap()
926 }
927
928 #[test]
929 fn approval_window_and_revocation_reject_tampering() {
930 let approval = approval();
931 let opened: Timestamp = "2026-09-20T12:00:00.000000Z".parse().unwrap();
932 let expires: Timestamp = "2026-09-20T12:01:00.000000Z".parse().unwrap();
933 let window = SkillActingWindow::new(
934 "018f1f65-45d3-7a2e-8a19-4de38b783453".parse().unwrap(),
935 approval,
936 opened,
937 expires,
938 )
939 .unwrap();
940 let encoded = serde_json::to_value(&window).unwrap();
941 assert_eq!(
942 serde_json::from_value::<SkillActingWindow>(encoded.clone()).unwrap(),
943 window
944 );
945 let mut changed = encoded;
946 changed["expires_at"] = serde_json::json!("2026-09-20T12:02:00.000000Z");
947 assert!(serde_json::from_value::<SkillActingWindow>(changed).is_err());
948
949 let revocation = SkillActingWindowRevocation::new(
950 window.approval().scope().tenant_id().clone(),
951 window.window_id(),
952 SkillActingWindowRevocationReason::Policy,
953 expires,
954 )
955 .unwrap();
956 assert_eq!(
957 serde_json::from_value::<SkillActingWindowRevocation>(
958 serde_json::to_value(&revocation).unwrap()
959 )
960 .unwrap(),
961 revocation
962 );
963 }
964
965 #[test]
966 fn subject_and_duration_are_strictly_bounded() {
967 assert!(
968 SkillAuthorizationSubject::new(
969 "MCP",
970 "origin",
971 "skill://a/SKILL.md",
972 Digest::sha256(b"x")
973 )
974 .is_err()
975 );
976 assert!(SkillActingWindowDuration::new(DurationMillis::new(999).unwrap()).is_err());
977 assert!(SkillActingWindowDuration::new(DurationMillis::new(86_400_001).unwrap()).is_err());
978 }
979}