fallow-license 2.40.2

Offline Ed25519-signed license JWT verification for the fallow CLI (paid feature gating)
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
//! Offline Ed25519-signed license JWT verification for the fallow CLI.
//!
//! This crate is the public-binary side of fallow's paid-feature gating. It
//! does NOT perform any network I/O; the license file is loaded from disk or
//! environment, the signature is verified against a public key compiled in by
//! the embedding binary, and the result is exposed as a [`LicenseStatus`].
//!
//! # Storage precedence
//!
//! License material is sourced in this order (first match wins):
//!
//! 1. `$FALLOW_LICENSE` environment variable (full JWT string).
//! 2. `$FALLOW_LICENSE_PATH` environment variable (path to a file containing the JWT).
//! 3. `~/.fallow/license.jwt` (default path under the user's home directory).
//!
//! # Algorithm pinning
//!
//! Only Ed25519 (`EdDSA`) is accepted. The JWT header's `alg` claim is verified
//! to equal `"EdDSA"` *after* base64 decoding; we never trust the header to pick
//! the algorithm.
//!
//! # Grace ladder
//!
//! Matches Docker Desktop / JetBrains conventions. See [`grace_state`].

#![forbid(unsafe_code)]

use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use ed25519_dalek::{Signature, VerifyingKey};
use serde::{Deserialize, Serialize};

/// Default cap on the grace window before hard-fail in the public CLI.
///
/// The enterprise binary (`--features enterprise-license`) lifts this cap.
pub const DEFAULT_HARD_FAIL_DAYS: u64 = 30;

/// Days post-expiry after which the public output gains a visible watermark.
pub const WATERMARK_DAYS: u64 = 7;

/// JWT claims emitted by `api.fallow.cloud` for fallow CLI licenses.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LicenseClaims {
    /// Issuer (typically `"https://api.fallow.cloud"`).
    pub iss: String,
    /// Subject — opaque org identifier.
    pub sub: String,
    /// Tenant identifier.
    pub tid: String,
    /// Number of seats licensed.
    pub seats: u32,
    /// Tier string: `team`, `enterprise`, `trial`, `founding`.
    pub tier: String,
    /// Feature flags. Modeled as strings on the wire for forward-compat;
    /// callers convert to [`Feature`] for matching.
    pub features: Vec<String>,
    /// Issued-at, seconds since UNIX epoch.
    pub iat: i64,
    /// Expiration, seconds since UNIX epoch.
    pub exp: i64,
    /// Unique JWT ID (used for refresh + revocation).
    pub jti: String,
    /// Suggested refresh timestamp, seconds since UNIX epoch. Backend emits
    /// this at `iat + 15 days` so CI runs can proactively refresh before the
    /// hard-fail window. `None` when the backend did not include the claim
    /// (older license payloads or third-party issuers).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refresh_after: Option<i64>,
}

/// Feature flag enum aligned with the protocol's `Feature` strings.
///
/// Wire format stays a string array; new variants are additive in minor protocol
/// bumps and unrecognized strings round-trip through [`Feature::Other`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Feature {
    /// The Phase-2 paid local analyzer.
    ProductionCoverage,
    /// Phase-3+ cloud features (placeholder).
    PortfolioDashboard,
    /// Phase-4+ MCP cloud tools (placeholder).
    McpCloudTools,
    /// Phase-3+ cross-repo aggregation (placeholder).
    CrossRepoAggregation,
    /// Forward-compat sentinel for unrecognized feature strings.
    Other(String),
}

impl Feature {
    /// Parse a wire string into a [`Feature`]. Unrecognized strings round-trip
    /// through [`Feature::Other`] so older CLIs do not error on newer license
    /// payloads.
    #[must_use]
    pub fn parse(s: &str) -> Self {
        match s {
            "production_coverage" => Self::ProductionCoverage,
            "portfolio_dashboard" => Self::PortfolioDashboard,
            "mcp_cloud_tools" => Self::McpCloudTools,
            "cross_repo_aggregation" => Self::CrossRepoAggregation,
            other => Self::Other(other.to_owned()),
        }
    }
}

impl LicenseClaims {
    /// True if the license's `features` claim contains the requested feature.
    #[must_use]
    pub fn has_feature(&self, feature: &Feature) -> bool {
        self.features.iter().any(|s| Feature::parse(s) == *feature)
    }
}

/// Outcome of [`load_and_verify`].
#[derive(Debug, Clone)]
pub enum LicenseStatus {
    /// License is valid and not yet expired.
    Valid {
        claims: LicenseClaims,
        days_until_expiry: i64,
    },
    /// License is in the warning window (0..[`WATERMARK_DAYS`] days post-expiry).
    /// Analysis runs normally; human output prints a refresh hint.
    ExpiredWarning {
        claims: LicenseClaims,
        days_since_expiry: u64,
    },
    /// License is in the watermark window
    /// ([`WATERMARK_DAYS`]..hard_fail_days post-expiry). Analysis runs but
    /// every human-facing surface gains a visible "license expired" watermark.
    ExpiredWatermark {
        claims: LicenseClaims,
        days_since_expiry: u64,
    },
    /// License is past the hard-fail cap. Analysis must NOT run.
    HardFail {
        claims: LicenseClaims,
        days_since_expiry: u64,
    },
    /// No license material was found at any of the precedence locations.
    Missing,
}

impl LicenseStatus {
    /// True if the holder is allowed to use paid features (any non-hard-fail
    /// state with the requested feature in the claims).
    #[must_use]
    pub fn permits(&self, feature: &Feature) -> bool {
        match self {
            Self::Valid { claims, .. }
            | Self::ExpiredWarning { claims, .. }
            | Self::ExpiredWatermark { claims, .. } => claims.has_feature(feature),
            Self::HardFail { .. } | Self::Missing => false,
        }
    }

    /// True if a watermark string should be appended to user-facing output.
    #[must_use]
    pub const fn show_watermark(&self) -> bool {
        matches!(self, Self::ExpiredWatermark { .. })
    }
}

/// Errors returned by [`load_and_verify`] when the license material is present
/// but malformed (vs simply missing, which is reported via [`LicenseStatus::Missing`]).
#[derive(Debug)]
pub enum LicenseError {
    /// I/O error reading the license file.
    Io(std::io::Error),
    /// JWT structure was not three base64url-encoded segments.
    MalformedJwt(String),
    /// Header could not be parsed as JSON or had wrong `alg`.
    BadHeader(String),
    /// Payload could not be parsed as [`LicenseClaims`].
    BadPayload(String),
    /// Signature verification failed.
    BadSignature,
    /// JWT length looks truncated (typical valid range 700-1500 chars).
    Truncated { actual: usize },
}

impl std::fmt::Display for LicenseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(err) => write!(f, "license I/O error: {err}"),
            Self::MalformedJwt(msg) => write!(f, "malformed JWT: {msg}"),
            Self::BadHeader(msg) => write!(f, "bad JWT header: {msg}"),
            Self::BadPayload(msg) => write!(f, "bad JWT payload: {msg}"),
            Self::BadSignature => write!(f, "JWT signature verification failed"),
            Self::Truncated { actual } => write!(
                f,
                "the token looks truncated (got {actual} chars; expected 700+). Did you copy the whole thing? Try: fallow license activate --from-file license.jwt"
            ),
        }
    }
}

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

impl From<std::io::Error> for LicenseError {
    fn from(err: std::io::Error) -> Self {
        Self::Io(err)
    }
}

/// Verify a raw JWT string against the supplied public key and (optionally)
/// the wall clock. The `now` parameter is the unix-seconds reference used to
/// classify expiry; pass [`current_unix_seconds`] in production.
pub fn verify_jwt(
    raw_jwt: &str,
    public_key: &VerifyingKey,
    now: i64,
    hard_fail_days: u64,
) -> Result<LicenseStatus, LicenseError> {
    let trimmed = normalize_jwt(raw_jwt);

    // Length sanity-check before crypto. Real JWTs are 700-1500 chars.
    if trimmed.len() < 200 {
        return Err(LicenseError::Truncated {
            actual: trimmed.len(),
        });
    }

    let parts: Vec<&str> = trimmed.split('.').collect();
    if parts.len() != 3 {
        return Err(LicenseError::MalformedJwt(format!(
            "expected 3 segments, got {}",
            parts.len()
        )));
    }
    let (header_b64, payload_b64, signature_b64) = (parts[0], parts[1], parts[2]);

    // 1. Verify header alg pinning. We never trust the header to pick the alg;
    // we verify the header's alg matches the alg we've already pinned in code.
    let header_bytes = URL_SAFE_NO_PAD
        .decode(header_b64)
        .map_err(|err| LicenseError::BadHeader(format!("base64 decode: {err}")))?;
    let header: serde_json::Value = serde_json::from_slice(&header_bytes)
        .map_err(|err| LicenseError::BadHeader(format!("json parse: {err}")))?;
    let alg = header
        .get("alg")
        .and_then(|v| v.as_str())
        .ok_or_else(|| LicenseError::BadHeader("missing alg claim".to_owned()))?;
    if alg != "EdDSA" {
        return Err(LicenseError::BadHeader(format!(
            "expected alg=EdDSA, got alg={alg}"
        )));
    }

    // 2. Verify signature over the canonical signing input (header.payload).
    let signature_bytes = URL_SAFE_NO_PAD
        .decode(signature_b64)
        .map_err(|_| LicenseError::BadSignature)?;
    let signature_array: [u8; 64] = signature_bytes
        .as_slice()
        .try_into()
        .map_err(|_| LicenseError::BadSignature)?;
    let signature = Signature::from_bytes(&signature_array);
    let signing_input = format!("{header_b64}.{payload_b64}");
    public_key
        .verify_strict(signing_input.as_bytes(), &signature)
        .map_err(|_| LicenseError::BadSignature)?;

    // 3. Parse payload claims.
    let payload_bytes = URL_SAFE_NO_PAD
        .decode(payload_b64)
        .map_err(|err| LicenseError::BadPayload(format!("base64 decode: {err}")))?;
    let claims: LicenseClaims = serde_json::from_slice(&payload_bytes)
        .map_err(|err| LicenseError::BadPayload(format!("json parse: {err}")))?;

    // 4. Apply grace ladder.
    Ok(grace_state(claims, now, hard_fail_days))
}

/// Map a verified [`LicenseClaims`] to a [`LicenseStatus`] using the 7/cap/hard-fail
/// ladder.
#[must_use]
pub fn grace_state(claims: LicenseClaims, now: i64, hard_fail_days: u64) -> LicenseStatus {
    let delta_seconds = i64::from(claims.exp != 0) * (claims.exp - now);
    if delta_seconds >= 0 {
        return LicenseStatus::Valid {
            days_until_expiry: delta_seconds / SECONDS_PER_DAY,
            claims,
        };
    }
    let days_since_expiry = (delta_seconds.unsigned_abs()).div_ceil(SECONDS_PER_DAY.unsigned_abs());
    if days_since_expiry > hard_fail_days {
        LicenseStatus::HardFail {
            claims,
            days_since_expiry,
        }
    } else if days_since_expiry > WATERMARK_DAYS {
        LicenseStatus::ExpiredWatermark {
            claims,
            days_since_expiry,
        }
    } else {
        LicenseStatus::ExpiredWarning {
            claims,
            days_since_expiry,
        }
    }
}

/// Discover and load a license JWT according to the storage precedence rules,
/// then verify it and apply the grace ladder.
///
/// Returns `Ok(LicenseStatus::Missing)` when no source provides material; an
/// `Err(LicenseError)` only when material was present but malformed.
pub fn load_and_verify(
    public_key: &VerifyingKey,
    hard_fail_days: u64,
) -> Result<LicenseStatus, LicenseError> {
    let now = current_unix_seconds();
    match load_raw_jwt()? {
        Some(jwt) => verify_jwt(&jwt, public_key, now, hard_fail_days),
        None => Ok(LicenseStatus::Missing),
    }
}

/// Resolve the JWT source according to [storage precedence](crate#storage-precedence).
///
/// Returns `Ok(None)` when no source provides material.
pub fn load_raw_jwt() -> Result<Option<String>, LicenseError> {
    if let Ok(jwt) = std::env::var("FALLOW_LICENSE") {
        let trimmed = normalize_jwt(&jwt);
        if !trimmed.is_empty() {
            return Ok(Some(trimmed));
        }
    }
    if let Ok(path) = std::env::var("FALLOW_LICENSE_PATH") {
        return Ok(Some(read_jwt_file(Path::new(&path))?));
    }
    let default = default_license_path();
    if default.exists() {
        return Ok(Some(read_jwt_file(&default)?));
    }
    Ok(None)
}

fn read_jwt_file(path: &Path) -> Result<String, LicenseError> {
    let raw = std::fs::read_to_string(path)?;
    Ok(normalize_jwt(&raw))
}

/// Resolve the user's home directory in a cross-platform way.
///
/// Checks `$HOME` first (standard on Unix and set by Git Bash / MSYS /
/// Cygwin on Windows), then `%USERPROFILE%` (native Windows). Returns
/// `None` only when neither resolves to a non-empty string, which in
/// practice means a bare container with no home set — callers decide
/// whether to fall back to cwd or error.
#[must_use]
pub fn user_home_dir() -> Option<PathBuf> {
    user_home_from_env(|key| std::env::var(key).ok())
}

fn user_home_from_env(getenv: impl Fn(&str) -> Option<String>) -> Option<PathBuf> {
    for key in ["HOME", "USERPROFILE"] {
        if let Some(value) = getenv(key)
            && !value.is_empty()
        {
            return Some(PathBuf::from(value));
        }
    }
    None
}

/// Compute the canonical default license path (`~/.fallow/license.jwt`).
///
/// On Unix this reads `$HOME`; on Windows it falls back to `%USERPROFILE%`
/// when `$HOME` is not set (native cmd / PowerShell). Falls back to
/// `./.fallow/license.jwt` if neither resolves — exotic containers and
/// CI sandboxes being the usual suspects.
#[must_use]
pub fn default_license_path() -> PathBuf {
    user_home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".fallow")
        .join("license.jwt")
}

/// Strip whitespace and embedded line breaks from a pasted JWT.
///
/// Shells routinely fold long tokens onto multiple lines, especially via
/// PowerShell or zsh's bracketed-paste. This is the single normalization
/// hook used by every input path (env var, file, CLI arg, stdin).
#[must_use]
pub fn normalize_jwt(raw: &str) -> String {
    raw.chars()
        .filter(|c| !c.is_whitespace())
        .collect::<String>()
}

/// Wrapper around `SystemTime::now()` returning unix seconds.
///
/// Returns `0` if the system clock is before the unix epoch (impossible in
/// practice — included to avoid `unwrap`).
#[must_use]
pub fn current_unix_seconds() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
}

const SECONDS_PER_DAY: i64 = 86_400;

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

    use ed25519_dalek::{Signer, SigningKey};
    use rand::rngs::OsRng;

    fn fixed_keypair() -> (SigningKey, VerifyingKey) {
        let mut csprng = OsRng;
        let signing = SigningKey::generate(&mut csprng);
        let verifying = signing.verifying_key();
        (signing, verifying)
    }

    fn sign_jwt(signing: &SigningKey, claims: &LicenseClaims) -> String {
        let header = serde_json::json!({"alg": "EdDSA", "typ": "JWT"});
        let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap());
        let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims).unwrap());
        let signing_input = format!("{header_b64}.{payload_b64}");
        let signature = signing.sign(signing_input.as_bytes());
        let sig_b64 = URL_SAFE_NO_PAD.encode(signature.to_bytes());
        format!("{header_b64}.{payload_b64}.{sig_b64}")
    }

    fn make_claims(exp: i64) -> LicenseClaims {
        LicenseClaims {
            iss: "https://api.fallow.cloud".into(),
            sub: "org_test".into(),
            tid: "tenant_test".into(),
            seats: 5,
            tier: "team".into(),
            features: vec!["production_coverage".into()],
            iat: 1_700_000_000,
            exp,
            jti: "jti_test".into(),
            refresh_after: Some(1_700_000_000 + 15 * SECONDS_PER_DAY),
        }
    }

    #[test]
    fn valid_jwt_passes_verification() {
        let (signing, verifying) = fixed_keypair();
        let claims = make_claims(2_000_000_000);
        let jwt = sign_jwt(&signing, &claims);
        let status = verify_jwt(&jwt, &verifying, 1_900_000_000, DEFAULT_HARD_FAIL_DAYS).unwrap();
        assert!(matches!(status, LicenseStatus::Valid { .. }));
        assert!(status.permits(&Feature::ProductionCoverage));
        assert!(!status.permits(&Feature::PortfolioDashboard));
    }

    #[test]
    fn tampered_payload_fails_signature() {
        let (signing, verifying) = fixed_keypair();
        let claims = make_claims(2_000_000_000);
        let mut jwt = sign_jwt(&signing, &claims);
        // Flip a byte in the payload segment.
        let mid = jwt.find('.').unwrap() + 5;
        let bad: String = jwt
            .chars()
            .enumerate()
            .map(|(i, c)| if i == mid { 'X' } else { c })
            .collect();
        jwt = bad;
        let err = verify_jwt(&jwt, &verifying, 1_900_000_000, DEFAULT_HARD_FAIL_DAYS).unwrap_err();
        assert!(matches!(
            err,
            LicenseError::BadSignature | LicenseError::BadPayload(_)
        ));
    }

    #[test]
    fn rs256_header_rejected() {
        // Build a JWT with alg=RS256 in the header but signed with Ed25519.
        // The verifier MUST reject because we pin alg=EdDSA in code.
        let (signing, verifying) = fixed_keypair();
        let header = serde_json::json!({"alg": "RS256", "typ": "JWT"});
        let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap());
        let claims = make_claims(2_000_000_000);
        let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
        let signing_input = format!("{header_b64}.{payload_b64}");
        let signature = signing.sign(signing_input.as_bytes());
        let sig_b64 = URL_SAFE_NO_PAD.encode(signature.to_bytes());
        let jwt = format!("{header_b64}.{payload_b64}.{sig_b64}");
        let err = verify_jwt(&jwt, &verifying, 1_900_000_000, DEFAULT_HARD_FAIL_DAYS).unwrap_err();
        assert!(matches!(err, LicenseError::BadHeader(_)));
    }

    #[test]
    fn alg_none_rejected() {
        // The classic JWT footgun: alg=none with empty signature. Must reject.
        let (_, verifying) = fixed_keypair();
        let header = serde_json::json!({"alg": "none", "typ": "JWT"});
        let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap());
        let claims = make_claims(2_000_000_000);
        let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
        let jwt = format!("{header_b64}.{payload_b64}.");
        let err = verify_jwt(&jwt, &verifying, 1_900_000_000, DEFAULT_HARD_FAIL_DAYS).unwrap_err();
        assert!(matches!(err, LicenseError::BadHeader(_)));
    }

    #[test]
    fn truncated_token_returns_specific_error() {
        let (_, verifying) = fixed_keypair();
        let err = verify_jwt("eyJh.short", &verifying, 0, DEFAULT_HARD_FAIL_DAYS).unwrap_err();
        assert!(matches!(err, LicenseError::Truncated { .. }));
    }

    #[test]
    fn whitespace_in_jwt_normalized() {
        let raw = "eyJ\n  abcd\r\nef.gh\nij.kl  mn";
        assert_eq!(normalize_jwt(raw), "eyJabcdef.ghij.klmn");
    }

    #[test]
    fn grace_ladder_classifies_correctly() {
        let claims = make_claims(1_000_000_000);
        // Now equals exp: still valid (delta == 0).
        assert!(matches!(
            grace_state(claims.clone(), 1_000_000_000, 30),
            LicenseStatus::Valid { .. }
        ));
        // 3 days past expiry: warning.
        assert!(matches!(
            grace_state(claims.clone(), 1_000_000_000 + 3 * SECONDS_PER_DAY, 30),
            LicenseStatus::ExpiredWarning { .. }
        ));
        // 15 days past expiry: watermark.
        assert!(matches!(
            grace_state(claims.clone(), 1_000_000_000 + 15 * SECONDS_PER_DAY, 30),
            LicenseStatus::ExpiredWatermark { .. }
        ));
        // 35 days past expiry: hard-fail.
        assert!(matches!(
            grace_state(claims, 1_000_000_000 + 35 * SECONDS_PER_DAY, 30),
            LicenseStatus::HardFail { .. }
        ));
    }

    #[test]
    fn watermark_status_only_in_watermark_window() {
        let claims = make_claims(1_000_000_000);
        let valid = grace_state(claims.clone(), 1_000_000_000 - 100, 30);
        let warn = grace_state(claims.clone(), 1_000_000_000 + 3 * SECONDS_PER_DAY, 30);
        let watermark = grace_state(claims.clone(), 1_000_000_000 + 15 * SECONDS_PER_DAY, 30);
        let hard = grace_state(claims, 1_000_000_000 + 60 * SECONDS_PER_DAY, 30);

        assert!(!valid.show_watermark());
        assert!(!warn.show_watermark());
        assert!(watermark.show_watermark());
        assert!(!hard.show_watermark());
    }

    #[test]
    fn permits_short_circuits_on_hard_fail() {
        let claims = make_claims(1_000_000_000);
        let hard = grace_state(claims, 1_000_000_000 + 60 * SECONDS_PER_DAY, 30);
        assert!(!hard.permits(&Feature::ProductionCoverage));
    }

    #[test]
    fn unknown_feature_round_trips_through_other() {
        let parsed = Feature::parse("future_feature");
        assert!(matches!(parsed, Feature::Other(ref s) if s == "future_feature"));
    }

    #[test]
    fn refresh_after_parses_when_present_and_defaults_to_none() {
        let with_refresh = serde_json::json!({
            "iss": "https://api.fallow.cloud",
            "sub": "org_test",
            "tid": "tenant_test",
            "seats": 5,
            "tier": "team",
            "features": ["production_coverage"],
            "iat": 1_700_000_000,
            "exp": 2_000_000_000_i64,
            "jti": "jti_test",
            "refresh_after": 1_701_296_000_i64,
        });
        let claims: LicenseClaims = serde_json::from_value(with_refresh).expect("parse");
        assert_eq!(claims.refresh_after, Some(1_701_296_000));

        let without_refresh = serde_json::json!({
            "iss": "https://api.fallow.cloud",
            "sub": "org_test",
            "tid": "tenant_test",
            "seats": 5,
            "tier": "team",
            "features": ["production_coverage"],
            "iat": 1_700_000_000,
            "exp": 2_000_000_000_i64,
            "jti": "jti_test",
        });
        let claims: LicenseClaims = serde_json::from_value(without_refresh).expect("parse");
        assert_eq!(claims.refresh_after, None);
    }

    #[test]
    fn user_home_from_env_prefers_home_over_userprofile() {
        let getenv = |key: &str| match key {
            "HOME" => Some("/home/alice".to_owned()),
            "USERPROFILE" => Some(r"C:\Users\alice".to_owned()),
            _ => None,
        };
        assert_eq!(
            user_home_from_env(getenv),
            Some(PathBuf::from("/home/alice"))
        );
    }

    #[test]
    fn user_home_from_env_falls_back_to_userprofile_on_windows() {
        let getenv = |key: &str| match key {
            "USERPROFILE" => Some(r"C:\Users\alice".to_owned()),
            _ => None,
        };
        assert_eq!(
            user_home_from_env(getenv),
            Some(PathBuf::from(r"C:\Users\alice"))
        );
    }

    #[test]
    fn user_home_from_env_skips_empty_values() {
        // A CI runner that exports HOME="" should not be treated as "HOME is /"
        // (was a real footgun: join(".fallow") produced "/.fallow").
        let getenv = |key: &str| match key {
            "HOME" => Some(String::new()),
            "USERPROFILE" => Some(r"C:\Users\alice".to_owned()),
            _ => None,
        };
        assert_eq!(
            user_home_from_env(getenv),
            Some(PathBuf::from(r"C:\Users\alice"))
        );
    }

    #[test]
    fn user_home_from_env_returns_none_when_nothing_set() {
        assert_eq!(user_home_from_env(|_| None), None);
    }
}