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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! Helper for unpacking DIDComm signed (JWS) messages using DID resolution.
//!
//! The v0.13 `affinidi-messaging-didcomm` crate removed the async `Message::unpack_string`
//! method that internally resolved DIDs. This module provides an equivalent by:
//!
//! 1. Parsing the JWS protected header to extract the signer's key ID (kid).
//! 2. Resolving the DID document via `DIDCacheClient` to obtain the Ed25519 verifying key.
//! 3. Calling the low-level `unpack()` function with the resolved public key.

use affinidi_did_resolver_cache_sdk::DIDCacheClient;
use affinidi_tdk::did_common::DocumentExt;
use affinidi_tdk::didcomm::Message;
use affinidi_tdk::didcomm::UnpackResult;
use affinidi_tdk::didcomm::jws::envelope::{Jws, JwsProtectedHeader};
use affinidi_tdk::didcomm::message::unpack;
use base64::Engine;

use super::error::AppError;

/// Maximum age of a DIDComm message accepted by `unpack_signed`, in
/// seconds. Messages older than this are rejected as stale; replay
/// caches use the same window as their TTL so a message that's still
/// fresh enough to accept is still tracked for replay detection.
pub const FRESHNESS_WINDOW_SECS: u64 = 300;

/// How far into the future a signed message or document's timestamp may sit
/// and still be accepted, absorbing ordinary clock skew between peers.
pub const FUTURE_SKEW_SECS: u64 = 60;

/// How long a replay cache must remember an accepted `(sender, id)` pair.
///
/// Not just [`FRESHNESS_WINDOW_SECS`]: a message stamped at the edge of the
/// future tolerance stays inside the freshness window for
/// `FRESHNESS_WINDOW_SECS + FUTURE_SKEW_SECS` after it was first accepted, so
/// a cache that forgot it sooner would accept it a second time.
pub const REPLAY_WINDOW_SECS: u64 = FRESHNESS_WINDOW_SECS + FUTURE_SKEW_SECS;

/// Extract the signer's key ID from a JWS protected header without verifying the signature.
///
/// Rejects multi-signature JWS envelopes outright — the threat model assumes a
/// single signer and accepting additional signatures silently would create
/// surprising states (which signature did we verify? which one bound the
/// `from` field?). If multi-sig becomes a real requirement, the decision
/// belongs in a separate, deliberate API.
fn extract_signer_kid(jws_str: &str) -> Result<String, AppError> {
    let jws: Jws = serde_json::from_str(jws_str)
        .map_err(|e| AppError::Authentication(format!("invalid JWS JSON: {e}")))?;

    if jws.signatures.is_empty() {
        return Err(AppError::Authentication("JWS has no signatures".into()));
    }
    if jws.signatures.len() > 1 {
        return Err(AppError::Authentication(format!(
            "JWS has {} signatures; only single-signer envelopes are accepted",
            jws.signatures.len()
        )));
    }

    let sig = &jws.signatures[0];

    let header_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(&sig.protected)
        .map_err(|e| AppError::Authentication(format!("invalid JWS protected header: {e}")))?;

    let header: JwsProtectedHeader = serde_json::from_slice(&header_bytes)
        .map_err(|e| AppError::Authentication(format!("invalid JWS header JSON: {e}")))?;

    header
        .kid
        .ok_or_else(|| AppError::Authentication("JWS header missing kid".into()))
}

/// Resolve an Ed25519 verifying key from a DID document given a key ID (DID URL fragment).
///
/// Rejects verification methods whose `type` declares them as X25519
/// key-agreement keys. Ed25519 (signing) and X25519 (DH) keys are both 32
/// bytes, so the length check below would not catch a kid that points at
/// the wrong key type — the operator would just see a mysterious "unpack
/// failed" downstream. An explicit type-class check produces a precise
/// error and avoids confusing-key-purpose attacks where a DID document
/// publishes both signing and key-agreement keys under predictable
/// fragments.
async fn resolve_verifying_key(
    did_resolver: &DIDCacheClient,
    kid: &str,
) -> Result<[u8; 32], AppError> {
    let base_did = kid.split('#').next().unwrap_or(kid);

    let resolved = did_resolver
        .resolve(base_did)
        .await
        .map_err(|e| AppError::Authentication(format!("failed to resolve DID {base_did}: {e}")))?;

    // Signing in is authentication, so the key must be one the DID lists under
    // `authentication` — not merely any key in its document (an
    // `assertionMethod` key is for attestations, a `keyAgreement` key for
    // encryption).
    let fragment = kid.find('#').map(|i| &kid[i..]);
    let refers = |id: &str| id == kid || fragment.is_some_and(|f| id == f);
    let listed = resolved.doc.authentication.iter().any(|r| {
        match r {
        affinidi_tdk::did_common::verification_method::VerificationRelationship::Reference(id) => {
            refers(id)
        }
        affinidi_tdk::did_common::verification_method::VerificationRelationship::VerificationMethod(
            m,
        ) => refers(m.id.as_str()),
        _ => false,
    }
    });
    if !listed {
        return Err(AppError::Authentication(format!(
            "verification method {kid} is not an authentication key of {base_did}"
        )));
    }

    let vm = resolved.doc.get_verification_method(kid).ok_or_else(|| {
        AppError::Authentication(format!(
            "verification method {kid} not found in DID document"
        ))
    })?;

    // Reject obvious key-agreement (X25519) types. We don't whitelist Ed25519
    // types because the spec admits several names (Ed25519VerificationKey2018,
    // Ed25519VerificationKey2020, Multikey with a z6Mk… prefix, JsonWebKey2020
    // with crv:Ed25519) — but X25519 has narrow, well-known type names that
    // are unambiguous to refuse.
    let vm_type = vm.type_.as_str();
    if matches!(
        vm_type,
        "X25519KeyAgreementKey2020" | "X25519KeyAgreementKey2019"
    ) {
        return Err(AppError::Authentication(format!(
            "verification method {kid} is an X25519 key-agreement key; expected an Ed25519 signing key"
        )));
    }

    let pk_bytes = vm
        .get_public_key_bytes()
        .map_err(|e| AppError::Authentication(format!("failed to get public key bytes: {e}")))?;

    pk_bytes
        .try_into()
        .map_err(|_| AppError::Authentication("public key must be 32 bytes".into()))
}

/// Refuse a signed sign-in message not addressed to this service
/// (affinidi-webvh-service#207; the rule is SPEC §7.2 item 5, as in VTI #1638).
///
/// A JWS-signed message is readable and forwardable by anyone holding it — the
/// signature proves who wrote it, not who it was for. Without this check a
/// service the holder signed in to could relay the message to this one and be
/// issued a session as the holder. So the message must name exactly one
/// recipient, and it must be this service's own DID, by exact string equality.
///
/// Call it on every sign-in path that accepts a signed (not encrypted)
/// envelope, before the canonical handler runs.
pub fn require_addressed_to(msg: &Message, own_did: Option<&str>) -> Result<(), AppError> {
    let own = own_did.ok_or_else(|| {
        AppError::Config(
            "server_did not configured; a signed sign-in cannot be addressed to this service"
                .into(),
        )
    })?;
    match msg.to.as_deref() {
        None | Some([]) => Err(AppError::Validation(
            "malformedRequest: a signed sign-in message must name this service in `to`".into(),
        )),
        Some([one]) if one == own => Ok(()),
        Some(to) => Err(AppError::Authentication(format!(
            "wrongRecipient: this message is addressed to {}, not to this service ({own})",
            to.join(", ")
        ))),
    }
}

/// Unpack a DIDComm signed (JWS) message and verify the JWS signer matches `msg.from`.
///
/// Resolves the signer's public key from the JWS protected-header `kid`, verifies
/// the signature, then asserts that the verified signer's DID equals the message's
/// `from` DID (compared on base, ignoring `#fragment`). Returns the unpacked `Message`
/// and the *verified* signer base DID.
///
/// **Security:** Callers must use the returned base DID for sender identification.
/// Trusting `msg.from` directly allows an attacker who controls any DID to forge the
/// `from` field while signing with their own key.
///
/// The message must:
/// - Be signed (plaintext and encrypted-only payloads are rejected — those would not
///   carry a verified signer identity).
/// - Carry a `from` field whose base DID matches the JWS signer.
/// - Have a `created_time` inside the 5-minute freshness window (with 60s future tolerance).
pub async fn unpack_signed(
    input: &str,
    did_resolver: &DIDCacheClient,
) -> Result<(Message, String), AppError> {
    let kid = extract_signer_kid(input)?;
    let verifying_key = resolve_verifying_key(did_resolver, &kid).await?;

    // Verify under the resolved key *as the key of `kid`*: the reported
    // `signer_kid` is then the key id the signature was checked against.
    let verify_key = affinidi_tdk::didcomm::jws::verify::VerifyKey::Ed25519(verifying_key);
    let signer = affinidi_tdk::didcomm::SignerKey::new(&kid, &verify_key);
    let result = unpack::unpack_bound(input, None, None, None, Some(signer))
        .map_err(|e| AppError::Authentication(format!("failed to unpack message: {e}")))?;

    let (message, signer_kid) = match result {
        UnpackResult::Signed {
            message,
            signer_kid,
        } => (message, signer_kid),
        UnpackResult::Plaintext(_) => {
            return Err(AppError::Authentication(
                "message is not signed; refusing to authenticate plaintext".into(),
            ));
        }
        UnpackResult::Encrypted { .. } => {
            return Err(AppError::Authentication(
                "message is encrypted-only; expected JWS-signed envelope".into(),
            ));
        }
        // `UnpackResult` is `#[non_exhaustive]` as of didcomm 0.14: reject any
        // future envelope shape we don't explicitly accept (fail closed — this
        // is an authentication path that must only trust verified JWS signers).
        _ => {
            return Err(AppError::Authentication(
                "unsupported DIDComm envelope shape; expected JWS-signed message".into(),
            ));
        }
    };

    // Signer kid is always present for Signed results; the resolver already used it.
    let signer_kid = signer_kid.unwrap_or(kid);
    let signer_base = signer_kid
        .split('#')
        .next()
        .unwrap_or(&signer_kid)
        .to_string();

    let claimed_from = message
        .from
        .as_deref()
        .ok_or_else(|| AppError::Authentication("signed message is missing `from` field".into()))?;
    let claimed_base = claimed_from.split('#').next().unwrap_or(claimed_from);
    if signer_base != claimed_base {
        return Err(AppError::Authentication(
            "JWS signer does not match message `from` DID".into(),
        ));
    }

    // `created_time` is REQUIRED, not optional. Freshness and the DIDComm
    // replay cache are a matched pair (the cache TTL equals the freshness
    // window and prunes entries past it), so a signed envelope with no
    // `created_time` would never become "stale" and could be replayed to
    // re-trigger a state-changing DID op once its replay-cache entry aged out.
    // `created_time` is inside the JWS-signed payload, so an attacker can't add
    // or strip it — every compliant sender sets it (this service's own clients,
    // and the VTA's webvh client, all do), so treating its absence as a
    // rejection closes the gap without refusing any real client.
    let created_time = message.created_time.ok_or_else(|| {
        AppError::Authentication(
            "signed message is missing `created_time` (required for freshness/replay protection)"
                .into(),
        )
    })?;
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    if now.saturating_sub(created_time) > FRESHNESS_WINDOW_SECS {
        return Err(AppError::Authentication(
            "message too old (created_time exceeds 5-minute window)".into(),
        ));
    }
    if created_time > now + FUTURE_SKEW_SECS {
        return Err(AppError::Authentication(
            "message created_time is in the future".into(),
        ));
    }

    Ok((message, signer_base))
}

// ---------------------------------------------------------------------------
// SIOPv2 self-issued `id_token` verification
// ---------------------------------------------------------------------------

/// Verified claims of a SIOPv2 self-issued `id_token`.
///
/// Only constructable via [`verify_siop_id_token`]. A function that
/// takes this type is guaranteed to be looking at a token whose
/// signature was verified against the `iss` DID's resolved Ed25519
/// authentication key, with `iss == sub`. Caller-relevant claims are
/// surfaced eagerly so consumers don't re-parse the JWS.
#[derive(Debug, Clone)]
pub struct VerifiedSiopIdToken {
    /// `iss` (== `sub`): the self-issued `did:key`. This is the
    /// authenticated subject DID.
    pub issuer: String,
    /// `aud`: the relying-party identifier the wallet targeted.
    pub audience: String,
    /// `nonce`: must be matched against the challenge by the caller.
    pub nonce: String,
    /// `iat`: issued-at (unix seconds).
    pub issued_at: u64,
    /// `exp`: expiry (unix seconds).
    pub expires_at: u64,
}

/// Pre-verification view of the `id_token` payload JSON. Anyone with
/// the compact JWS can produce this; nothing here is trustworthy until
/// the signature is verified.
#[derive(serde::Deserialize)]
struct SiopClaims {
    iss: Option<String>,
    sub: Option<String>,
    aud: Option<String>,
    nonce: Option<String>,
    iat: Option<u64>,
    exp: Option<u64>,
}

/// Decode the multibase tail of an Ed25519 `did:key` to its raw 32-byte
/// public key. Rejects anything that isn't `did:key:z…` with the
/// multicodec `0xed01` (Ed25519) prefix followed by exactly 32 bytes.
fn ed25519_pubkey_from_did_key(did: &str) -> Result<[u8; 32], AppError> {
    let multibase = did
        .strip_prefix("did:key:")
        .ok_or_else(|| AppError::Authentication("id_token `iss` is not a did:key".into()))?;
    // did:key uses base58btc multibase (`z` prefix). `multibase::decode`
    // handles the prefix and returns the raw multicodec-prefixed bytes.
    let (_base, bytes) = multibase::decode(multibase)
        .map_err(|e| AppError::Authentication(format!("id_token `iss` multibase invalid: {e}")))?;
    // Multicodec 0xed01 (varint) = Ed25519 public key, then 32 key bytes.
    let key = bytes.strip_prefix(&[0xed, 0x01]).ok_or_else(|| {
        AppError::Authentication("id_token `iss` is not an Ed25519 did:key".into())
    })?;
    key.try_into()
        .map_err(|_| AppError::Authentication("id_token `iss` Ed25519 key is not 32 bytes".into()))
}

/// Verify a SIOPv2 self-issued `id_token` (compact EdDSA JWS).
///
/// Performs the cryptographic security checks; envelope/session/TTL
/// checks (`nonce` ↔ challenge, session state, `iss` ↔ session DID,
/// `aud` ↔ RP id) are the caller's responsibility because they need
/// session and config state this module does not own.
///
/// Steps:
/// 1. Split the compact JWS into `header.payload.signature`.
/// 2. Parse the payload JSON (pre-verify) and require `iss` present and
///    `iss == sub`.
/// 3. Resolve the authentication key for `iss`. The `kid` is honoured
///    for the verification-method lookup (resolved via
///    [`resolve_verifying_key`], the same DID-resolve + Ed25519
///    key-extraction primitive `unpack_signed` uses), and the resolved
///    key's base DID must equal `iss`. Works for any DID method the
///    resolver supports — `did:key` (in-tree) and `did:webvh` (DID
///    document fetched) alike. For `did:key`, which is self-certifying,
///    the resolved key is *additionally* pinned against the key encoded
///    in the DID string, so a header pointing at a foreign DID's key
///    cannot impersonate the `iss`. For document-based methods the
///    resolved DID document is the authority.
/// 4. EdDSA-verify the signature over the ASCII `header.payload`.
///
/// Returns the [`VerifiedSiopIdToken`] with eagerly-parsed claims.
pub async fn verify_siop_id_token(
    id_token: &str,
    did_resolver: &DIDCacheClient,
) -> Result<VerifiedSiopIdToken, AppError> {
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use ed25519_dalek::{Signature, Verifier, VerifyingKey};

    // 1. Split the compact JWS.
    let mut parts = id_token.split('.');
    let (header_b64, payload_b64, sig_b64) =
        match (parts.next(), parts.next(), parts.next(), parts.next()) {
            (Some(h), Some(p), Some(s), None) => (h, p, s),
            _ => {
                return Err(AppError::Authentication(
                    "id_token is not a compact JWS (header.payload.signature)".into(),
                ));
            }
        };

    // 2. Parse the payload JSON (pre-verify) and check iss == sub.
    let payload_bytes = URL_SAFE_NO_PAD
        .decode(payload_b64)
        .map_err(|e| AppError::Authentication(format!("id_token payload not base64url: {e}")))?;
    let claims: SiopClaims = serde_json::from_slice(&payload_bytes)
        .map_err(|e| AppError::Authentication(format!("id_token payload not JSON: {e}")))?;

    let iss = claims
        .iss
        .ok_or_else(|| AppError::Authentication("id_token missing `iss`".into()))?;
    let sub = claims
        .sub
        .ok_or_else(|| AppError::Authentication("id_token missing `sub`".into()))?;
    if iss != sub {
        return Err(AppError::Authentication(
            "id_token `iss` does not equal `sub`".into(),
        ));
    }

    // 3. Resolve the Ed25519 key. The header `kid` drives the
    //    verification-method lookup; the resolved key's base DID must be
    //    `iss`. We additionally pin against the key encoded directly in
    //    the `iss` did:key so a `kid` pointing at a foreign DID can't
    //    sneak past resolution.
    let kid = extract_signer_kid_compact(header_b64)?;
    let kid_base = kid.split('#').next().unwrap_or(&kid);
    if kid_base != iss {
        return Err(AppError::Authentication(
            "id_token header `kid` DID does not match `iss`".into(),
        ));
    }
    // Resolve `iss`'s authentication key. The resolver handles any DID
    // method it supports — `did:key` in-tree, `did:webvh` by fetching
    // the DID document, etc. For `did:key` (self-certifying) we
    // additionally pin the resolved key against the key encoded directly
    // in the DID string, so a `kid` can't point at a foreign key. For
    // document-based methods (`did:webvh`, `did:peer`) the resolved DID
    // document is the authority — there is no in-string key to pin to.
    let resolved_key = resolve_verifying_key(did_resolver, &kid).await?;
    if iss.starts_with("did:key:") {
        let did_key_pub = ed25519_pubkey_from_did_key(&iss)?;
        if resolved_key != did_key_pub {
            return Err(AppError::Authentication(
                "id_token `iss` did:key does not match its resolved authentication key".into(),
            ));
        }
    }

    // 4. EdDSA-verify the signature over the ASCII `header.payload`
    //    against the resolved authentication key.
    let verifying_key = VerifyingKey::from_bytes(&resolved_key)
        .map_err(|e| AppError::Authentication(format!("invalid Ed25519 public key: {e}")))?;
    let sig_bytes = URL_SAFE_NO_PAD
        .decode(sig_b64)
        .map_err(|e| AppError::Authentication(format!("id_token signature not base64url: {e}")))?;
    let signature = Signature::from_slice(&sig_bytes)
        .map_err(|e| AppError::Authentication(format!("id_token signature malformed: {e}")))?;
    let signing_input = format!("{header_b64}.{payload_b64}");
    verifying_key
        .verify(signing_input.as_bytes(), &signature)
        .map_err(|_| AppError::Authentication("id_token signature verification failed".into()))?;

    Ok(VerifiedSiopIdToken {
        issuer: iss,
        audience: claims
            .aud
            .ok_or_else(|| AppError::Authentication("id_token missing `aud`".into()))?,
        nonce: claims
            .nonce
            .ok_or_else(|| AppError::Authentication("id_token missing `nonce`".into()))?,
        issued_at: claims
            .iat
            .ok_or_else(|| AppError::Authentication("id_token missing `iat`".into()))?,
        expires_at: claims
            .exp
            .ok_or_else(|| AppError::Authentication("id_token missing `exp`".into()))?,
    })
}

/// Extract the `kid` from a base64url-encoded compact-JWS protected
/// header. Mirrors [`extract_signer_kid`] (which reads a DIDComm
/// general-JSON JWS) for the compact serialization used by SIOPv2.
fn extract_signer_kid_compact(header_b64: &str) -> Result<String, AppError> {
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;

    let header_bytes = URL_SAFE_NO_PAD
        .decode(header_b64)
        .map_err(|e| AppError::Authentication(format!("id_token header not base64url: {e}")))?;
    let header: JwsProtectedHeader = serde_json::from_slice(&header_bytes)
        .map_err(|e| AppError::Authentication(format!("id_token header not JSON: {e}")))?;
    header
        .kid
        .ok_or_else(|| AppError::Authentication("id_token header missing kid".into()))
}

#[cfg(test)]
mod addressed_to_tests {
    use super::require_addressed_to;
    use affinidi_tdk::didcomm::Message;
    use serde_json::json;

    fn msg(to: Option<Vec<&str>>) -> Message {
        let mut m = Message::build("id-1".to_string(), "t".to_string(), json!({})).finalize();
        m.to = to.map(|v| v.into_iter().map(String::from).collect());
        m
    }

    /// affinidi-webvh-service#207: only a message addressed to this service,
    /// and to it alone, signs in here.
    #[test]
    fn a_signed_sign_in_must_be_addressed_to_this_service_alone() {
        let own = Some("did:web:svc.example");
        assert!(require_addressed_to(&msg(Some(vec!["did:web:svc.example"])), own).is_ok());
        // Another service — the relay.
        assert!(require_addressed_to(&msg(Some(vec!["did:web:other.example"])), own).is_err());
        // Several recipients: valid at each, so not bound to this one.
        assert!(
            require_addressed_to(
                &msg(Some(vec!["did:web:svc.example", "did:web:other.example"])),
                own
            )
            .is_err()
        );
        // None.
        assert!(require_addressed_to(&msg(None), own).is_err());
        assert!(require_addressed_to(&msg(Some(vec![])), own).is_err());
        // Exact equality, no normalisation.
        assert!(require_addressed_to(&msg(Some(vec!["did:web:svc.example "])), own).is_err());
        // A service with no DID cannot be addressed.
        assert!(require_addressed_to(&msg(Some(vec!["did:web:svc.example"])), None).is_err());
    }
}

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

    /// `extract_signer_kid` must return the kid embedded in the JWS protected
    /// header. This is the input to the signer-verification flow; if it
    /// regressed to "the first available kid" or similar, the bypass would
    /// reopen.
    #[test]
    fn extract_signer_kid_reads_protected_header_kid() {
        // Build a synthetic JWS envelope with a known kid.
        // protected = base64url({"kid":"did:example:123#key-1","alg":"EdDSA"})
        let header_json = serde_json::json!({
            "kid": "did:example:123#key-1",
            "alg": "EdDSA",
        });
        let protected_b64 = base64::Engine::encode(
            &base64::engine::general_purpose::URL_SAFE_NO_PAD,
            serde_json::to_vec(&header_json).unwrap(),
        );
        let jws = serde_json::json!({
            "payload": "ignored",
            "signatures": [
                {
                    "protected": protected_b64,
                    "signature": "ignored",
                }
            ],
        });
        let kid = extract_signer_kid(&jws.to_string()).unwrap();
        assert_eq!(kid, "did:example:123#key-1");
    }

    #[test]
    fn extract_signer_kid_rejects_envelope_without_signatures() {
        let jws = serde_json::json!({ "payload": "ignored", "signatures": [] });
        assert!(extract_signer_kid(&jws.to_string()).is_err());
    }

    #[test]
    fn extract_signer_kid_rejects_envelope_with_no_kid() {
        let header_json = serde_json::json!({ "alg": "EdDSA" });
        let protected_b64 = base64::Engine::encode(
            &base64::engine::general_purpose::URL_SAFE_NO_PAD,
            serde_json::to_vec(&header_json).unwrap(),
        );
        let jws = serde_json::json!({
            "payload": "ignored",
            "signatures": [{ "protected": protected_b64, "signature": "ignored" }],
        });
        assert!(extract_signer_kid(&jws.to_string()).is_err());
    }

    #[test]
    fn extract_signer_kid_rejects_invalid_json() {
        assert!(extract_signer_kid("not-json").is_err());
    }

    #[test]
    fn extract_signer_kid_rejects_multi_signature_envelope() {
        let header_json = serde_json::json!({ "kid": "did:example:123#key-1", "alg": "EdDSA" });
        let protected_b64 = base64::Engine::encode(
            &base64::engine::general_purpose::URL_SAFE_NO_PAD,
            serde_json::to_vec(&header_json).unwrap(),
        );
        let jws = serde_json::json!({
            "payload": "ignored",
            "signatures": [
                { "protected": protected_b64.clone(), "signature": "ignored" },
                { "protected": protected_b64, "signature": "second" },
            ],
        });
        let err = extract_signer_kid(&jws.to_string()).unwrap_err();
        match err {
            AppError::Authentication(msg) => assert!(
                msg.contains("only single-signer"),
                "expected multi-sig rejection message, got: {msg}",
            ),
            other => panic!("expected Authentication, got {other:?}"),
        }
    }

    // ---- SIOPv2 id_token helpers ----

    /// A 32-byte Ed25519 public key encodes to a `did:key:z6Mk…` whose
    /// multibase tail decodes back to the same key bytes. Round-trips
    /// the exact `0xed01 ‖ 32-byte` multicodec shape the verifier pins
    /// `iss` against.
    #[test]
    fn ed25519_pubkey_from_did_key_round_trips() {
        let pk = [7u8; 32];
        // 0xed01 multicodec prefix + raw key, base58btc multibase.
        let mut multicodec = vec![0xed, 0x01];
        multicodec.extend_from_slice(&pk);
        let multibase = multibase::encode(multibase::Base::Base58Btc, &multicodec);
        assert!(multibase.starts_with("z6Mk"), "got {multibase}");
        let did = format!("did:key:{multibase}");
        let decoded = ed25519_pubkey_from_did_key(&did).unwrap();
        assert_eq!(decoded, pk);
    }

    #[test]
    fn ed25519_pubkey_from_did_key_rejects_non_did_key() {
        assert!(ed25519_pubkey_from_did_key("did:web:example.com").is_err());
    }

    /// A did:key whose multicodec prefix is X25519 (`0xec01`) must be
    /// rejected — only Ed25519 (`0xed01`) signing keys are admissible
    /// issuers.
    #[test]
    fn ed25519_pubkey_from_did_key_rejects_x25519_multicodec() {
        let mut multicodec = vec![0xec, 0x01];
        multicodec.extend_from_slice(&[9u8; 32]);
        let multibase = multibase::encode(multibase::Base::Base58Btc, &multicodec);
        let did = format!("did:key:{multibase}");
        assert!(ed25519_pubkey_from_did_key(&did).is_err());
    }

    #[test]
    fn extract_signer_kid_compact_reads_header_kid() {
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        let header = serde_json::json!({
            "alg": "EdDSA",
            "typ": "JWT",
            "kid": "did:key:z6MkABC#z6MkABC",
        });
        let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap());
        let kid = extract_signer_kid_compact(&header_b64).unwrap();
        assert_eq!(kid, "did:key:z6MkABC#z6MkABC");
    }

    #[test]
    fn extract_signer_kid_compact_rejects_missing_kid() {
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        let header = serde_json::json!({ "alg": "EdDSA", "typ": "JWT" });
        let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap());
        assert!(extract_signer_kid_compact(&header_b64).is_err());
    }

    /// End-to-end: a wallet-shaped token (EdDSA over `header.payload`,
    /// `iss == sub`, header `kid` == `<iss>#<multibase>`) verifies, and
    /// the eagerly-parsed claims surface. Uses the in-crate `did:key`
    /// resolver so no network is touched.
    #[tokio::test]
    async fn verify_siop_id_token_accepts_well_formed_token() {
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        use ed25519_dalek::{Signer, SigningKey};

        let sk = SigningKey::from_bytes(&[42u8; 32]);
        let pk = sk.verifying_key().to_bytes();
        let mut multicodec = vec![0xed, 0x01];
        multicodec.extend_from_slice(&pk);
        let multibase = multibase::encode(multibase::Base::Base58Btc, &multicodec);
        let did = format!("did:key:{multibase}");

        let header = serde_json::json!({
            "alg": "EdDSA",
            "typ": "JWT",
            "kid": format!("{did}#{multibase}"),
        });
        let payload = serde_json::json!({
            "iss": did,
            "sub": did,
            "aud": "did:key:server-rp",
            "nonce": "deadbeef",
            "iat": 1_700_000_000u64,
            "exp": 1_700_003_600u64,
        });
        let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap());
        let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).unwrap());
        let signing_input = format!("{header_b64}.{payload_b64}");
        let sig = sk.sign(signing_input.as_bytes());
        let sig_b64 = URL_SAFE_NO_PAD.encode(sig.to_bytes());
        let token = format!("{signing_input}.{sig_b64}");

        let resolver = DIDCacheClient::new(
            affinidi_did_resolver_cache_sdk::config::DIDCacheConfigBuilder::default().build(),
        )
        .await
        .expect("did:key resolver");
        let verified = verify_siop_id_token(&token, &resolver)
            .await
            .expect("well-formed token verifies");
        assert_eq!(verified.issuer, did);
        assert_eq!(verified.audience, "did:key:server-rp");
        assert_eq!(verified.nonce, "deadbeef");
        assert_eq!(verified.issued_at, 1_700_000_000);
        assert_eq!(verified.expires_at, 1_700_003_600);
    }

    /// A flipped signature must be rejected even though everything else
    /// is well-formed — the EdDSA check is the security boundary.
    #[tokio::test]
    async fn verify_siop_id_token_rejects_bad_signature() {
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        use ed25519_dalek::{Signer, SigningKey};

        let sk = SigningKey::from_bytes(&[1u8; 32]);
        let pk = sk.verifying_key().to_bytes();
        let mut multicodec = vec![0xed, 0x01];
        multicodec.extend_from_slice(&pk);
        let multibase = multibase::encode(multibase::Base::Base58Btc, &multicodec);
        let did = format!("did:key:{multibase}");

        let header = serde_json::json!({ "alg": "EdDSA", "typ": "JWT", "kid": format!("{did}#{multibase}") });
        let payload = serde_json::json!({
            "iss": did, "sub": did, "aud": "rp", "nonce": "n", "iat": 1u64, "exp": 2u64,
        });
        let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap());
        let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).unwrap());
        let sig = sk.sign(format!("{header_b64}.{payload_b64}").as_bytes());
        let mut sig_bytes = sig.to_bytes();
        sig_bytes[0] ^= 0xff; // tamper
        let sig_b64 = URL_SAFE_NO_PAD.encode(sig_bytes);
        let token = format!("{header_b64}.{payload_b64}.{sig_b64}");

        let resolver = DIDCacheClient::new(
            affinidi_did_resolver_cache_sdk::config::DIDCacheConfigBuilder::default().build(),
        )
        .await
        .expect("did:key resolver");
        assert!(verify_siop_id_token(&token, &resolver).await.is_err());
    }

    /// A signed sign-in or refresh must use a key the DID lists under
    /// `authentication`; an `assertionMethod`-only key is refused.
    #[tokio::test]
    async fn sign_in_keys_must_be_authentication_keys() {
        use affinidi_secrets_resolver::secrets::Secret;
        let secret = Secret::generate_ed25519(None, Some(&[4u8; 32]));
        let pk = secret.get_public_keymultibase().unwrap();
        let mut resolver = DIDCacheClient::new(
            affinidi_did_resolver_cache_sdk::config::DIDCacheConfigBuilder::default().build(),
        )
        .await
        .unwrap();
        for (did, rel) in [
            ("did:web:auth.example", "authentication"),
            ("did:web:assert.example", "assertionMethod"),
        ] {
            let doc: affinidi_tdk::did_common::Document =
                serde_json::from_value(serde_json::json!({
                    "id": did,
                    "verificationMethod": [{
                        "id": format!("{did}#key-1"),
                        "type": "Multikey",
                        "controller": did,
                        "publicKeyMultibase": pk,
                    }],
                    rel: [format!("{did}#key-1")],
                }))
                .unwrap();
            resolver.add_did_document(did, doc).await;
        }
        resolve_verifying_key(&resolver, "did:web:auth.example#key-1")
            .await
            .expect("authentication key accepted");
        let err = resolve_verifying_key(&resolver, "did:web:assert.example#key-1")
            .await
            .unwrap_err();
        assert!(
            err.to_string().contains("not an authentication key"),
            "{err}"
        );
    }
}