1use serde::{Deserialize, Serialize};
23use std::fmt;
24
25pub const MAX_GRANTS: usize = 64;
27pub const MAX_DELEGATION_DEPTH: u8 = 16;
29pub const MAX_TOKEN_SIZE: usize = 65536;
31
32#[derive(Clone, Serialize, Deserialize, PartialEq)]
39#[serde(deny_unknown_fields)]
40pub struct CapabilityToken {
41 pub token_id: String,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
45 pub parent_token_id: Option<String>,
46 pub issuer: String,
48 pub holder: String,
50 pub grants: Vec<CapabilityGrant>,
52 pub remaining_depth: u8,
54 pub issued_at: String,
56 pub expires_at: String,
58 pub signature: String,
60 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 .field("issuer_public_key", &"[REDACTED]")
79 .finish()
80 }
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
88#[serde(deny_unknown_fields)]
89pub struct CapabilityGrant {
90 pub tool_pattern: String,
92 pub function_pattern: String,
94 #[serde(default, skip_serializing_if = "Vec::is_empty")]
96 pub allowed_paths: Vec<String>,
97 #[serde(default, skip_serializing_if = "Vec::is_empty")]
99 pub allowed_domains: Vec<String>,
100 #[serde(default)]
102 pub max_invocations: u64,
103}
104
105impl CapabilityGrant {
106 pub const MAX_ENTRIES: usize = 1000;
108 pub const MAX_ENTRY_LEN: usize = 2048;
110 pub const MAX_PATTERN_LEN: usize = 1024;
112
113 pub fn validate(&self) -> Result<(), CapabilityError> {
114 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 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 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
193#[serde(deny_unknown_fields)]
194pub struct CapabilityVerification {
195 pub valid: bool,
197 pub failure_reason: Option<String>,
199}
200
201impl CapabilityVerification {
202 const MAX_FAILURE_REASON_LEN: usize = 4096;
204
205 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#[derive(Debug, Clone, PartialEq, Eq)]
231pub enum CapabilityError {
232 InvalidKey(String),
234 SigningFailed(String),
236 VerificationFailed(String),
238 Expired,
240 AttenuationViolation(String),
242 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 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 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 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 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 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 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 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}