Skip to main content

dekopon_capability/
lib.rs

1//! ```compile_fail
2//! use dekopon_capability::{AuthorizedInvocation, ExecutionConstraints, ProposedInvocation};
3//!
4//! fn fabricate(proposal: ProposedInvocation, constraints: ExecutionConstraints) {
5//!     // Ordinary callers cannot use a struct literal to cross the authority boundary.
6//!     let _forged = AuthorizedInvocation {
7//!         proposal,
8//!         provider: todo!(),
9//!         receipt: todo!(),
10//!         constraints,
11//!     };
12//! }
13//! ```
14//! ```compile_fail
15//! use dekopon_capability::AuthorizedInvocation;
16//! use serde::de::DeserializeOwned;
17//!
18//! fn require_deserializable<T: DeserializeOwned>() {}
19//!
20//! fn main() {
21//!     require_deserializable::<AuthorizedInvocation>();
22//! }
23//! ```
24//! ```compile_fail
25//! use dekopon_capability::AuthorizedInvocation;
26//!
27//! fn require_clone<T: Clone>() {}
28//!
29//! fn main() {
30//!     require_clone::<AuthorizedInvocation>();
31//! }
32//! ```
33
34#![forbid(unsafe_code)]
35#![cfg_attr(test, allow(clippy::unwrap_used))]
36#![cfg_attr(
37    test,
38    allow(
39        clippy::disallowed_methods,
40        clippy::disallowed_types,
41        reason = "tests spawn, join and drain freely; production sites carry their own expectation"
42    )
43)]
44mod template;
45
46use std::{collections::BTreeSet, fmt, num::NonZeroU8};
47
48use dekopon_core::{
49    Actor, CapabilityId, InvocationId, PrincipalId, ProviderFailureDetail, ProviderId, SecretDrn,
50    SecretSinkKind, SecretUseProposal, TraceId,
51};
52use serde::{Deserialize, Serialize};
53use serde_json::Value;
54use thiserror::Error;
55
56pub use template::{
57    ChatSlot, ChatSlotValues, MAX_TEMPLATE_PATH_BYTES, MAX_TEMPLATE_QUERY_KEY_BYTES, PathSegment,
58    PathTemplate, PathTemplateError, QueryTemplate, RequestTemplate,
59};
60
61#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
62#[serde(rename_all = "kebab-case")]
63pub enum EffectKind {
64    ReadOnly,
65    LocalWrite,
66    ExternalWrite,
67}
68
69impl fmt::Display for EffectKind {
70    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
71        let value = match self {
72            Self::ReadOnly => "read-only",
73            Self::LocalWrite => "local-write",
74            Self::ExternalWrite => "external-write",
75        };
76        formatter.write_str(value)
77    }
78}
79
80#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
81#[serde(deny_unknown_fields, rename_all = "camelCase")]
82pub struct Permission {
83    pub operation: String,
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub resource: Option<String>,
86}
87
88#[derive(Clone, Debug, PartialEq, Serialize)]
89#[serde(deny_unknown_fields, rename_all = "camelCase")]
90pub struct ProposedInvocation {
91    pub id: InvocationId,
92    pub capability: CapabilityId,
93    pub actor: Actor,
94    pub trace: TraceId,
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub secret_use: Option<SecretUseProposal>,
97    pub input: Value,
98}
99
100impl ProposedInvocation {
101    #[must_use]
102    pub fn new(
103        id: InvocationId,
104        capability: CapabilityId,
105        actor: Actor,
106        trace: TraceId,
107        input: Value,
108    ) -> Self {
109        Self {
110            id,
111            capability,
112            actor,
113            trace,
114            secret_use: None,
115            input,
116        }
117    }
118
119    #[must_use]
120    pub fn with_secret_use(mut self, secret_use: Option<SecretUseProposal>) -> Self {
121        self.secret_use = secret_use;
122        self
123    }
124}
125
126#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
127#[serde(deny_unknown_fields, rename_all = "camelCase")]
128pub struct HttpConstraints {
129    pub allowed_hosts: Vec<String>,
130    pub allowed_methods: Vec<String>,
131    pub max_requests: u32,
132    pub max_request_bytes: u64,
133    pub max_response_bytes: u64,
134    #[serde(default, skip_serializing_if = "is_false")]
135    pub allow_plaintext_loopback: bool,
136    #[serde(default, skip_serializing_if = "is_false")]
137    pub propagate_trace: bool,
138    #[serde(default, skip_serializing_if = "Vec::is_empty")]
139    pub request_templates: Vec<RequestTemplate>,
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub signed_download: Option<SignedDownload>,
142}
143
144#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
145#[serde(rename_all = "kebab-case")]
146pub enum SignedDownload {
147    GithubActionsLogsV1,
148}
149
150const fn is_false(value: &bool) -> bool {
151    !*value
152}
153
154pub const MAX_HTTP_SCOPE_ENTRIES: usize = 64;
155pub const MAX_HTTP_HOST_BYTES: usize = 512;
156pub const MAX_HTTP_METHOD_BYTES: usize = 64;
157
158impl HttpConstraints {
159    pub fn validate(&self) -> Result<(), HttpConstraintsError> {
160        if self.allowed_hosts.is_empty() {
161            return Err(HttpConstraintsError::NoHosts);
162        }
163        if self.allowed_methods.is_empty() {
164            return Err(HttpConstraintsError::NoMethods);
165        }
166        if self.allowed_hosts.len() > MAX_HTTP_SCOPE_ENTRIES
167            || self.allowed_methods.len() > MAX_HTTP_SCOPE_ENTRIES
168        {
169            return Err(HttpConstraintsError::TooManyEntries {
170                maximum: MAX_HTTP_SCOPE_ENTRIES,
171            });
172        }
173        if let Some(value) = self
174            .allowed_hosts
175            .iter()
176            .find(|value| !is_authority_scope(value))
177        {
178            return Err(HttpConstraintsError::InvalidHost {
179                value: value.clone(),
180            });
181        }
182        if let Some(value) = self
183            .allowed_methods
184            .iter()
185            .find(|value| value.len() > MAX_HTTP_METHOD_BYTES || !is_http_token(value))
186        {
187            return Err(HttpConstraintsError::InvalidMethod {
188                value: value.clone(),
189            });
190        }
191        if self.max_requests == 0 || self.max_request_bytes == 0 || self.max_response_bytes == 0 {
192            return Err(HttpConstraintsError::ZeroLimit);
193        }
194        self.validate_request_templates()
195    }
196
197    #[must_use]
198    pub fn template_slots(&self) -> BTreeSet<ChatSlot> {
199        self.request_templates
200            .iter()
201            .flat_map(RequestTemplate::slots)
202            .collect()
203    }
204
205    fn validate_request_templates(&self) -> Result<(), HttpConstraintsError> {
206        if self.request_templates.len() > MAX_HTTP_SCOPE_ENTRIES {
207            return Err(HttpConstraintsError::TooManyEntries {
208                maximum: MAX_HTTP_SCOPE_ENTRIES,
209            });
210        }
211        let unsafe_rules = self
212            .request_templates
213            .iter()
214            .filter(|template| !matches!(template.method.as_str(), "GET" | "HEAD"))
215            .map(ToString::to_string)
216            .collect::<Vec<_>>();
217        if !unsafe_rules.is_empty() {
218            return Err(HttpConstraintsError::TemplateMethodNotReadOnly {
219                rules: unsafe_rules,
220            });
221        }
222        let mut routes = BTreeSet::new();
223        for template in &self.request_templates {
224            let rule = template.to_string();
225            if !self.allowed_methods.contains(&template.method) {
226                return Err(HttpConstraintsError::TemplateMethodNotAllowed { rule });
227            }
228            if !routes.insert((&template.method, &template.path)) {
229                return Err(HttpConstraintsError::DuplicateTemplate { rule });
230            }
231            let query = &template.query;
232            if query.pinned.len() + query.allowed.len() > MAX_HTTP_SCOPE_ENTRIES {
233                return Err(HttpConstraintsError::TooManyEntries {
234                    maximum: MAX_HTTP_SCOPE_ENTRIES,
235                });
236            }
237            if let Some(key) = query
238                .pinned
239                .keys()
240                .chain(&query.allowed)
241                .find(|key| !template::is_query_key(key))
242            {
243                return Err(HttpConstraintsError::InvalidTemplateQueryKey {
244                    rule,
245                    key: key.clone(),
246                });
247            }
248            if let Some(key) = query
249                .allowed
250                .iter()
251                .find(|key| query.pinned.contains_key(*key))
252            {
253                return Err(HttpConstraintsError::TemplateKeyPinnedAndAllowed {
254                    rule,
255                    key: key.clone(),
256                });
257            }
258        }
259        Ok(())
260    }
261}
262
263fn is_authority_scope(value: &str) -> bool {
264    !value.is_empty()
265        && value.len() <= MAX_HTTP_HOST_BYTES
266        && value.trim() == value
267        && !value
268            .bytes()
269            .any(|byte| byte.is_ascii_control() || byte.is_ascii_whitespace())
270        && !value.contains(['/', '?', '#', '@', '*'])
271}
272
273fn is_http_token(value: &str) -> bool {
274    !value.is_empty()
275        && value.bytes().all(|byte| {
276            byte.is_ascii_alphanumeric()
277                || matches!(
278                    byte,
279                    b'!' | b'#'
280                        | b'$'
281                        | b'%'
282                        | b'&'
283                        | b'\''
284                        | b'*'
285                        | b'+'
286                        | b'-'
287                        | b'.'
288                        | b'^'
289                        | b'_'
290                        | b'`'
291                        | b'|'
292                        | b'~'
293                )
294        })
295}
296
297#[derive(Clone, Debug, Eq, Error, PartialEq)]
298pub enum HttpConstraintsError {
299    #[error("HTTP authorization requires at least one allowed host")]
300    NoHosts,
301    #[error("HTTP authorization requires at least one allowed method")]
302    NoMethods,
303    #[error("HTTP authorization allows at most {maximum} host or method entries")]
304    TooManyEntries { maximum: usize },
305    #[error("HTTP allowed host {value:?} is not an exact authority")]
306    InvalidHost { value: String },
307    #[error("HTTP allowed method {value:?} is not an exact HTTP method token")]
308    InvalidMethod { value: String },
309    #[error("HTTP authorization limits must be greater than zero")]
310    ZeroLimit,
311    #[error(
312        "HTTP request templates {rules:?} name a method other than GET or HEAD; send templates \
313         come with the send capability's body grammar"
314    )]
315    TemplateMethodNotReadOnly { rules: Vec<String> },
316    #[error("HTTP request template {rule:?} names a method allowedMethods does not grant")]
317    TemplateMethodNotAllowed { rule: String },
318    #[error("HTTP request template {rule:?} appears more than once")]
319    DuplicateTemplate { rule: String },
320    #[error("HTTP request template {rule:?} has an invalid query key {key:?}")]
321    InvalidTemplateQueryKey { rule: String, key: String },
322    #[error("HTTP request template {rule:?} both pins and allows query key {key:?}")]
323    TemplateKeyPinnedAndAllowed { rule: String, key: String },
324}
325
326#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
327#[serde(tag = "match", rename_all = "camelCase", deny_unknown_fields)]
328pub enum HttpPathRule {
329    Exact { path: String },
330    SegmentPrefix { path: String },
331}
332
333impl HttpPathRule {
334    pub fn validate(&self) -> Result<(), SecretUseGrantError> {
335        let path = self.path();
336        if !canonical_secret_path(path) {
337            return Err(SecretUseGrantError::InvalidPath {
338                path: path.to_owned(),
339            });
340        }
341        Ok(())
342    }
343
344    #[must_use]
345    pub fn path(&self) -> &str {
346        match self {
347            Self::Exact { path } | Self::SegmentPrefix { path } => path,
348        }
349    }
350
351    #[must_use]
352    pub fn matches(&self, candidate: &str) -> bool {
353        match self {
354            Self::Exact { path } => candidate == path,
355            Self::SegmentPrefix { path } if path == "/" => candidate.starts_with('/'),
356            Self::SegmentPrefix { path } => {
357                candidate == path
358                    || candidate
359                        .strip_prefix(path)
360                        .is_some_and(|suffix| suffix.starts_with('/'))
361            }
362        }
363    }
364}
365
366fn canonical_secret_path(path: &str) -> bool {
367    path.starts_with('/')
368        && path.len() <= 4096
369        && !path.contains(['%', '\\', '?', '#'])
370        && !path.contains("//")
371        && !path
372            .bytes()
373            .any(|byte| byte.is_ascii_control() || byte.is_ascii_whitespace())
374        && path
375            .split('/')
376            .skip(1)
377            .all(|segment| !matches!(segment, "." | ".."))
378}
379
380#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
381#[serde(deny_unknown_fields, rename_all = "camelCase")]
382pub struct SecretUseGrant {
383    pub secret: SecretDrn,
384    pub sink: SecretSinkKind,
385    #[serde(default, skip_serializing_if = "Option::is_none")]
386    pub basic_username: Option<String>,
387    pub allowed_hosts: Vec<String>,
388    pub allowed_methods: Vec<String>,
389    pub allowed_paths: Vec<HttpPathRule>,
390    #[serde(default, skip_serializing_if = "is_false")]
391    pub allow_query: bool,
392    pub max_injections: u32,
393    pub binding_id: String,
394    #[serde(default, skip_serializing_if = "Option::is_none")]
395    pub map_revision: Option<String>,
396}
397
398impl SecretUseGrant {
399    pub fn validate(&self) -> Result<(), SecretUseGrantError> {
400        if self.allowed_hosts.is_empty()
401            || self.allowed_methods.is_empty()
402            || self.allowed_paths.is_empty()
403        {
404            return Err(SecretUseGrantError::EmptyScope);
405        }
406        if self.max_injections == 0 {
407            return Err(SecretUseGrantError::ZeroInjections);
408        }
409        if self.binding_id.is_empty()
410            || self.binding_id.len() > 128
411            || !self
412                .binding_id
413                .bytes()
414                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_'))
415        {
416            return Err(SecretUseGrantError::InvalidBindingId);
417        }
418        if self.map_revision.as_ref().is_some_and(|revision| {
419            revision.is_empty()
420                || revision.len() > 128
421                || revision.trim() != revision
422                || revision.bytes().any(|byte| byte.is_ascii_control())
423        }) {
424            return Err(SecretUseGrantError::InvalidMapRevision);
425        }
426        if self.allowed_hosts.len() > MAX_HTTP_SCOPE_ENTRIES
427            || self.allowed_methods.len() > MAX_HTTP_SCOPE_ENTRIES
428            || self.allowed_paths.len() > MAX_HTTP_SCOPE_ENTRIES
429            || self
430                .allowed_hosts
431                .iter()
432                .any(|value| !is_authority_scope(value))
433            || self
434                .allowed_methods
435                .iter()
436                .any(|value| value.len() > MAX_HTTP_METHOD_BYTES || !is_http_token(value))
437        {
438            return Err(SecretUseGrantError::InvalidScope);
439        }
440        for path in &self.allowed_paths {
441            path.validate()?;
442        }
443        match (self.sink, self.basic_username.as_deref()) {
444            (SecretSinkKind::HttpBasic, Some(username))
445                if !username.is_empty()
446                    && username.len() <= dekopon_core::MAX_SECRET_USERNAME_LENGTH
447                    && !username.contains(':')
448                    && !username.bytes().any(|byte| byte.is_ascii_control()) => {}
449            (SecretSinkKind::HttpBearer | SecretSinkKind::HttpBot, None) => {}
450            _ => return Err(SecretUseGrantError::InvalidUsername),
451        }
452        Ok(())
453    }
454}
455
456#[derive(Clone, Debug, Eq, Error, PartialEq)]
457pub enum SecretUseGrantError {
458    #[error("secret use requires nonempty host, method, and path scopes")]
459    EmptyScope,
460    #[error("secret use scopes are oversized or structurally invalid")]
461    InvalidScope,
462    #[error("secret path {path:?} is not canonical")]
463    InvalidPath { path: String },
464    #[error("secret use maximum injections must be greater than zero")]
465    ZeroInjections,
466    #[error("secret use binding identifier is invalid")]
467    InvalidBindingId,
468    #[error("secret use private-map revision is invalid")]
469    InvalidMapRevision,
470    #[error("secret sink and Basic username do not agree")]
471    InvalidUsername,
472}
473
474#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
475#[serde(rename_all = "kebab-case")]
476pub enum StorageInterface {
477    Jsonl,
478    DurableFiles,
479}
480
481#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
482#[serde(rename_all = "kebab-case")]
483pub enum StorageAccess {
484    ReadOnly,
485    ReadWrite,
486}
487
488#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
489#[serde(rename_all = "kebab-case")]
490pub enum StorageScope {
491    PrivateConversation,
492    SharedConversation,
493    Agent,
494    Space,
495}
496
497#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
498pub enum StorageRetention {
499    #[default]
500    Keep,
501    IdleTtl(std::time::Duration),
502}
503
504#[derive(Deserialize, Serialize)]
505#[serde(rename_all = "kebab-case")]
506enum StorageRetentionMode {
507    Keep,
508    IdleTtl,
509}
510
511#[derive(Deserialize, Serialize)]
512#[serde(deny_unknown_fields, rename_all = "camelCase")]
513struct StorageRetentionWire {
514    mode: StorageRetentionMode,
515    #[serde(default, skip_serializing_if = "Option::is_none")]
516    idle_ttl_ms: Option<std::num::NonZeroU64>,
517}
518
519impl Serialize for StorageRetention {
520    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
521        match self {
522            Self::Keep => StorageRetentionWire {
523                mode: StorageRetentionMode::Keep,
524                idle_ttl_ms: None,
525            },
526            Self::IdleTtl(duration) => {
527                let millis = u64::try_from(duration.as_millis())
528                    .ok()
529                    .and_then(std::num::NonZeroU64::new)
530                    .ok_or_else(|| {
531                        serde::ser::Error::custom(
532                            "idle TTL must be a positive number of milliseconds fitting in u64",
533                        )
534                    })?;
535                StorageRetentionWire {
536                    mode: StorageRetentionMode::IdleTtl,
537                    idle_ttl_ms: Some(millis),
538                }
539            }
540        }
541        .serialize(serializer)
542    }
543}
544
545impl<'de> Deserialize<'de> for StorageRetention {
546    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
547        let wire = StorageRetentionWire::deserialize(deserializer)?;
548        match (wire.mode, wire.idle_ttl_ms) {
549            (StorageRetentionMode::Keep, None) => Ok(Self::Keep),
550            (StorageRetentionMode::IdleTtl, Some(millis)) => Ok(Self::IdleTtl(
551                std::time::Duration::from_millis(millis.get()),
552            )),
553            _ => Err(serde::de::Error::custom(
554                "idleTtlMs must occur exactly when mode is idle-ttl",
555            )),
556        }
557    }
558}
559
560#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
561#[serde(deny_unknown_fields, rename_all = "camelCase")]
562pub struct StorageConstraints {
563    pub interface: StorageInterface,
564    pub access: StorageAccess,
565    pub scope: StorageScope,
566    #[serde(default)]
567    pub retention: StorageRetention,
568    #[serde(default, skip_serializing_if = "Option::is_none")]
569    pub namespace: Option<ProviderId>,
570}
571
572#[cfg(test)]
573mod storage_retention_tests {
574    use super::{StorageConstraints, StorageRetention, StorageScope};
575
576    #[test]
577    fn storage_scope_and_retention_are_strict_and_default_to_keep() {
578        let configured = r#"{"interface":"durable-files","access":"read-only","scope":"agent"}"#;
579        let parsed: StorageConstraints = serde_json::from_str(configured).expect("scope");
580        assert_eq!(parsed.scope, StorageScope::Agent);
581        let space: StorageConstraints =
582            serde_json::from_str(r#"{"interface":"jsonl","access":"read-only","scope":"space"}"#)
583                .expect("space scope");
584        assert_eq!(space.scope, StorageScope::Space);
585        assert_eq!(parsed.retention, StorageRetention::Keep);
586        let ttl = r#"{"interface":"durable-files","access":"read-only","scope":"shared-conversation","retention":{"mode":"idle-ttl","idleTtlMs":60000}}"#;
587        let parsed: StorageConstraints = serde_json::from_str(ttl).expect("idle TTL");
588        assert_eq!(
589            parsed.retention,
590            StorageRetention::IdleTtl(std::time::Duration::from_secs(60))
591        );
592        assert_eq!(serde_json::to_string(&parsed).expect("encode"), ttl);
593        for invalid in [
594            r#"{"mode":"idle-ttl","idleTtlMs":0}"#,
595            r#"{"mode":"idle-ttl","idleTtlMs":18446744073709551616}"#,
596            r#"{"mode":"idle-ttl","idleTtlMs":1,"other":true}"#,
597            r#"{"mode":"idle-ttl"}"#,
598            r#"{"mode":"keep","idleTtlMs":1}"#,
599            r#"{"mode":"later"}"#,
600        ] {
601            assert!(
602                serde_json::from_str::<StorageRetention>(invalid).is_err(),
603                "{invalid}"
604            );
605        }
606        for invalid in [
607            r#"{"interface":"jsonl","access":"read-only","namespace":"chat"}"#,
608            r#"{"interface":"durable-files","access":"read-only","scope":"agent","namespace":"-turso"}"#,
609            r#"{"interface":"durable-files","access":"read-only","scope":"agent","path":"turso"}"#,
610        ] {
611            assert!(
612                serde_json::from_str::<StorageConstraints>(invalid).is_err(),
613                "{invalid}"
614            );
615        }
616        assert_eq!(parsed.namespace, None);
617        let shared = r#"{"interface":"durable-files","access":"read-write","scope":"agent","retention":{"mode":"keep"},"namespace":"turso"}"#;
618        let parsed: StorageConstraints = serde_json::from_str(shared).expect("shared namespace");
619        assert_eq!(parsed.namespace, Some("turso".parse().expect("provider")));
620        assert_eq!(serde_json::to_string(&parsed).expect("encode"), shared);
621    }
622}
623
624#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
625#[serde(deny_unknown_fields, rename_all = "camelCase")]
626pub struct AssetConstraints {
627    #[serde(default)]
628    pub attach: bool,
629    #[serde(default)]
630    pub remove: bool,
631    #[serde(default)]
632    pub send: bool,
633}
634
635#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
636#[serde(deny_unknown_fields, rename_all = "camelCase")]
637pub struct ExecutionConstraints {
638    pub timeout_ms: u64,
639    #[serde(default, skip_serializing_if = "Option::is_none")]
640    pub http: Option<HttpConstraints>,
641    #[serde(default, skip_serializing_if = "Option::is_none")]
642    pub storage: Option<StorageConstraints>,
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub asset: Option<AssetConstraints>,
645    #[serde(default, skip_serializing_if = "Option::is_none")]
646    pub secret_use: Option<SecretUseGrant>,
647}
648
649impl Default for ExecutionConstraints {
650    fn default() -> Self {
651        Self {
652            timeout_ms: 30_000,
653            http: None,
654            storage: None,
655            asset: None,
656            secret_use: None,
657        }
658    }
659}
660
661#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
662#[serde(rename_all = "camelCase")]
663pub struct AuthorizationReceipt {
664    decision_id: String,
665    authorized_by: PrincipalId,
666    policy_digest: String,
667}
668
669impl AuthorizationReceipt {
670    #[must_use]
671    pub fn decision_id(&self) -> &str {
672        &self.decision_id
673    }
674
675    #[must_use]
676    pub fn authorized_by(&self) -> &PrincipalId {
677        &self.authorized_by
678    }
679
680    #[must_use]
681    pub fn policy_digest(&self) -> &str {
682        &self.policy_digest
683    }
684}
685
686#[derive(Debug, PartialEq, Serialize)]
687#[serde(rename_all = "camelCase")]
688pub struct AuthorizedInvocation {
689    proposal: ProposedInvocation,
690    provider: ProviderId,
691    receipt: AuthorizationReceipt,
692    constraints: ExecutionConstraints,
693}
694
695impl AuthorizedInvocation {
696    #[must_use]
697    pub fn proposal(&self) -> &ProposedInvocation {
698        &self.proposal
699    }
700
701    #[must_use]
702    pub fn provider(&self) -> &ProviderId {
703        &self.provider
704    }
705
706    #[must_use]
707    pub fn receipt(&self) -> &AuthorizationReceipt {
708        &self.receipt
709    }
710
711    #[must_use]
712    pub fn constraints(&self) -> &ExecutionConstraints {
713        &self.constraints
714    }
715}
716
717#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
718#[serde(deny_unknown_fields, rename_all = "camelCase")]
719pub struct DecisionReference {
720    pub decision_id: String,
721    pub authorized_by: PrincipalId,
722    #[serde(deserialize_with = "deserialize_policy_digest")]
723    pub policy_digest: String,
724}
725
726fn valid_policy_digest(digest: &str) -> bool {
727    digest.len() == 64
728        && digest
729            .bytes()
730            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
731}
732
733fn deserialize_policy_digest<'de, D: serde::Deserializer<'de>>(
734    deserializer: D,
735) -> Result<String, D::Error> {
736    let digest = String::deserialize(deserializer)?;
737    if valid_policy_digest(&digest) {
738        Ok(digest)
739    } else {
740        Err(serde::de::Error::custom(
741            "policyDigest must be 64 lowercase hexadecimal characters",
742        ))
743    }
744}
745
746#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
747#[serde(deny_unknown_fields, rename_all = "camelCase")]
748pub struct Evidence {
749    pub kind: String,
750    pub digest: String,
751    pub media_type: String,
752    #[serde(default, skip_serializing_if = "Option::is_none")]
753    pub uri: Option<String>,
754}
755
756#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
757#[serde(rename_all = "PascalCase")]
758pub enum InvocationOutcome {
759    Succeeded,
760    Denied,
761    Failed,
762}
763
764#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
765#[serde(deny_unknown_fields, rename_all = "camelCase")]
766pub struct InvocationResult {
767    pub invocation: InvocationId,
768    pub decision: DecisionReference,
769    pub outcome: InvocationOutcome,
770    #[serde(default, skip_serializing_if = "Option::is_none")]
771    pub exit_status: Option<NonZeroU8>,
772    #[serde(default, skip_serializing_if = "Option::is_none")]
773    pub error: Option<String>,
774    #[serde(default, skip_serializing_if = "Option::is_none")]
775    pub detail: Option<ProviderFailureDetail>,
776    #[serde(default, skip_serializing_if = "Vec::is_empty")]
777    pub evidence: Vec<Evidence>,
778}
779
780#[derive(Clone, Debug, Eq, Error, PartialEq)]
781pub enum AuthorizationError {
782    #[error("authorization decision identifier must not be empty")]
783    EmptyDecisionId,
784    #[error("authorization policy digest must be 64 lowercase hexadecimal characters")]
785    InvalidPolicyDigest,
786    #[error("authorization timeout must be greater than zero")]
787    ZeroTimeout,
788    #[error(transparent)]
789    InvalidHttp(#[from] HttpConstraintsError),
790    #[error("HTTP and storage authority cannot coexist in one capability")]
791    MixedHttpAndStorage,
792    #[error("authorization secret-use proposal does not match its effective grant")]
793    SecretUseMismatch,
794    #[error(transparent)]
795    InvalidSecretUse(#[from] SecretUseGrantError),
796}
797
798pub mod broker {
799    use dekopon_core::{PrincipalId, ProviderId};
800
801    use super::{
802        AuthorizationError, AuthorizationReceipt, AuthorizedInvocation, ExecutionConstraints,
803        ProposedInvocation,
804    };
805
806    #[derive(Debug)]
807    pub struct AuthorizationGate {
808        _private: (),
809    }
810
811    #[allow(
812        clippy::new_without_default,
813        reason = "authority transitions should require an explicit broker-owned constructor"
814    )]
815    impl AuthorizationGate {
816        #[must_use]
817        pub const fn new() -> Self {
818            Self { _private: () }
819        }
820
821        #[expect(
822            clippy::too_many_arguments,
823            reason = "reshaped by the unit that next rewrites this"
824        )]
825        pub fn authorize(
826            &self,
827            proposal: ProposedInvocation,
828            provider: ProviderId,
829            decision_id: String,
830            authorized_by: PrincipalId,
831            policy_digest: String,
832            constraints: ExecutionConstraints,
833        ) -> Result<AuthorizedInvocation, AuthorizationError> {
834            if decision_id.trim().is_empty() {
835                return Err(AuthorizationError::EmptyDecisionId);
836            }
837            if !super::valid_policy_digest(&policy_digest) {
838                return Err(AuthorizationError::InvalidPolicyDigest);
839            }
840            if constraints.timeout_ms == 0 {
841                return Err(AuthorizationError::ZeroTimeout);
842            }
843            if constraints.http.is_some() && constraints.storage.is_some() {
844                return Err(AuthorizationError::MixedHttpAndStorage);
845            }
846            if let Some(http) = &constraints.http {
847                http.validate()?;
848            }
849            if let Some(secret) = &constraints.secret_use {
850                secret.validate()?;
851            }
852            let secret_matches = match (&proposal.secret_use, &constraints.secret_use) {
853                (None, None) => true,
854                (Some(proposal), Some(grant)) => {
855                    proposal.secret() == &grant.secret
856                        && proposal.sink() == grant.sink
857                        && proposal.username() == grant.basic_username.as_deref()
858                        && constraints.http.is_some()
859                }
860                _ => false,
861            };
862            if !secret_matches {
863                return Err(AuthorizationError::SecretUseMismatch);
864            }
865
866            Ok(AuthorizedInvocation {
867                proposal,
868                provider,
869                receipt: AuthorizationReceipt {
870                    decision_id,
871                    authorized_by,
872                    policy_digest,
873                },
874                constraints,
875            })
876        }
877    }
878}
879
880#[cfg(test)]
881mod tests {
882    use dekopon_core::{Actor, AgentId, CapabilityId, InvocationId, PrincipalId, TraceId};
883    use serde_json::json;
884
885    use super::{
886        AuthorizationError, EffectKind, ExecutionConstraints, HttpConstraints,
887        HttpConstraintsError, MAX_HTTP_SCOPE_ENTRIES, ProposedInvocation, broker,
888    };
889
890    fn proposal() -> ProposedInvocation {
891        ProposedInvocation::new(
892            "invoke-1".parse::<InvocationId>().expect("valid fixture"),
893            "github.pull-request.comment"
894                .parse::<CapabilityId>()
895                .expect("valid fixture"),
896            Actor::Agent {
897                agent: "reviewer".parse::<AgentId>().expect("valid fixture"),
898            },
899            "0000000000000000000000000000f1c7"
900                .parse::<TraceId>()
901                .expect("valid fixture"),
902            json!({"body": "Looks good"}),
903        )
904    }
905
906    #[test]
907    fn display_matches_the_serde_rendering_for_every_variant() {
908        for effect in [
909            EffectKind::ReadOnly,
910            EffectKind::LocalWrite,
911            EffectKind::ExternalWrite,
912        ] {
913            assert_eq!(
914                serde_json::to_value(effect).expect("effect serializes"),
915                json!(effect.to_string()),
916            );
917        }
918    }
919
920    #[test]
921    fn broker_gate_performs_explicit_authority_transition() {
922        let authorized = broker::AuthorizationGate::new()
923            .authorize(
924                proposal(),
925                "github".parse().expect("valid provider fixture"),
926                "decision-1".to_owned(),
927                "broker".parse::<PrincipalId>().expect("valid fixture"),
928                "a".repeat(64),
929                ExecutionConstraints::default(),
930            )
931            .expect("valid broker decision");
932
933        assert_eq!(authorized.proposal().id.as_str(), "invoke-1");
934        assert_eq!(authorized.provider().as_str(), "github");
935        assert_eq!(authorized.receipt().decision_id(), "decision-1");
936        assert_eq!(authorized.constraints().timeout_ms, 30_000);
937    }
938
939    #[test]
940    fn broker_gate_rejects_unbounded_execution() {
941        let constraints = ExecutionConstraints {
942            timeout_ms: 0,
943            ..ExecutionConstraints::default()
944        };
945        let error = broker::AuthorizationGate::new()
946            .authorize(
947                proposal(),
948                "github".parse().expect("valid provider fixture"),
949                "decision-1".to_owned(),
950                "broker".parse::<PrincipalId>().expect("valid fixture"),
951                "a".repeat(64),
952                constraints,
953            )
954            .expect_err("zero timeout must fail");
955
956        assert_eq!(error, AuthorizationError::ZeroTimeout);
957    }
958
959    #[test]
960    fn broker_gate_rejects_incomplete_http_authority() {
961        let valid = HttpConstraints {
962            allowed_hosts: vec!["api.example.test".to_owned()],
963            allowed_methods: vec!["GET".to_owned()],
964            max_requests: 1,
965            max_request_bytes: 1024,
966            max_response_bytes: 1024,
967            allow_plaintext_loopback: false,
968            propagate_trace: false,
969            request_templates: Vec::new(),
970            signed_download: None,
971        };
972        let cases = [
973            (
974                HttpConstraints {
975                    allowed_hosts: Vec::new(),
976                    ..valid.clone()
977                },
978                HttpConstraintsError::NoHosts,
979            ),
980            (
981                HttpConstraints {
982                    allowed_methods: Vec::new(),
983                    ..valid.clone()
984                },
985                HttpConstraintsError::NoMethods,
986            ),
987            (
988                HttpConstraints {
989                    max_requests: 0,
990                    ..valid.clone()
991                },
992                HttpConstraintsError::ZeroLimit,
993            ),
994            (
995                HttpConstraints {
996                    allowed_hosts: vec![" api.github.com".to_owned()],
997                    ..valid.clone()
998                },
999                HttpConstraintsError::InvalidHost {
1000                    value: " api.github.com".to_owned(),
1001                },
1002            ),
1003            (
1004                HttpConstraints {
1005                    allowed_hosts: vec!["*".to_owned()],
1006                    ..valid.clone()
1007                },
1008                HttpConstraintsError::InvalidHost {
1009                    value: "*".to_owned(),
1010                },
1011            ),
1012            (
1013                HttpConstraints {
1014                    allowed_hosts: vec!["a/b".to_owned()],
1015                    ..valid.clone()
1016                },
1017                HttpConstraintsError::InvalidHost {
1018                    value: "a/b".to_owned(),
1019                },
1020            ),
1021            (
1022                HttpConstraints {
1023                    allowed_hosts: vec![String::new()],
1024                    ..valid.clone()
1025                },
1026                HttpConstraintsError::InvalidHost {
1027                    value: String::new(),
1028                },
1029            ),
1030            (
1031                HttpConstraints {
1032                    allowed_methods: vec!["GET POST".to_owned()],
1033                    ..valid.clone()
1034                },
1035                HttpConstraintsError::InvalidMethod {
1036                    value: "GET POST".to_owned(),
1037                },
1038            ),
1039            (
1040                HttpConstraints {
1041                    allowed_hosts: (0..=MAX_HTTP_SCOPE_ENTRIES)
1042                        .map(|index| format!("host{index}.example.test"))
1043                        .collect(),
1044                    ..valid
1045                },
1046                HttpConstraintsError::TooManyEntries {
1047                    maximum: MAX_HTTP_SCOPE_ENTRIES,
1048                },
1049            ),
1050        ];
1051
1052        for (http, expected) in cases {
1053            let error = broker::AuthorizationGate::new()
1054                .authorize(
1055                    proposal(),
1056                    "github".parse().expect("valid provider fixture"),
1057                    "decision-1".to_owned(),
1058                    "broker".parse::<PrincipalId>().expect("valid fixture"),
1059                    "a".repeat(64),
1060                    ExecutionConstraints {
1061                        http: Some(http),
1062                        ..ExecutionConstraints::default()
1063                    },
1064                )
1065                .expect_err("incomplete HTTP authority must fail");
1066            assert_eq!(error, AuthorizationError::InvalidHttp(expected));
1067        }
1068    }
1069
1070    #[test]
1071    fn request_templates_must_be_reachable_unique_and_unambiguous() {
1072        let with = |templates: serde_json::Value| HttpConstraints {
1073            allowed_hosts: vec!["slack.com".to_owned()],
1074            allowed_methods: vec!["GET".to_owned()],
1075            max_requests: 1,
1076            max_request_bytes: 1,
1077            max_response_bytes: 1,
1078            allow_plaintext_loopback: false,
1079            propagate_trace: false,
1080            signed_download: None,
1081            request_templates: serde_json::from_value(templates).expect("template fixtures"),
1082        };
1083        let replies = json!({"method": "GET", "path": "/api/conversations.replies",
1084            "query": {"pinned": {"channel": "conversation.id"}, "allowed": ["limit"]}});
1085        assert_eq!(with(json!([replies])).validate(), Ok(()));
1086        assert!(matches!(
1087            with(json!([{"method": "HEAD", "path": "/api/conversations.replies"}])).validate(),
1088            Err(HttpConstraintsError::TemplateMethodNotAllowed { .. })
1089        ));
1090        let send = HttpConstraints {
1091            allowed_methods: vec!["GET".to_owned(), "POST".to_owned(), "PUT".to_owned()],
1092            ..with(json!([
1093                replies,
1094                {"method": "POST", "path": "/api/chat.postMessage",
1095                    "query": {"pinned": {"channel": "conversation.id"}}},
1096                {"method": "PUT", "path": "/api/chat.update"}
1097            ]))
1098        };
1099        assert_eq!(
1100            send.validate(),
1101            Err(HttpConstraintsError::TemplateMethodNotReadOnly {
1102                rules: vec![
1103                    "POST /api/chat.postMessage".to_owned(),
1104                    "PUT /api/chat.update".to_owned()
1105                ]
1106            })
1107        );
1108        assert!(matches!(
1109            with(json!([replies, {"method": "GET", "path": "/api/conversations.replies"}]))
1110                .validate(),
1111            Err(HttpConstraintsError::DuplicateTemplate { .. })
1112        ));
1113        assert!(matches!(
1114            with(json!([{"method": "GET", "path": "/api",
1115                "query": {"pinned": {"channel": "conversation.id"}, "allowed": ["channel"]}}]))
1116            .validate(),
1117            Err(HttpConstraintsError::TemplateKeyPinnedAndAllowed { .. })
1118        ));
1119        assert!(matches!(
1120            with(json!([{"method": "GET", "path": "/api", "query": {"allowed": [""]}}])).validate(),
1121            Err(HttpConstraintsError::InvalidTemplateQueryKey { .. })
1122        ));
1123    }
1124
1125    #[test]
1126    fn broker_gate_accepts_exact_http_authority() {
1127        let http = HttpConstraints {
1128            allowed_hosts: vec!["api.example.test".to_owned(), "127.0.0.1:8080".to_owned()],
1129            allowed_methods: vec![
1130                "GET".to_owned(),
1131                "POST".to_owned(),
1132                "PATCH".to_owned(),
1133                "DELETE".to_owned(),
1134            ],
1135            max_requests: 4,
1136            max_request_bytes: 65_536,
1137            max_response_bytes: 1_048_576,
1138            allow_plaintext_loopback: true,
1139            propagate_trace: false,
1140            request_templates: Vec::new(),
1141            signed_download: None,
1142        };
1143
1144        http.validate().expect("an exact grant is enforceable");
1145    }
1146
1147    #[test]
1148    fn policy_digest_is_required_and_has_the_same_shape_on_receipt_and_reference() {
1149        for invalid in ["", "policy-1", &"A".repeat(64), &"g".repeat(64)] {
1150            let err = broker::AuthorizationGate::new()
1151                .authorize(
1152                    proposal(),
1153                    "github".parse().unwrap(),
1154                    "decision-1".into(),
1155                    "broker".parse().unwrap(),
1156                    invalid.into(),
1157                    ExecutionConstraints::default(),
1158                )
1159                .expect_err("malformed receipt digest must fail");
1160            assert!(matches!(err, AuthorizationError::InvalidPolicyDigest));
1161            let value = json!({"decisionId": "decision-1", "authorizedBy": "broker", "policyDigest": invalid});
1162            assert!(serde_json::from_value::<super::DecisionReference>(value).is_err());
1163        }
1164        let old = json!({"decisionId": "decision-1", "authorizedBy": "broker", "policyRevision": "a".repeat(64)});
1165        assert!(serde_json::from_value::<super::DecisionReference>(old).is_err());
1166        let valid = json!({"decisionId": "decision-1", "authorizedBy": "broker", "policyDigest": "a".repeat(64)});
1167        let reference: super::DecisionReference =
1168            serde_json::from_value(valid.clone()).expect("new record decodes");
1169        assert_eq!(serde_json::to_value(reference).unwrap(), valid);
1170    }
1171
1172    #[test]
1173    fn authorized_invocation_serialization_preserves_linkage() {
1174        let constraints = ExecutionConstraints {
1175            http: Some(HttpConstraints {
1176                allowed_hosts: vec!["api.github.com".to_owned()],
1177                allowed_methods: vec!["POST".to_owned()],
1178                max_requests: 1,
1179                max_request_bytes: 65_536,
1180                max_response_bytes: 1_048_576,
1181                allow_plaintext_loopback: false,
1182                propagate_trace: false,
1183                request_templates: Vec::new(),
1184                signed_download: None,
1185            }),
1186            ..ExecutionConstraints::default()
1187        };
1188        let authorized = broker::AuthorizationGate::new()
1189            .authorize(
1190                proposal(),
1191                "github".parse().expect("valid provider fixture"),
1192                "decision-1".to_owned(),
1193                "broker".parse::<PrincipalId>().expect("valid fixture"),
1194                "a".repeat(64),
1195                constraints,
1196            )
1197            .expect("valid broker decision");
1198        let value = serde_json::to_value(authorized).expect("authorization serializes");
1199
1200        assert_eq!(
1201            value,
1202            json!({
1203                "proposal": {
1204                    "id": "invoke-1",
1205                    "capability": "github.pull-request.comment",
1206                    "actor": {"type": "agent", "agent": "reviewer"},
1207                    "trace": "0000000000000000000000000000f1c7",
1208                    "input": {"body": "Looks good"}
1209                },
1210                "provider": "github",
1211                "receipt": {
1212                    "decisionId": "decision-1",
1213                    "authorizedBy": "broker",
1214                    "policyDigest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
1215                },
1216                "constraints": {
1217                    "timeoutMs": 30_000,
1218                    "http": {
1219                        "allowedHosts": ["api.github.com"],
1220                        "allowedMethods": ["POST"],
1221                        "maxRequests": 1,
1222                        "maxRequestBytes": 65_536,
1223                        "maxResponseBytes": 1_048_576
1224                    }
1225                }
1226            })
1227        );
1228    }
1229}