Skip to main content

vellaveto_types/
capability.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4//
5// Copyright 2026 Paolo Vella
6// SPDX-License-Identifier: MPL-2.0
7
8//! Capability-based delegation token types.
9//!
10//! Capability tokens enable fine-grained, attenuatable delegation of tool
11//! access between agents. Each token grants specific permissions (tools,
12//! paths, domains) and can be delegated with monotonically decreasing
13//! privileges (depth decrements, grants narrow, expiry clamps).
14//!
15//! # Security Properties
16//!
17//! - **Monotonic attenuation:** delegated tokens can only narrow permissions
18//! - **Bounded delegation depth:** prevents infinite delegation chains
19//! - **Fail-closed:** missing or invalid tokens produce `Deny`
20//! - **Ed25519 signed:** prevents token forgery
21
22use serde::{Deserialize, Serialize};
23use std::fmt;
24
25/// Maximum number of grants per token.
26pub const MAX_GRANTS: usize = 64;
27/// Maximum delegation depth (0 = terminal, cannot delegate further).
28pub const MAX_DELEGATION_DEPTH: u8 = 16;
29/// Maximum serialized token size in bytes.
30pub const MAX_TOKEN_SIZE: usize = 65536;
31
32/// A capability-based delegation token granting specific tool permissions.
33///
34/// Tokens form a delegation chain: each token can optionally reference a
35/// parent token, and its grants must be a subset of the parent's grants.
36/// The `remaining_depth` decrements with each delegation, preventing
37/// unbounded chains.
38#[derive(Clone, Serialize, Deserialize, PartialEq)]
39#[serde(deny_unknown_fields)]
40pub struct CapabilityToken {
41    /// Unique token identifier (UUID v4).
42    pub token_id: String,
43    /// Parent token ID if this was delegated (None for root tokens).
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub parent_token_id: Option<String>,
46    /// Identity of the token issuer (who signed it).
47    pub issuer: String,
48    /// Identity of the token holder (who can use it).
49    pub holder: String,
50    /// Permissions granted by this token.
51    pub grants: Vec<CapabilityGrant>,
52    /// Remaining delegation depth (0 = terminal, cannot delegate further).
53    pub remaining_depth: u8,
54    /// ISO 8601 timestamp when the token was issued.
55    pub issued_at: String,
56    /// ISO 8601 timestamp when the token expires.
57    pub expires_at: String,
58    /// Ed25519 signature over the canonical token content (hex-encoded).
59    pub signature: String,
60    /// Ed25519 public key of the issuer (hex-encoded).
61    pub issuer_public_key: String,
62}
63
64impl fmt::Debug for CapabilityToken {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.debug_struct("CapabilityToken")
67            .field("token_id", &self.token_id)
68            .field("parent_token_id", &self.parent_token_id)
69            .field("issuer", &self.issuer)
70            .field("holder", &self.holder)
71            .field("grants", &self.grants)
72            .field("remaining_depth", &self.remaining_depth)
73            .field("issued_at", &self.issued_at)
74            .field("expires_at", &self.expires_at)
75            .field("signature", &"[REDACTED]")
76            // SECURITY (FIND-R216-001): Redact issuer_public_key — cryptographic
77            // material must not leak into logs or debug output.
78            .field("issuer_public_key", &"[REDACTED]")
79            .finish()
80    }
81}
82
83/// A single permission grant within a capability token.
84///
85/// Each grant specifies which tools/functions the holder can invoke,
86/// optionally restricted to specific paths and domains.
87#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
88#[serde(deny_unknown_fields)]
89pub struct CapabilityGrant {
90    /// Tool name pattern (exact or glob, e.g., "file_system" or "db_*").
91    pub tool_pattern: String,
92    /// Function name pattern (exact or glob, e.g., "read_file" or "*").
93    pub function_pattern: String,
94    /// Allowed path globs (empty = no path restriction).
95    #[serde(default, skip_serializing_if = "Vec::is_empty")]
96    pub allowed_paths: Vec<String>,
97    /// Allowed domain patterns (empty = no domain restriction).
98    #[serde(default, skip_serializing_if = "Vec::is_empty")]
99    pub allowed_domains: Vec<String>,
100    /// Maximum number of invocations (0 = unlimited).
101    #[serde(default)]
102    pub max_invocations: u64,
103}
104
105impl CapabilityGrant {
106    /// Maximum entries in `allowed_paths` or `allowed_domains`.
107    pub const MAX_ENTRIES: usize = 1000;
108    /// Maximum byte length per path or domain entry.
109    pub const MAX_ENTRY_LEN: usize = 2048;
110    /// SECURITY (FIND-R174-005): Maximum byte length for pattern fields.
111    pub const MAX_PATTERN_LEN: usize = 1024;
112
113    pub fn validate(&self) -> Result<(), CapabilityError> {
114        // SECURITY (FIND-R174-005): Validate pattern field lengths.
115        if self.tool_pattern.len() > Self::MAX_PATTERN_LEN {
116            return Err(CapabilityError::ValidationFailed(format!(
117                "CapabilityGrant tool_pattern length {} exceeds maximum {}",
118                self.tool_pattern.len(),
119                Self::MAX_PATTERN_LEN
120            )));
121        }
122        if self.function_pattern.len() > Self::MAX_PATTERN_LEN {
123            return Err(CapabilityError::ValidationFailed(format!(
124                "CapabilityGrant function_pattern length {} exceeds maximum {}",
125                self.function_pattern.len(),
126                Self::MAX_PATTERN_LEN
127            )));
128        }
129        // SECURITY (FIND-R113-007): Validate control/format chars on pattern fields.
130        if crate::core::has_dangerous_chars(&self.tool_pattern) {
131            return Err(CapabilityError::ValidationFailed(
132                "CapabilityGrant tool_pattern contains control or format characters".to_string(),
133            ));
134        }
135        if crate::core::has_dangerous_chars(&self.function_pattern) {
136            return Err(CapabilityError::ValidationFailed(
137                "CapabilityGrant function_pattern contains control or format characters"
138                    .to_string(),
139            ));
140        }
141        if self.allowed_paths.len() > Self::MAX_ENTRIES {
142            return Err(CapabilityError::ValidationFailed(format!(
143                "allowed_paths count {} exceeds max {}",
144                self.allowed_paths.len(),
145                Self::MAX_ENTRIES
146            )));
147        }
148        if self.allowed_domains.len() > Self::MAX_ENTRIES {
149            return Err(CapabilityError::ValidationFailed(format!(
150                "allowed_domains count {} exceeds max {}",
151                self.allowed_domains.len(),
152                Self::MAX_ENTRIES
153            )));
154        }
155        for (i, p) in self.allowed_paths.iter().enumerate() {
156            if p.len() > Self::MAX_ENTRY_LEN {
157                return Err(CapabilityError::ValidationFailed(format!(
158                    "allowed_paths[{}] length {} exceeds max {}",
159                    i,
160                    p.len(),
161                    Self::MAX_ENTRY_LEN
162                )));
163            }
164            // SECURITY (FIND-R113-007): Validate control/format chars on path entries.
165            if crate::core::has_dangerous_chars(p) {
166                return Err(CapabilityError::ValidationFailed(format!(
167                    "allowed_paths[{i}] contains control or format characters"
168                )));
169            }
170        }
171        for (i, d) in self.allowed_domains.iter().enumerate() {
172            if d.len() > Self::MAX_ENTRY_LEN {
173                return Err(CapabilityError::ValidationFailed(format!(
174                    "allowed_domains[{}] length {} exceeds max {}",
175                    i,
176                    d.len(),
177                    Self::MAX_ENTRY_LEN
178                )));
179            }
180            // SECURITY (FIND-R113-007): Validate control/format chars on domain entries.
181            if crate::core::has_dangerous_chars(d) {
182                return Err(CapabilityError::ValidationFailed(format!(
183                    "allowed_domains[{i}] contains control or format characters"
184                )));
185            }
186        }
187        Ok(())
188    }
189}
190
191/// Result of verifying a capability token.
192#[derive(Debug, Clone, Serialize, Deserialize)]
193#[serde(deny_unknown_fields)]
194pub struct CapabilityVerification {
195    /// Whether the token is valid.
196    pub valid: bool,
197    /// Reason for failure, if any.
198    pub failure_reason: Option<String>,
199}
200
201impl CapabilityVerification {
202    /// Maximum length for `failure_reason` field.
203    const MAX_FAILURE_REASON_LEN: usize = 4096;
204
205    /// Validate structural bounds on deserialized data.
206    ///
207    /// SECURITY (FIND-R216-011): Prevents oversized or injection-prone failure
208    /// reason strings from untrusted deserialized payloads.
209    pub fn validate(&self) -> Result<(), CapabilityError> {
210        if let Some(ref reason) = self.failure_reason {
211            if reason.len() > Self::MAX_FAILURE_REASON_LEN {
212                return Err(CapabilityError::ValidationFailed(format!(
213                    "CapabilityVerification failure_reason length {} exceeds max {}",
214                    reason.len(),
215                    Self::MAX_FAILURE_REASON_LEN,
216                )));
217            }
218            if crate::core::has_dangerous_chars(reason) {
219                return Err(CapabilityError::ValidationFailed(
220                    "CapabilityVerification failure_reason contains control or format characters"
221                        .to_string(),
222                ));
223            }
224        }
225        Ok(())
226    }
227}
228
229/// Errors from capability token operations.
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub enum CapabilityError {
232    /// The signing key is invalid.
233    InvalidKey(String),
234    /// Token signing failed.
235    SigningFailed(String),
236    /// Token verification failed.
237    VerificationFailed(String),
238    /// The token has expired.
239    Expired,
240    /// Attenuation violation (grants not a subset of parent).
241    AttenuationViolation(String),
242    /// Structural validation failed.
243    ValidationFailed(String),
244}
245
246impl fmt::Display for CapabilityError {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        match self {
249            CapabilityError::InvalidKey(msg) => write!(f, "Invalid key: {msg}"),
250            CapabilityError::SigningFailed(msg) => write!(f, "Signing failed: {msg}"),
251            CapabilityError::VerificationFailed(msg) => {
252                write!(f, "Verification failed: {msg}")
253            }
254            CapabilityError::Expired => write!(f, "Token has expired"),
255            CapabilityError::AttenuationViolation(msg) => {
256                write!(f, "Attenuation violation: {msg}")
257            }
258            CapabilityError::ValidationFailed(msg) => {
259                write!(f, "Validation failed: {msg}")
260            }
261        }
262    }
263}
264
265impl std::error::Error for CapabilityError {}
266
267impl CapabilityToken {
268    /// Validate the structural integrity of the token.
269    ///
270    /// Checks bounds on grants, depth, field lengths, and serialized size.
271    pub fn validate_structure(&self) -> Result<(), CapabilityError> {
272        if self.token_id.is_empty() {
273            return Err(CapabilityError::ValidationFailed(
274                "token_id must not be empty".to_string(),
275            ));
276        }
277        // SECURITY (FIND-R115-001): Reject control/format chars in identity fields
278        // to prevent zero-width space or bidi override bypasses of string equality checks.
279        if crate::core::has_dangerous_chars(&self.token_id) {
280            return Err(CapabilityError::ValidationFailed(
281                "token_id contains control or format characters".to_string(),
282            ));
283        }
284        if self.issuer.is_empty() {
285            return Err(CapabilityError::ValidationFailed(
286                "issuer must not be empty".to_string(),
287            ));
288        }
289        if crate::core::has_dangerous_chars(&self.issuer) {
290            return Err(CapabilityError::ValidationFailed(
291                "issuer contains control or format characters".to_string(),
292            ));
293        }
294        if self.holder.is_empty() {
295            return Err(CapabilityError::ValidationFailed(
296                "holder must not be empty".to_string(),
297            ));
298        }
299        if crate::core::has_dangerous_chars(&self.holder) {
300            return Err(CapabilityError::ValidationFailed(
301                "holder contains control or format characters".to_string(),
302            ));
303        }
304        // SECURITY (FIND-R224-002): Validate parent_token_id when present — reject
305        // empty strings and dangerous characters to prevent delegation chain confusion.
306        if let Some(ref parent_id) = self.parent_token_id {
307            if parent_id.is_empty() {
308                return Err(CapabilityError::ValidationFailed(
309                    "parent_token_id must not be empty when present".to_string(),
310                ));
311            }
312            if crate::core::has_dangerous_chars(parent_id) {
313                return Err(CapabilityError::ValidationFailed(
314                    "parent_token_id contains control or format characters".to_string(),
315                ));
316            }
317        }
318        // SECURITY (FIND-R224-006): Validate signature and issuer_public_key for
319        // dangerous characters. These hex-encoded cryptographic fields should never
320        // contain control or Unicode format characters.
321        if crate::core::has_dangerous_chars(&self.signature) {
322            return Err(CapabilityError::ValidationFailed(
323                "signature contains control or format characters".to_string(),
324            ));
325        }
326        if crate::core::has_dangerous_chars(&self.issuer_public_key) {
327            return Err(CapabilityError::ValidationFailed(
328                "issuer_public_key contains control or format characters".to_string(),
329            ));
330        }
331        if self.grants.is_empty() {
332            return Err(CapabilityError::ValidationFailed(
333                "grants must not be empty".to_string(),
334            ));
335        }
336        if self.grants.len() > MAX_GRANTS {
337            return Err(CapabilityError::ValidationFailed(format!(
338                "too many grants: {} (max {})",
339                self.grants.len(),
340                MAX_GRANTS
341            )));
342        }
343        if self.remaining_depth > MAX_DELEGATION_DEPTH {
344            return Err(CapabilityError::ValidationFailed(format!(
345                "remaining_depth {} exceeds max {}",
346                self.remaining_depth, MAX_DELEGATION_DEPTH
347            )));
348        }
349        if self.issued_at.is_empty() {
350            return Err(CapabilityError::ValidationFailed(
351                "issued_at must not be empty".to_string(),
352            ));
353        }
354        if self.expires_at.is_empty() {
355            return Err(CapabilityError::ValidationFailed(
356                "expires_at must not be empty".to_string(),
357            ));
358        }
359        // SECURITY (FIND-R51-008): Validate temporal ordering.
360        // For ISO 8601 timestamps, lexicographic comparison preserves chronological order.
361        if self.expires_at <= self.issued_at {
362            return Err(CapabilityError::ValidationFailed(
363                "expires_at must be after issued_at".to_string(),
364            ));
365        }
366        // Validate grants
367        for (i, grant) in self.grants.iter().enumerate() {
368            if grant.tool_pattern.is_empty() {
369                return Err(CapabilityError::ValidationFailed(format!(
370                    "grant {i} tool_pattern must not be empty"
371                )));
372            }
373            if grant.function_pattern.is_empty() {
374                return Err(CapabilityError::ValidationFailed(format!(
375                    "grant {i} function_pattern must not be empty"
376                )));
377            }
378            grant.validate()?;
379        }
380        // Check serialized size
381        let serialized = serde_json::to_string(self)
382            .map_err(|e| CapabilityError::ValidationFailed(format!("serialization failed: {e}")))?;
383        if serialized.len() > MAX_TOKEN_SIZE {
384            return Err(CapabilityError::ValidationFailed(format!(
385                "serialized token size {} exceeds max {}",
386                serialized.len(),
387                MAX_TOKEN_SIZE
388            )));
389        }
390        Ok(())
391    }
392}