1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! AITP error codes from the registry.
//!
//! See `agentidentitytrustprotocol/registries/error-codes.md` for the
//! authoritative list.
use serde::{Deserialize, Serialize};
/// Top-level error type for AITP operations.
///
/// Each variant maps to one or more wire-level [`ErrorCode`] values.
/// Protocol-specific crates have their own narrower error types
/// (e.g. `TctError`, `ManifestError`) that flatten into this with
/// `From` impls.
///
/// Marked `#[non_exhaustive]` so future error categories can be added
/// without a semver-major bump. Downstream matches must include a
/// fall-through arm.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum AitpError {
/// Replay-protection or envelope-level rejection.
#[error("envelope rejected: {0}")]
Envelope(String),
/// Identity proof was invalid (OIDC, pinned key, etc.).
#[error("identity verification failed: {0}")]
Identity(String),
/// Manifest-level error (signature, PoP, expiry).
#[error("manifest error: {0}")]
Manifest(String),
/// TCT-level error (signature, audience, expiry, grants).
#[error("TCT error: {0}")]
Tct(String),
/// Delegation-token error.
#[error("delegation error: {0}")]
Delegation(String),
/// Cryptographic failure (signature, key parsing).
#[error("crypto error: {0}")]
Crypto(String),
/// Other / catch-all.
#[error("AITP error: {0}")]
Other(String),
}
/// Wire-level error code as it appears on the protocol.
///
/// Serialized as `SCREAMING_SNAKE_CASE` strings matching the registry.
///
/// Marked `#[non_exhaustive]` so new codes added to the spec's error
/// registry can ship in a future minor version without breaking
/// downstream `match` statements. Downstream matches must include a
/// fall-through arm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum ErrorCode {
// ── Envelope-level ──────────────────────────────────────────────────
/// Envelope JSON failed schema validation.
InvalidEnvelope,
/// Envelope signature did not verify.
InvalidSignature,
/// Duplicate message_id seen.
ReplayDetected,
/// Timestamp outside ±300s tolerance.
TimestampExpired,
/// Protocol version not supported.
UnknownVersion,
/// Compact-JWS header `alg` is not the sole value derived from the
/// signer's AID — including `none` in any capitalization and unknown
/// algorithms (RFC-AITP-0001 §5.4.5).
TokenAlgMismatch,
/// Compact-JWS header `typ` does not exactly match the value expected
/// for the verification context (`aitp-tct+jwt`, `aitp-grant+jwt`, or
/// `aitp-delegation+jwt`) (RFC-AITP-0001 §5.4.5).
TokenTypMismatch,
/// A JSON member outside the object's declared member set (and outside
/// any extension namespace) was present (RFC-AITP-0001 §7).
UnknownField,
// ── Identity / Manifest ─────────────────────────────────────────────
/// Identity binding could not be verified.
IdentityFailed,
/// Manifest expires_at is in the past.
ManifestExpired,
/// Manifest signature did not verify.
ManifestSignatureInvalid,
/// Manifest proof-of-possession did not verify.
ManifestPopFailed,
/// Manifest version not supported by this implementation.
ManifestVersionUnknown,
// ── Trust ───────────────────────────────────────────────────────────
/// Trust evaluation failed for an unspecified policy reason.
TrustFailed,
/// Requested capability not granted.
PolicyViolation,
/// Issuer's keys could not be resolved.
KeyResolutionFailed,
/// Peer's identity issuer is not in this peer's trust anchors.
IncompatibleTrustAnchors,
// ── Mutual handshake ────────────────────────────────────────────────
/// PoP signature in MUTUAL_COMMIT/_ACK did not verify.
PopVerificationFailed,
/// pop_nonce_echo did not match the previously sent nonce.
NonceMismatch,
/// Peer-issued TCT audience did not equal own AID.
AudienceMismatch,
/// Peer-issued TCT grants exceed peer's offered_capabilities.
GrantOverflow,
/// Received TCT did not include required peer capabilities.
InsufficientGrants,
/// Proposed handshake_mode not supported.
HandshakeModeUnsupported,
// ── TCT-specific ────────────────────────────────────────────────────
/// TCT expires_at is in the past.
TctExpired,
// ── PoP ─────────────────────────────────────────────────────────────
/// Downstream PoP challenge was malformed or stale.
PopChallengeInvalid,
/// Downstream PoP response did not verify.
PopResponseInvalid,
// ── Delegation ──────────────────────────────────────────────────────
/// Delegation token: audience did not match self AID.
DelegationAudienceMismatch,
/// Delegation token: scope contained capabilities outside grant_proof.
DelegationScopeExceeded,
/// Delegation token: embedded voucher JWS signature invalid,
/// `voucher.iss` ≠ verifier's AID, or `voucher.sub` ≠ outer `iss`.
/// Renamed in v0.2 from `DELEGATION_INVALID_GRANT_PROOF` (the
/// `grant_proof` reconstruction mechanism was removed by the JWS
/// migration).
DelegationInvalidVoucher,
/// Delegation token: source TCT has been revoked.
DelegationSourceTctRevoked,
/// Delegation token: signature did not verify.
DelegationInvalidSignature,
/// Delegation token: token or grant proof has expired.
DelegationExpired,
/// Delegation token: PoP binding (cnf) verification failed.
DelegationPopFailed,
/// Delegation token: chain length exceeds v0.1 single-hop limit.
DelegationMultihopNotSupported,
/// Multi-hop delegation: chain length exceeds `max_delegation_hops`
/// (RFC-AITP-0011).
DelegationHopLimitExceeded,
/// Multi-hop delegation: `chain_hash` does not match the `chain`
/// array contents (truncation or tampering detected — RFC-AITP-0011).
DelegationChainHashMismatch,
/// Manifest service: no manifest for the requested AID.
ManifestNotFound,
/// TCT verification: signature did not validate under issuer's key.
TctSignatureInvalid,
/// TCT verification: jti is in issuer's deny list.
TctRevoked,
/// TCT verification: TCT `expires_at` exceeds the issuing peer's
/// Manifest `expires_at` (RFC-AITP-0004 §4.3).
TctExpiresAfterManifest,
// ── Session Bundle (RFC-AITP-0010, Draft) ───────────────────────────
/// Coordinator's outer bundle signature failed verification under
/// the coordinator's Manifest key.
BundleInvalidSignature,
/// `version` is not `"aitp/0.2"` (or a later supported version).
BundleVersionMismatch,
/// Bundle `expires_at` is in the past at verification time.
BundleExpired,
/// `expires_at` is greater than
/// `min(participants[*].tct.expires_at)` (RFC-AITP-0010 §6).
BundleExpiryWindowInvariant,
/// One or more `participants[*].tct.issuer` values do not equal
/// `coordinator`.
BundleCoordinatorIssuerMismatch,
/// A `participants[i].tct.audience` does not equal
/// `participants[i].aid`.
BundleAudienceMismatch,
/// `participants` array is empty.
BundleEmptyParticipants,
/// At least one embedded participant TCT failed standard TCT
/// verification.
BundleParticipantTctInvalid,
/// Receiver's AID is not in `participants[*].aid`.
BundleNotMember,
/// Aggregate fallback — implementations MAY return this when a
/// deployment policy requires a single-error surface for bundles,
/// in lieu of the specific BUNDLE_* codes above.
///
/// Also the mandatory code for a structurally invalid wire form,
/// ahead of any of the specific `BUNDLE_*` checks: e.g. the
/// `{"session_bundle": …}` transport wrapper carrying an
/// unexpected sibling member (notably the pre-erratum shape where
/// `signature` sat beside the wrapper instead of inside the signed
/// body — RFC-AITP-0010 §3, fixture
/// `bundle-004-signature-sibling-rejected`), or an inner body that
/// fails to deserialize as a bundle at all. These cases have no
/// bundle to run the specific `BUNDLE_*` checks against.
SessionBundleInvalid,
// ── Manifest (RFC-AITP-0003) ────────────────────────────────────────
/// Manifest failed schema validation — a missing REQUIRED member, a
/// member of the wrong type, or a value outside its grammar
/// (RFC-AITP-0003 §5 step 2). Mirrors `InvalidEnvelope` for the
/// Manifest. MUST NOT be reported as `ManifestSignatureInvalid`: the
/// signature was never reached, and a misleading signature code sends
/// an operator debugging keys and signing when the real defect is the
/// object's shape. When the only defect is an unknown member outside
/// `extensions`, `UnknownField` is more specific and wins instead.
ManifestInvalid,
// ── Revocation (RFC-AITP-0008) ──────────────────────────────────────
/// Revocation snapshot failed schema validation — the transport
/// wrapper carried members other than `revocation_list` and
/// `signature`, or the inner body has a missing/mistyped member. When
/// the only defect is an unknown member outside `extensions`,
/// `UnknownField` is more specific and wins instead.
RevocationSnapshotInvalid,
/// Revocation snapshot signature does not validate under the issuing
/// peer's key, resolved from that peer's Manifest. Distinct from
/// `TctSignatureInvalid`, which is about a token's own JWS.
RevocationSnapshotSignatureInvalid,
}
#[cfg(test)]
mod tests {
use super::*;
/// Pinned wire strings — the contract with the AITP error-code registry.
/// Drift here would silently break interop with other implementations.
#[test]
fn pinned_wire_strings() {
let cases: &[(ErrorCode, &str)] = &[
(ErrorCode::AudienceMismatch, "AUDIENCE_MISMATCH"),
(ErrorCode::TctExpired, "TCT_EXPIRED"),
(
ErrorCode::ManifestSignatureInvalid,
"MANIFEST_SIGNATURE_INVALID",
),
(ErrorCode::ReplayDetected, "REPLAY_DETECTED"),
(
ErrorCode::DelegationSourceTctRevoked,
"DELEGATION_SOURCE_TCT_REVOKED",
),
(ErrorCode::InvalidEnvelope, "INVALID_ENVELOPE"),
(ErrorCode::InvalidSignature, "INVALID_SIGNATURE"),
(ErrorCode::TimestampExpired, "TIMESTAMP_EXPIRED"),
(ErrorCode::UnknownVersion, "UNKNOWN_VERSION"),
(ErrorCode::TokenAlgMismatch, "TOKEN_ALG_MISMATCH"),
(ErrorCode::TokenTypMismatch, "TOKEN_TYP_MISMATCH"),
(ErrorCode::UnknownField, "UNKNOWN_FIELD"),
(ErrorCode::IdentityFailed, "IDENTITY_FAILED"),
(ErrorCode::PolicyViolation, "POLICY_VIOLATION"),
(ErrorCode::GrantOverflow, "GRANT_OVERFLOW"),
(ErrorCode::InsufficientGrants, "INSUFFICIENT_GRANTS"),
(ErrorCode::KeyResolutionFailed, "KEY_RESOLUTION_FAILED"),
(ErrorCode::ManifestExpired, "MANIFEST_EXPIRED"),
(ErrorCode::ManifestPopFailed, "MANIFEST_POP_FAILED"),
(
ErrorCode::ManifestVersionUnknown,
"MANIFEST_VERSION_UNKNOWN",
),
(ErrorCode::ManifestInvalid, "MANIFEST_INVALID"),
(
ErrorCode::IncompatibleTrustAnchors,
"INCOMPATIBLE_TRUST_ANCHORS",
),
(ErrorCode::PopVerificationFailed, "POP_VERIFICATION_FAILED"),
(ErrorCode::NonceMismatch, "NONCE_MISMATCH"),
(ErrorCode::PopChallengeInvalid, "POP_CHALLENGE_INVALID"),
(ErrorCode::PopResponseInvalid, "POP_RESPONSE_INVALID"),
(
ErrorCode::DelegationAudienceMismatch,
"DELEGATION_AUDIENCE_MISMATCH",
),
(
ErrorCode::DelegationScopeExceeded,
"DELEGATION_SCOPE_EXCEEDED",
),
(
ErrorCode::DelegationInvalidVoucher,
"DELEGATION_INVALID_VOUCHER",
),
(
ErrorCode::DelegationInvalidSignature,
"DELEGATION_INVALID_SIGNATURE",
),
(ErrorCode::DelegationExpired, "DELEGATION_EXPIRED"),
(ErrorCode::DelegationPopFailed, "DELEGATION_POP_FAILED"),
(
ErrorCode::DelegationMultihopNotSupported,
"DELEGATION_MULTIHOP_NOT_SUPPORTED",
),
(
ErrorCode::DelegationHopLimitExceeded,
"DELEGATION_HOP_LIMIT_EXCEEDED",
),
(
ErrorCode::DelegationChainHashMismatch,
"DELEGATION_CHAIN_HASH_MISMATCH",
),
(ErrorCode::ManifestNotFound, "MANIFEST_NOT_FOUND"),
(ErrorCode::TrustFailed, "TRUST_FAILED"),
(
ErrorCode::HandshakeModeUnsupported,
"HANDSHAKE_MODE_UNSUPPORTED",
),
(ErrorCode::TctSignatureInvalid, "TCT_SIGNATURE_INVALID"),
(ErrorCode::TctRevoked, "TCT_REVOKED"),
(
ErrorCode::TctExpiresAfterManifest,
"TCT_EXPIRES_AFTER_MANIFEST",
),
// Revocation (RFC-AITP-0008)
(
ErrorCode::RevocationSnapshotInvalid,
"REVOCATION_SNAPSHOT_INVALID",
),
(
ErrorCode::RevocationSnapshotSignatureInvalid,
"REVOCATION_SNAPSHOT_SIGNATURE_INVALID",
),
// Session Bundle (RFC-AITP-0010, Draft)
(
ErrorCode::BundleInvalidSignature,
"BUNDLE_INVALID_SIGNATURE",
),
(ErrorCode::BundleVersionMismatch, "BUNDLE_VERSION_MISMATCH"),
(ErrorCode::BundleExpired, "BUNDLE_EXPIRED"),
(
ErrorCode::BundleExpiryWindowInvariant,
"BUNDLE_EXPIRY_WINDOW_INVARIANT",
),
(
ErrorCode::BundleCoordinatorIssuerMismatch,
"BUNDLE_COORDINATOR_ISSUER_MISMATCH",
),
(
ErrorCode::BundleAudienceMismatch,
"BUNDLE_AUDIENCE_MISMATCH",
),
(
ErrorCode::BundleEmptyParticipants,
"BUNDLE_EMPTY_PARTICIPANTS",
),
(
ErrorCode::BundleParticipantTctInvalid,
"BUNDLE_PARTICIPANT_TCT_INVALID",
),
(ErrorCode::BundleNotMember, "BUNDLE_NOT_MEMBER"),
(ErrorCode::SessionBundleInvalid, "SESSION_BUNDLE_INVALID"),
];
for (code, wire) in cases {
let v = serde_json::to_value(code).unwrap();
assert_eq!(v.as_str().unwrap(), *wire, "encode {:?}", code);
let back: ErrorCode = serde_json::from_value(v).unwrap();
assert_eq!(back, *code, "decode {}", wire);
}
// Completeness guard, part 1: this match is exhaustive (no `_` arm),
// so the crate fails to *compile* the moment a new `ErrorCode`
// variant is added without extending the or-pattern below.
// (`ErrorCode` is `#[non_exhaustive]` for downstream crates only —
// within this crate an exhaustive match is still enforced.)
fn assert_every_variant_named(code: ErrorCode) {
match code {
ErrorCode::InvalidEnvelope
| ErrorCode::InvalidSignature
| ErrorCode::ReplayDetected
| ErrorCode::TimestampExpired
| ErrorCode::UnknownVersion
| ErrorCode::TokenAlgMismatch
| ErrorCode::TokenTypMismatch
| ErrorCode::UnknownField
| ErrorCode::IdentityFailed
| ErrorCode::ManifestExpired
| ErrorCode::ManifestSignatureInvalid
| ErrorCode::ManifestPopFailed
| ErrorCode::ManifestVersionUnknown
| ErrorCode::ManifestInvalid
| ErrorCode::TrustFailed
| ErrorCode::PolicyViolation
| ErrorCode::KeyResolutionFailed
| ErrorCode::IncompatibleTrustAnchors
| ErrorCode::PopVerificationFailed
| ErrorCode::NonceMismatch
| ErrorCode::AudienceMismatch
| ErrorCode::GrantOverflow
| ErrorCode::InsufficientGrants
| ErrorCode::HandshakeModeUnsupported
| ErrorCode::TctExpired
| ErrorCode::PopChallengeInvalid
| ErrorCode::PopResponseInvalid
| ErrorCode::DelegationAudienceMismatch
| ErrorCode::DelegationScopeExceeded
| ErrorCode::DelegationInvalidVoucher
| ErrorCode::DelegationSourceTctRevoked
| ErrorCode::DelegationInvalidSignature
| ErrorCode::DelegationExpired
| ErrorCode::DelegationPopFailed
| ErrorCode::DelegationMultihopNotSupported
| ErrorCode::DelegationHopLimitExceeded
| ErrorCode::DelegationChainHashMismatch
| ErrorCode::ManifestNotFound
| ErrorCode::TctSignatureInvalid
| ErrorCode::TctRevoked
| ErrorCode::TctExpiresAfterManifest
| ErrorCode::RevocationSnapshotInvalid
| ErrorCode::RevocationSnapshotSignatureInvalid
| ErrorCode::BundleInvalidSignature
| ErrorCode::BundleVersionMismatch
| ErrorCode::BundleExpired
| ErrorCode::BundleExpiryWindowInvariant
| ErrorCode::BundleCoordinatorIssuerMismatch
| ErrorCode::BundleAudienceMismatch
| ErrorCode::BundleEmptyParticipants
| ErrorCode::BundleParticipantTctInvalid
| ErrorCode::BundleNotMember
| ErrorCode::SessionBundleInvalid => {}
}
}
for (code, _) in cases {
assert_every_variant_named(*code);
}
// Completeness guard, part 2: pins the row count against the
// variant count enforced by the match above. Part 1 only forces a
// *compile error* when a variant is missing from the match's
// or-pattern — it says nothing about whether that variant also got
// a `cases` row. This assertion is what actually catches a missing
// row, but only if it's kept in sync: bump this number *and* add a
// row above whenever `ErrorCode` grows a variant — forgetting both
// together defeats this guard, since an unchanged row count still
// equals an unchanged (stale) target.
assert_eq!(
cases.len(),
53,
"ErrorCode variant count and pinned_wire_strings row count have diverged"
);
}
#[test]
fn round_trip_through_json_string() {
let s = serde_json::to_string(&ErrorCode::PopVerificationFailed).unwrap();
assert_eq!(s, "\"POP_VERIFICATION_FAILED\"");
let back: ErrorCode = serde_json::from_str(&s).unwrap();
assert_eq!(back, ErrorCode::PopVerificationFailed);
}
#[test]
fn rejects_unknown_wire_strings() {
assert!(serde_json::from_str::<ErrorCode>("\"NOT_A_REAL_CODE\"").is_err());
assert!(serde_json::from_str::<ErrorCode>("\"audience_mismatch\"").is_err());
}
}