Skip to main content

trust_tasks_rs/
error.rs

1//! Error-response payload for the `trust-task-error` framework spec. The SDK
2//! emits the `0.5` form — lowerCamelCase codes including `idConflict` and
3//! `cancelled`, and the
4//! `inResponseTo` member that names the document being reported on. The parser
5//! also accepts the `0.1` snake_case codes, so a current consumer can read a
6//! `0.1` peer.
7//!
8//! Models the structure defined in SPEC.md §8.2 and §8.3. The set of standard
9//! codes is encoded as the [`StandardCode`] enum; task-specific extensions
10//! (SPEC.md §8.5) are namespaced strings carried in the [`TrustTaskCode`]
11//! `Extended` variant.
12
13use std::error::Error as StdError;
14use std::fmt;
15use std::str::FromStr;
16
17use chrono::{DateTime, Utc};
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20use serde_with::{DeserializeFromStr, SerializeDisplay};
21use thiserror::Error;
22
23use crate::transport::ConsistencyError;
24
25/// Names the *Trust Task document* an [`ErrorPayload`] reports on (SPEC.md
26/// §8.2).
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct InResponseTo {
29    /// The reported-on document's `type`, **including** any `#request` or
30    /// `#response` fragment it carried — that fragment is what tells a consumer
31    /// which variant's semantics apply.
32    #[serde(rename = "typeUri")]
33    pub type_uri: String,
34
35    /// The reported-on document's `id`. Globally unique and never reused
36    /// (SPEC.md §4.3), so it names one instance where `threadId` names an
37    /// exchange.
38    ///
39    /// Omitted under `identityMismatch`: per §8.1 the response is addressed to
40    /// the transport-authenticated sender rather than the in-band `issuer`, and
41    /// that party did not necessarily compose the document.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub id: Option<String>,
44}
45
46/// The `payload` of a `trust-task-error/0.6` document, per SPEC.md §8.2.
47///
48/// Exchange-level correlation is carried by the surrounding
49/// [`TrustTask`](crate::TrustTask)'s `threadId`; *which document* this error
50/// reports on is carried here, by [`in_response_to`](Self::in_response_to).
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub struct ErrorPayload {
53    /// Short identifier for the failure category.
54    pub code: TrustTaskCode,
55
56    /// Identifies the *Trust Task document* this error reports on (SPEC.md
57    /// §8.2).
58    ///
59    /// `threadId` correlates the exchange for a party that saw the originating
60    /// request, and identifies nothing to anyone else. Without this, a retained
61    /// error names neither the specification the failure occurred under nor the
62    /// instance that triggered it — and for the standard codes of §8.3 there is
63    /// no other signal of origin at all.
64    ///
65    /// **SHOULD** be populated in general, and **MUST** be where the error will
66    /// be retained, replayed, or relied upon beyond the original producer. The
67    /// document builders on [`TrustTask`](crate::TrustTask) populate it for you.
68    #[serde(
69        rename = "inResponseTo",
70        default,
71        skip_serializing_if = "Option::is_none"
72    )]
73    pub in_response_to: Option<InResponseTo>,
74
75    /// Human-readable description. Non-normative; intended for logs and
76    /// operator UI.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub message: Option<String>,
79
80    /// Whether the producer MAY retry the original document. Per SPEC.md §8.4,
81    /// "retry" means re-sending bit-for-bit; a new document with a fresh `id`
82    /// is not a retry.
83    pub retryable: bool,
84
85    /// Earliest time at which the producer SHOULD retry. Meaningful only when
86    /// [`retryable`](Self::retryable) is `true`.
87    #[serde(
88        rename = "retryAfter",
89        default,
90        skip_serializing_if = "Option::is_none"
91    )]
92    pub retry_after: Option<DateTime<Utc>>,
93
94    /// Task-specific extension data. The shape is defined by the
95    /// originating *Trust Task specification* (SPEC.md §8.5).
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub details: Option<Value>,
98}
99
100impl ErrorPayload {
101    /// Construct a minimal payload for `code`. `retryable` is initialized to
102    /// the code's default per the §8.3 table (overridable via
103    /// [`with_retryable`](Self::with_retryable)). All other members are absent.
104    pub fn new(code: impl Into<TrustTaskCode>) -> Self {
105        let code = code.into();
106        let retryable = match &code {
107            TrustTaskCode::Standard(c) => c.default_retryable(),
108            // Per SPEC §8.5, an unrecognized extension code is treated as
109            // `taskFailed` — which defaults to non-retryable. The producer of
110            // the extension MAY override.
111            TrustTaskCode::Extended { .. } => false,
112        };
113        Self {
114            code,
115            in_response_to: None,
116            message: None,
117            retryable,
118            retry_after: None,
119            details: None,
120        }
121    }
122
123    /// Name the document this error reports on (SPEC.md §8.2).
124    ///
125    /// Prefer the builders on [`TrustTask`](crate::TrustTask), which populate
126    /// this from the request being rejected — including the §8.1 rule that the
127    /// `id` is omitted under `identityMismatch`. Use this directly only when
128    /// constructing a payload without the originating document in hand.
129    pub fn about(mut self, type_uri: impl Into<String>, id: Option<String>) -> Self {
130        self.in_response_to = Some(InResponseTo {
131            type_uri: type_uri.into(),
132            id,
133        });
134        self
135    }
136
137    /// Attach a human-readable message.
138    pub fn with_message(mut self, message: impl Into<String>) -> Self {
139        self.message = Some(message.into());
140        self
141    }
142
143    /// Override the `retryable` flag (default is taken from
144    /// [`StandardCode::default_retryable`]).
145    pub fn with_retryable(mut self, retryable: bool) -> Self {
146        self.retryable = retryable;
147        self
148    }
149
150    /// Attach a `retryAfter` hint. Meaningful only when `retryable` is `true`.
151    pub fn with_retry_after(mut self, when: DateTime<Utc>) -> Self {
152        self.retry_after = Some(when);
153        self
154    }
155
156    /// Attach task-specific extension data.
157    pub fn with_details(mut self, details: Value) -> Self {
158        self.details = Some(details);
159        self
160    }
161
162    /// Resolve this payload's code to a [`StandardCode`] the consumer is
163    /// guaranteed to recognize, applying the SPEC §8.5 fallback:
164    /// unrecognized extension codes collapse to [`StandardCode::TaskFailed`].
165    ///
166    /// Standard codes are returned as-is.
167    pub fn effective_code(&self) -> StandardCode {
168        match &self.code {
169            TrustTaskCode::Standard(c) => *c,
170            TrustTaskCode::Extended { .. } => StandardCode::TaskFailed,
171        }
172    }
173
174    /// Apply the SPEC §8.4 retry-semantics check.
175    ///
176    /// Returns `true` only when:
177    ///   * `retryable` is `true`, AND
178    ///   * `retry_after` is either absent or already past `now`.
179    ///
180    /// A `false` return means the producer **MUST NOT** retry yet (or at all,
181    /// when `retryable` is `false`). "Retry" here is the strict bit-for-bit
182    /// sense from SPEC §8.4 — issuing a new document with a fresh `id` is
183    /// always permitted regardless of this value.
184    pub fn should_retry_at(&self, now: DateTime<Utc>) -> bool {
185        if !self.retryable {
186            return false;
187        }
188        match self.retry_after {
189            None => true,
190            Some(t) => t <= now,
191        }
192    }
193}
194
195/// `trust-task-error` is a *Trust Task specification* like any other (SPEC
196/// §8.1), so its payload is a [`Payload`](crate::Payload): an error response
197/// can be built with [`TrustTask::for_payload`](crate::TrustTask::for_payload),
198/// sealed by a binding's `pack_trust_task`, consumed with
199/// [`consume_inbound`](crate::consume_inbound) and routed by a
200/// [`Dispatcher`](crate::Dispatcher).
201///
202/// [`TYPE_URI`](crate::Payload::TYPE_URI) is the version this library
203/// **emits** ([`crate::trust_task_error_type_uri`]), because a `Payload`'s Type
204/// URI is the one its documents are stamped with. Deserializing is more
205/// lenient than that: the `0.1` snake_case codes still parse. A dispatcher
206/// routes `0.6`, and any later version whose declared extension chain reaches
207/// it (SPEC §5.2); an earlier version's document is `unsupportedVersion` there,
208/// so a producer reading replies from older peers reads them untyped.
209///
210/// The constants are the `0.6` front matter's, hand-copied because the
211/// codegen skips this slug: the original producer (`recipient`) is a
212/// **REQUIRED** party, and a proof is `RECOMMENDED`, not required.
213/// [`PAYLOAD_SCHEMA`](crate::Payload::PAYLOAD_SCHEMA) stays `None`: the type is
214/// the constraint, as it was before this impl existed.
215impl crate::Payload for ErrorPayload {
216    const TYPE_URI: &'static str = crate::document::TRUST_TASK_ERROR_TYPE_URI;
217    const IS_RECIPIENT_REQUIRED: bool = true;
218}
219
220impl From<StandardCode> for ErrorPayload {
221    fn from(code: StandardCode) -> Self {
222        Self::new(code)
223    }
224}
225
226impl From<TrustTaskCode> for ErrorPayload {
227    fn from(code: TrustTaskCode) -> Self {
228        Self::new(code)
229    }
230}
231
232impl fmt::Display for ErrorPayload {
233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234        match self.message.as_deref() {
235            Some(msg) => write!(f, "{}: {}", self.code, msg),
236            None => write!(f, "{}", self.code),
237        }
238    }
239}
240
241impl StdError for ErrorPayload {}
242
243/// An error code — either a framework-standard code (SPEC.md §8.3) or an
244/// extension code namespaced by a spec's slug (SPEC.md §8.5).
245#[derive(Debug, Clone, PartialEq, Eq, SerializeDisplay, DeserializeFromStr)]
246pub enum TrustTaskCode {
247    /// One of the framework-defined codes recognized by every conforming
248    /// consumer.
249    Standard(StandardCode),
250
251    /// A specification-extended code in the form `<slug>:<local>`.
252    ///
253    /// The code names a slug but no authority, so it means something only
254    /// against the Type URI of the request it answers (SPEC.md §8.5):
255    /// `vault/get:notFound` from the registry's `vault/get` and from a private
256    /// one are different codes. Resolve it with `inResponseTo.typeUri` (or
257    /// the request you sent), never by the string alone, and keep that Type
258    /// URI beside it anywhere the code outlives the exchange.
259    Extended {
260        /// The slug owning this extension, e.g. `"trust-task-control"` or `"acl/grant"`.
261        slug: String,
262        /// The local code identifier within the slug's namespace.
263        local: String,
264    },
265}
266
267/// The framework-defined standard error codes (SPEC.md §8.3).
268///
269/// Marked `#[non_exhaustive]` as of 0.7.0: the framework adds a standard code
270/// from time to time (`idConflict` in 0.4), and without this every such
271/// addition would be a breaking change for any downstream `match`. Downstream
272/// code must carry a wildcard arm; in exchange, future codes arrive as a minor
273/// bump rather than a major one.
274#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
275#[non_exhaustive]
276pub enum StandardCode {
277    /// The document did not validate against the framework schema or the
278    /// task-specific payload schema.
279    MalformedRequest,
280    /// The consumer does not recognize the `type` URI.
281    UnsupportedType,
282    /// The `type` URI was recognized but its `MAJOR.MINOR` is not supported.
283    UnsupportedVersion,
284    /// `expiresAt` was in the past at the time of evaluation.
285    Expired,
286    /// A `proof` was required and was missing.
287    ProofRequired,
288    /// A `proof` was present but failed verification.
289    ProofInvalid,
290    /// The requesting party is not authorized to invoke this task.
291    PermissionDenied,
292    /// The document's `recipient` does not identify the receiving consumer.
293    WrongRecipient,
294    /// An in-band `issuer` or `recipient` is inconsistent with the transport-
295    /// authenticated identity for the same party.
296    IdentityMismatch,
297    /// The document's `id` matches one the consumer has already accepted, but
298    /// its content differs (SPEC.md §7.2 item 11).
299    IdConflict,
300    /// The consumer stopped the task on its own initiative — operator action,
301    /// policy, capacity, or a compliance hold (SPEC.md §11). Distinct from a
302    /// producer-requested cancellation, which is answered by a response to the
303    /// `trust-task-control` document rather than by an error.
304    Cancelled,
305    /// The recipient party attempted the task and could not complete it.
306    TaskFailed,
307    /// The recipient party is temporarily unable to process the task.
308    Unavailable,
309    /// The recipient party encountered an unexpected internal failure.
310    InternalError,
311    /// The document named a namespace critical under `extCritical` that the
312    /// consumer does not recognize (SPEC.md §4.5.2). The consumer understood
313    /// the `type` and its version, and refused rather than process the
314    /// document without the namespace. New in `trust-task-error/0.6`.
315    UnsupportedExtension,
316    /// The recipient party could not decide, because something it needed and
317    /// does not control could not be obtained or checked: the schema behind a
318    /// `type`, the material behind a `verificationMethod`, a status list, or a
319    /// referenced document whose digest no longer matches (SPEC.md §8.3).
320    /// Neither a refusal nor a failed verification: a party retaining it
321    /// must not read it as either. New in `trust-task-error/0.6`.
322    Indeterminate,
323}
324
325impl StandardCode {
326    /// The default `retryable` value an emitter SHOULD use per SPEC.md §8.3,
327    /// unless task-specific knowledge dictates otherwise.
328    ///
329    /// `TaskFailed` is `varies` in the spec; we treat its default as `false`.
330    pub fn default_retryable(self) -> bool {
331        matches!(
332            self,
333            StandardCode::Unavailable | StandardCode::InternalError | StandardCode::Indeterminate
334        )
335    }
336
337    /// The wire-form string this code is emitted as.
338    ///
339    /// As of framework 0.2 the standard codes are lowerCamelCase (SPEC.md
340    /// §8.3 / Appendix B). `parse_standard` still accepts the framework
341    /// 0.1 snake_case spellings so a 0.2 consumer can read a 0.1 peer.
342    pub fn as_str(self) -> &'static str {
343        match self {
344            StandardCode::MalformedRequest => "malformedRequest",
345            StandardCode::UnsupportedType => "unsupportedType",
346            StandardCode::UnsupportedVersion => "unsupportedVersion",
347            StandardCode::Expired => "expired",
348            StandardCode::ProofRequired => "proofRequired",
349            StandardCode::ProofInvalid => "proofInvalid",
350            StandardCode::PermissionDenied => "permissionDenied",
351            StandardCode::WrongRecipient => "wrongRecipient",
352            StandardCode::IdentityMismatch => "identityMismatch",
353            StandardCode::IdConflict => "idConflict",
354            StandardCode::Cancelled => "cancelled",
355            StandardCode::TaskFailed => "taskFailed",
356            StandardCode::Unavailable => "unavailable",
357            StandardCode::InternalError => "internalError",
358            StandardCode::UnsupportedExtension => "unsupportedExtension",
359            StandardCode::Indeterminate => "indeterminate",
360        }
361    }
362}
363
364impl fmt::Display for StandardCode {
365    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366        f.write_str(self.as_str())
367    }
368}
369
370/// Reason a string fails to parse as a [`TrustTaskCode`].
371#[derive(Debug, Error, PartialEq, Eq)]
372pub enum ParseCodeError {
373    /// The code is empty.
374    #[error("error code is empty")]
375    Empty,
376    /// The namespace portion before `:` is not a valid slug.
377    #[error("extension code namespace {0:?} is not a valid slug")]
378    InvalidNamespace(String),
379    /// The local portion after `:` is empty or malformed.
380    #[error("extension code local part {0:?} is invalid")]
381    InvalidLocal(String),
382}
383
384impl FromStr for TrustTaskCode {
385    type Err = ParseCodeError;
386
387    fn from_str(s: &str) -> Result<Self, Self::Err> {
388        if s.is_empty() {
389            return Err(ParseCodeError::Empty);
390        }
391        match s.split_once(':') {
392            Some((slug, local)) => {
393                validate_slug(slug)
394                    .map_err(|_| ParseCodeError::InvalidNamespace(slug.to_string()))?;
395                validate_local(local)
396                    .map_err(|_| ParseCodeError::InvalidLocal(local.to_string()))?;
397                Ok(TrustTaskCode::Extended {
398                    slug: slug.to_string(),
399                    local: local.to_string(),
400                })
401            }
402            None => Ok(TrustTaskCode::Standard(parse_standard(s)?)),
403        }
404    }
405}
406
407impl fmt::Display for TrustTaskCode {
408    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409        match self {
410            TrustTaskCode::Standard(c) => f.write_str(c.as_str()),
411            TrustTaskCode::Extended { slug, local } => write!(f, "{slug}:{local}"),
412        }
413    }
414}
415
416impl From<StandardCode> for TrustTaskCode {
417    fn from(code: StandardCode) -> Self {
418        TrustTaskCode::Standard(code)
419    }
420}
421
422impl TrustTaskCode {
423    /// Construct an extended code `<slug>:<local>` after validating both
424    /// halves against SPEC.md §8.5's grammar (slug per §6.1, local per
425    /// `spec.meta.schema.json`'s `errorCodes[].code` pattern after the
426    /// colon). Returns [`ParseCodeError`] when either is malformed.
427    ///
428    /// Round-trips cleanly through [`Display`](fmt::Display) and
429    /// [`FromStr`](std::str::FromStr) — a guarantee the hand-rolled
430    /// struct-literal form (`TrustTaskCode::Extended { slug, local }`)
431    /// does not enforce.
432    pub fn new_extended(
433        slug: impl Into<String>,
434        local: impl Into<String>,
435    ) -> Result<Self, ParseCodeError> {
436        let slug = slug.into();
437        let local = local.into();
438        validate_slug(&slug).map_err(|_| ParseCodeError::InvalidNamespace(slug.clone()))?;
439        validate_local(&local).map_err(|_| ParseCodeError::InvalidLocal(local.clone()))?;
440        Ok(TrustTaskCode::Extended { slug, local })
441    }
442}
443
444/// An extended error code a *Trust Task specification* declares in its
445/// `errorCodes` front matter (SPEC.md §7.3 item 9, §8.5).
446///
447/// `trust-tasks-codegen` emits one of these per declaration, as a constant in
448/// the generated module's `error_codes` submodule, and collects them into that
449/// module's `ERROR_CODES` slice. [`crate::schema_index::error_codes_for`]
450/// serves the same slice by Type URI, for a consumer that dispatches on the URI
451/// and has no module to name.
452///
453/// The point is that the code string is **read from the specification**, not
454/// written at the call site. A hand-written literal can name a code the
455/// specification never declared, and nothing notices: the consumer on the other
456/// end degrades it to `taskFailed` (§8.5) and the distinction the specification
457/// drew is lost without a trace.
458///
459/// ```rust,ignore
460/// use trust_tasks_rs::specs::acl::grant::v0_2 as grant;
461///
462/// // Emit it — `retryable` comes from the declaration, not a guess.
463/// let payload: ErrorPayload = grant::error_codes::ROLE_NOT_RECOGNIZED.into();
464///
465/// // Or keep the wire string, in a `const` context.
466/// const ROLE_NOT_RECOGNIZED: &str = grant::error_codes::ROLE_NOT_RECOGNIZED.code;
467/// ```
468///
469/// `#[non_exhaustive]` so the declaration's remaining member (`meaning`) can be
470/// carried later without a breaking change.
471#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
472#[non_exhaustive]
473pub struct DeclaredErrorCode {
474    /// The fully qualified code as it appears on the wire, `<namespace>:<local>`
475    /// — e.g. `"acl/grant:roleNotRecognized"`. The namespace is the declaring
476    /// specification's slug or a family prefix of it (§8.5 rule 2).
477    pub code: &'static str,
478
479    /// The `retryable` value the specification declares for this code — the
480    /// value an emitter SHOULD send (§8.4).
481    pub retryable: bool,
482
483    /// The JSON Schema the specification declares for this error's `details`
484    /// member (`detailsSchema`, §7.3 item 9), or `None` when it declares none.
485    ///
486    /// Self-contained: a `$ref` the specification makes into a shared schema
487    /// file is resolved and carried inline, so the text compiles with no base
488    /// URI. An emitter can check the `details` it builds against it, rather than
489    /// against a copy it keeps by hand and that drifts when the specification
490    /// changes — with the `validate` feature, [`check_details`](Self::check_details).
491    pub details_schema: Option<&'static str>,
492}
493
494impl DeclaredErrorCode {
495    /// The constructor code generated outside this crate uses — by
496    /// `trust-tasks-build`, in an application, where the `#[non_exhaustive]`
497    /// struct cannot be written as a literal. Not a public API: a code built by
498    /// hand is exactly the undeclared literal this type exists to replace.
499    #[doc(hidden)]
500    pub const fn __from_declaration(
501        code: &'static str,
502        retryable: bool,
503        details_schema: Option<&'static str>,
504    ) -> Self {
505        Self {
506            code,
507            retryable,
508            details_schema,
509        }
510    }
511
512    /// The namespace before the colon: the declaring specification's slug, or
513    /// a family prefix of it.
514    pub fn namespace(&self) -> &'static str {
515        self.code
516            .split_once(':')
517            .map(|(namespace, _)| namespace)
518            .unwrap_or(self.code)
519    }
520
521    /// The local part after the colon, e.g. `"roleNotRecognized"`.
522    pub fn local(&self) -> &'static str {
523        self.code
524            .split_once(':')
525            .map(|(_, local)| local)
526            .unwrap_or("")
527    }
528
529    /// Check `details` against this code's declared
530    /// [`details_schema`](Self::details_schema).
531    ///
532    /// Succeeds when the specification declares no `detailsSchema`: it then
533    /// places no constraint on the member beyond its being an object (§8.2),
534    /// and there is nothing here to check. The §8.2.2 size bound is not a
535    /// schema constraint and is not checked here.
536    #[cfg(feature = "validate")]
537    #[cfg_attr(docsrs, doc(cfg(feature = "validate")))]
538    pub fn check_details(
539        &self,
540        details: &serde_json::Value,
541    ) -> Result<(), crate::validate::ValidationError> {
542        match self.details_schema {
543            Some(schema) => crate::validate::SHARED.check(schema, details),
544            None => Ok(()),
545        }
546    }
547
548    /// Whether `code` is this declared code.
549    ///
550    /// A method rather than `PartialEq<DeclaredErrorCode> for TrustTaskCode`:
551    /// a second `PartialEq` impl on `TrustTaskCode` makes every
552    /// `assert_eq!(code, StandardCode::X.into())` ambiguous, which would break
553    /// consumers that compile today.
554    ///
555    /// Compares namespace and local part, so a [`TrustTaskCode`] parsed off the
556    /// wire and one built with [`Payload::extended_code`](crate::Payload::extended_code)
557    /// both match.
558    pub fn matches(&self, code: &TrustTaskCode) -> bool {
559        match code {
560            TrustTaskCode::Extended { slug, local } => {
561                slug == self.namespace() && local == self.local()
562            }
563            TrustTaskCode::Standard(_) => false,
564        }
565    }
566}
567
568impl fmt::Display for DeclaredErrorCode {
569    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570        f.write_str(self.code)
571    }
572}
573
574impl From<DeclaredErrorCode> for TrustTaskCode {
575    /// Infallible: the generator refuses to emit a code that does not parse,
576    /// so a [`DeclaredErrorCode`] from `crate::specs` always converts.
577    fn from(declared: DeclaredErrorCode) -> Self {
578        TrustTaskCode::Extended {
579            slug: declared.namespace().to_string(),
580            local: declared.local().to_string(),
581        }
582    }
583}
584
585impl From<DeclaredErrorCode> for ErrorPayload {
586    /// An error payload carrying `declared`, with `retryable` set to the value
587    /// the specification declares rather than the §8.5 `taskFailed` default
588    /// [`ErrorPayload::new`] applies to an extended code it knows nothing about.
589    fn from(declared: DeclaredErrorCode) -> Self {
590        ErrorPayload::new(TrustTaskCode::from(declared)).with_retryable(declared.retryable)
591    }
592}
593
594/// Typed rejection conditions a conforming consumer raises while applying
595/// SPEC.md §7.2.
596///
597/// Each variant carries the context needed to render a meaningful operator
598/// message and maps to a single [`StandardCode`] from §8.3. The `From` impl
599/// produces an [`ErrorPayload`] with the matching code, retryable default,
600/// and a message derived from the variant's fields.
601///
602/// Use this on the consumer side to turn `?`-propagated errors from
603/// `resolve_parties` / `validate_basic` / your own task logic into a
604/// well-formed error response.
605#[derive(Debug, Clone, PartialEq, Eq, Error)]
606pub enum RejectReason {
607    /// The document did not validate against the framework or payload schema.
608    #[error("malformed request: {reason}")]
609    MalformedRequest {
610        /// Human-readable explanation, surfaced as `message` in the response.
611        reason: String,
612    },
613
614    /// The consumer does not implement this `type` URI.
615    #[error("unsupported type: {type_uri}")]
616    UnsupportedType {
617        /// The unsupported Type URI as it appeared in the document.
618        type_uri: String,
619    },
620
621    /// The consumer recognizes the type but not at this `MAJOR.MINOR`.
622    #[error("unsupported version: {type_uri}")]
623    UnsupportedVersion {
624        /// The unsupported Type URI as it appeared in the document.
625        type_uri: String,
626    },
627
628    /// The document's `expiresAt` was in the past.
629    #[error("document expired at {expires_at}")]
630    Expired {
631        /// The expiry timestamp carried in the rejected document.
632        expires_at: DateTime<Utc>,
633    },
634
635    /// The document falls outside the consumer's acceptance window
636    /// (SPEC.md §7.2, *Bounding the record*) — either because its `issuedAt`
637    /// is older than the window, or because it carries no timestamp the
638    /// consumer can place in one.
639    ///
640    /// Reported as `expired`: §8.3 defines no separate code, and the window is
641    /// the consumer's own bound on when it is still willing to act, which is
642    /// what `expired` means to the producer.
643    #[error("outside the consumer's acceptance window ({detail:?})")]
644    Stale {
645        /// Which of the two window failures occurred. For the operator's log;
646        /// both render the same wire message.
647        detail: crate::freshness::StaleReason,
648    },
649
650    /// The document's `id` matches one the consumer has already accepted, but
651    /// its content differs (SPEC.md §7.2 item 11).
652    ///
653    /// The later document **MUST NOT** be treated as a retry of the original.
654    #[error("id already accepted under different content (SPEC §7.2 item 11)")]
655    IdConflict,
656
657    /// A `proof` was required by the spec or consumer policy but was missing.
658    #[error("proof required but not present")]
659    ProofRequired,
660
661    /// A `proof` was present but failed verification.
662    #[error("proof verification failed: {reason}")]
663    ProofInvalid {
664        /// Human-readable explanation, surfaced as `message`.
665        reason: String,
666    },
667
668    /// The requesting party is not authorized to invoke this task.
669    #[error("permission denied: {reason}")]
670    PermissionDenied {
671        /// Human-readable explanation, surfaced as `message`.
672        reason: String,
673    },
674
675    /// The document's `recipient` is set but does not identify the consumer.
676    #[error("wrong recipient: in-band {in_band:?}, expected {expected:?}")]
677    WrongRecipient {
678        /// Value carried by the document's `recipient` member.
679        in_band: String,
680        /// VID of the consumer that received the document.
681        expected: String,
682    },
683
684    /// An in-band party identity contradicts the transport-derived value.
685    #[error(transparent)]
686    IdentityMismatch(#[from] ConsistencyError),
687
688    /// The task was attempted but could not be completed.
689    #[error("task failed: {reason}")]
690    TaskFailed {
691        /// Human-readable explanation, surfaced as `message`.
692        reason: String,
693        /// Optional spec-defined extension data; carried verbatim into
694        /// [`ErrorPayload::details`].
695        details: Option<Value>,
696    },
697
698    /// The consumer is temporarily unable to process the task.
699    #[error("temporarily unavailable")]
700    Unavailable {
701        /// Optional retry-after hint, surfaced as `retryAfter`.
702        retry_after: Option<DateTime<Utc>>,
703    },
704
705    /// The document marked an `ext` namespace critical (SPEC §4.5.2) that
706    /// the consumer does not recognize.
707    #[error("unsupported critical extension: {namespace}")]
708    UnsupportedExtension {
709        /// The first unrecognized namespace named in `extCritical`.
710        namespace: String,
711    },
712
713    /// The consumer encountered an unexpected internal failure.
714    #[error("internal error: {reason}")]
715    InternalError {
716        /// Human-readable explanation, surfaced as `message`.
717        reason: String,
718    },
719}
720
721impl RejectReason {
722    /// The [`StandardCode`] that corresponds to this rejection.
723    pub fn code(&self) -> StandardCode {
724        match self {
725            RejectReason::MalformedRequest { .. } => StandardCode::MalformedRequest,
726            RejectReason::UnsupportedType { .. } => StandardCode::UnsupportedType,
727            RejectReason::UnsupportedVersion { .. } => StandardCode::UnsupportedVersion,
728            RejectReason::Expired { .. } => StandardCode::Expired,
729            RejectReason::Stale { .. } => StandardCode::Expired,
730            RejectReason::IdConflict => StandardCode::IdConflict,
731            RejectReason::ProofRequired => StandardCode::ProofRequired,
732            RejectReason::ProofInvalid { .. } => StandardCode::ProofInvalid,
733            RejectReason::PermissionDenied { .. } => StandardCode::PermissionDenied,
734            RejectReason::WrongRecipient { .. } => StandardCode::WrongRecipient,
735            RejectReason::IdentityMismatch(_) => StandardCode::IdentityMismatch,
736            RejectReason::TaskFailed { .. } => StandardCode::TaskFailed,
737            RejectReason::Unavailable { .. } => StandardCode::Unavailable,
738            RejectReason::InternalError { .. } => StandardCode::InternalError,
739            RejectReason::UnsupportedExtension { .. } => StandardCode::UnsupportedExtension,
740        }
741    }
742
743    /// Message safe to attach to a wire-serialised [`ErrorPayload`].
744    ///
745    /// SPEC.md §8.1 (final paragraph) and §10.4 require error-response
746    /// messages to be free of consumer-side authentication context. The
747    /// [`Display`](std::fmt::Display) implementation (and `to_string()`)
748    /// is intentionally chatty for *diagnostic* purposes — it names both the
749    /// in-band and the transport-authenticated identities under
750    /// [`Self::IdentityMismatch`] and the consumer's own VID under
751    /// [`Self::WrongRecipient`], which makes log lines actionable but is
752    /// exactly the identity oracle a wire-exposed message must not provide.
753    ///
754    /// Variants whose `Display` is already consumer-side-neutral (`Expired`,
755    /// `ProofRequired`, …) return the same string the `Display` would. The
756    /// variants that would otherwise leak consumer-side state return a
757    /// sanitised constant.
758    ///
759    /// # `ProofInvalid` is sanitised
760    ///
761    /// SPEC §12.4 states the rule for `identityMismatch` and then generalises
762    /// it: "the same principle applies to every standard code: error messages
763    /// **SHOULD** be derived from the code identifier and the *Trust Task
764    /// specification*'s public vocabulary, not from consumer-side
765    /// authentication context."
766    ///
767    /// A `ProofInvalid { reason }` built from a verifier's error text is
768    /// exactly that context. Real strings a cryptosuite backend produces
769    /// include `resolve did:web:x: connection refused`, `verificationMethod …
770    /// not present in DID document`, and `verificationMethod is controlled by
771    /// {vm_did}, not the document issuer {issuer}`. Returned on the wire to an
772    /// *unauthenticated* sender — the proof did not verify, so the sender is
773    /// by definition not authenticated — those answer questions the sender
774    /// asked by choosing what to put in `proof`: which DIDs this consumer can
775    /// reach, whether a resolver is up, and what a DID document it fetched
776    /// contains. That is a resolver-reachability and DID-document oracle, free
777    /// of charge and at the sender's chosen rate.
778    ///
779    /// The `reason` remains on the [`Display`](std::fmt::Display) impl, which
780    /// is where the operator reads it.
781    pub fn wire_message(&self) -> String {
782        match self {
783            // Identity-bearing rejections: sanitised constants. The
784            // transport-derived and in-band values stay in logs only.
785            RejectReason::IdentityMismatch(_) => IDENTITY_MISMATCH_WIRE_MESSAGE.to_string(),
786            RejectReason::WrongRecipient { .. } => WRONG_RECIPIENT_WIRE_MESSAGE.to_string(),
787            // Verifier-internal detail: resolver reachability, DID document
788            // content, key-controller relationships. See the note above.
789            RejectReason::ProofInvalid { .. } => PROOF_INVALID_WIRE_MESSAGE.to_string(),
790            // The window is consumer policy; its size is not the producer's
791            // business and stating it invites a probe for the boundary.
792            RejectReason::Stale { .. } => STALE_WIRE_MESSAGE.to_string(),
793            // Names the store, its host, and its failure mode.
794            RejectReason::Unavailable { .. } => UNAVAILABLE_WIRE_MESSAGE.to_string(),
795            // All other variants carry no consumer-side authentication
796            // context — their `Display` is safe for the wire.
797            other => other.to_string(),
798        }
799    }
800
801    /// Build a `malformedRequest` from a `serde_json` failure without echoing
802    /// the deserializer's pointer into the document.
803    ///
804    /// `serde_json::Error::to_string()` renders as, for example, `missing
805    /// field 'subject' at line 1 column 214` or `unknown field 'admin',
806    /// expected one of …` — the member path, the offset, and sometimes the
807    /// full set of expected members. On the wire that describes the
808    /// consumer's internal type layout to anyone willing to send malformed
809    /// JSON, and the offsets describe how the consumer framed the body.
810    ///
811    /// This maps the error to its *category* — which is what a producer can
812    /// act on — and leaves the detail for the log. Transport bindings that
813    /// deserialize a body themselves should use this rather than
814    /// `format!("{e}")`, so one rule holds across the framework.
815    pub fn malformed_from_serde(err: &serde_json::Error) -> Self {
816        use serde_json::error::Category;
817        let reason = match err.classify() {
818            Category::Syntax => "document is not well-formed JSON",
819            Category::Eof => "document ended before a complete JSON value was read",
820            Category::Data => {
821                "document does not match the schema for its type \
822                 (a member is missing, unexpected, or of the wrong type)"
823            }
824            Category::Io => "document could not be read",
825        };
826        RejectReason::MalformedRequest {
827            reason: reason.to_string(),
828        }
829    }
830}
831
832/// Wire message for `identityMismatch` (SPEC §8.1, §10.4).
833pub const IDENTITY_MISMATCH_WIRE_MESSAGE: &str =
834    "in-band identity does not match transport-derived identity";
835
836/// Wire message for `wrongRecipient` — never naming the consumer's own VID.
837pub const WRONG_RECIPIENT_WIRE_MESSAGE: &str = "document recipient does not identify this consumer";
838
839/// Wire message for `proofInvalid`. Constant by design — see
840/// [`RejectReason::wire_message`].
841pub const PROOF_INVALID_WIRE_MESSAGE: &str = "proof verification failed";
842
843/// Wire message for a document outside the consumer's acceptance window.
844pub const STALE_WIRE_MESSAGE: &str =
845    "document is outside the consumer's acceptance window (SPEC §7.2)";
846
847/// Wire message for `unavailable`. Constant so a backing-store outage does not
848/// name the store on the wire.
849pub const UNAVAILABLE_WIRE_MESSAGE: &str = "temporarily unavailable";
850
851impl From<RejectReason> for ErrorPayload {
852    fn from(reason: RejectReason) -> Self {
853        let code = reason.code();
854        let mut payload = ErrorPayload::new(code).with_message(reason.wire_message());
855        match reason {
856            RejectReason::Unavailable {
857                retry_after: Some(when),
858            } => {
859                payload = payload.with_retry_after(when);
860            }
861            RejectReason::TaskFailed {
862                details: Some(d), ..
863            } => {
864                payload = payload.with_details(d);
865            }
866            _ => {}
867        }
868        payload
869    }
870}
871
872fn parse_standard(s: &str) -> Result<StandardCode, ParseCodeError> {
873    Ok(match s {
874        // Framework 0.2 lowerCamelCase spellings (emitted form) and the
875        // framework 0.1 snake_case spellings are both accepted, so a 0.2
876        // consumer can still read an error response from a 0.1 peer.
877        "malformedRequest" | "malformed_request" => StandardCode::MalformedRequest,
878        "unsupportedType" | "unsupported_type" => StandardCode::UnsupportedType,
879        "unsupportedVersion" | "unsupported_version" => StandardCode::UnsupportedVersion,
880        "expired" => StandardCode::Expired,
881        "proofRequired" | "proof_required" => StandardCode::ProofRequired,
882        "proofInvalid" | "proof_invalid" => StandardCode::ProofInvalid,
883        "permissionDenied" | "permission_denied" => StandardCode::PermissionDenied,
884        "wrongRecipient" | "wrong_recipient" => StandardCode::WrongRecipient,
885        "idConflict" | "id_conflict" => StandardCode::IdConflict,
886        "cancelled" | "canceled" => StandardCode::Cancelled,
887        "identityMismatch" | "identity_mismatch" => StandardCode::IdentityMismatch,
888        "taskFailed" | "task_failed" => StandardCode::TaskFailed,
889        "unavailable" => StandardCode::Unavailable,
890        "internalError" | "internal_error" => StandardCode::InternalError,
891        "unsupportedExtension" => StandardCode::UnsupportedExtension,
892        "indeterminate" => StandardCode::Indeterminate,
893        // A bare token that doesn't match a standard code is treated as a
894        // malformed extension (extensions require a colon-namespaced slug).
895        other => return Err(ParseCodeError::InvalidLocal(other.to_string())),
896    })
897}
898
899fn validate_slug(slug: &str) -> Result<(), ()> {
900    if slug.is_empty() {
901        return Err(());
902    }
903    for segment in slug.split('/') {
904        validate_segment(segment).ok_or(())?;
905    }
906    Ok(())
907}
908
909fn validate_segment(seg: &str) -> Option<()> {
910    let mut chars = seg.chars();
911    let first = chars.next()?;
912    if !first.is_ascii_lowercase() {
913        return None;
914    }
915    let mut prev_hyphen = false;
916    for c in chars {
917        match c {
918            'a'..='z' | '0'..='9' => prev_hyphen = false,
919            '-' => {
920                if prev_hyphen {
921                    return None;
922                }
923                prev_hyphen = true;
924            }
925            _ => return None,
926        }
927    }
928    if prev_hyphen {
929        return None;
930    }
931    Some(())
932}
933
934fn validate_local(local: &str) -> Result<(), ()> {
935    // The local portion of an extended code (`<slug>:<local>`) must start with
936    // a lowercase letter, then permits letters, digits, and underscores —
937    // matching the `errorCodes` pattern in spec.meta.schema.json. Uppercase is
938    // accepted so framework 0.2 lowerCamelCase locals (e.g. `documentRevoked`)
939    // parse; underscores are accepted so frozen framework 0.1 snake_case locals
940    // (e.g. `document_revoked`) still parse.
941    let mut chars = local.chars();
942    let first = chars.next().ok_or(())?;
943    if !first.is_ascii_lowercase() {
944        return Err(());
945    }
946    for c in chars {
947        match c {
948            'a'..='z' | 'A'..='Z' | '0'..='9' | '_' => {}
949            _ => return Err(()),
950        }
951    }
952    Ok(())
953}
954
955#[cfg(test)]
956mod tests {
957    use super::*;
958
959    #[test]
960    fn round_trips_standard_codes() {
961        for code in [
962            StandardCode::MalformedRequest,
963            StandardCode::UnsupportedType,
964            StandardCode::UnsupportedVersion,
965            StandardCode::Expired,
966            StandardCode::ProofRequired,
967            StandardCode::ProofInvalid,
968            StandardCode::PermissionDenied,
969            StandardCode::WrongRecipient,
970            StandardCode::IdentityMismatch,
971            StandardCode::TaskFailed,
972            StandardCode::Unavailable,
973            StandardCode::InternalError,
974            StandardCode::UnsupportedExtension,
975            StandardCode::Indeterminate,
976        ] {
977            let wire = code.as_str();
978            let parsed: TrustTaskCode = wire.parse().unwrap();
979            assert_eq!(parsed, TrustTaskCode::Standard(code));
980            assert_eq!(parsed.to_string(), wire);
981        }
982    }
983
984    #[test]
985    fn parses_legacy_snake_case_codes_and_re_emits_camel() {
986        // Framework 0.1 emitted snake_case codes; a 0.2 consumer must still
987        // parse those (lenient parse) while re-emitting the 0.2 camelCase form
988        // so the wire moves forward. This pins the whole 0.1-compat arm of
989        // `parse_standard`, which was otherwise untested.
990        let legacy = [
991            ("malformed_request", StandardCode::MalformedRequest),
992            ("unsupported_type", StandardCode::UnsupportedType),
993            ("unsupported_version", StandardCode::UnsupportedVersion),
994            ("proof_required", StandardCode::ProofRequired),
995            ("proof_invalid", StandardCode::ProofInvalid),
996            ("permission_denied", StandardCode::PermissionDenied),
997            ("wrong_recipient", StandardCode::WrongRecipient),
998            ("identity_mismatch", StandardCode::IdentityMismatch),
999            ("task_failed", StandardCode::TaskFailed),
1000            ("internal_error", StandardCode::InternalError),
1001        ];
1002        for (snake, code) in legacy {
1003            let parsed: TrustTaskCode = snake.parse().unwrap();
1004            assert_eq!(parsed, TrustTaskCode::Standard(code), "parse {snake}");
1005            // Re-emits the 0.2 camelCase spelling, not the snake input.
1006            assert_eq!(parsed.to_string(), code.as_str());
1007            assert_ne!(
1008                parsed.to_string(),
1009                snake,
1010                "{snake} should re-emit as camelCase"
1011            );
1012        }
1013    }
1014
1015    #[test]
1016    fn deserializes_legacy_snake_error_payload_and_re_emits_camel() {
1017        // A trust-task-error/0.1 payload with a snake_case code deserializes,
1018        // its code resolves to the camelCase StandardCode, and re-serializing
1019        // emits the 0.2 spelling.
1020        let payload: ErrorPayload =
1021            serde_json::from_str(r#"{"code":"proof_invalid","retryable":false}"#).unwrap();
1022        assert_eq!(payload.code, StandardCode::ProofInvalid.into());
1023        let out = serde_json::to_value(&payload).unwrap();
1024        assert_eq!(out["code"], "proofInvalid");
1025    }
1026
1027    #[test]
1028    fn parses_extension_code() {
1029        let parsed: TrustTaskCode = "trust-task-control:already_cancelled".parse().unwrap();
1030        assert_eq!(
1031            parsed,
1032            TrustTaskCode::Extended {
1033                slug: "trust-task-control".to_string(),
1034                local: "already_cancelled".to_string(),
1035            }
1036        );
1037        assert_eq!(parsed.to_string(), "trust-task-control:already_cancelled");
1038    }
1039
1040    #[test]
1041    fn parses_hierarchical_extension_code() {
1042        let parsed: TrustTaskCode = "acl/grant:permission_denied".parse().unwrap();
1043        assert!(matches!(
1044            parsed,
1045            TrustTaskCode::Extended { ref slug, ref local }
1046            if slug == "acl/grant" && local == "permission_denied"
1047        ));
1048    }
1049
1050    #[test]
1051    fn rejects_invalid_namespace() {
1052        let err: ParseCodeError = "Bad:code".parse::<TrustTaskCode>().unwrap_err();
1053        assert!(matches!(err, ParseCodeError::InvalidNamespace(s) if s == "Bad"));
1054    }
1055
1056    #[test]
1057    fn default_retryable_matches_spec_table() {
1058        assert!(!StandardCode::MalformedRequest.default_retryable());
1059        assert!(!StandardCode::Expired.default_retryable());
1060        assert!(StandardCode::Unavailable.default_retryable());
1061        assert!(StandardCode::InternalError.default_retryable());
1062        assert!(StandardCode::Indeterminate.default_retryable());
1063        assert!(!StandardCode::UnsupportedExtension.default_retryable());
1064    }
1065
1066    #[test]
1067    fn serializes_payload_as_json() {
1068        let payload = ErrorPayload {
1069            code: StandardCode::Expired.into(),
1070            in_response_to: None,
1071            message: Some("expired".to_string()),
1072            retryable: false,
1073            retry_after: None,
1074            details: None,
1075        };
1076        let json = serde_json::to_value(&payload).unwrap();
1077        assert_eq!(
1078            json,
1079            serde_json::json!({
1080                "code": "expired",
1081                "message": "expired",
1082                "retryable": false
1083            })
1084        );
1085    }
1086
1087    #[test]
1088    fn new_payload_takes_default_retryable() {
1089        let p = ErrorPayload::new(StandardCode::Expired);
1090        assert!(!p.retryable);
1091        let p = ErrorPayload::new(StandardCode::Unavailable);
1092        assert!(p.retryable);
1093    }
1094
1095    #[test]
1096    fn builder_methods_compose() {
1097        let when: DateTime<Utc> = "2026-05-17T00:00:00Z".parse().unwrap();
1098        let payload = ErrorPayload::new(StandardCode::Unavailable)
1099            .with_message("nodes draining")
1100            .with_retry_after(when)
1101            .with_details(serde_json::json!({ "drain_eta": "30s" }));
1102
1103        assert_eq!(payload.message.as_deref(), Some("nodes draining"));
1104        assert_eq!(payload.retry_after, Some(when));
1105        assert!(payload.retryable);
1106        assert!(payload.details.is_some());
1107    }
1108
1109    #[test]
1110    fn effective_code_falls_back_for_extensions() {
1111        // SPEC §8.5: unrecognized extension codes are treated as taskFailed
1112        // by consumers that don't implement the originating spec.
1113        let payload = ErrorPayload::new(TrustTaskCode::Extended {
1114            slug: "trust-task-control".into(),
1115            local: "alreadyCancelled".into(),
1116        });
1117        assert_eq!(payload.effective_code(), StandardCode::TaskFailed);
1118
1119        let payload = ErrorPayload::new(StandardCode::Expired);
1120        assert_eq!(payload.effective_code(), StandardCode::Expired);
1121    }
1122
1123    #[test]
1124    fn should_retry_at_respects_retryable_flag() {
1125        let now: DateTime<Utc> = "2026-05-17T12:00:00Z".parse().unwrap();
1126        let p = ErrorPayload::new(StandardCode::Expired);
1127        assert!(!p.should_retry_at(now));
1128    }
1129
1130    #[test]
1131    fn should_retry_at_waits_for_retry_after() {
1132        let later: DateTime<Utc> = "2026-05-17T12:00:00Z".parse().unwrap();
1133        let now: DateTime<Utc> = "2026-05-17T11:59:00Z".parse().unwrap();
1134        let p = ErrorPayload::new(StandardCode::Unavailable).with_retry_after(later);
1135        assert!(!p.should_retry_at(now));
1136        assert!(p.should_retry_at(later));
1137    }
1138
1139    #[test]
1140    fn reject_reason_maps_to_correct_code() {
1141        let cases: &[(RejectReason, StandardCode)] = &[
1142            (
1143                RejectReason::MalformedRequest { reason: "x".into() },
1144                StandardCode::MalformedRequest,
1145            ),
1146            (RejectReason::ProofRequired, StandardCode::ProofRequired),
1147            (
1148                RejectReason::Unavailable { retry_after: None },
1149                StandardCode::Unavailable,
1150            ),
1151        ];
1152        for (reason, expected) in cases {
1153            assert_eq!(reason.code(), *expected);
1154        }
1155    }
1156
1157    #[test]
1158    fn reject_reason_into_payload_carries_message_and_details() {
1159        let payload: ErrorPayload = RejectReason::Expired {
1160            expires_at: "2026-04-12T09:31:00Z".parse().unwrap(),
1161        }
1162        .into();
1163        assert_eq!(payload.code, StandardCode::Expired.into());
1164        assert!(payload.message.as_deref().unwrap().contains("2026-04-12"));
1165        assert!(!payload.retryable);
1166
1167        let payload: ErrorPayload = RejectReason::TaskFailed {
1168            reason: "downstream rejected".into(),
1169            details: Some(serde_json::json!({ "trace": "abc" })),
1170        }
1171        .into();
1172        assert!(payload.details.is_some());
1173    }
1174
1175    #[test]
1176    fn consistency_error_flows_into_reject_reason_via_question_mark() {
1177        fn go() -> Result<(), RejectReason> {
1178            Err(ConsistencyError::IssuerMismatch {
1179                in_band: "did:web:a".into(),
1180                transport: "did:web:b".into(),
1181            })?;
1182            Ok(())
1183        }
1184        let err = go().unwrap_err();
1185        assert_eq!(err.code(), StandardCode::IdentityMismatch);
1186    }
1187}