Skip to main content

vcp_core/
error.rs

1//! VCP error types.
2//!
3//! All fallible operations in `vcp-core` return [`VcpError`] through
4//! the standard [`Result`] alias [`VcpResult`].
5
6use std::fmt;
7
8/// Convenience alias used throughout the crate.
9pub type VcpResult<T> = Result<T, VcpError>;
10
11/// Errors that can occur during VCP token parsing, encoding, or verification.
12#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
13pub enum VcpError {
14    /// A string could not be parsed into the expected VCP structure.
15    #[error("parse error: {0}")]
16    ParseError(String),
17
18    /// An unrecognised persona character was encountered.
19    #[error("invalid persona character: '{0}'")]
20    InvalidPersona(char),
21
22    /// An adherence level outside the valid 0-5 range.
23    #[error("invalid adherence level: {0} (must be 0-5)")]
24    InvalidAdherence(u8),
25
26    /// An intensity value outside the valid 1-5 range.
27    #[error("invalid intensity: {0} (must be 1-5)")]
28    InvalidIntensity(u8),
29
30    /// An unrecognised scope character was encountered.
31    #[error("invalid scope character: '{0}'")]
32    InvalidScope(char),
33
34    /// A token string is structurally malformed.
35    #[error("malformed token: {0}")]
36    MalformedToken(String),
37
38    /// A content hash did not match its expected value.
39    #[error("hash mismatch: expected {expected}, got {actual}")]
40    HashMismatch { expected: String, actual: String },
41
42    /// A cryptographic signature could not be verified.
43    #[error("signature error: {0}")]
44    SignatureError(String),
45
46    /// A JSON serialization / deserialization error.
47    #[error("json error: {0}")]
48    JsonError(String),
49
50    /// A hook registration or execution error.
51    #[error("hook error: {0}")]
52    HookError(String),
53
54    /// A revocation check error.
55    #[error("revocation error: {0}")]
56    RevocationError(String),
57}
58
59impl From<serde_json::Error> for VcpError {
60    fn from(err: serde_json::Error) -> Self {
61        VcpError::JsonError(err.to_string())
62    }
63}
64
65/// Validation result codes mirroring the Python `VerificationResult` enum.
66///
67/// These are returned by bundle verification routines to indicate
68/// exactly why verification succeeded or failed.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
70#[repr(u8)]
71pub enum VerificationCode {
72    Valid = 0,
73    SizeExceeded = 1,
74    InvalidSchema = 2,
75    UntrustedIssuer = 3,
76    InvalidSignature = 4,
77    UntrustedAuditor = 5,
78    InvalidAttestation = 6,
79    HashMismatch = 7,
80    NotYetValid = 8,
81    Expired = 9,
82    FutureTimestamp = 10,
83    ReplayDetected = 11,
84    TokenMismatch = 12,
85    BudgetExceeded = 13,
86    ScopeMismatch = 14,
87    Revoked = 15,
88    FetchFailed = 16,
89    RevocationUnavailable = 17,
90}
91
92impl VerificationCode {
93    /// Returns `true` when the code represents a successful verification.
94    pub fn is_valid(self) -> bool {
95        matches!(self, VerificationCode::Valid)
96    }
97
98    /// Broad classification of the failure reason.
99    pub fn category(self) -> &'static str {
100        match self {
101            VerificationCode::Valid => "success",
102            VerificationCode::InvalidSignature
103            | VerificationCode::InvalidAttestation
104            | VerificationCode::HashMismatch
105            | VerificationCode::FutureTimestamp
106            | VerificationCode::ReplayDetected
107            | VerificationCode::TokenMismatch
108            | VerificationCode::SizeExceeded
109            | VerificationCode::Revoked => "security",
110            VerificationCode::NotYetValid | VerificationCode::Expired => "temporal",
111            VerificationCode::FetchFailed | VerificationCode::RevocationUnavailable => "transient",
112            _ => "configuration",
113        }
114    }
115}
116
117impl fmt::Display for VerificationCode {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        let label = match self {
120            VerificationCode::Valid => "valid",
121            VerificationCode::SizeExceeded => "size_exceeded",
122            VerificationCode::InvalidSchema => "invalid_schema",
123            VerificationCode::UntrustedIssuer => "untrusted_issuer",
124            VerificationCode::InvalidSignature => "invalid_signature",
125            VerificationCode::UntrustedAuditor => "untrusted_auditor",
126            VerificationCode::InvalidAttestation => "invalid_attestation",
127            VerificationCode::HashMismatch => "hash_mismatch",
128            VerificationCode::NotYetValid => "not_yet_valid",
129            VerificationCode::Expired => "expired",
130            VerificationCode::FutureTimestamp => "future_timestamp",
131            VerificationCode::ReplayDetected => "replay_detected",
132            VerificationCode::TokenMismatch => "token_mismatch",
133            VerificationCode::BudgetExceeded => "budget_exceeded",
134            VerificationCode::ScopeMismatch => "scope_mismatch",
135            VerificationCode::Revoked => "revoked",
136            VerificationCode::FetchFailed => "fetch_failed",
137            VerificationCode::RevocationUnavailable => "revocation_unavailable",
138        };
139        f.write_str(label)
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[test]
148    fn verification_code_valid() {
149        assert!(VerificationCode::Valid.is_valid());
150        assert!(!VerificationCode::Expired.is_valid());
151    }
152
153    #[test]
154    fn verification_code_categories() {
155        assert_eq!(VerificationCode::Valid.category(), "success");
156        assert_eq!(VerificationCode::HashMismatch.category(), "security");
157        assert_eq!(VerificationCode::Expired.category(), "temporal");
158        assert_eq!(VerificationCode::FetchFailed.category(), "transient");
159        assert_eq!(VerificationCode::BudgetExceeded.category(), "configuration");
160    }
161
162    #[test]
163    fn vcp_error_display() {
164        let e = VcpError::InvalidPersona('X');
165        assert_eq!(e.to_string(), "invalid persona character: 'X'");
166
167        let e = VcpError::HashMismatch {
168            expected: "abc".into(),
169            actual: "def".into(),
170        };
171        assert!(e.to_string().contains("abc"));
172        assert!(e.to_string().contains("def"));
173    }
174}