Skip to main content

rustify_licensing/core/
engine.rs

1//! The pure heart of the gate: run a check against a provider, then **fold the result
2//! into a status** honoring offline grace — and failing closed on an authoritative
3//! denial. Extracted into a single pure, testable function.
4
5use crate::core::error::CheckErr;
6use crate::core::state::LicenseState;
7use crate::core::status::LicenseStatus;
8use crate::provider::LicenseProvider;
9
10/// Run a full validation against the provider. The validate → activate → re-validate
11/// dance is the provider's concern; `progress` receives human-readable step messages.
12/// Returns a definitive verdict (`Ok(valid)`) or a [`CheckErr`] distinguishing an
13/// authoritative denial from a transient connectivity failure.
14pub fn run_check(
15    provider: &dyn LicenseProvider,
16    state: &LicenseState,
17    progress: &mut dyn FnMut(String),
18) -> Result<bool, CheckErr> {
19    provider.check(state.key.trim(), &state.fingerprint, progress)
20}
21
22/// The verdict of a finished check, ready for the UI/log.
23pub struct Resolution {
24    pub status: LicenseStatus,
25    /// A line to surface to the user/log, if any.
26    pub message: Option<String>,
27}
28
29/// Fold a check result into a [`LicenseStatus`], stamping `last_validated` on success and
30/// honoring the offline grace window. **Fail closed:** [`CheckErr::Denied`] never rides
31/// grace. (Pure — the caller decides when to persist `state`.)
32pub fn resolve(
33    result: Result<bool, CheckErr>,
34    state: &mut LicenseState,
35    now: u64,
36    grace_secs: u64,
37) -> Resolution {
38    match result {
39        Ok(true) => {
40            state.last_validated = Some(now);
41            Resolution {
42                status: LicenseStatus::Active,
43                message: Some("license active".into()),
44            }
45        }
46        // Valid=false but no error (e.g. revoked key returns HTTP 200 valid:false) → lock.
47        Ok(false) => Resolution {
48            status: LicenseStatus::Locked,
49            message: None,
50        },
51        // Authoritative denial (bad account/key/policy, revoked) → fail closed, no grace.
52        Err(CheckErr::Denied(e)) => Resolution {
53            status: LicenseStatus::Locked,
54            message: Some(format!("license invalid — {e}")),
55        },
56        // Transient connectivity failure → honor the offline grace window.
57        Err(CheckErr::Offline(e)) => {
58            if state.within_grace(now, grace_secs) {
59                Resolution {
60                    status: LicenseStatus::Grace,
61                    message: Some("offline — using cached license (grace period)".into()),
62                }
63            } else {
64                Resolution {
65                    status: LicenseStatus::Locked,
66                    message: Some(format!("license check failed — {e}")),
67                }
68            }
69        }
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76
77    const GRACE: u64 = 14 * 24 * 60 * 60;
78
79    fn state(last_validated: Option<u64>) -> LicenseState {
80        LicenseState {
81            key: "K".into(),
82            fingerprint: "fp".into(),
83            last_validated,
84        }
85    }
86
87    #[test]
88    fn ok_true_activates_and_stamps_now() {
89        let mut s = state(None);
90        let r = resolve(Ok(true), &mut s, 1000, GRACE);
91        assert_eq!(r.status, LicenseStatus::Active);
92        assert_eq!(s.last_validated, Some(1000), "stamps last_validated");
93    }
94
95    #[test]
96    fn ok_false_locks() {
97        let mut s = state(Some(1000));
98        let r = resolve(Ok(false), &mut s, 1000, GRACE);
99        assert_eq!(r.status, LicenseStatus::Locked);
100    }
101
102    #[test]
103    fn denied_locks_even_within_grace() {
104        // The original silent-unlock bug: a wrong-account/revoked license must NOT ride
105        // grace. last_validated is "now", so grace would otherwise apply.
106        let mut s = state(Some(1000));
107        let r = resolve(Err(CheckErr::Denied("HTTP 403".into())), &mut s, 1000, GRACE);
108        assert_eq!(r.status, LicenseStatus::Locked, "fail closed");
109    }
110
111    #[test]
112    fn offline_within_grace_is_grace() {
113        let mut s = state(Some(1000));
114        let r = resolve(
115            Err(CheckErr::Offline("network".into())),
116            &mut s,
117            1000 + GRACE - 1,
118            GRACE,
119        );
120        assert_eq!(r.status, LicenseStatus::Grace);
121    }
122
123    #[test]
124    fn offline_past_grace_locks() {
125        let mut s = state(Some(1000));
126        let r = resolve(
127            Err(CheckErr::Offline("network".into())),
128            &mut s,
129            1000 + GRACE + 1,
130            GRACE,
131        );
132        assert_eq!(r.status, LicenseStatus::Locked);
133    }
134
135    #[test]
136    fn offline_with_no_prior_validation_locks() {
137        let mut s = state(None);
138        let r = resolve(Err(CheckErr::Offline("network".into())), &mut s, 5000, GRACE);
139        assert_eq!(r.status, LicenseStatus::Locked, "no cache ⇒ no grace");
140    }
141}