Skip to main content

mid_verify/
error.rs

1//! Typed error variants for the mID verifier.
2//!
3//! Every variant maps to a specific failure mode so the RP backend can
4//! react distinctly (log it, return 401 with a specific code, alert a
5//! security team). Generic catch-alls like `Other` are deliberately
6//! avoided — production code reading `match err { ... }` should never
7//! hit a fallback.
8
9use thiserror::Error;
10
11/// The single error type returned by [`crate::verify_mid_response`].
12#[derive(Debug, Error)]
13pub enum VerifyError {
14    // ─── JWS shape / encoding ──────────────────────────────────────────────
15    /// The JWT string did not have exactly 3 dot-separated segments.
16    #[error("invalid JWS compact form: expected 3 segments, got {0}")]
17    InvalidJwsShape(usize),
18
19    /// One of the base64url segments failed to decode.
20    #[error("base64url decoding failed for {segment} segment: {source}")]
21    Base64Decode {
22        /// Which segment failed: "header", "payload", or "signature".
23        segment: &'static str,
24        /// The underlying base64 error.
25        source: base64::DecodeError,
26    },
27
28    /// The JWS header was not valid JSON or did not declare `alg: ES256`.
29    #[error("invalid or unsupported JWS header (alg must be ES256, typ must be JWT)")]
30    InvalidJwsHeader,
31
32    /// The JWT payload JSON was not parseable into a [`mid_issuer::MidJwtPayload`].
33    #[error("JWT payload JSON malformed: {0}")]
34    PayloadJson(#[from] serde_json::Error),
35
36    // ─── Metadata checks ───────────────────────────────────────────────────
37    /// The `aud` claim did not match the verifier's expected audience.
38    #[error("audience mismatch: expected `{expected}`, got `{actual}`")]
39    AudienceMismatch {
40        /// What the RP configured.
41        expected: String,
42        /// What the JWT carried.
43        actual: String,
44    },
45
46    /// The `nonce` claim did not match the nonce the RP issued for this
47    /// session — possible replay attempt or stale tab.
48    #[error("nonce mismatch — possible replay or stale request")]
49    NonceMismatch,
50
51    /// The JWT's `exp` is in the past relative to the verifier's clock.
52    #[error("token expired: exp={exp}, now={now}")]
53    Expired {
54        /// JWT's expiry claim.
55        exp: u64,
56        /// Verifier's wall clock.
57        now: u64,
58    },
59
60    /// The JWT's `iat` is too far in the future for the verifier's clock
61    /// skew tolerance — possible attacker producing forward-dated tokens
62    /// or genuine clock skew.
63    #[error("token issued too far in the future: iat={iat}, now={now}, max skew {max_skew_secs}s")]
64    NotYetValid {
65        /// JWT's issued-at claim.
66        iat: u64,
67        /// Verifier's wall clock.
68        now: u64,
69        /// Verifier's configured skew tolerance.
70        max_skew_secs: u64,
71    },
72
73    // ─── Key decoding ──────────────────────────────────────────────────────
74    /// The DID's base58 suffix did not decode to a valid P-256 public key.
75    /// Either the DID is malformed or it's from a non-mID identity system.
76    #[error("DID `{did}` does not encode a valid P-256 public key")]
77    MalformedDid {
78        /// The DID that failed to decode.
79        did: String,
80    },
81
82    /// A verification method's `publicKeyMultibase` did not decode to a
83    /// valid P-256 public key.
84    #[error("verification method `{vm_id}` has an invalid public_key_multibase")]
85    MalformedVmPubkey {
86        /// The VM ID whose pubkey failed to decode.
87        vm_id: String,
88    },
89
90    /// A base64url-encoded signature was not 64 bytes (the expected
91    /// `r || s` form for ES256).
92    #[error("signature has wrong length: expected 64 bytes, got {actual}")]
93    SignatureWrongLength {
94        /// The length actually decoded.
95        actual: usize,
96    },
97
98    /// The signature was 64 bytes but `r`/`s` are not valid P-256 scalars
99    /// (zero, >= curve order). Often means the wallet returned a placeholder
100    /// all-zero signature (vault locked / sign failed).
101    #[error("signature bytes are not a valid P-256 r||s (zero or out-of-range scalar)")]
102    SignatureInvalidScalars,
103
104    // ─── Cryptographic checks ──────────────────────────────────────────────
105    /// The genesis roster's self-signature did not verify against the key
106    /// recoverable from the DID. Either the genesis roster was tampered
107    /// with or the signature is from a different key — the user does not
108    /// hold the genesis key.
109    #[error("genesis roster self-signature is invalid (does not verify against key encoded in DID)")]
110    GenesisSignatureInvalid,
111
112    /// A roster chain entry was signed by a verification method that is
113    /// not present in the prior entry's roster — the chain is broken.
114    #[error(
115        "chain entry version {entry_version} signed by `{signer_kid}`, which is not in the prior roster"
116    )]
117    ChainSignerNotInPriorRoster {
118        /// The version of the chain entry whose signer is unknown.
119        entry_version: u64,
120        /// The signer_kid that doesn't appear in the prior roster.
121        signer_kid: String,
122    },
123
124    /// A roster chain entry's signature did not verify against the
125    /// claimed signer's public key. Either the entry was tampered with
126    /// or the signature is from a different key.
127    #[error("chain entry version {entry_version} has an invalid signature")]
128    ChainSignatureInvalid {
129        /// The chain entry version that failed signature verification.
130        entry_version: u64,
131    },
132
133    /// Chain versions did not strictly increase. Indicates a stolen
134    /// device trying to bundle an older roster envelope as the head, or
135    /// a malformed chain.
136    #[error(
137        "chain version not strictly monotonic: entry version {entry_version} <= prior version {prior_version}"
138    )]
139    ChainVersionNotMonotonic {
140        /// The non-monotonic entry's version.
141        entry_version: u64,
142        /// The prior entry's version (must be < entry_version).
143        prior_version: u64,
144    },
145
146    /// The verification method that signed the JWT is not present in the
147    /// head roster — the signing device has been revoked.
148    #[error(
149        "current verification method `{vm_id}` is not in the head roster — device has been revoked"
150    )]
151    CurrentVmNotInHeadRoster {
152        /// The VM ID that's not in the head roster.
153        vm_id: String,
154    },
155
156    /// The JWS outer signature did not verify against the embedded
157    /// verification method's public key.
158    #[error("JWS outer signature did not verify against the embedded verification method")]
159    JwtSignatureInvalid,
160
161    // ─── Optional rollback detection ───────────────────────────────────────
162    /// The current roster version is less than the highest the RP has
163    /// seen for this DID — possible stolen-device replay of an old
164    /// (pre-revocation) roster envelope.
165    ///
166    /// This variant is NEVER produced by [`crate::verify_mid_response`]
167    /// directly; the RP uses [`crate::VerifiedMid::check_rollback`] after
168    /// looking up `last_seen_version` from its own per-DID store.
169    #[error("rollback detected: current version {current} < last seen {last_seen}")]
170    RollbackDetected {
171        /// The current head roster version from the verified JWT.
172        current: u64,
173        /// The highest version this RP has seen for this DID.
174        last_seen: u64,
175    },
176
177    /// The token's roster history does not contain the exact roster the RP saw
178    /// last at `version`: another history was branched off an older roster.
179    /// Returned by [`crate::VerifiedMid::check_continuity`]. A device removed at
180    /// some version, but listed in an earlier one, can sign its own later
181    /// versions from that earlier roster; only the content of the version the RP
182    /// already saw tells the two histories apart.
183    #[error("roster fork detected: this token's history differs from the one seen at version {version}")]
184    ForkDetected {
185        /// The version the RP recorded, whose roster this token does not carry.
186        version: u64,
187    },
188
189    /// A roster chain entry names a different DID than the token's issuer.
190    #[error("roster chain entry v{entry_version} names {entry_did}, not the issuer")]
191    ChainEntryDidMismatch {
192        /// The entry's version.
193        entry_version: u64,
194        /// The DID the entry names.
195        entry_did: String,
196    },
197}