use serde::{Deserialize, Serialize};
use std::fmt;
pub const MAX_GRANTS: usize = 64;
pub const MAX_DELEGATION_DEPTH: u8 = 16;
pub const MAX_TOKEN_SIZE: usize = 65536;
#[derive(Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct CapabilityToken {
pub token_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent_token_id: Option<String>,
pub issuer: String,
pub holder: String,
pub grants: Vec<CapabilityGrant>,
pub remaining_depth: u8,
pub issued_at: String,
pub expires_at: String,
pub signature: String,
pub issuer_public_key: String,
}
impl fmt::Debug for CapabilityToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CapabilityToken")
.field("token_id", &self.token_id)
.field("parent_token_id", &self.parent_token_id)
.field("issuer", &self.issuer)
.field("holder", &self.holder)
.field("grants", &self.grants)
.field("remaining_depth", &self.remaining_depth)
.field("issued_at", &self.issued_at)
.field("expires_at", &self.expires_at)
.field("signature", &"[REDACTED]")
.field("issuer_public_key", &"[REDACTED]")
.finish()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct CapabilityGrant {
pub tool_pattern: String,
pub function_pattern: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub allowed_paths: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub allowed_domains: Vec<String>,
#[serde(default)]
pub max_invocations: u64,
}
impl CapabilityGrant {
pub const MAX_ENTRIES: usize = 1000;
pub const MAX_ENTRY_LEN: usize = 2048;
pub const MAX_PATTERN_LEN: usize = 1024;
pub fn validate(&self) -> Result<(), CapabilityError> {
if self.tool_pattern.len() > Self::MAX_PATTERN_LEN {
return Err(CapabilityError::ValidationFailed(format!(
"CapabilityGrant tool_pattern length {} exceeds maximum {}",
self.tool_pattern.len(),
Self::MAX_PATTERN_LEN
)));
}
if self.function_pattern.len() > Self::MAX_PATTERN_LEN {
return Err(CapabilityError::ValidationFailed(format!(
"CapabilityGrant function_pattern length {} exceeds maximum {}",
self.function_pattern.len(),
Self::MAX_PATTERN_LEN
)));
}
if crate::core::has_dangerous_chars(&self.tool_pattern) {
return Err(CapabilityError::ValidationFailed(
"CapabilityGrant tool_pattern contains control or format characters".to_string(),
));
}
if crate::core::has_dangerous_chars(&self.function_pattern) {
return Err(CapabilityError::ValidationFailed(
"CapabilityGrant function_pattern contains control or format characters"
.to_string(),
));
}
if self.allowed_paths.len() > Self::MAX_ENTRIES {
return Err(CapabilityError::ValidationFailed(format!(
"allowed_paths count {} exceeds max {}",
self.allowed_paths.len(),
Self::MAX_ENTRIES
)));
}
if self.allowed_domains.len() > Self::MAX_ENTRIES {
return Err(CapabilityError::ValidationFailed(format!(
"allowed_domains count {} exceeds max {}",
self.allowed_domains.len(),
Self::MAX_ENTRIES
)));
}
for (i, p) in self.allowed_paths.iter().enumerate() {
if p.len() > Self::MAX_ENTRY_LEN {
return Err(CapabilityError::ValidationFailed(format!(
"allowed_paths[{}] length {} exceeds max {}",
i,
p.len(),
Self::MAX_ENTRY_LEN
)));
}
if crate::core::has_dangerous_chars(p) {
return Err(CapabilityError::ValidationFailed(format!(
"allowed_paths[{i}] contains control or format characters"
)));
}
}
for (i, d) in self.allowed_domains.iter().enumerate() {
if d.len() > Self::MAX_ENTRY_LEN {
return Err(CapabilityError::ValidationFailed(format!(
"allowed_domains[{}] length {} exceeds max {}",
i,
d.len(),
Self::MAX_ENTRY_LEN
)));
}
if crate::core::has_dangerous_chars(d) {
return Err(CapabilityError::ValidationFailed(format!(
"allowed_domains[{i}] contains control or format characters"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CapabilityVerification {
pub valid: bool,
pub failure_reason: Option<String>,
}
impl CapabilityVerification {
const MAX_FAILURE_REASON_LEN: usize = 4096;
pub fn validate(&self) -> Result<(), CapabilityError> {
if let Some(ref reason) = self.failure_reason {
if reason.len() > Self::MAX_FAILURE_REASON_LEN {
return Err(CapabilityError::ValidationFailed(format!(
"CapabilityVerification failure_reason length {} exceeds max {}",
reason.len(),
Self::MAX_FAILURE_REASON_LEN,
)));
}
if crate::core::has_dangerous_chars(reason) {
return Err(CapabilityError::ValidationFailed(
"CapabilityVerification failure_reason contains control or format characters"
.to_string(),
));
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CapabilityError {
InvalidKey(String),
SigningFailed(String),
VerificationFailed(String),
Expired,
AttenuationViolation(String),
ValidationFailed(String),
}
impl fmt::Display for CapabilityError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CapabilityError::InvalidKey(msg) => write!(f, "Invalid key: {msg}"),
CapabilityError::SigningFailed(msg) => write!(f, "Signing failed: {msg}"),
CapabilityError::VerificationFailed(msg) => {
write!(f, "Verification failed: {msg}")
}
CapabilityError::Expired => write!(f, "Token has expired"),
CapabilityError::AttenuationViolation(msg) => {
write!(f, "Attenuation violation: {msg}")
}
CapabilityError::ValidationFailed(msg) => {
write!(f, "Validation failed: {msg}")
}
}
}
}
impl std::error::Error for CapabilityError {}
impl CapabilityToken {
pub fn validate_structure(&self) -> Result<(), CapabilityError> {
if self.token_id.is_empty() {
return Err(CapabilityError::ValidationFailed(
"token_id must not be empty".to_string(),
));
}
if crate::core::has_dangerous_chars(&self.token_id) {
return Err(CapabilityError::ValidationFailed(
"token_id contains control or format characters".to_string(),
));
}
if self.issuer.is_empty() {
return Err(CapabilityError::ValidationFailed(
"issuer must not be empty".to_string(),
));
}
if crate::core::has_dangerous_chars(&self.issuer) {
return Err(CapabilityError::ValidationFailed(
"issuer contains control or format characters".to_string(),
));
}
if self.holder.is_empty() {
return Err(CapabilityError::ValidationFailed(
"holder must not be empty".to_string(),
));
}
if crate::core::has_dangerous_chars(&self.holder) {
return Err(CapabilityError::ValidationFailed(
"holder contains control or format characters".to_string(),
));
}
if let Some(ref parent_id) = self.parent_token_id {
if parent_id.is_empty() {
return Err(CapabilityError::ValidationFailed(
"parent_token_id must not be empty when present".to_string(),
));
}
if crate::core::has_dangerous_chars(parent_id) {
return Err(CapabilityError::ValidationFailed(
"parent_token_id contains control or format characters".to_string(),
));
}
}
if crate::core::has_dangerous_chars(&self.signature) {
return Err(CapabilityError::ValidationFailed(
"signature contains control or format characters".to_string(),
));
}
if crate::core::has_dangerous_chars(&self.issuer_public_key) {
return Err(CapabilityError::ValidationFailed(
"issuer_public_key contains control or format characters".to_string(),
));
}
if self.grants.is_empty() {
return Err(CapabilityError::ValidationFailed(
"grants must not be empty".to_string(),
));
}
if self.grants.len() > MAX_GRANTS {
return Err(CapabilityError::ValidationFailed(format!(
"too many grants: {} (max {})",
self.grants.len(),
MAX_GRANTS
)));
}
if self.remaining_depth > MAX_DELEGATION_DEPTH {
return Err(CapabilityError::ValidationFailed(format!(
"remaining_depth {} exceeds max {}",
self.remaining_depth, MAX_DELEGATION_DEPTH
)));
}
if self.issued_at.is_empty() {
return Err(CapabilityError::ValidationFailed(
"issued_at must not be empty".to_string(),
));
}
if self.expires_at.is_empty() {
return Err(CapabilityError::ValidationFailed(
"expires_at must not be empty".to_string(),
));
}
if self.expires_at <= self.issued_at {
return Err(CapabilityError::ValidationFailed(
"expires_at must be after issued_at".to_string(),
));
}
for (i, grant) in self.grants.iter().enumerate() {
if grant.tool_pattern.is_empty() {
return Err(CapabilityError::ValidationFailed(format!(
"grant {i} tool_pattern must not be empty"
)));
}
if grant.function_pattern.is_empty() {
return Err(CapabilityError::ValidationFailed(format!(
"grant {i} function_pattern must not be empty"
)));
}
grant.validate()?;
}
let serialized = serde_json::to_string(self)
.map_err(|e| CapabilityError::ValidationFailed(format!("serialization failed: {e}")))?;
if serialized.len() > MAX_TOKEN_SIZE {
return Err(CapabilityError::ValidationFailed(format!(
"serialized token size {} exceeds max {}",
serialized.len(),
MAX_TOKEN_SIZE
)));
}
Ok(())
}
}