oxo-license 0.1.1

Generic dual-license runtime verification library for Traitome projects
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
//! Generic dual-license runtime verification library for Traitome Rust projects.
//!
//! # Overview
//!
//! `oxo-license` provides an Ed25519-based license verification system that
//! can be embedded into any Rust application. It supports:
//!
//! - **Any number of license types** (e.g., `"academic"`, `"commercial"`, `"enterprise"`)
//! - **Shared key infrastructure** — all Traitome products use the same signing key pair
//! - **Offline verification** — no network calls required at runtime
//! - **Configurable discovery** — customize env var names and platform config dirs
//!
//! # Architecture
//!
//! ```text
//!  Issuer (offline tool)              Application (runtime)
//!  ──────────────────────             ─────────────────────
//!  LicensePayload ──┐                 license.json ──▶ LicenseFile
//!  SigningKey (Ed25519)               │                     │
//!      │                             │                     ▼
//!      └──▶ serde_json::to_vec ──▶  sign ──▶   verify_license_with_key
//!                                             (EMBEDDED_PUBLIC_KEY_BASE64)
//! ```
//!
//! # Quick Start
//!
//! ```rust,no_run
//! use oxo_license::{LicenseConfig, load_and_verify};
//!
//! // Define your project's license configuration
//! static MY_CONFIG: LicenseConfig = LicenseConfig {
//!     schema_version: "my-app-license-v1",
//!     public_key_base64: "BASE64_ENCODED_32_BYTE_PUBLIC_KEY",
//!     license_env_var: "MY_APP_LICENSE",
//!     app_qualifier: "io",
//!     app_org: "myorg",
//!     app_name: "my-app",
//!     license_filename: "license.json",
//! };
//!
//! // Verify a license at runtime
//! fn check_license(path: Option<&std::path::Path>) -> Result<(), oxo_license::LicenseError> {
//!     load_and_verify(path, &MY_CONFIG)?;
//!     Ok(())
//! }
//! ```
//!
//! # License Schema
//!
//! A signed license file is a JSON object with these fields:
//!
//! ```json
//! {
//!   "schema": "my-app-license-v1",
//!   "license_id": "550e8400-e29b-41d4-a716-446655440000",
//!   "issued_to_org": "Acme University",
//!   "contact_email": "research@acme.edu",
//!   "license_type": "academic",
//!   "scope": "org",
//!   "perpetual": true,
//!   "issued_at": "2025-01-01",
//!   "signature": "BASE64_ENCODED_64_BYTE_ED25519_SIGNATURE"
//! }
//! ```
//!
//! **Field order in the JSON object is the canonical wire format** — the
//! signature covers `serde_json::to_vec(&payload)` with fields in the order
//! they are declared in [`LicensePayload`].

use base64::{Engine as _, engine::general_purpose::STANDARD};
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

// ── Configuration ─────────────────────────────────────────────────────────────

/// Project-specific configuration for the license system.
///
/// Create a `static` instance of this struct in your application to define
/// the schema version, embedded public key, and file discovery parameters.
///
/// # Example
///
/// ```rust
/// use oxo_license::LicenseConfig;
///
/// pub static MY_LICENSE_CONFIG: LicenseConfig = LicenseConfig {
///     schema_version: "my-app-license-v1",
///     public_key_base64: "BASE64_32_BYTES",
///     license_env_var: "MY_APP_LICENSE",
///     app_qualifier: "io",
///     app_org: "myorg",
///     app_name: "my-app",
///     license_filename: "license.json",
/// };
/// ```
#[derive(Debug, Clone)]
pub struct LicenseConfig {
    /// Schema version string embedded in every license payload.
    /// Must match exactly between issuer and verifier.
    /// Example: `"my-app-license-v1"`
    pub schema_version: &'static str,

    /// Base64-encoded 32-byte Ed25519 public key (verifying key).
    /// Generated by the `oxo-license-issuer generate-keypair` command.
    pub public_key_base64: &'static str,

    /// Environment variable name that users can set to point to their license file.
    /// Example: `"MY_APP_LICENSE"`
    pub license_env_var: &'static str,

    /// Application qualifier for platform config directory discovery.
    /// Example: `"io"` → `io.myorg.my-app`
    pub app_qualifier: &'static str,

    /// Application organization for platform config directory discovery.
    /// Example: `"traitome"`
    pub app_org: &'static str,

    /// Application name for platform config directory discovery.
    /// Example: `"my-app"`
    pub app_name: &'static str,

    /// License filename to look for in config directories.
    /// Example: `"license.json"` or `"license.oxo.json"`
    pub license_filename: &'static str,
}

// ── Data structures ───────────────────────────────────────────────────────────

/// The payload that is signed by the license issuer.
///
/// **Field order is part of the wire format** — do not reorder fields.
/// `serde_json::to_vec` is used for canonicalization; struct field order
/// determines JSON key order, which must be identical between issuer and verifier.
///
/// The `license_type` field is a free-form string, which allows arbitrary
/// license types to be defined (e.g., `"academic"`, `"commercial"`,
/// `"enterprise"`, `"trial"`, `"internal"`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LicensePayload {
    /// License schema identifier — must match [`LicenseConfig::schema_version`].
    pub schema: String,
    /// Unique license ID (UUID v4 recommended).
    pub license_id: String,
    /// Full legal name of the licensed organization or individual.
    pub issued_to_org: String,
    /// Optional contact e-mail for the licensee.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub contact_email: Option<String>,
    /// License type — any string (e.g., `"academic"`, `"commercial"`, `"enterprise"`).
    pub license_type: String,
    /// Authorization scope — typically `"org"`.
    pub scope: String,
    /// Whether the license is perpetual.
    pub perpetual: bool,
    /// Issue date in `YYYY-MM-DD` format.
    pub issued_at: String,
}

/// Full on-disk license file: payload fields flattened + Ed25519 `signature`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LicenseFile {
    /// All payload fields (flattened into the top-level JSON object).
    #[serde(flatten)]
    pub payload: LicensePayload,
    /// Base64-encoded Ed25519 signature over `serde_json::to_vec(&payload)`.
    pub signature: String,
}

// ── Error type ────────────────────────────────────────────────────────────────

/// Errors returned by the license verification subsystem.
#[derive(Debug, thiserror::Error)]
pub enum LicenseError {
    /// No license file was found in any of the standard search locations.
    #[error(
        "No license file found.\n\
         \n\
         Place your license file at one of:\n\
         \t1. Pass the path via the CLI argument\n\
         \t2. Set the license environment variable\n\
         \t3. Platform config directory\n\
         \t4. Legacy Unix path: ~/.config/<app>/license.json"
    )]
    NotFound,

    /// The license file could not be read from disk.
    #[error("Failed to read license file '{path}': {source}")]
    ReadError {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    /// The license file could not be parsed as JSON.
    #[error(
        "Failed to parse license file as JSON: {0}\n\
         \n\
         Common causes:\n\
         • The file was modified or truncated\n\
         • The file was saved with a UTF-8 BOM\n\
         • The file was downloaded as HTML instead of raw JSON"
    )]
    ParseError(#[from] serde_json::Error),

    /// The license schema does not match the expected value.
    #[error(
        "Invalid license schema: expected '{expected}', found '{found}'.\n\
         This license was issued for a different version or application."
    )]
    InvalidSchema { expected: String, found: String },

    /// The Ed25519 signature on the license is invalid.
    #[error(
        "License signature is invalid.\n\
         The license file may have been tampered with or was not issued by Traitome."
    )]
    InvalidSignature,

    /// The embedded public key is malformed.
    #[error("Internal error — invalid embedded public key: {0}")]
    InvalidPublicKey(String),

    /// The signature field in the license file has invalid encoding.
    #[error("Invalid signature encoding in license file: {0}")]
    InvalidSignatureEncoding(String),
}

// ── Core verification ─────────────────────────────────────────────────────────

/// Verify a [`LicenseFile`] against the public key embedded in `config`.
///
/// Returns `Ok(())` when the license is valid, or a descriptive [`LicenseError`].
///
/// # Example
///
/// ```rust,no_run
/// use oxo_license::{LicenseConfig, LicenseFile, verify_license};
///
/// static CONFIG: LicenseConfig = LicenseConfig {
///     schema_version: "my-app-license-v1",
///     public_key_base64: "BASE64_32_BYTES",
///     license_env_var: "MY_APP_LICENSE",
///     app_qualifier: "io",
///     app_org: "myorg",
///     app_name: "my-app",
///     license_filename: "license.json",
/// };
///
/// fn check(license: &LicenseFile) -> Result<(), oxo_license::LicenseError> {
///     verify_license(license, &CONFIG)
/// }
/// ```
pub fn verify_license(license: &LicenseFile, config: &LicenseConfig) -> Result<(), LicenseError> {
    verify_license_with_key(license, config.public_key_base64, config.schema_version)
}

/// Verify a [`LicenseFile`] against an arbitrary Base64-encoded public key.
///
/// This is the low-level function used by [`verify_license`] and by unit tests
/// with ephemeral test keys.
///
/// # Arguments
///
/// * `license` — The license file to verify.
/// * `pubkey_base64` — Base64-encoded 32-byte Ed25519 public key.
/// * `schema_version` — Expected schema version string.
pub fn verify_license_with_key(
    license: &LicenseFile,
    pubkey_base64: &str,
    schema_version: &str,
) -> Result<(), LicenseError> {
    // 1. Schema check
    if license.payload.schema != schema_version {
        return Err(LicenseError::InvalidSchema {
            expected: schema_version.to_string(),
            found: license.payload.schema.clone(),
        });
    }

    // 2. Decode the public key
    let pubkey_bytes = STANDARD
        .decode(pubkey_base64)
        .map_err(|e| LicenseError::InvalidPublicKey(e.to_string()))?;
    let pubkey_array: [u8; 32] = pubkey_bytes
        .try_into()
        .map_err(|_| LicenseError::InvalidPublicKey("expected exactly 32 bytes".to_string()))?;
    let verifying_key = VerifyingKey::from_bytes(&pubkey_array)
        .map_err(|e| LicenseError::InvalidPublicKey(e.to_string()))?;

    // 3. Decode the signature
    let sig_bytes = STANDARD
        .decode(&license.signature)
        .map_err(|e| LicenseError::InvalidSignatureEncoding(e.to_string()))?;
    let sig_array: [u8; 64] = sig_bytes.try_into().map_err(|_| {
        LicenseError::InvalidSignatureEncoding("expected exactly 64 bytes".to_string())
    })?;
    let signature = Signature::from_bytes(&sig_array);

    // 4. Canonical payload bytes (field order defined by LicensePayload struct)
    let payload_bytes = serde_json::to_vec(&license.payload).map_err(LicenseError::ParseError)?;

    // 5. Verify
    verifying_key
        .verify(&payload_bytes, &signature)
        .map_err(|_| LicenseError::InvalidSignature)?;

    Ok(())
}

// ── Discovery ─────────────────────────────────────────────────────────────────

/// Find the license file path using the priority chain:
///
/// 1. `cli_arg` (if provided and the file exists)
/// 2. Environment variable named `config.license_env_var` (if set and file exists)
/// 3. Platform config directory: `<config_dir>/<license_filename>`
/// 4. Legacy Unix path: `~/.config/<app_name>/<license_filename>`
///
/// Returns the first path that **exists on disk**, or `None`.
pub fn find_license_path(cli_arg: Option<&Path>, config: &LicenseConfig) -> Option<PathBuf> {
    // 1. CLI argument takes highest priority
    if let Some(p) = cli_arg {
        return Some(p.to_path_buf());
    }

    // 2. Environment variable
    if let Ok(val) = std::env::var(config.license_env_var) {
        let p = PathBuf::from(val.trim());
        return Some(p);
    }

    // 3 & 4. Default candidates
    default_license_candidates(config)
        .into_iter()
        .find(|candidate| candidate.exists())
}

/// Load a license file from disk and verify its signature.
///
/// The path is resolved using [`find_license_path`] if not explicitly provided.
///
/// # Errors
///
/// Returns [`LicenseError::NotFound`] when no license file can be located.
/// Returns [`LicenseError::ReadError`] when the file cannot be read.
/// Returns [`LicenseError::ParseError`] when the JSON is malformed.
/// Returns [`LicenseError::InvalidSignature`] when the signature is wrong.
pub fn load_and_verify(
    cli_arg: Option<&Path>,
    config: &LicenseConfig,
) -> Result<LicenseFile, LicenseError> {
    let path = find_license_path(cli_arg, config).ok_or(LicenseError::NotFound)?;

    let contents = std::fs::read_to_string(&path).map_err(|e| LicenseError::ReadError {
        path: path.clone(),
        source: e,
    })?;

    let license: LicenseFile = serde_json::from_str(&contents)?;

    verify_license(&license, config)?;

    Ok(license)
}

// ── Internal helpers ──────────────────────────────────────────────────────────

fn legacy_unix_license_path(home_dir: Option<PathBuf>, config: &LicenseConfig) -> Option<PathBuf> {
    home_dir.map(|home| {
        home.join(".config")
            .join(config.app_name)
            .join(config.license_filename)
    })
}

fn default_license_candidates(config: &LicenseConfig) -> Vec<PathBuf> {
    let mut candidates: Vec<PathBuf> = Vec::new();

    // Platform config directory (uses `directories` crate on native targets)
    #[cfg(not(target_arch = "wasm32"))]
    {
        if let Some(dirs) =
            directories::ProjectDirs::from(config.app_qualifier, config.app_org, config.app_name)
        {
            candidates.push(dirs.config_dir().join(config.license_filename));
        }
    }

    // Legacy Unix fallback: ~/.config/<app_name>/<license_filename>
    let home_dir = std::env::var_os("HOME").map(PathBuf::from);
    if let Some(path) = legacy_unix_license_path(home_dir, config)
        && !candidates.contains(&path)
    {
        candidates.push(path);
    }

    candidates
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    #[allow(unused_imports)]
    use base64::{Engine as _, engine::general_purpose::STANDARD};
    use ed25519_dalek::{Signer, SigningKey};
    use rand::rngs::OsRng;
    use std::sync::Mutex;

    const TEST_SCHEMA: &str = "test-app-license-v1";

    /// Serializes tests that read/write `TEST_APP_LICENSE` to prevent races.
    static ENV_MUTEX: Mutex<()> = Mutex::new(());

    fn make_test_keypair() -> (SigningKey, String) {
        let key = SigningKey::generate(&mut OsRng);
        let pubkey_b64 = STANDARD.encode(key.verifying_key().as_bytes());
        (key, pubkey_b64)
    }

    fn make_config(pubkey_b64: &'static str) -> LicenseConfig {
        LicenseConfig {
            schema_version: TEST_SCHEMA,
            public_key_base64: pubkey_b64,
            license_env_var: "TEST_APP_LICENSE",
            app_qualifier: "io",
            app_org: "testorg",
            app_name: "test-app",
            license_filename: "license.json",
        }
    }

    fn make_license(key: &SigningKey, license_type: &str) -> LicenseFile {
        let payload = LicensePayload {
            schema: TEST_SCHEMA.to_string(),
            license_id: "00000000-0000-0000-0000-000000000001".to_string(),
            issued_to_org: "Test Organization".to_string(),
            contact_email: Some("test@example.com".to_string()),
            license_type: license_type.to_string(),
            scope: "org".to_string(),
            perpetual: true,
            issued_at: "2025-01-01".to_string(),
        };
        let payload_bytes = serde_json::to_vec(&payload).unwrap();
        let sig = key.sign(&payload_bytes);
        LicenseFile {
            payload,
            signature: STANDARD.encode(sig.to_bytes()),
        }
    }

    #[test]
    fn test_verify_academic_license_ok() {
        let (key, pubkey_b64) = make_test_keypair();
        let license = make_license(&key, "academic");
        assert!(verify_license_with_key(&license, &pubkey_b64, TEST_SCHEMA).is_ok());
    }

    #[test]
    fn test_verify_commercial_license_ok() {
        let (key, pubkey_b64) = make_test_keypair();
        let license = make_license(&key, "commercial");
        assert!(verify_license_with_key(&license, &pubkey_b64, TEST_SCHEMA).is_ok());
    }

    #[test]
    fn test_verify_enterprise_license_ok() {
        let (key, pubkey_b64) = make_test_keypair();
        let license = make_license(&key, "enterprise");
        assert!(verify_license_with_key(&license, &pubkey_b64, TEST_SCHEMA).is_ok());
    }

    #[test]
    fn test_wrong_pubkey_fails() {
        let (key, _) = make_test_keypair();
        let (_, other_pubkey_b64) = make_test_keypair();
        let license = make_license(&key, "academic");
        let result = verify_license_with_key(&license, &other_pubkey_b64, TEST_SCHEMA);
        assert!(
            matches!(result, Err(LicenseError::InvalidSignature)),
            "expected InvalidSignature, got: {result:?}"
        );
    }

    #[test]
    fn test_tampered_org_fails() {
        let (key, pubkey_b64) = make_test_keypair();
        let mut license = make_license(&key, "academic");
        license.payload.issued_to_org = "Tampered Org".to_string();
        let result = verify_license_with_key(&license, &pubkey_b64, TEST_SCHEMA);
        assert!(
            matches!(result, Err(LicenseError::InvalidSignature)),
            "expected InvalidSignature after tampering, got: {result:?}"
        );
    }

    #[test]
    fn test_wrong_schema_fails() {
        let (key, pubkey_b64) = make_test_keypair();
        let mut license = make_license(&key, "academic");
        license.payload.schema = "wrong-schema-v99".to_string();
        let payload_bytes = serde_json::to_vec(&license.payload).unwrap();
        let sig = key.sign(&payload_bytes);
        license.signature = STANDARD.encode(sig.to_bytes());

        let result = verify_license_with_key(&license, &pubkey_b64, TEST_SCHEMA);
        assert!(
            matches!(result, Err(LicenseError::InvalidSchema { .. })),
            "expected InvalidSchema, got: {result:?}"
        );
    }

    #[test]
    fn test_invalid_public_key_base64_fails() {
        let (key, _) = make_test_keypair();
        let license = make_license(&key, "academic");
        let result = verify_license_with_key(&license, "!!!not-valid-base64!!!", TEST_SCHEMA);
        assert!(
            matches!(result, Err(LicenseError::InvalidPublicKey(_))),
            "expected InvalidPublicKey, got: {result:?}"
        );
    }

    #[test]
    fn test_invalid_public_key_wrong_length_fails() {
        let (key, _) = make_test_keypair();
        let license = make_license(&key, "academic");
        let short_key = STANDARD.encode([0u8; 16]);
        let result = verify_license_with_key(&license, &short_key, TEST_SCHEMA);
        assert!(
            matches!(result, Err(LicenseError::InvalidPublicKey(_))),
            "expected InvalidPublicKey, got: {result:?}"
        );
    }

    #[test]
    fn test_invalid_signature_encoding_fails() {
        let (key, pubkey_b64) = make_test_keypair();
        let mut license = make_license(&key, "academic");
        license.signature = "!!!not-valid-base64!!!".to_string();
        let result = verify_license_with_key(&license, &pubkey_b64, TEST_SCHEMA);
        assert!(
            matches!(result, Err(LicenseError::InvalidSignatureEncoding(_))),
            "expected InvalidSignatureEncoding, got: {result:?}"
        );
    }

    #[test]
    fn test_invalid_signature_wrong_length_fails() {
        let (key, pubkey_b64) = make_test_keypair();
        let mut license = make_license(&key, "academic");
        license.signature = STANDARD.encode([0u8; 32]); // 32 bytes, not 64
        let result = verify_license_with_key(&license, &pubkey_b64, TEST_SCHEMA);
        assert!(
            matches!(result, Err(LicenseError::InvalidSignatureEncoding(_))),
            "expected InvalidSignatureEncoding, got: {result:?}"
        );
    }

    #[test]
    fn test_roundtrip_json_serialization() {
        let (key, _) = make_test_keypair();
        let license = make_license(&key, "commercial");
        let json = serde_json::to_string_pretty(&license).unwrap();
        let parsed: LicenseFile = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.payload.license_id, license.payload.license_id);
        assert_eq!(parsed.payload.license_type, license.payload.license_type);
        assert_eq!(parsed.signature, license.signature);
    }

    #[test]
    fn test_contact_email_optional_in_signing() {
        let (key, pubkey_b64) = make_test_keypair();
        let mut payload = LicensePayload {
            schema: TEST_SCHEMA.to_string(),
            license_id: "00000000-0000-0000-0000-000000000002".to_string(),
            issued_to_org: "Acme Corp".to_string(),
            contact_email: None,
            license_type: "commercial".to_string(),
            scope: "org".to_string(),
            perpetual: true,
            issued_at: "2025-06-01".to_string(),
        };
        let sig1 = {
            let bytes = serde_json::to_vec(&payload).unwrap();
            key.sign(&bytes)
        };
        let lic_no_email = LicenseFile {
            payload: payload.clone(),
            signature: STANDARD.encode(sig1.to_bytes()),
        };
        assert!(verify_license_with_key(&lic_no_email, &pubkey_b64, TEST_SCHEMA).is_ok());

        payload.contact_email = Some("admin@acme.com".to_string());
        let sig2 = {
            let bytes = serde_json::to_vec(&payload).unwrap();
            key.sign(&bytes)
        };
        let lic_with_email = LicenseFile {
            payload,
            signature: STANDARD.encode(sig2.to_bytes()),
        };
        assert!(verify_license_with_key(&lic_with_email, &pubkey_b64, TEST_SCHEMA).is_ok());

        // Cross-verify: email license with no-email signature should fail
        let lic_tampered = LicenseFile {
            payload: lic_with_email.payload.clone(),
            signature: lic_no_email.signature.clone(),
        };
        assert!(verify_license_with_key(&lic_tampered, &pubkey_b64, TEST_SCHEMA).is_err());
    }

    #[test]
    fn test_find_license_path_from_env_var() {
        let _guard = ENV_MUTEX.lock().unwrap();
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let path = tmp.path().to_path_buf();
        unsafe {
            std::env::set_var("TEST_APP_LICENSE", path.to_str().unwrap());
        }
        let config = make_config("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
        let found = find_license_path(None, &config);
        assert_eq!(found.as_deref(), Some(path.as_path()));
        unsafe {
            std::env::remove_var("TEST_APP_LICENSE");
        }
    }

    #[test]
    fn test_find_license_path_cli_arg_takes_precedence() {
        let _guard = ENV_MUTEX.lock().unwrap();
        let cli_path = PathBuf::from("/nonexistent/cli-license.json");
        let env_path = PathBuf::from("/nonexistent/env-license.json");
        unsafe {
            std::env::set_var("TEST_APP_LICENSE", env_path.to_str().unwrap());
        }
        let config = make_config("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
        let found = find_license_path(Some(&cli_path), &config);
        assert_eq!(found.as_deref(), Some(cli_path.as_path()));
        unsafe {
            std::env::remove_var("TEST_APP_LICENSE");
        }
    }

    #[test]
    fn test_load_and_verify_not_found() {
        let config = make_config("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
        let result = load_and_verify(
            Some(Path::new("/nonexistent/oxo-license-test.json")),
            &config,
        );
        // Path is provided but doesn't exist → ReadError
        assert!(result.is_err());
    }

    #[test]
    fn test_load_and_verify_invalid_json() {
        use std::io::Write;
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(b"not valid json {{{").unwrap();
        let config = make_config("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
        let result = load_and_verify(Some(f.path()), &config);
        assert!(
            matches!(result, Err(LicenseError::ParseError(_))),
            "expected ParseError, got: {result:?}"
        );
    }

    #[test]
    fn test_load_and_verify_valid_license() {
        let (key, pubkey_b64) = make_test_keypair();
        let license = make_license(&key, "academic");
        let json = serde_json::to_string_pretty(&license).unwrap();

        use std::io::Write;
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(json.as_bytes()).unwrap();

        // We need a static pubkey for the config — use box leak for test
        let pubkey_static: &'static str = Box::leak(pubkey_b64.into_boxed_str());
        let config = make_config(pubkey_static);
        let result = load_and_verify(Some(f.path()), &config);
        assert!(result.is_ok(), "expected Ok, got: {result:?}");
    }
}