did-hosting-common 0.10.0

DID Hosting Common, Common methods and structs related to WebVH Content
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
use axum::http::{HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use tracing::{debug, warn};

/// Response header naming the service whose own limiter refused a request.
///
/// Part of the ecosystem-wide 429 contract: every refusal a service's *own*
/// limiter emits carries this header, so a client can tell it apart from a
/// `429` raised by a reverse proxy, a load balancer, or another service on the
/// path (the VTA sends `vta`, the VTC `vtc`, the mediator `mediator`). A `429`
/// without it is, by contract, unattributable. The VTI client reads it in
/// `vta_sdk::rate_limit`.
pub const RATE_LIMIT_SOURCE_HEADER: &str = "x-rate-limit-source";

/// This workspace's value for [`RATE_LIMIT_SOURCE_HEADER`]. Every binary here
/// (control, server, daemon, witness) is a DID host from the client's point of
/// view, and the operator guidance a client prints for `did-host` applies to
/// all of them.
pub const RATE_LIMIT_SOURCE: &str = "did-host";

/// Limiter name for the per-DID cap on concurrently pending auth challenges.
pub const LIMITER_PENDING_CHALLENGES_PER_DID: &str = "auth-challenge-pending-per-did";

/// Retry hint for a pending-challenge cap raised where the deployment's
/// configured timings are not known (the conversion from the canonical
/// `AuthError`): `AuthConfig::pending_challenge_retry_after_secs` over the
/// default `challenge_ttl` and `session_cleanup_interval`. Route handlers
/// substitute the configured values via [`AppError::with_retry_after`].
pub const DEFAULT_PENDING_CHALLENGE_RETRY_AFTER_SECS: u64 = 30 + 600;

#[derive(Debug, thiserror::Error)]
pub enum AppError {
    #[error("configuration error: {0}")]
    Config(String),

    #[error("io error: {0}")]
    Io(#[from] std::io::Error),

    #[error("store error: {0}")]
    Store(String),

    #[error("secret store error: {0}")]
    SecretStore(String),

    #[error("serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    #[error("internal error: {0}")]
    Internal(String),

    #[error("not found: {0}")]
    NotFound(String),

    #[error("conflict: {0}")]
    Conflict(String),

    #[error("authentication error: {0}")]
    Authentication(String),

    #[error("unauthorized: {0}")]
    Unauthorized(String),

    #[error("forbidden: {0}")]
    Forbidden(String),

    /// The caller is authenticated but the operation requires a higher
    /// assurance level (`acr == aal2`) than the session currently holds.
    /// Renders to 403 with the distinct body `{ "error":
    /// "step_up_required", "required_acr": "aal2" }` so the wallet can
    /// trigger a step-up ceremony rather than treating it as a plain
    /// permission denial.
    #[error("step-up required: {0}")]
    StepUpRequired(String),

    #[error("validation error: {0}")]
    Validation(String),

    #[error("quota exceeded: {0}")]
    QuotaExceeded(String),

    /// One of this service's own rate limiters refused the request.
    ///
    /// Renders to **429** with `x-rate-limit-source: did-host`, a
    /// `Retry-After` in seconds, and the body `{ "error": "rate_limited",
    /// "limiter": "<limiter>", "message": "...", "retryAfterSecs": N }`.
    /// Deliberately not `Validation`: a refusal rendered as `400` reads as a
    /// malformed request, so no client can recognise it as a limit and back
    /// off.
    #[error("rate limited ({limiter}): {message}")]
    RateLimited {
        /// Stable, machine-readable name of the limiter that refused, so an
        /// operator can tell which limit applies.
        limiter: &'static str,
        message: String,
        /// Seconds after which a retry can succeed. Rendered as at least 1.
        retry_after_secs: u64,
    },

    // ---- Trust-Tasks transport errors (REST `Trust-Task:` header) ----
    //
    // Surfaced by `super::trust_task` (router + extractor). The router
    // enforces exact-match at attach time; the response body for these
    // variants is structured (`{ "error": "<VariantName>", ... }`) so
    // callers can switch on the discriminant without parsing prose.
    /// `Trust-Task` header was absent on a route that requires it.
    /// Renders to 400 Bad Request with body `{ "error": "TrustTaskMissing" }`.
    #[error("Trust-Task header missing")]
    TrustTaskMissing,

    /// `Trust-Task` header was present but malformed (non-HTTPS, empty,
    /// or contained control characters). Carries the offending value so
    /// callers can debug. Renders to 400 with body
    /// `{ "error": "TrustTaskMalformed", "received": "..." }`.
    #[error("Trust-Task header malformed: {0}")]
    TrustTaskMalformed(String),

    /// `Trust-Task` header was well-formed but did not exact-match the
    /// route's registered task. Renders to 415 Unsupported Media Type
    /// with body `{ "error": "TrustTaskMismatch", "expected": "...",
    /// "received": "..." }`.
    #[error("Trust-Task header mismatch: expected {expected}, got {received:?}")]
    TrustTaskMismatch {
        expected: String,
        received: Option<String>,
    },

    /// Resolution attempted against a configured-but-disabled domain.
    /// Per `docs/multi-domain-spec.md` §3, renders to **503** with the
    /// maintenance-status JSON body `{ "status": "disabled", "domain":
    /// "<name>", "message"?, "eta"? }`. Distinct from `NotFound` —
    /// 404 means "we don't serve this", 503 means "we serve this but
    /// it's temporarily unavailable".
    #[error("domain '{domain}' is disabled")]
    DomainDisabled {
        domain: String,
        message: Option<String>,
    },

    /// An agent-name operation (`did_ops::set_agent_name` and friends) failed
    /// a name-specific precondition. Carries a typed [`AgentNameError`] so the
    /// Trust-Task and REST surfaces can map it to a spec error code without
    /// sniffing message prose — the same discipline `ValidationKind` follows.
    #[error("agent name error: {0}")]
    AgentName(#[from] AgentNameError),
}

/// Failure modes specific to the agent-name operations. Kept as a typed enum,
/// rather than folded into `Validation`/`Conflict`/`NotFound`, so each maps
/// one-to-one onto its `did-management/agent-name/*` spec error code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum AgentNameError {
    /// The requested name is on the host's reserved list (`@admin`,
    /// `@support`, …) → `name_reserved`.
    #[error("agent name is reserved")]
    Reserved,

    /// The name is already bound to a different DID on this domain →
    /// `name_taken`.
    #[error("agent name is already taken")]
    Taken,

    /// No such name is bound to this DID → `not_found`.
    #[error("agent name not found")]
    NotFound,

    /// An `enable` target is not in the disabled state → `not_disabled`.
    #[error("agent name is not disabled")]
    NotDisabled,

    /// A `disable` target is already disabled → `already_disabled`.
    #[error("agent name is already disabled")]
    AlreadyDisabled,

    /// The submitted document's `alsoKnownAs` does not match the operation's
    /// requirement — it must claim the name for `set`/`enable`, and must not
    /// for `remove`/`disable` → `also_known_as_mismatch`.
    #[error("submitted document's alsoKnownAs does not match the requested name")]
    AlsoKnownAsMismatch,
}

impl AgentNameError {
    /// The HTTP status this failure renders to.
    fn http_status(self) -> StatusCode {
        match self {
            AgentNameError::NotFound => StatusCode::NOT_FOUND,
            AgentNameError::Reserved
            | AgentNameError::Taken
            | AgentNameError::NotDisabled
            | AgentNameError::AlreadyDisabled => StatusCode::CONFLICT,
            AgentNameError::AlsoKnownAsMismatch => StatusCode::BAD_REQUEST,
        }
    }
}

/// Semantic tags for finer-grained error classification without string matching.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidationKind {
    InvalidLog,
    InvalidPath,
    InvalidWitness,
    Other,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuotaKind {
    Size,
    Count,
}

/// Conversion from the canonical auth-flow errors in
/// vti-common into did-hosting's `AppError`. Mirrors the
/// `From<AuthError> for vti_common::AppError` impl on the
/// VTI side — the canonical /auth/* handlers raise
/// `vti_common::AuthError` variants and each service's
/// `AppError` knows how to render them through its own
/// `IntoResponse` plumbing.
impl From<vti_common::auth::backend::AuthError> for AppError {
    fn from(e: vti_common::auth::backend::AuthError) -> Self {
        use vti_common::auth::backend::AuthError as A;
        match e {
            A::Forbidden | A::DidMethodRejected => AppError::Forbidden(e.to_string()),
            A::PendingChallengeLimitReached => AppError::RateLimited {
                limiter: LIMITER_PENDING_CHALLENGES_PER_DID,
                message: e.to_string(),
                retry_after_secs: DEFAULT_PENDING_CHALLENGE_RETRY_AFTER_SECS,
            },
            A::SessionNotFound
            | A::SessionStateMismatch
            | A::ChallengeMismatch
            | A::ChallengeExpired
            | A::SignerMismatch
            | A::StaleMessage
            | A::RefreshTokenInvalid
            | A::RefreshTokenExpired
            | A::SessionIdleTimeout
            | A::WrongRecipient { .. } => AppError::Authentication(e.to_string()),
            A::MissingRecipient => AppError::Validation(e.to_string()),
            A::AttestationFailed(msg) => AppError::Internal(format!("tee attestation: {msg}")),
            A::Internal(msg) => AppError::Internal(msg),
            // `AuthError` is `#[non_exhaustive]` since vti-common 0.20, so a
            // wildcard is mandatory here. A variant this build does not know
            // is still an auth-flow refusal: fail closed as a 401 rather than
            // surface it as a server fault.
            _ => AppError::Authentication(e.to_string()),
        }
    }
}

impl AppError {
    /// Replace the retry hint on an [`AppError::RateLimited`]; any other
    /// variant is returned unchanged. For route handlers that know the
    /// deployment's configured timings when the refusal was raised by code
    /// that does not (the canonical challenge handler).
    pub fn with_retry_after(self, secs: u64) -> Self {
        match self {
            AppError::RateLimited {
                limiter, message, ..
            } => AppError::RateLimited {
                limiter,
                message,
                retry_after_secs: secs,
            },
            other => other,
        }
    }

    /// Create a tagged validation error.
    pub fn validation(kind: ValidationKind, msg: impl Into<String>) -> Self {
        let mut s = msg.into();
        // Embed a machine-readable tag prefix for structured matching
        let tag = match kind {
            ValidationKind::InvalidLog => "[log]",
            ValidationKind::InvalidPath => "[path]",
            ValidationKind::InvalidWitness => "[witness]",
            ValidationKind::Other => "",
        };
        if !tag.is_empty() {
            s = format!("{tag} {s}");
        }
        AppError::Validation(s)
    }

    /// Classify a Validation error's kind by its tag prefix.
    pub fn validation_kind(&self) -> ValidationKind {
        match self {
            AppError::Validation(msg) => {
                if msg.starts_with("[log]") {
                    ValidationKind::InvalidLog
                } else if msg.starts_with("[path]") {
                    ValidationKind::InvalidPath
                } else if msg.starts_with("[witness]") {
                    ValidationKind::InvalidWitness
                } else {
                    ValidationKind::Other
                }
            }
            _ => ValidationKind::Other,
        }
    }

    /// Classify a QuotaExceeded error's kind by its content.
    pub fn quota_kind(&self) -> QuotaKind {
        match self {
            AppError::QuotaExceeded(msg) if msg.contains("size") => QuotaKind::Size,
            _ => QuotaKind::Count,
        }
    }
}

/// Maximum length of a user-facing error message in an HTTP response
/// body. Prevents accidental reflection of unbounded user input
/// (long DIDs, large pasted blobs) into logs and headers.
const MAX_USER_MESSAGE_LEN: usize = 256;

/// Strip ASCII control characters and cap length. Used for variants
/// whose `Display` includes user-supplied input — Validation, Conflict,
/// QuotaExceeded — to prevent log injection / response splitting via a
/// caller-controlled string and to bound response-body size.
fn sanitize_user_message(s: &str) -> String {
    let mut out: String = s.chars().filter(|c| !c.is_ascii_control()).collect();
    if out.len() > MAX_USER_MESSAGE_LEN {
        out.truncate(MAX_USER_MESSAGE_LEN);
        out.push('…');
    }
    out
}

impl AppError {
    /// Stable wire-level DIDComm protocol-error code for this `AppError`.
    ///
    /// Backed by `ValidationKind` tags rather than substring sniffing on
    /// the `Display` message, so a wording change in any
    /// `AppError::Validation("...")` literal doesn't silently re-route
    /// the protocol code. Both DIDComm dispatchers
    /// (`messaging::dispatch_did_op` and `routes/didcomm.rs::dispatch`)
    /// call this so the same error always produces the same wire code
    /// regardless of transport.
    ///
    /// The mapping:
    /// - `Unauthorized` / `Forbidden` → `e.p.did.unauthorized`
    /// - `QuotaExceeded(Size)` → `e.p.did.size-exceeded`
    /// - `QuotaExceeded(Count)` → `e.p.did.quota-exceeded`
    /// - `Conflict` → `e.p.did.path-unavailable`
    /// - `NotFound` → `e.p.did.mnemonic-not-found`
    /// - `Validation(InvalidLog)` → `e.p.did.invalid-log`
    /// - `Validation(InvalidPath)` → `e.p.did.path-invalid`
    /// - `Validation(InvalidWitness)` → `e.p.did.witness-invalid`
    /// - `Validation(Other)` → `e.p.did.validation-error`
    /// - everything else (5xx-shaped) → `e.p.did.internal-error`
    pub fn didcomm_code(&self) -> &'static str {
        match self {
            AppError::Unauthorized(_) | AppError::Forbidden(_) => "e.p.did.unauthorized",
            AppError::QuotaExceeded(_) => match self.quota_kind() {
                QuotaKind::Size => "e.p.did.size-exceeded",
                QuotaKind::Count => "e.p.did.quota-exceeded",
            },
            AppError::Conflict(_) => "e.p.did.path-unavailable",
            AppError::NotFound(_) => "e.p.did.mnemonic-not-found",
            AppError::Validation(_) => match self.validation_kind() {
                ValidationKind::InvalidLog => "e.p.did.invalid-log",
                ValidationKind::InvalidPath => "e.p.did.path-invalid",
                ValidationKind::InvalidWitness => "e.p.did.witness-invalid",
                ValidationKind::Other => "e.p.did.validation-error",
            },
            // Legacy did-management DIDComm codes for agent-name failures. The
            // dedicated agent-name Trust Tasks (PR 4) carry their own spec
            // error codes in the response; these keep a stray agent-name error
            // on the old dispatch path from collapsing to `internal-error`.
            AppError::AgentName(e) => match e {
                AgentNameError::NotFound => "e.p.did.mnemonic-not-found",
                AgentNameError::Reserved => "e.p.did.path-invalid",
                AgentNameError::Taken => "e.p.did.path-unavailable",
                AgentNameError::NotDisabled
                | AgentNameError::AlreadyDisabled
                | AgentNameError::AlsoKnownAsMismatch => "e.p.did.validation-error",
            },
            _ => "e.p.did.internal-error",
        }
    }

    /// Stable public message intended for HTTP responses. Decoupled from
    /// `Display` (which tracing/logging uses) so the wire-level contract
    /// doesn't drift when an `AppError(...)` literal's wording changes
    /// elsewhere.
    ///
    /// Variants that name internal identifiers (`Forbidden` may carry a
    /// DID or ACL reason; `NotFound` may include a mnemonic) collapse
    /// to a fixed string. Variants that are user-input-shaped
    /// (`Validation`, `Conflict`, `QuotaExceeded`) pass the message
    /// through `sanitize_user_message` so a caller can't get arbitrary
    /// control characters echoed back. 5xx variants never reach this
    /// path (the response builder short-circuits to a generic body).
    pub fn user_message(&self) -> String {
        match self {
            AppError::NotFound(_) => "not found".into(),
            AppError::Authentication(_) => "authentication failed".into(),
            AppError::Unauthorized(_) => "unauthorized".into(),
            AppError::Forbidden(_) => "forbidden".into(),
            AppError::StepUpRequired(_) => "step_up_required".into(),
            AppError::Validation(msg) => sanitize_user_message(msg),
            AppError::Conflict(msg) => sanitize_user_message(msg),
            AppError::QuotaExceeded(msg) => sanitize_user_message(msg),
            AppError::RateLimited { message, .. } => sanitize_user_message(message),
            // Fixed, name-free strings — safe to surface verbatim.
            AppError::AgentName(e) => e.to_string(),
            // 5xx variants — covered by the server-error branch in
            // into_response — but return a stable string here too in
            // case anyone calls `user_message()` directly.
            _ => "internal error".into(),
        }
    }
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let status = match &self {
            AppError::Config(_) => StatusCode::INTERNAL_SERVER_ERROR,
            AppError::Io(_) => StatusCode::INTERNAL_SERVER_ERROR,
            AppError::Store(_) => StatusCode::INTERNAL_SERVER_ERROR,
            AppError::SecretStore(_) => StatusCode::INTERNAL_SERVER_ERROR,
            AppError::Serialization(_) => StatusCode::INTERNAL_SERVER_ERROR,
            AppError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
            AppError::NotFound(_) => StatusCode::NOT_FOUND,
            AppError::Conflict(_) => StatusCode::CONFLICT,
            AppError::Authentication(_) => StatusCode::UNAUTHORIZED,
            AppError::Unauthorized(_) => StatusCode::UNAUTHORIZED,
            AppError::Forbidden(_) => StatusCode::FORBIDDEN,
            AppError::StepUpRequired(_) => StatusCode::FORBIDDEN,
            AppError::Validation(_) => StatusCode::BAD_REQUEST,
            AppError::QuotaExceeded(_) => StatusCode::FORBIDDEN,
            AppError::RateLimited { .. } => StatusCode::TOO_MANY_REQUESTS,
            AppError::TrustTaskMissing => StatusCode::BAD_REQUEST,
            AppError::TrustTaskMalformed(_) => StatusCode::BAD_REQUEST,
            AppError::TrustTaskMismatch { .. } => StatusCode::UNSUPPORTED_MEDIA_TYPE,
            AppError::DomainDisabled { .. } => StatusCode::SERVICE_UNAVAILABLE,
            AppError::AgentName(e) => e.http_status(),
        };

        // DomainDisabled is a 5xx but the body is part of the public
        // contract (status / domain / message) so clients can render a
        // maintenance page. Fall through to the structured-body branch
        // below; everything else 5xx collapses to a generic message.
        if status.is_server_error() && !matches!(self, AppError::DomainDisabled { .. }) {
            warn!(status = %status.as_u16(), error = %self, "server error");
            let body = serde_json::json!({ "error": "internal server error" });
            return (status, axum::Json(body)).into_response();
        }

        debug!(status = %status.as_u16(), error = %self, "client error");

        if let AppError::RateLimited {
            limiter,
            message,
            retry_after_secs,
        } = &self
        {
            // `Retry-After: 0` would invite an immediate retry into the same
            // refusal; one second is the smallest honest hint.
            let retry_after_secs = (*retry_after_secs).max(1);
            let body = serde_json::json!({
                "error": "rate_limited",
                "limiter": limiter,
                "message": sanitize_user_message(message),
                "retryAfterSecs": retry_after_secs,
            });
            let mut response = (status, axum::Json(body)).into_response();
            let headers = response.headers_mut();
            headers.insert(
                RATE_LIMIT_SOURCE_HEADER,
                HeaderValue::from_static(RATE_LIMIT_SOURCE),
            );
            headers.insert(
                axum::http::header::RETRY_AFTER,
                HeaderValue::from(retry_after_secs),
            );
            return response;
        }

        // Trust-Task variants use a structured body so callers can switch
        // on the discriminant. Match the VTI canonical impl's shape so
        // the parity harness in T9 can assert byte-equivalent responses.
        let body = match &self {
            AppError::TrustTaskMissing => serde_json::json!({ "error": "TrustTaskMissing" }),
            AppError::TrustTaskMalformed(received) => serde_json::json!({
                "error": "TrustTaskMalformed",
                "received": received,
            }),
            AppError::TrustTaskMismatch { expected, received } => serde_json::json!({
                "error": "TrustTaskMismatch",
                "expected": expected,
                "received": received,
            }),
            AppError::DomainDisabled { domain, message } => serde_json::json!({
                "status": "disabled",
                "domain": domain,
                "message": message,
            }),
            AppError::StepUpRequired(_) => serde_json::json!({
                "error": "step_up_required",
                "required_acr": "aal2",
            }),
            _ => serde_json::json!({ "error": self.user_message() }),
        };
        (status, axum::Json(body)).into_response()
    }
}

#[cfg(test)]
mod response_tests {
    use super::*;

    #[test]
    fn forbidden_always_collapses_to_fixed_string() {
        // Pre-fix behaviour: substring `"ACL"` redacted, but
        // "not the owner of this DID" leaked through. Now both collapse.
        let leaky = AppError::Forbidden("not the owner of this DID".into());
        assert_eq!(leaky.user_message(), "forbidden");
        let acl = AppError::Forbidden("DID not in the ACL: did:web:bob".into());
        assert_eq!(acl.user_message(), "forbidden");
    }

    #[test]
    fn validation_strips_control_chars() {
        // Caller submits `did:web:tenant\nrest` as new_owner; the
        // resulting Validation message would otherwise reflect the
        // newline back into the response body.
        let err = AppError::Validation("bad input: did:web:t\nrest".into());
        let msg = err.user_message();
        assert!(!msg.contains('\n'));
        assert!(!msg.contains('\r'));
    }

    #[test]
    fn validation_caps_length() {
        let huge = "x".repeat(MAX_USER_MESSAGE_LEN + 100);
        let err = AppError::Validation(huge);
        let msg = err.user_message();
        assert!(msg.chars().count() <= MAX_USER_MESSAGE_LEN + 1); // +1 for '…'
        assert!(msg.ends_with('…'));
    }

    #[test]
    fn validation_preserves_short_messages_unchanged() {
        let err = AppError::Validation("path 'foo' is already taken".into());
        assert_eq!(err.user_message(), "path 'foo' is already taken");
    }

    #[tokio::test]
    async fn rate_limited_renders_the_429_contract() {
        use http_body_util::BodyExt;

        let response = AppError::RateLimited {
            limiter: "auth-challenge-per-ip",
            message: "slow down".into(),
            retry_after_secs: 17,
        }
        .into_response();
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(response.headers()["x-rate-limit-source"], "did-host");
        assert_eq!(response.headers()["retry-after"], "17");
        assert_eq!(response.headers()["content-type"], "application/json");
        let bytes = response.into_body().collect().await.unwrap().to_bytes();
        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(
            body,
            serde_json::json!({
                "error": "rate_limited",
                "limiter": "auth-challenge-per-ip",
                "message": "slow down",
                "retryAfterSecs": 17,
            })
        );
    }

    /// A zero hint would invite an immediate retry into the same refusal.
    #[test]
    fn rate_limited_retry_after_is_at_least_one_second() {
        let response = AppError::RateLimited {
            limiter: "x",
            message: String::new(),
            retry_after_secs: 0,
        }
        .into_response();
        assert_eq!(response.headers()["retry-after"], "1");
    }

    #[test]
    fn pending_challenge_limit_is_a_rate_limit_not_a_validation_error() {
        let err: AppError =
            vti_common::auth::backend::AuthError::PendingChallengeLimitReached.into();
        assert!(matches!(
            err,
            AppError::RateLimited {
                limiter: LIMITER_PENDING_CHALLENGES_PER_DID,
                ..
            }
        ));
        assert!(matches!(
            err.with_retry_after(42),
            AppError::RateLimited {
                retry_after_secs: 42,
                ..
            }
        ));
        assert!(matches!(
            AppError::Conflict("c".into()).with_retry_after(5),
            AppError::Conflict(_)
        ));
    }

    #[test]
    fn not_found_does_not_leak_mnemonic() {
        let err = AppError::NotFound("DID not found: super-secret-mnemonic".into());
        assert_eq!(err.user_message(), "not found");
    }
}