tamga 0.3.5

Official Rust SDK for Tamga. Integrate license activation, offline verification, and machine management into your Rust applications.
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
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
//! `.lic` file parsing and verification — the core payload format this SDK's
//! verifier must implement exactly right, since `tamga-c` (and transitively
//! `tamga-java`/`tamga-swift`) re-export this crate's implementation instead
//! of re-implementing it.
//!
//! **File format**:
//! ```text
//! -----BEGIN LICENSE FILE-----
//! <base64 of JSON: { "enc": "<base64>", "sig": "<base64 ed25519 sig over enc's UTF-8 bytes>", "alg": "<algorithm string>" }>
//! -----END LICENSE FILE-----
//! ```
//!
//! `alg` is exactly `"base64+ed25519+v2"` (plain) or
//! `"aes-256-gcm+ed25519+v2"` (encrypted) — **Ed25519 only** for the checkout
//! signature, independent of the license's own key `scheme`.
//!
//! **Format v2 and why v1 is refused outright.** In v1 the `ttl`/`expiry` a
//! caller asked for lived only in the JSON:API envelope *around* the
//! certificate, never inside the signed bytes. A 24-hour trial file was
//! therefore cryptographically valid forever: the client is the attacker, so
//! any check built on the envelope is bypassed by keeping — or
//! redistributing — the raw `certificate` string. v2 moves the claims inside
//! the signature. Accepting both formats would give that back, so a file whose
//! `alg` does not end in `+v2` is rejected.
//!
//! **Verification flow** an implementation must follow:
//! 1. Strip the `-----BEGIN/END LICENSE FILE-----` PEM markers.
//! 2. Base64-decode the body → parse the inner `{ enc, sig, alg }` JSON.
//! 3. Base64-decode `sig`.
//! 4. Ed25519-verify `sig` against **`enc`'s ASCII/UTF-8 bytes — the base64
//!    STRING itself, not its decoded bytes** (see the gotcha documented in
//!    `src/crypto/ed25519.rs`) using the account's public Ed25519 key.
//! 5. Base64-decode `enc`.
//! 6. If `alg` contains `aes-256-gcm`: split `nonce(12B) ‖ ciphertext ‖
//!    tag(16B)`, AES-256-GCM-open with
//!    `crypto::hkdf::derive_license_file_key` (HKDF-SHA256, salt
//!    `"tamga:license-file-key-v1"`, info `"license-file"`).
//! 7. Parse the resulting bytes as `{"data": <LicenseResource>, "meta": <claims>}`.
//! 8. **Enforce `meta.exp`.** Steps 1–7 only establish that the file is
//!    authentic; without this step v2 buys nothing over v1.
//!
//! Also documented here (doc comments only, not enforced by code yet):
//! - `includes` on the checkout response is **always `[]`** — there is no
//!   working `include[]` param despite the field existing; do not build a
//!   "checkout with embedded relationships" feature around it.
//! - `id` is a fresh UUIDv7 per call, **not idempotent** — calling checkout
//!   twice yields two different certificates (different signature nonce for
//!   the encrypted variant).
//! - The envelope's `ttl`/`expiry` fields are still metadata and still must
//!   not be trusted; the authoritative expiry is `meta.exp` inside the signed
//!   payload, which this module enforces.
//!
//! **Key rotation.** The three functions above take one public key, which
//! means a file signed before the account rotated its signing key fails with
//! exactly the error a forged file produces. Where that distinction matters —
//! and it usually does, since one calls for refreshing keys and the other for
//! refusing the customer — verify through a
//! [`crate::checkout::key_set::SigningKeySet`] instead: every held key is
//! tried against the signature, and a failure is labelled by the `kid`: not
//! held is [`crate::error::CheckoutError::UnknownSigningKey`], held is
//! [`crate::error::CryptoError::VerificationFailed`].
//!
//! Public API: [`verify_license_file`] orchestrates the full flow above,
//! [`verify_license_file_with_claims`] additionally returns the signed claims,
//! and [`verify_license_file_at`] takes the current time from the caller.
//! [`verify_license_file_with_key_set`] and
//! [`verify_license_file_with_key_set_at`] are the rotation-aware equivalents.

const PEM_HEADER: &str = "-----BEGIN LICENSE FILE-----";
const PEM_FOOTER: &str = "-----END LICENSE FILE-----";

/// The `license-files` JSON:API resource returned by
/// `POST .../licenses/{id}/actions/check-out`: `{ id, type, attributes }`.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct LicenseFileResource {
    /// Fresh UUIDv7 per call — **not idempotent**; checking out twice
    /// yields two different certificates (different signature nonce for
    /// the encrypted variant).
    pub id: uuid::Uuid,
    /// Always `"license-files"`.
    #[serde(rename = "type")]
    pub resource_type: String,
    /// The resource's attribute bag — see [`LicenseFile`].
    pub attributes: LicenseFile,
}

/// `{ certificate, algorithm, includes, ttl, expiry, issued }` — the
/// checkout response attributes.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct LicenseFile {
    /// The PEM-wrapped `.lic` certificate string — pass to
    /// [`verify_license_file`].
    pub certificate: String,
    /// `"base64+ed25519+v2"` or `"aes-256-gcm+ed25519+v2"`, matching
    /// `certificate`'s inner `alg` field.
    pub algorithm: String,
    /// **Always `[]`** — there is no working `include[]` param despite this
    /// field existing; do not build a "checkout with embedded
    /// relationships" feature around it.
    pub includes: Vec<String>,
    /// TTL in seconds, if requested. **Metadata only** — not embedded in
    /// the signed payload, and not re-checked by the server on any later
    /// validation. Expiry enforcement for an offline file is entirely this
    /// SDK's/caller's responsibility.
    pub ttl: Option<i64>,
    /// Absolute expiry timestamp derived from `issued + ttl`, if `ttl` was
    /// set. Same "metadata only" caveat as `ttl`.
    pub expiry: Option<chrono::DateTime<chrono::Utc>>,
    /// When this checkout call was issued.
    pub issued: chrono::DateTime<chrono::Utc>,
}

/// The inner `{ enc, sig, alg }` JSON payload wrapped by the PEM envelope.
#[derive(Debug, serde::Deserialize)]
struct CertPayload {
    enc: String,
    sig: String,
    alg: String,
}

/// `{"data": <LicenseResource>, "meta": <claims>}` — what `enc`
/// decodes/decrypts to in format v2.
#[derive(Debug, serde::Deserialize)]
struct DataPayload {
    data: crate::models::license::LicenseResource,
    meta: LicenseFileClaims,
}

/// The claims carried *inside* the signed bytes.
///
/// These are the point of format v2. Everything here is covered by the
/// signature, so unlike the response envelope it cannot be edited by whoever
/// holds the file.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct LicenseFileClaims {
    /// Issued-at, seconds since the Unix epoch.
    pub iat: i64,
    /// Expiry, seconds since the Unix epoch. Absent means the file never
    /// expires (checkout was made without a `ttl`).
    #[serde(default)]
    pub exp: Option<i64>,
    /// Unique per checkout — usable for replay detection.
    pub jti: String,
    /// Identifies the signing key, so a file survives a key rotation.
    ///
    /// The first eight bytes of `SHA-256` over the signing key's **base64
    /// string**, lowercase hex — see [`crate::crypto::ed25519::key_id`], and
    /// [`verify_license_file_with_key_set`] for verifying through it rather
    /// than merely reading it back.
    pub kid: String,
}

/// A verified licence file: the resource plus the claims that were signed
/// alongside it.
#[derive(Debug, Clone)]
pub struct VerifiedLicenseFile {
    /// The licence the file describes.
    pub license: crate::models::license::LicenseResource,
    /// The claims that were covered by the signature.
    pub claims: LicenseFileClaims,
}

/// How much clock skew to tolerate when checking `exp`.
///
/// Deliberately small. The client's clock is under the attacker's control, so
/// a generous allowance is just a free extension of every expired file; this
/// covers ordinary NTP drift and nothing more.
///
/// Shared with [`crate::checkout::machine_file`], which enforces the same
/// `exp` claim over the same signed `meta` block. Two constants would let the
/// two file formats silently drift into different grace periods.
pub(crate) const CLOCK_SKEW_TOLERANCE_SECS: i64 = 60;

/// Parses and fully verifies a `.lic` file (from either
/// [`crate::Client::check_out_license`]'s raw PEM string or
/// [`LicenseFileResource::attributes`]'s `certificate` field), returning
/// the embedded [`crate::models::license::LicenseResource`] once the
/// signature (and decryption, if encrypted) has checked out. Works fully
/// offline — no network access required — once `ed25519_pubkey` is
/// embedded in the calling application.
///
/// `license_key` is required only for the encrypted
/// (`aes-256-gcm+ed25519+v2`) variant; pass `None` for a plain
/// (`base64+ed25519+v2`) file. A file whose `alg` lacks the `+v2` suffix is
/// rejected as [`crate::error::CheckoutError::UnsupportedAlgorithm`] — there
/// is no v1 fallback.
///
/// The signed `exp` claim is enforced against the system clock with a 60
/// second skew tolerance; use [`verify_license_file_at`] to supply the time
/// yourself.
///
/// See the module doc comment for the full verification flow this
/// implements, [`crate::crypto::ed25519`] for the signature gotcha (the
/// signature covers the base64 **string**, not its decoded bytes), and
/// [`crate::crypto::hkdf::derive_license_file_key`] for the encryption key
/// derivation.
pub fn verify_license_file(
    pem: &str,
    ed25519_pubkey: &[u8; 32],
    license_key: Option<&str>,
) -> Result<crate::models::license::LicenseResource, crate::error::CheckoutError> {
    verify_license_file_with_claims(pem, ed25519_pubkey, license_key).map(|v| v.license)
}

/// As [`verify_license_file`], also returning the signed claims.
///
/// Use this when you want `jti` for replay detection or `kid` for key-rotation
/// bookkeeping. Expiry is enforced either way — it is not opt-in.
pub fn verify_license_file_with_claims(
    pem: &str,
    ed25519_pubkey: &[u8; 32],
    license_key: Option<&str>,
) -> Result<VerifiedLicenseFile, crate::error::CheckoutError> {
    verify_license_file_at(pem, ed25519_pubkey, license_key, unix_now())
}

/// Current wall-clock time as a Unix timestamp.
///
/// `chrono` is built here without its `clock` feature on purpose (the SDK does
/// not want a system-time dependency in its default build), so this reads the
/// clock directly. A clock set before the epoch yields 0.
///
/// Shared with [`crate::checkout::machine_file`] so both offline file formats
/// read the same clock.
pub(crate) fn unix_now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

/// As [`verify_license_file_with_claims`], with the current time supplied by
/// the caller.
///
/// Two uses. Tests get determinism. And an application that keeps a
/// server-supplied timestamp — the recommended defence against a user winding
/// the system clock back to revive an expired file — can pass that instead of
/// trusting the local clock.
pub fn verify_license_file_at(
    pem: &str,
    ed25519_pubkey: &[u8; 32],
    license_key: Option<&str>,
    now_unix: i64,
) -> Result<VerifiedLicenseFile, crate::error::CheckoutError> {
    let cert = parse_envelope(pem)?;
    // The `alg` gate runs before any key or signature work on every entry
    // point, so a v1 file gets the same answer whichever key it meets.
    let encoding = validate_alg(&cert.alg)?;
    // Nothing is decoded or decrypted until the signature over `enc` has
    // passed.
    verify_signature(ed25519_pubkey, &cert)?;
    let plaintext = decode_plaintext(&cert, encoding, license_key)?;
    finish(&plaintext, now_unix)
}

/// As [`verify_license_file`], verifying against a set of keys the caller
/// trusts rather than one, and labelling a failure by the file's own `kid`
/// claim.
///
/// This is what makes a key rotation survivable. Verifying against one
/// embedded key reports a file signed before the rotation with exactly the
/// error a forged file produces; through a key set the two are distinct:
///
/// - no held key verifies the signature and the `kid` is not in the set →
///   [`crate::error::CheckoutError::UnknownSigningKey`] — fetch the
///   account's key set, or ship an application update, and try again;
/// - no held key verifies and the `kid` *is* in the set →
///   [`crate::error::CryptoError::VerificationFailed`] — refuse the file.
///
/// Build the set with [`crate::Client::signing_key_set`] (one call, cacheable
/// for the life of the process) or, with no network at all, from public keys
/// pinned in the binary via
/// [`crate::checkout::key_set::SigningKeySet::from_public_keys`].
///
/// `license_key` is required only for an encrypted file, exactly as in
/// [`verify_license_file`]. The signed `exp` claim is enforced the same way
/// too; use [`verify_license_file_with_key_set_at`] to supply the time.
///
/// The order is the same as [`verify_license_file`]'s: the `alg` gate, then
/// every held key against the signature over `enc`'s base64 string, and only
/// then is `enc` decoded — so nothing attacker-chosen reaches the decoder,
/// the cipher or the JSON parser on the success path. When no key verifies,
/// `enc` is decoded (and, when encrypted, decrypted under the licence key)
/// solely to read `meta.kid` and label the failure; nothing else is taken
/// from those bytes. One consequence worth knowing: once a signature has
/// verified, a [`crate::error::CryptoError::DecryptionFailed`] can only mean
/// the wrong licence key, because the ciphertext is inside the signature that
/// just passed.
pub fn verify_license_file_with_key_set(
    pem: &str,
    keys: &crate::checkout::key_set::SigningKeySet,
    license_key: Option<&str>,
) -> Result<VerifiedLicenseFile, crate::error::CheckoutError> {
    verify_license_file_with_key_set_at(pem, keys, license_key, unix_now())
}

/// As [`verify_license_file_with_key_set`], with the current time supplied by
/// the caller — see [`verify_license_file_at`] for why that matters.
pub fn verify_license_file_with_key_set_at(
    pem: &str,
    keys: &crate::checkout::key_set::SigningKeySet,
    license_key: Option<&str>,
    now_unix: i64,
) -> Result<VerifiedLicenseFile, crate::error::CheckoutError> {
    let cert = parse_envelope(pem)?;
    let encoding = validate_alg(&cert.alg)?;
    let sig_bytes = decode_signature(&cert)?;

    // ⚠️ Every held key is tried against `enc`'s base64 STRING bytes, before
    // a byte of `enc` is decoded — the same order as the single-key path.
    match keys.find_verifying_key(cert.enc.as_bytes(), &sig_bytes)? {
        Some(_verified_key) => {
            let plaintext = decode_plaintext(&cert, encoding, license_key)?;
            finish(&plaintext, now_unix)
        }
        // No held key signed this. `enc` is opened now, and only now, and
        // only so the `kid` it names can label the failure.
        None => Err(keys.label_failure(decode_plaintext(&cert, encoding, license_key))),
    }
}

/// Strips the PEM markers and parses the inner `{ enc, sig, alg }` JSON.
fn parse_envelope(pem: &str) -> Result<CertPayload, crate::error::CheckoutError> {
    use base64::Engine as _;
    const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;

    let body = pem
        .trim()
        .strip_prefix(PEM_HEADER)
        .and_then(|rest| rest.strip_suffix(PEM_FOOTER))
        .ok_or(crate::error::CheckoutError::MalformedPem)?
        .trim();

    let cert_json = B64
        .decode(body)
        .map_err(|_| crate::error::CheckoutError::InvalidBase64)?;
    Ok(serde_json::from_slice(&cert_json)?)
}

/// Base64-decodes `sig`. Shared by both entry points.
fn decode_signature(cert: &CertPayload) -> Result<Vec<u8>, crate::error::CheckoutError> {
    use base64::Engine as _;
    base64::engine::general_purpose::STANDARD
        .decode(&cert.sig)
        .map_err(|_| crate::error::CheckoutError::InvalidBase64)
}

/// Ed25519-verifies `cert.sig` against `cert.enc`.
///
/// ⚠️ The signature covers `enc`'s ASCII/UTF-8 bytes — the base64 STRING
/// itself, never its decoded bytes. See `src/crypto/ed25519.rs`.
fn verify_signature(
    ed25519_pubkey: &[u8; 32],
    cert: &CertPayload,
) -> Result<(), crate::error::CheckoutError> {
    let sig_bytes = decode_signature(cert)?;
    crate::crypto::ed25519::verify(ed25519_pubkey, cert.enc.as_bytes(), &sig_bytes)?;
    Ok(())
}

/// How `enc` is encoded, as declared by `alg`. Private: the two legal
/// strings are matched whole and nothing outside this module needs the
/// distinction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EncEncoding {
    /// `base64+ed25519+v2` — `enc` is base64 of the payload JSON.
    Plain,
    /// `aes-256-gcm+ed25519+v2` — `enc` is base64 of `nonce ‖ ciphertext ‖ tag`.
    Aes256Gcm,
}

/// The `alg` gate. Runs before any key or signature work on every entry
/// point, single-key and key-set alike.
///
/// Exactly two strings are legal, matched whole; a v1 file (no `+v2`) is
/// [`crate::error::CheckoutError::UnsupportedAlgorithm`] and there is no
/// fallback — see the module doc for why. Running it first is what makes
/// the answer entry-point-independent: a v1 file presented with the wrong
/// key used to report a signature failure through [`verify_license_file`]
/// and an unsupported algorithm through
/// [`verify_license_file_with_key_set`] — one file, two diagnoses.
fn validate_alg(alg: &str) -> Result<EncEncoding, crate::error::CheckoutError> {
    match alg {
        "base64+ed25519+v2" => Ok(EncEncoding::Plain),
        "aes-256-gcm+ed25519+v2" => Ok(EncEncoding::Aes256Gcm),
        other => Err(crate::error::CheckoutError::UnsupportedAlgorithm(
            other.to_string(),
        )),
    }
}

/// Base64-decodes `enc`, decrypting it first when `encoding` says so.
///
/// `encoding` comes from [`validate_alg`], which every caller has already
/// run, so no `alg` check happens here.
fn decode_plaintext(
    cert: &CertPayload,
    encoding: EncEncoding,
    license_key: Option<&str>,
) -> Result<Vec<u8>, crate::error::CheckoutError> {
    use base64::Engine as _;
    const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;

    let enc_bytes = B64
        .decode(&cert.enc)
        .map_err(|_| crate::error::CheckoutError::InvalidBase64)?;

    match encoding {
        EncEncoding::Plain => Ok(enc_bytes),
        EncEncoding::Aes256Gcm => {
            let key_str = license_key.ok_or(crate::error::CheckoutError::LicenseKeyMissing)?;
            let key = crate::crypto::hkdf::derive_license_file_key(key_str);
            // nonce(12B) ‖ ciphertext ‖ tag(16B) — at least 28 bytes even
            // for an empty plaintext.
            if enc_bytes.len() < 12 + 16 {
                return Err(crate::error::CryptoError::DecryptionFailed.into());
            }
            let (nonce_bytes, ciphertext_and_tag) = enc_bytes.split_at(12);
            let nonce: [u8; 12] = nonce_bytes
                .try_into()
                .expect("split_at(12) guarantees a 12-byte slice");
            Ok(crate::crypto::aes_gcm::decrypt(
                &key,
                &nonce,
                ciphertext_and_tag,
            )?)
        }
    }
}

/// Reads **only** the `kid` claim out of not-yet-verified payload bytes.
///
/// Deliberately its own minimal type rather than a full [`DataPayload`] parse:
/// the one value taken from unverified bytes should be the one value needed to
/// pick a key, and everything else waits until the signature has passed.
///
/// Shared with [`crate::checkout::machine_file`], whose payload carries the
/// same `meta` block built from the same server-side struct.
pub(crate) fn probe_kid(plaintext: &[u8]) -> Result<String, crate::error::CheckoutError> {
    #[derive(serde::Deserialize)]
    struct KidProbe {
        meta: KidProbeMeta,
    }
    #[derive(serde::Deserialize)]
    struct KidProbeMeta {
        kid: String,
    }

    let probe: KidProbe = serde_json::from_slice(plaintext)?;
    Ok(probe.meta.kid)
}

/// Parses the verified payload and enforces its signed `exp` claim.
fn finish(
    plaintext: &[u8],
    now_unix: i64,
) -> Result<VerifiedLicenseFile, crate::error::CheckoutError> {
    let payload: DataPayload = serde_json::from_slice(plaintext)?;

    // The signature proves the file is authentic. It does not prove it is
    // still valid — that is this check, and skipping it is what made v1 files
    // permanent.
    if let Some(exp) = payload.meta.exp {
        // `saturating_sub`, not `-`: `now_unix` comes from the caller, and an
        // absurd one must not panic in a debug build or wrap in a release one.
        if now_unix.saturating_sub(CLOCK_SKEW_TOLERANCE_SECS) > exp {
            return Err(crate::error::CheckoutError::Expired { exp });
        }
    }

    Ok(VerifiedLicenseFile {
        license: payload.data,
        claims: payload.meta,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use ed25519_dalek::{Signer, SigningKey};
    use rand::rngs::OsRng;
    use rand::RngCore;

    const B64_TEST: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;

    fn gen_keypair() -> ([u8; 32], SigningKey) {
        let mut secret = [0u8; 32];
        OsRng.fill_bytes(&mut secret);
        let signing_key = SigningKey::from_bytes(&secret);
        (signing_key.verifying_key().to_bytes(), signing_key)
    }

    /// Builds a `.lic` PEM exactly the way the server's own encoder does, so
    /// these tests exercise the same wire format a real server produces —
    /// notably signing over the base64 **string**, not decoded bytes.
    fn build_pem(
        payload_json: &str,
        signing_key: &SigningKey,
        encryption_key: Option<&[u8; 32]>,
    ) -> String {
        use base64::Engine as _;
        const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;

        let (enc, alg) = match encryption_key {
            None => (B64.encode(payload_json.as_bytes()), "base64+ed25519+v2"),
            Some(key) => {
                use aes_gcm::aead::Aead;
                use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce};
                use rand::{rngs::OsRng as AeadOsRng, RngCore as _};
                let cipher = Aes256Gcm::new(&Key::<Aes256Gcm>::from(*key));
                let mut nonce_bytes = [0u8; 12];
                AeadOsRng.fill_bytes(&mut nonce_bytes);
                let nonce = Nonce::from(nonce_bytes);
                let ciphertext_and_tag = cipher.encrypt(&nonce, payload_json.as_bytes()).unwrap();
                let mut out = nonce_bytes.to_vec();
                out.extend_from_slice(&ciphertext_and_tag);
                (B64.encode(&out), "aes-256-gcm+ed25519+v2")
            }
        };

        let sig = B64.encode(signing_key.sign(enc.as_bytes()).to_bytes());
        let cert = serde_json::json!({ "enc": enc, "sig": sig, "alg": alg });
        let cert_json = serde_json::to_string(&cert).unwrap();
        let pem_body = B64.encode(cert_json.as_bytes());
        format!("{PEM_HEADER}\n{pem_body}\n{PEM_FOOTER}")
    }

    /// The same payload with a chosen `kid` claim, so a test can name a key.
    fn payload_json_with_kid(kid: &str) -> String {
        let mut v: serde_json::Value =
            serde_json::from_str(&representative_payload_json()).unwrap();
        v["meta"]["kid"] = serde_json::json!(kid);
        v.to_string()
    }

    /// Base64 of a raw public key, the format the server publishes and the
    /// format [`crate::crypto::ed25519::key_id`] hashes.
    fn pubkey_b64(pubkey: &[u8; 32]) -> String {
        use base64::Engine as _;
        base64::engine::general_purpose::STANDARD.encode(pubkey)
    }

    /// Re-wraps `pem` with a different `alg`, leaving `enc` and `sig` intact.
    /// `alg` is not covered by the signature, so this is exactly the downgrade
    /// an attacker can attempt.
    fn repack_alg(pem: &str, alg: &str) -> String {
        use base64::Engine as _;
        let body: String = pem.lines().filter(|l| !l.starts_with("-----")).collect();
        let cert_json = B64_TEST.decode(body.trim()).unwrap();
        let mut cert: serde_json::Value = serde_json::from_slice(&cert_json).unwrap();
        cert["alg"] = serde_json::json!(alg);
        let repacked = B64_TEST.encode(serde_json::to_string(&cert).unwrap().as_bytes());
        format!("{PEM_HEADER}\n{repacked}\n{PEM_FOOTER}")
    }

    fn representative_payload_json() -> String {
        serde_json::json!({
            "data": {
                "type": "licenses",
                "id": "01926b3e-0000-7000-8000-000000000000",
                "attributes": {
                    "name": "Acme Corp", "key": "lic-abc123", "status": "ACTIVE",
                    "expiry": null, "suspended": false, "protected": false,
                    "scheme": null, "encrypted": false, "strict": false, "floating": false,
                    "max_machines": null, "max_users": null,
                    "last_validated_at": null, "last_check_in_at": null, "last_check_out_at": null,
                    "machines_count": 0, "metadata": {},
                    "created": "2026-01-01T00:00:00Z", "updated": "2026-01-01T00:00:00Z",
                }
            },
            "meta": { "iat": 1_767_225_600, "jti": "test-jti", "kid": "test-kid" }
        })
        .to_string()
    }

    /// The same payload with an `exp` claim `offset` seconds from `iat`.
    fn payload_json_expiring_at(exp: i64) -> String {
        let mut v: serde_json::Value =
            serde_json::from_str(&representative_payload_json()).unwrap();
        v["meta"]["exp"] = serde_json::json!(exp);
        v.to_string()
    }

    // ── Format v2: the expiry claim ──────────────────────────────────────

    #[test]
    fn an_expired_file_is_refused_even_though_its_signature_is_valid() {
        // The whole point of v2. In v1 the requested TTL lived only in the
        // JSON:API envelope around the certificate, so a 24-hour trial file
        // stayed cryptographically valid forever and the client — which is the
        // attacker — simply kept the raw PEM.
        let (pubkey, signing_key) = gen_keypair();
        let exp = 1_767_225_600;
        let pem = build_pem(&payload_json_expiring_at(exp), &signing_key, None);

        let err = verify_license_file_at(&pem, &pubkey, None, exp + 3600).unwrap_err();
        assert!(matches!(err, crate::error::CheckoutError::Expired { .. }));
    }

    #[test]
    fn a_file_within_its_ttl_verifies() {
        let (pubkey, signing_key) = gen_keypair();
        let exp = 1_767_225_600;
        let pem = build_pem(&payload_json_expiring_at(exp), &signing_key, None);

        let verified = verify_license_file_at(&pem, &pubkey, None, exp - 3600).unwrap();
        assert_eq!(verified.claims.exp, Some(exp));
    }

    #[test]
    fn a_file_without_an_exp_claim_never_expires() {
        // Checkout without a `ttl` produces no `exp`. That must read as
        // perpetual, not as "expired at the epoch".
        let (pubkey, signing_key) = gen_keypair();
        let pem = build_pem(&representative_payload_json(), &signing_key, None);

        let verified = verify_license_file_at(&pem, &pubkey, None, i64::MAX / 2).unwrap();
        assert!(verified.claims.exp.is_none());
    }

    #[test]
    fn clock_skew_tolerance_is_seconds_not_hours() {
        // A generous allowance would just be a free extension on every expired
        // file, since the clock belongs to the attacker.
        let (pubkey, signing_key) = gen_keypair();
        let exp = 1_767_225_600;
        let pem = build_pem(&payload_json_expiring_at(exp), &signing_key, None);

        // Just inside the tolerance.
        assert!(verify_license_file_at(&pem, &pubkey, None, exp + 30).is_ok());
        // Comfortably outside it.
        assert!(verify_license_file_at(&pem, &pubkey, None, exp + 600).is_err());
    }

    #[test]
    fn a_v1_file_is_refused_outright() {
        use base64::Engine as _;
        // Accepting both formats would hand back the permanent-file problem:
        // an attacker holding any v1 certificate could keep using it forever.
        let (pubkey, signing_key) = gen_keypair();
        let pem = build_pem(&representative_payload_json(), &signing_key, None);
        // Repack the same certificate with a v1 `alg`.
        let body: String = pem.lines().filter(|l| !l.starts_with("-----")).collect();
        let cert_json = B64_TEST.decode(body.trim()).unwrap();
        let mut cert: serde_json::Value = serde_json::from_slice(&cert_json).unwrap();
        cert["alg"] = serde_json::json!("base64+ed25519");
        let repacked = B64_TEST.encode(serde_json::to_string(&cert).unwrap().as_bytes());
        let v1_pem = format!("{PEM_HEADER}\n{repacked}\n{PEM_FOOTER}");

        let err = verify_license_file(&v1_pem, &pubkey, None).unwrap_err();
        assert!(matches!(
            err,
            crate::error::CheckoutError::UnsupportedAlgorithm(ref a) if a == "base64+ed25519"
        ));
    }

    #[test]
    fn a_v1_alg_is_refused_before_the_signature_is_even_checked() {
        // D17. The same file must produce the same error from every entry
        // point, and the `alg` gate must not depend on holding the right
        // key: presented with the WRONG key, a v1 file used to report a
        // signature failure here and UnsupportedAlgorithm through a key set.
        let (_pubkey, signing_key) = gen_keypair();
        let (wrong_pubkey, _) = gen_keypair();
        let pem = build_pem(&representative_payload_json(), &signing_key, None);
        let v1_pem = repack_alg(&pem, "base64+ed25519");

        assert!(matches!(
            verify_license_file(&v1_pem, &wrong_pubkey, None).unwrap_err(),
            crate::error::CheckoutError::UnsupportedAlgorithm(ref a) if a == "base64+ed25519"
        ));
    }

    #[test]
    fn the_claims_carry_a_replay_id_and_a_key_id() {
        let (pubkey, signing_key) = gen_keypair();
        let pem = build_pem(&representative_payload_json(), &signing_key, None);

        let verified = verify_license_file_with_claims(&pem, &pubkey, None).unwrap();
        assert!(!verified.claims.jti.is_empty());
        assert!(!verified.claims.kid.is_empty());
    }

    #[test]
    fn verifies_a_known_good_plain_fixture() {
        let (pubkey, signing_key) = gen_keypair();
        let pem = build_pem(&representative_payload_json(), &signing_key, None);
        let license = verify_license_file(&pem, &pubkey, None).unwrap();
        assert_eq!(license.attributes.key, Some("lic-abc123".to_string()));
    }

    #[test]
    fn verifies_a_known_good_encrypted_fixture() {
        let (pubkey, signing_key) = gen_keypair();
        let license_key = "lic-abc123";
        let enc_key = crate::crypto::hkdf::derive_license_file_key(license_key);
        let pem = build_pem(&representative_payload_json(), &signing_key, Some(&enc_key));
        let license = verify_license_file(&pem, &pubkey, Some(license_key)).unwrap();
        assert_eq!(license.attributes.key, Some("lic-abc123".to_string()));
    }

    #[test]
    fn rejects_tampered_signature() {
        let (pubkey, signing_key) = gen_keypair();
        let mut pem = build_pem(&representative_payload_json(), &signing_key, None);
        // Flip a character inside the base64 PEM body — corrupts the
        // encoded `sig` field without breaking base64/JSON parsing.
        let mid = pem.len() / 2;
        let corrupted_char = if pem.as_bytes()[mid] == b'A' {
            'B'
        } else {
            'A'
        };
        pem.replace_range(mid..mid + 1, &corrupted_char.to_string());
        assert!(verify_license_file(&pem, &pubkey, None).is_err());
    }

    #[test]
    fn rejects_tampered_ciphertext_aead_tag_mismatch() {
        let (pubkey, signing_key) = gen_keypair();
        let license_key = "lic-abc123";
        let enc_key = crate::crypto::hkdf::derive_license_file_key(license_key);
        // Re-sign a manually tampered `enc` so signature verification
        // passes but AEAD decryption must fail — proves the AEAD tag
        // check itself, independent of signature verification.
        use base64::Engine as _;
        const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
        let mut enc_bytes = {
            use aes_gcm::aead::Aead;
            use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce};
            use rand::{rngs::OsRng as AeadOsRng, RngCore as _};
            let cipher = Aes256Gcm::new(&Key::<Aes256Gcm>::from(*enc_key));
            let mut nonce_bytes = [0u8; 12];
            AeadOsRng.fill_bytes(&mut nonce_bytes);
            let nonce = Nonce::from(nonce_bytes);
            let ciphertext_and_tag = cipher
                .encrypt(&nonce, representative_payload_json().as_bytes())
                .unwrap();
            let mut out = nonce_bytes.to_vec();
            out.extend_from_slice(&ciphertext_and_tag);
            out
        };
        let last = enc_bytes.len() - 1;
        enc_bytes[last] ^= 0xff;
        let enc = B64.encode(&enc_bytes);
        let sig = B64.encode(signing_key.sign(enc.as_bytes()).to_bytes());
        let cert = serde_json::json!({ "enc": enc, "sig": sig, "alg": "aes-256-gcm+ed25519+v2" });
        let pem_body = B64.encode(serde_json::to_string(&cert).unwrap().as_bytes());
        let pem = format!("{PEM_HEADER}\n{pem_body}\n{PEM_FOOTER}");

        assert!(verify_license_file(&pem, &pubkey, Some(license_key)).is_err());
    }

    // ── Key rotation: verifying through a key set ────────────────────────

    #[test]
    fn a_file_signed_before_a_rotation_still_verifies_against_the_retired_key() {
        // The scenario the whole key-set path exists for. Two keys, the file
        // signed by the older one, and a set that holds both — the retired key
        // is in the set precisely because the server never deletes it.
        let (old_pubkey, old_signing) = gen_keypair();
        let (new_pubkey, _new_signing) = gen_keypair();
        let old_b64 = pubkey_b64(&old_pubkey);
        let kid = crate::crypto::ed25519::key_id(&old_b64);

        let pem = build_pem(&payload_json_with_kid(&kid), &old_signing, None);
        let keys = crate::checkout::key_set::SigningKeySet::from_public_keys([
            pubkey_b64(&new_pubkey),
            old_b64,
        ])
        .unwrap();

        let verified = verify_license_file_with_key_set(&pem, &keys, None).unwrap();
        assert_eq!(verified.claims.kid, kid);
        assert_eq!(
            verified.license.attributes.key,
            Some("lic-abc123".to_string())
        );

        // …and the single-key call against the *current* key is exactly the
        // false alarm this replaces.
        assert!(verify_license_file(&pem, &new_pubkey, None).is_err());
    }

    #[test]
    fn an_unknown_kid_is_reported_distinctly_from_a_bad_signature() {
        // The distinction M22 exists to create. Same file, two key sets: one
        // that has never heard of the signer, and one that has and rejects the
        // signature. Collapsing these into one error is what left a caller
        // unable to tell a stale key set from a forgery.
        let (_pubkey, signing) = gen_keypair();
        let (other_pubkey, _) = gen_keypair();
        let other_b64 = pubkey_b64(&other_pubkey);

        let pem = build_pem(&payload_json_with_kid("00ff00ff00ff00ff"), &signing, None);

        // 1. The claimed kid is in no key we hold.
        let stale =
            crate::checkout::key_set::SigningKeySet::from_public_keys([&other_b64]).unwrap();
        let err = verify_license_file_with_key_set(&pem, &stale, None).unwrap_err();
        assert!(
            matches!(
                err,
                crate::error::CheckoutError::UnknownSigningKey { ref kid }
                    if kid == "00ff00ff00ff00ff"
            ),
            "expected UnknownSigningKey, got {err:?}"
        );

        // 2. The claimed kid resolves — to a key that did not sign this file.
        let wrong_key_under_the_claimed_kid = build_pem(
            &payload_json_with_kid(&crate::crypto::ed25519::key_id(&other_b64)),
            &signing,
            None,
        );
        let err = verify_license_file_with_key_set(&wrong_key_under_the_claimed_kid, &stale, None)
            .unwrap_err();
        assert!(matches!(
            err,
            crate::error::CheckoutError::Crypto(crate::error::CryptoError::VerificationFailed)
        ));
    }

    #[test]
    fn an_empty_key_set_reports_the_kid_rather_than_a_forgery() {
        // A fetch that returned nothing, or an application shipped with no
        // pinned key: honest as "I hold no key for this", never as "forged".
        let (_pubkey, signing) = gen_keypair();
        let pem = build_pem(&payload_json_with_kid("abcdef0123456789"), &signing, None);
        let empty = crate::checkout::key_set::SigningKeySet::default();

        let err = verify_license_file_with_key_set(&pem, &empty, None).unwrap_err();
        assert!(matches!(
            err,
            crate::error::CheckoutError::UnknownSigningKey { ref kid } if kid == "abcdef0123456789"
        ));
    }

    #[test]
    fn the_key_set_path_verifies_before_it_decrypts() {
        // D16, stated as the order of two checks. Every held key is tried
        // against the signature BEFORE a byte of `enc` is opened; the kid
        // inside the ciphertext is read only when none verifies, and only
        // to label the failure. Two observable consequences:
        // - a set that does not hold the signer, plus the wrong licence key:
        //   a signature failure. The ciphertext was opened only to read the
        //   kid, could not be, and the failure stands unlabelled.
        // - a set that holds the signer, plus the wrong licence key:
        //   DecryptionFailed — and since `enc` is inside the signature that
        //   just passed, that can only mean the wrong key, never tampering.
        let (pubkey, signing) = gen_keypair();
        let (other_pubkey, _) = gen_keypair();
        let b64 = pubkey_b64(&pubkey);
        let kid = crate::crypto::ed25519::key_id(&b64);
        let enc_key = crate::crypto::hkdf::derive_license_file_key("lic-abc123");
        let pem = build_pem(&payload_json_with_kid(&kid), &signing, Some(&enc_key));

        let stale =
            crate::checkout::key_set::SigningKeySet::from_public_keys([pubkey_b64(&other_pubkey)])
                .unwrap();
        assert!(
            matches!(
                verify_license_file_with_key_set(&pem, &stale, Some("wrong-key")).unwrap_err(),
                crate::error::CheckoutError::Crypto(crate::error::CryptoError::VerificationFailed)
            ),
            "an unreadable kid leaves the signature failure standing"
        );

        let held = crate::checkout::key_set::SigningKeySet::from_public_keys([&b64]).unwrap();
        assert!(
            matches!(
                verify_license_file_with_key_set(&pem, &held, Some("wrong-key")).unwrap_err(),
                crate::error::CheckoutError::Crypto(crate::error::CryptoError::DecryptionFailed)
            ),
            "after a verified signature, a decryption failure is a wrong-key report"
        );
        assert!(verify_license_file_with_key_set(&pem, &held, Some("lic-abc123")).is_ok());
    }

    #[test]
    fn a_held_key_verifies_a_file_whatever_kid_it_names() {
        // The signature decides; the kid only labels a failure. A file
        // signed by a held key verifies even when its kid names another
        // held key — the "no try-every-key" rule is gone on purpose.
        let (pubkey_a, signing_a) = gen_keypair();
        let (pubkey_b, _) = gen_keypair();
        let a_b64 = pubkey_b64(&pubkey_a);
        let b_b64 = pubkey_b64(&pubkey_b);
        let pem = build_pem(
            &payload_json_with_kid(&crate::crypto::ed25519::key_id(&b_b64)),
            &signing_a,
            None,
        );
        let keys =
            crate::checkout::key_set::SigningKeySet::from_public_keys([&a_b64, &b_b64]).unwrap();

        assert!(verify_license_file_with_key_set(&pem, &keys, None).is_ok());
    }

    #[test]
    fn a_stale_set_with_an_encrypted_file_still_names_the_kid_given_the_licence_key() {
        // The label needs the kid and the kid is inside the ciphertext: with
        // the right licence key the probe reads it and names the stale set.
        // With no licence key at all, the missing argument is reported as
        // such rather than dressed up as a verdict.
        let (_pubkey, signing) = gen_keypair();
        let (other_pubkey, _) = gen_keypair();
        let enc_key = crate::crypto::hkdf::derive_license_file_key("lic-abc123");
        let pem = build_pem(
            &payload_json_with_kid("abcdef0123456789"),
            &signing,
            Some(&enc_key),
        );
        let stale =
            crate::checkout::key_set::SigningKeySet::from_public_keys([pubkey_b64(&other_pubkey)])
                .unwrap();

        assert!(matches!(
            verify_license_file_with_key_set(&pem, &stale, Some("lic-abc123")).unwrap_err(),
            crate::error::CheckoutError::UnknownSigningKey { ref kid } if kid == "abcdef0123456789"
        ));
        assert!(matches!(
            verify_license_file_with_key_set(&pem, &stale, None).unwrap_err(),
            crate::error::CheckoutError::LicenseKeyMissing
        ));
    }

    #[test]
    fn the_key_set_path_opens_an_encrypted_file_and_still_enforces_exp() {
        // The signature is checked against every held key first; the
        // ciphertext is opened only afterwards — and expiry is enforced
        // exactly as on the single-key path, not skipped.
        let (pubkey, signing) = gen_keypair();
        let b64 = pubkey_b64(&pubkey);
        let kid = crate::crypto::ed25519::key_id(&b64);
        let keys = crate::checkout::key_set::SigningKeySet::from_public_keys([&b64]).unwrap();

        let license_key = "lic-abc123";
        let enc_key = crate::crypto::hkdf::derive_license_file_key(license_key);
        let exp = 1_767_225_600;
        let mut payload: serde_json::Value =
            serde_json::from_str(&payload_json_with_kid(&kid)).unwrap();
        payload["meta"]["exp"] = serde_json::json!(exp);
        let pem = build_pem(&payload.to_string(), &signing, Some(&enc_key));

        let verified =
            verify_license_file_with_key_set_at(&pem, &keys, Some(license_key), exp - 3600)
                .unwrap();
        assert_eq!(verified.claims.exp, Some(exp));

        let err = verify_license_file_with_key_set_at(&pem, &keys, Some(license_key), exp + 3600)
            .unwrap_err();
        assert!(matches!(err, crate::error::CheckoutError::Expired { .. }));

        // Without the licence key the payload cannot be decoded at all, so no
        // key can be selected — reported as the missing key, not as a forgery.
        assert!(matches!(
            verify_license_file_with_key_set(&pem, &keys, None).unwrap_err(),
            crate::error::CheckoutError::LicenseKeyMissing
        ));
    }

    #[test]
    fn the_key_set_path_refuses_a_v1_file_too() {
        use base64::Engine as _;
        // The alg gate runs first on every entry point; the key-set path is
        // no way round it.
        let (pubkey, signing) = gen_keypair();
        let b64 = pubkey_b64(&pubkey);
        let keys = crate::checkout::key_set::SigningKeySet::from_public_keys([&b64]).unwrap();
        let pem = build_pem(
            &payload_json_with_kid(&crate::crypto::ed25519::key_id(&b64)),
            &signing,
            None,
        );

        let body: String = pem.lines().filter(|l| !l.starts_with("-----")).collect();
        let cert_json = B64_TEST.decode(body.trim()).unwrap();
        let mut cert: serde_json::Value = serde_json::from_slice(&cert_json).unwrap();
        cert["alg"] = serde_json::json!("base64+ed25519");
        let repacked = B64_TEST.encode(serde_json::to_string(&cert).unwrap().as_bytes());
        let v1_pem = format!("{PEM_HEADER}\n{repacked}\n{PEM_FOOTER}");

        assert!(matches!(
            verify_license_file_with_key_set(&v1_pem, &keys, None).unwrap_err(),
            crate::error::CheckoutError::UnsupportedAlgorithm(ref a) if a == "base64+ed25519"
        ));
    }

    #[test]
    fn a_payload_without_a_kid_claim_is_a_parse_failure_not_an_unknown_key() {
        use base64::Engine as _;
        // Every v2 file the server issues carries one. A payload missing it is
        // malformed, and calling that "signed by a key I do not have" would
        // point the caller at the wrong remedy.
        let (pubkey, signing) = gen_keypair();
        let b64 = pubkey_b64(&pubkey);
        let keys = crate::checkout::key_set::SigningKeySet::from_public_keys([&b64]).unwrap();

        let mut payload: serde_json::Value =
            serde_json::from_str(&representative_payload_json()).unwrap();
        payload["meta"].as_object_mut().unwrap().remove("kid");
        let enc = B64_TEST.encode(payload.to_string().as_bytes());
        let sig = B64_TEST.encode(signing.sign(enc.as_bytes()).to_bytes());
        let cert = serde_json::json!({ "enc": enc, "sig": sig, "alg": "base64+ed25519+v2" });
        let pem_body = B64_TEST.encode(serde_json::to_string(&cert).unwrap().as_bytes());
        let pem = format!("{PEM_HEADER}\n{pem_body}\n{PEM_FOOTER}");

        assert!(matches!(
            verify_license_file_with_key_set(&pem, &keys, None).unwrap_err(),
            crate::error::CheckoutError::InvalidJson(_)
        ));
    }

    #[test]
    fn decoded_bytes_signature_verification_fails_proving_the_string_bytes_gotcha() {
        // Negative test proving the SDK signs/verifies over the base64
        // STRING, not decoded bytes.
        let (pubkey, signing_key) = gen_keypair();
        let payload = representative_payload_json();
        use base64::Engine as _;
        const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
        let enc = B64.encode(payload.as_bytes());
        let decoded_enc_bytes = B64.decode(&enc).unwrap();

        // Sign over the DECODED bytes instead of the string — the wrong
        // way to do it.
        let wrong_sig = signing_key.sign(&decoded_enc_bytes);

        // This SDK's `verify_license_file` always verifies against the
        // base64 STRING bytes (`cert.enc.as_bytes()`), so a signature
        // computed over decoded bytes must NOT verify.
        let verify_result =
            crate::crypto::ed25519::verify(&pubkey, enc.as_bytes(), &wrong_sig.to_bytes());
        assert!(
            verify_result.is_err(),
            "a signature over decoded bytes must not verify against the base64 string bytes"
        );
    }
}