sylphx 0.3.2

The Sylphx SDK: one API, one key, every Sylphx service. Generated from the Sylphx schema registry.
Documentation
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
// @generated by sylphx-gen 0.1.0 from contracts@c8a7361c53e572321b0ec9fb014fd1e8279b007b62562423038e0d0e5b9d767a. Do not edit.
//! Offline verification of tokens Sylphx signs: Auth session tokens and
//! service-to-service invocation tokens. A token is a compact JWS (ES256 or
//! EdDSA) whose key is published in the issuer's JWKS; verification needs no
//! call to Sylphx once the key set is cached.
//!
//! ```no_run
//! # async fn run() -> Result<(), sylphx::auth::verify::VerifyError> {
//! use sylphx::auth::verify::{Verifier, Expect};
//! let verifier = Verifier::new(Expect::issuer("https://api.sylphx.com").audience("my-app"));
//! let claims = verifier.verify("eyJ…").await?;
//! let user = claims.subject();
//! # Ok(()) }
//! ```
//!
//! [`verify_with_keys`] is the pure core (no network, caller-supplied time)
//! for tests and for callers who distribute keys themselves.

use std::time::{Duration, SystemTime, UNIX_EPOCH};

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use serde::Deserialize;
use serde_json::{Map, Value};

/// Why a token was refused. Every variant means "do not trust this token".
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerifyError {
    /// Not three base64url parts, or a part is not the JSON it must be.
    Malformed(String),
    /// `alg` is not ES256 or EdDSA (`none` and HMAC are never accepted).
    Algorithm(String),
    /// No key in the set has the token's `kid` (after one refetch).
    UnknownKey(String),
    /// The signature does not verify.
    Signature,
    /// `exp` is past, `nbf`/`iat` is in the future, or `exp` is missing.
    Expired,
    /// `iss` is not the expected issuer.
    Issuer(String),
    /// None of the token's audiences is expected.
    Audience,
    /// The key set could not be fetched or read.
    Keys(String),
    /// A callback receipt whose `jti` was already admitted ([`ReplayGuard`]).
    Replayed,
}

impl std::fmt::Display for VerifyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VerifyError::Malformed(m) => write!(f, "malformed token: {m}"),
            VerifyError::Algorithm(a) => write!(f, "algorithm {a} is not accepted"),
            VerifyError::UnknownKey(k) => write!(f, "no key {k} in the issuer's key set"),
            VerifyError::Signature => f.write_str("the signature does not verify"),
            VerifyError::Expired => f.write_str("the token is expired or not yet valid"),
            VerifyError::Issuer(i) => write!(f, "unexpected issuer {i}"),
            VerifyError::Audience => f.write_str("the token is not for this audience"),
            VerifyError::Keys(m) => write!(f, "key set: {m}"),
            VerifyError::Replayed => f.write_str("the receipt was already used"),
        }
    }
}

impl std::error::Error for VerifyError {}

/// What a token must carry.
#[derive(Debug, Clone)]
pub struct Expect {
    pub issuer: String,
    /// Accepted audiences; the token must name at least one. Empty refuses
    /// every token: a verifier with no audience is a configuration error, not
    /// a request to accept any `aud`.
    pub audiences: Vec<String>,
    /// Clock skew tolerated on `exp`, `nbf`, and `iat`.
    pub leeway: Duration,
    /// Required JOSE `typ`, when set (callback receipts fix it).
    pub typ: Option<String>,
}

impl Expect {
    pub fn issuer(issuer: impl Into<String>) -> Expect {
        Expect {
            issuer: issuer.into().trim_end_matches('/').to_string(),
            audiences: vec![],
            leeway: Duration::from_secs(60),
            typ: None,
        }
    }

    pub fn typ(mut self, typ: impl Into<String>) -> Expect {
        self.typ = Some(typ.into());
        self
    }

    pub fn audience(mut self, audience: impl Into<String>) -> Expect {
        self.audiences.push(audience.into());
        self
    }

    pub fn leeway(mut self, leeway: Duration) -> Expect {
        self.leeway = leeway;
        self
    }

    /// What a callback receipt must carry: the Compute issuer and `aud` equal
    /// to `callback_url`, the exact URL the platform was given for the
    /// callback (scheme, host, path and query, byte for byte).
    pub fn callback(callback_url: impl Into<String>) -> Expect {
        Expect::issuer(CALLBACK_RECEIPT_ISSUER)
            .audience(callback_url)
            .leeway(Duration::from_secs(CALLBACK_LEEWAY_SECONDS))
            .typ(CALLBACK_RECEIPT_TYP)
    }
}

/// Remembers admitted receipt ids (`jti`) until they expire, so a captured
/// receipt cannot be presented twice. In memory: a fleet of receivers behind
/// one URL records `jti` until `exp` in a store they share instead.
#[derive(Debug, Default)]
pub struct ReplayGuard {
    seen: std::sync::Mutex<std::collections::HashMap<String, i64>>,
}

impl ReplayGuard {
    pub fn new() -> ReplayGuard {
        ReplayGuard::default()
    }

    /// Admits verified `claims` once. A missing `jti` or a `jti` seen before
    /// (and not yet expired) is [`VerifyError::Replayed`].
    pub fn admit(&self, claims: &Claims, now: i64) -> Result<(), VerifyError> {
        let (Some(jti), Some(exp)) = (claims.jti(), claims.expires_at()) else {
            return Err(VerifyError::Replayed);
        };
        let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
        seen.retain(|_, until| *until > now);
        if seen.contains_key(jti) {
            return Err(VerifyError::Replayed);
        }
        // The verifier accepts until exp + leeway; remember at least that long.
        seen.insert(jti.to_string(), exp + CALLBACK_LEEWAY_SECONDS as i64);
        Ok(())
    }
}

/// Verifies a callback receipt (`Authorization: Bearer <receipt>`) against the
/// published keys, then admits its `jti` once.
pub fn verify_callback_with_keys(
    token: &str,
    keys: &Jwks,
    callback_url: &str,
    guard: &ReplayGuard,
    now: i64,
) -> Result<Claims, VerifyError> {
    let claims = verify_with_keys(token, keys, &Expect::callback(callback_url), now)?;
    guard.admit(&claims, now)?;
    Ok(claims)
}

/// A verified token's claims.
#[derive(Debug, Clone, PartialEq)]
pub struct Claims(pub Map<String, Value>);

impl Claims {
    pub fn subject(&self) -> Option<&str> {
        self.0.get("sub").and_then(Value::as_str)
    }
    pub fn get(&self, claim: &str) -> Option<&Value> {
        self.0.get(claim)
    }
    pub fn expires_at(&self) -> Option<i64> {
        self.0.get("exp").and_then(Value::as_i64)
    }
    /// The token id (`jti`), the key a [`ReplayGuard`] remembers.
    pub fn jti(&self) -> Option<&str> {
        self.0.get("jti").and_then(Value::as_str)
    }
}

/// Issuer of the receipt on every platform-originated callback (Task and
/// program-run callbacks carry the same receipt a Compute Tick does).
pub const CALLBACK_RECEIPT_TYP: &str = "compute-tick-receipt+jwt";
/// Clock skew a callback verifier tolerates; a [`ReplayGuard`] keeps each
/// `jti` this much past `exp`, so a receipt cannot be replayed inside it.
pub const CALLBACK_LEEWAY_SECONDS: u64 = 30;
pub const CALLBACK_RECEIPT_ISSUER: &str = "https://api.compute.sylphx.com";
/// Where the receipt keys are published. Two keys overlap during a rotation;
/// the token's `kid` picks one, so a verifier that refetches on an unknown
/// `kid` (as [`Verifier`] does) never needs a change at rotation.
pub const CALLBACK_RECEIPT_JWKS_URL: &str =
    "https://api.compute.sylphx.com/.well-known/compute-tick-receipt-jwks.json";

/// A JSON Web Key Set (RFC 7517), the keys this module can use.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Jwks {
    #[serde(default)]
    pub keys: Vec<Jwk>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Jwk {
    #[serde(default)]
    pub kid: String,
    pub kty: String,
    #[serde(default)]
    pub crv: String,
    #[serde(default)]
    pub x: String,
    #[serde(default)]
    pub y: String,
    #[serde(default)]
    pub alg: Option<String>,
    #[serde(rename = "use", default)]
    pub use_: Option<String>,
}

#[derive(Deserialize)]
struct Header {
    alg: String,
    #[serde(default)]
    kid: String,
    #[serde(default)]
    typ: Option<String>,
}

fn part(s: &str, what: &str) -> Result<Vec<u8>, VerifyError> {
    URL_SAFE_NO_PAD
        .decode(s)
        .map_err(|_| VerifyError::Malformed(format!("{what} is not base64url")))
}

fn verify_signature(jwk: &Jwk, alg: &str, signed: &[u8], sig: &[u8]) -> Result<(), VerifyError> {
    if jwk.use_.as_deref().is_some_and(|u| u != "sig")
        || jwk.alg.as_deref().is_some_and(|a| a != alg)
    {
        return Err(VerifyError::Signature);
    }
    match (alg, jwk.kty.as_str(), jwk.crv.as_str()) {
        ("ES256", "EC", "P-256") => {
            use p256::ecdsa::signature::Verifier as _;
            let mut point = vec![0x04];
            point.extend(part(&jwk.x, "key x")?);
            point.extend(part(&jwk.y, "key y")?);
            let key = p256::ecdsa::VerifyingKey::from_sec1_bytes(&point)
                .map_err(|_| VerifyError::Keys("bad P-256 key".into()))?;
            let sig =
                p256::ecdsa::Signature::from_slice(sig).map_err(|_| VerifyError::Signature)?;
            key.verify(signed, &sig).map_err(|_| VerifyError::Signature)
        }
        ("EdDSA", "OKP", "Ed25519") => {
            use ed25519_dalek::Verifier as _;
            let raw: [u8; 32] = part(&jwk.x, "key x")?
                .try_into()
                .map_err(|_| VerifyError::Keys("bad Ed25519 key".into()))?;
            let key = ed25519_dalek::VerifyingKey::from_bytes(&raw)
                .map_err(|_| VerifyError::Keys("bad Ed25519 key".into()))?;
            let sig: [u8; 64] = sig.try_into().map_err(|_| VerifyError::Signature)?;
            key.verify(signed, &ed25519_dalek::Signature::from_bytes(&sig))
                .map_err(|_| VerifyError::Signature)
        }
        _ => Err(VerifyError::Signature),
    }
}

/// The token's `kid` (to pick or refetch keys), without verifying anything.
pub fn key_id(token: &str) -> Result<String, VerifyError> {
    let head = token.split('.').next().unwrap_or_default();
    let h: Header = serde_json::from_slice(&part(head, "header")?)
        .map_err(|_| VerifyError::Malformed("header is not JSON".into()))?;
    Ok(h.kid)
}

/// Verifies `token` against `keys` at `now` (Unix seconds).
pub fn verify_with_keys(
    token: &str,
    keys: &Jwks,
    expect: &Expect,
    now: i64,
) -> Result<Claims, VerifyError> {
    let mut it = token.split('.');
    let (Some(h), Some(p), Some(s), None) = (it.next(), it.next(), it.next(), it.next()) else {
        return Err(VerifyError::Malformed("not three parts".into()));
    };
    let header: Header = serde_json::from_slice(&part(h, "header")?)
        .map_err(|_| VerifyError::Malformed("header is not JSON".into()))?;
    if !matches!(header.alg.as_str(), "ES256" | "EdDSA") {
        return Err(VerifyError::Algorithm(header.alg));
    }
    if expect
        .typ
        .as_deref()
        .is_some_and(|want| header.typ.as_deref() != Some(want))
    {
        return Err(VerifyError::Malformed("unexpected token type".into()));
    }
    let candidates: Vec<&Jwk> = keys
        .keys
        .iter()
        .filter(|k| header.kid.is_empty() || k.kid == header.kid)
        .collect();
    if candidates.is_empty() {
        return Err(VerifyError::UnknownKey(header.kid));
    }
    let sig = part(s, "signature")?;
    let signed = format!("{h}.{p}");
    if !candidates
        .iter()
        .any(|k| verify_signature(k, &header.alg, signed.as_bytes(), &sig).is_ok())
    {
        return Err(VerifyError::Signature);
    }
    let claims: Map<String, Value> = serde_json::from_slice(&part(p, "payload")?)
        .map_err(|_| VerifyError::Malformed("payload is not a JSON object".into()))?;
    let leeway = expect.leeway.as_secs() as i64;
    let num = |k: &str| claims.get(k).and_then(Value::as_i64);
    match num("exp") {
        Some(exp) if exp + leeway > now => {}
        _ => return Err(VerifyError::Expired),
    }
    if num("nbf").is_some_and(|nbf| nbf - leeway > now)
        || num("iat").is_some_and(|iat| iat - leeway > now)
    {
        return Err(VerifyError::Expired);
    }
    let iss = claims
        .get("iss")
        .and_then(Value::as_str)
        .unwrap_or_default();
    if iss.trim_end_matches('/') != expect.issuer {
        return Err(VerifyError::Issuer(iss.to_string()));
    }
    let auds: Vec<&str> = match claims.get("aud") {
        Some(Value::String(a)) => vec![a.as_str()],
        Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(),
        _ => vec![],
    };
    if expect.audiences.is_empty() || !auds.iter().any(|a| expect.audiences.iter().any(|e| e == a))
    {
        return Err(VerifyError::Audience);
    }
    Ok(Claims(claims))
}

fn now_unix() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

/// Verifies tokens against the issuer's published key set, cached. An
/// unknown `kid` refetches the set at once, but at most once every
/// [`Verifier::MIN_REFETCH`] (so key rotation is picked up and a flood of bad
/// `kid`s cannot hammer the issuer).
#[cfg(feature = "http")]
pub struct Verifier {
    expect: Expect,
    jwks_url: String,
    http: reqwest::Client,
    cache: tokio::sync::RwLock<Option<(Jwks, std::time::Instant)>>,
    last_forced: std::sync::Mutex<Option<std::time::Instant>>,
}

#[cfg(feature = "http")]
impl Verifier {
    /// Keys are kept this long before a refresh.
    pub const TTL: Duration = Duration::from_secs(600);
    /// The shortest interval between two refetches caused by an unknown `kid`.
    pub const MIN_REFETCH: Duration = Duration::from_secs(30);

    /// Keys from `{issuer}/v1/oauth/jwks.json`.
    pub fn new(expect: Expect) -> Verifier {
        let url = format!("{}/v1/oauth/jwks.json", expect.issuer);
        Verifier::with_jwks_url(expect, url)
    }

    /// Verifies callback receipts for `callback_url` against
    /// [`CALLBACK_RECEIPT_JWKS_URL`]. Check replay with [`ReplayGuard`].
    pub fn callback(callback_url: impl Into<String>) -> Verifier {
        Verifier::with_jwks_url(Expect::callback(callback_url), CALLBACK_RECEIPT_JWKS_URL)
    }

    pub fn with_jwks_url(expect: Expect, jwks_url: impl Into<String>) -> Verifier {
        Verifier {
            expect,
            jwks_url: jwks_url.into(),
            http: reqwest::Client::builder()
                .timeout(Duration::from_secs(10))
                .build()
                .expect("a reqwest client"),
            cache: tokio::sync::RwLock::new(None),
            last_forced: std::sync::Mutex::new(None),
        }
    }

    async fn keys(&self, force: bool) -> Result<Jwks, VerifyError> {
        if let Some((k, at)) = self.cache.read().await.as_ref() {
            let fresh = at.elapsed() < Verifier::TTL;
            let throttled = force && {
                let mut last = self.last_forced.lock().unwrap_or_else(|e| e.into_inner());
                let recent = last.is_some_and(|t| t.elapsed() < Verifier::MIN_REFETCH);
                if !recent {
                    *last = Some(std::time::Instant::now());
                }
                recent
            };
            if fresh && (!force || throttled) {
                return Ok(k.clone());
            }
        }
        let fetched: Jwks = self
            .http
            .get(&self.jwks_url)
            .send()
            .await
            .and_then(|r| r.error_for_status())
            .map_err(|e| VerifyError::Keys(e.to_string()))?
            .json()
            .await
            .map_err(|e| VerifyError::Keys(e.to_string()))?;
        *self.cache.write().await = Some((fetched.clone(), std::time::Instant::now()));
        Ok(fetched)
    }

    pub async fn verify(&self, token: &str) -> Result<Claims, VerifyError> {
        let keys = self.keys(false).await?;
        match verify_with_keys(token, &keys, &self.expect, now_unix()) {
            Err(VerifyError::UnknownKey(_)) => {
                let keys = self.keys(true).await?;
                verify_with_keys(token, &keys, &self.expect, now_unix())
            }
            other => other,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use p256::ecdsa::signature::Signer as _;
    use serde_json::json;

    fn b64(v: &[u8]) -> String {
        URL_SAFE_NO_PAD.encode(v)
    }

    fn es256() -> (p256::ecdsa::SigningKey, Jwk) {
        let sk = p256::ecdsa::SigningKey::from_slice(&[7u8; 32]).unwrap();
        let pt = sk.verifying_key().to_encoded_point(false);
        let jwk = Jwk {
            kid: "k1".into(),
            kty: "EC".into(),
            crv: "P-256".into(),
            x: b64(pt.x().unwrap()),
            y: b64(pt.y().unwrap()),
            alg: Some("ES256".into()),
            use_: Some("sig".into()),
        };
        (sk, jwk)
    }

    fn sign_es(sk: &p256::ecdsa::SigningKey, header: Value, claims: Value) -> String {
        let signed = format!(
            "{}.{}",
            b64(header.to_string().as_bytes()),
            b64(claims.to_string().as_bytes())
        );
        let sig: p256::ecdsa::Signature = sk.sign(signed.as_bytes());
        format!("{signed}.{}", b64(&sig.to_bytes()))
    }

    const NOW: i64 = 1_800_000_000;

    fn good() -> Value {
        json!({"iss": "https://api.sylphx.com", "aud": ["app"], "sub": "u1", "exp": NOW + 300, "iat": NOW - 10})
    }

    fn expect() -> Expect {
        Expect::issuer("https://api.sylphx.com").audience("app")
    }

    #[test]
    fn a_valid_es256_token_verifies() {
        let (sk, jwk) = es256();
        let keys = Jwks { keys: vec![jwk] };
        let t = sign_es(&sk, json!({"alg": "ES256", "kid": "k1"}), good());
        let c = verify_with_keys(&t, &keys, &expect(), NOW).unwrap();
        assert_eq!(c.subject(), Some("u1"));
        assert_eq!(key_id(&t).unwrap(), "k1");
    }

    #[test]
    fn a_valid_eddsa_token_verifies() {
        use ed25519_dalek::Signer as _;
        let sk = ed25519_dalek::SigningKey::from_bytes(&[9u8; 32]);
        let keys = Jwks {
            keys: vec![Jwk {
                kid: "e1".into(),
                kty: "OKP".into(),
                crv: "Ed25519".into(),
                x: b64(sk.verifying_key().as_bytes()),
                y: String::new(),
                alg: None,
                use_: None,
            }],
        };
        let signed = format!(
            "{}.{}",
            b64(json!({"alg": "EdDSA", "kid": "e1"}).to_string().as_bytes()),
            b64(good().to_string().as_bytes())
        );
        let t = format!("{signed}.{}", b64(&sk.sign(signed.as_bytes()).to_bytes()));
        assert!(verify_with_keys(&t, &keys, &expect(), NOW).is_ok());
    }

    #[test]
    fn an_empty_audience_list_refuses_every_token() {
        let (sk, jwk) = es256();
        let keys = Jwks { keys: vec![jwk] };
        let t = sign_es(&sk, json!({"alg": "ES256", "kid": "k1"}), good());
        let none = Expect::issuer("https://api.sylphx.com");
        assert_eq!(
            verify_with_keys(&t, &keys, &none, NOW).unwrap_err(),
            VerifyError::Audience
        );
    }

    #[test]
    fn hostile_tokens_are_refused() {
        let (sk, jwk) = es256();
        let keys = Jwks { keys: vec![jwk] };
        let h = json!({"alg": "ES256", "kid": "k1"});
        let with = |f: &dyn Fn(&mut Map<String, Value>)| {
            let mut c = good().as_object().unwrap().clone();
            f(&mut c);
            sign_es(&sk, h.clone(), Value::Object(c))
        };
        let cases: Vec<(&str, String, fn(&VerifyError) -> bool)> = vec![
            (
                "expired",
                with(&|c| {
                    c.insert("exp".into(), json!(NOW - 120));
                }),
                |e| *e == VerifyError::Expired,
            ),
            (
                "no exp",
                with(&|c| {
                    c.remove("exp");
                }),
                |e| *e == VerifyError::Expired,
            ),
            (
                "not yet valid",
                with(&|c| {
                    c.insert("nbf".into(), json!(NOW + 600));
                }),
                |e| *e == VerifyError::Expired,
            ),
            (
                "other issuer",
                with(&|c| {
                    c.insert("iss".into(), json!("https://evil.example"));
                }),
                |e| matches!(e, VerifyError::Issuer(_)),
            ),
            (
                "other audience",
                with(&|c| {
                    c.insert("aud".into(), json!("other"));
                }),
                |e| *e == VerifyError::Audience,
            ),
            (
                "alg none",
                format!(
                    "{}.{}.",
                    b64(br#"{"alg":"none"}"#),
                    b64(good().to_string().as_bytes())
                ),
                |e| matches!(e, VerifyError::Algorithm(_)),
            ),
            (
                "alg HS256",
                format!(
                    "{}.{}.x",
                    b64(br#"{"alg":"HS256","kid":"k1"}"#),
                    b64(good().to_string().as_bytes())
                ),
                |e| matches!(e, VerifyError::Algorithm(_)),
            ),
            (
                "unknown kid",
                sign_es(&sk, json!({"alg": "ES256", "kid": "zz"}), good()),
                |e| matches!(e, VerifyError::UnknownKey(_)),
            ),
            ("two parts", "a.b".into(), |e| {
                matches!(e, VerifyError::Malformed(_))
            }),
            ("garbage", "!!.!!.!!".into(), |e| {
                matches!(e, VerifyError::Malformed(_))
            }),
        ];
        for (name, token, ok) in cases {
            let e = verify_with_keys(&token, &keys, &expect(), NOW).expect_err(name);
            assert!(ok(&e), "{name}: {e:?}");
        }
        // A payload swapped under a valid signature.
        let t = sign_es(&sk, h.clone(), good());
        let mut parts: Vec<&str> = t.split('.').collect();
        let forged = b64(json!({"iss": "https://api.sylphx.com", "aud": "app", "sub": "admin", "exp": NOW + 300}).to_string().as_bytes());
        parts[1] = &forged;
        assert_eq!(
            verify_with_keys(&parts.join("."), &keys, &expect(), NOW),
            Err(VerifyError::Signature)
        );
        // A key from another issuer set under the same kid.
        let other = p256::ecdsa::SigningKey::from_slice(&[8u8; 32]).unwrap();
        let t = sign_es(&other, h.clone(), good());
        assert_eq!(
            verify_with_keys(&t, &keys, &expect(), NOW),
            Err(VerifyError::Signature)
        );
        // Leeway: 30 s past exp is still inside the default 60 s.
        let t = with(&|c| {
            c.insert("exp".into(), json!(NOW - 30));
        });
        assert!(verify_with_keys(&t, &keys, &expect(), NOW).is_ok());
    }

    fn receipt(
        sk: &ed25519_dalek::SigningKey,
        kid: &str,
        aud: &str,
        jti: &str,
        exp: i64,
    ) -> String {
        use ed25519_dalek::Signer as _;
        let signed = format!(
            "{}.{}",
            b64(json!({"alg": "EdDSA", "typ": "compute-tick-receipt+jwt", "kid": kid}).to_string().as_bytes()),
            b64(json!({"iss": CALLBACK_RECEIPT_ISSUER, "aud": aud, "jti": jti, "iat": NOW, "nbf": NOW, "exp": exp}).to_string().as_bytes())
        );
        format!("{signed}.{}", b64(&sk.sign(signed.as_bytes()).to_bytes()))
    }

    #[test]
    fn a_callback_receipt_verifies_for_its_url_once() {
        let sk = ed25519_dalek::SigningKey::from_bytes(&[5u8; 32]);
        // The shape the Compute JWKS publishes, extra fields included.
        let keys: Jwks = serde_json::from_value(json!({"keys": [{
            "issuer": CALLBACK_RECEIPT_ISSUER, "typ": "compute-tick-receipt+jwt",
            "kty": "OKP", "crv": "Ed25519", "alg": "EdDSA", "use": "sig", "kid": "cb-1",
            "x": b64(sk.verifying_key().as_bytes()),
            "not_before_unix_seconds": 0, "not_after_unix_seconds": 4_102_444_800i64
        }]}))
        .unwrap();
        let url = "https://hooks.example.com/task";
        let guard = ReplayGuard::new();
        let t = receipt(&sk, "cb-1", url, "s:2026:t1", NOW + 300);
        let c = verify_callback_with_keys(&t, &keys, url, &guard, NOW).unwrap();
        assert_eq!(c.jti(), Some("s:2026:t1"));
        // The same receipt again is a replay, until it has expired.
        assert_eq!(
            verify_callback_with_keys(&t, &keys, url, &guard, NOW + 5),
            Err(VerifyError::Replayed)
        );
        // A receipt for another URL is not for this receiver.
        let other = receipt(
            &sk,
            "cb-1",
            "https://evil.example.com/x",
            "s:2026:t2",
            NOW + 300,
        );
        assert_eq!(
            verify_callback_with_keys(&other, &keys, url, &guard, NOW),
            Err(VerifyError::Audience)
        );
        // Expired (past the leeway) is refused before replay is considered.
        let old = receipt(&sk, "cb-1", url, "s:2026:t3", NOW - 120);
        assert_eq!(
            verify_callback_with_keys(&old, &keys, url, &guard, NOW),
            Err(VerifyError::Expired)
        );
        // Rotation: a key set holding both keys verifies a receipt of either.
        let sk2 = ed25519_dalek::SigningKey::from_bytes(&[6u8; 32]);
        let mut both = keys.clone();
        both.keys.push(Jwk {
            kid: "cb-2".into(),
            kty: "OKP".into(),
            crv: "Ed25519".into(),
            x: b64(sk2.verifying_key().as_bytes()),
            y: String::new(),
            alg: Some("EdDSA".into()),
            use_: Some("sig".into()),
        });
        let t2 = receipt(&sk2, "cb-2", url, "s:2026:t4", NOW + 300);
        assert!(verify_callback_with_keys(&t2, &both, url, &guard, NOW).is_ok());
        // A jti stays remembered through exp + leeway, forgotten after.
        let t5 = receipt(&sk, "cb-1", url, "s:2026:t5", NOW + 10);
        assert!(verify_callback_with_keys(&t5, &keys, url, &guard, NOW).is_ok());
        assert_eq!(
            verify_callback_with_keys(&t5, &keys, url, &guard, NOW + 35),
            Err(VerifyError::Replayed)
        );
        // A token of another type is refused.
        let signed = format!(
            "{}.{}",
            b64(json!({"alg": "EdDSA", "kid": "cb-1"})
                .to_string()
                .as_bytes()),
            b64(
                json!({"iss": CALLBACK_RECEIPT_ISSUER, "aud": url, "jti": "x", "exp": NOW + 300})
                    .to_string()
                    .as_bytes()
            )
        );
        use ed25519_dalek::Signer as _;
        let untyped = format!("{signed}.{}", b64(&sk.sign(signed.as_bytes()).to_bytes()));
        assert!(matches!(
            verify_callback_with_keys(&untyped, &keys, url, &guard, NOW),
            Err(VerifyError::Malformed(_))
        ));
    }
}