Skip to main content

rustify_licensing/provider/
keygen.rs

1//! Keygen provider — the exact Keygen API contract, ported verbatim (every detail
2//! here cost real debugging):
3//!
4//! - **validate** (no auth): `POST {api}/accounts/{acct}/licenses/actions/validate-key`
5//!   with `{"meta":{"key","scope":{"fingerprint"}}}` → HTTP 200 with `meta.valid` +
6//!   `meta.code`. A revoked/unknown key still returns 200 with `valid:false`.
7//! - **activate** (node-lock): `POST {api}/accounts/{acct}/machines` with
8//!   `Authorization: License <KEY>` — the **`License` scheme, NOT `Bearer`** (Bearer →
9//!   `TOKEN_INVALID`). The policy must allow license authentication.
10//! - **error mapping is the safety property:** `408 | 429 | 5xx`, network errors, and
11//!   ambiguous non-JSON 2xx bodies → [`CheckErr::Offline`] (grace may apply); every other
12//!   4xx → [`CheckErr::Denied`] (fail closed).
13
14use serde_json::{json, Value};
15
16use crate::core::config::LicenseConfig;
17use crate::core::error::CheckErr;
18
19use super::LicenseProvider;
20
21/// Keygen-backed [`LicenseProvider`]. The account id is a public UUID; no secrets here
22/// (clients ship no admin token — license-key auth only).
23pub struct KeygenProvider {
24    account_id: String,
25    api_base: String,
26}
27
28impl KeygenProvider {
29    pub fn new(account_id: impl Into<String>, api_base: impl Into<String>) -> Self {
30        Self {
31            account_id: account_id.into(),
32            api_base: api_base.into(),
33        }
34    }
35
36    /// Build from the shared [`LicenseConfig`].
37    pub fn from_config(config: &LicenseConfig) -> Self {
38        Self::new(config.account_id.clone(), config.api_base.clone())
39    }
40
41    /// `POST {api}/accounts/{acct}/{path}`. `auth` (the license key) adds the `License`
42    /// scheme header. Maps transport/status into [`CheckErr`] per the safety rules above.
43    fn post(&self, path: &str, auth: Option<&str>, body: &Value) -> Result<Value, CheckErr> {
44        let url = format!("{}/accounts/{}/{}", self.api_base, self.account_id, path);
45        let mut req = ureq::post(&url)
46            .set("Content-Type", "application/vnd.api+json")
47            .set("Accept", "application/vnd.api+json");
48        // Keygen license-key authentication uses the `License` scheme (not `Bearer`,
49        // which is for tokens). Requires the policy to allow license authentication.
50        if let Some(key) = auth {
51            req = req.set("Authorization", &format!("License {key}"));
52        }
53        let payload = serde_json::to_string(body).map_err(|e| CheckErr::Denied(e.to_string()))?;
54        match req.send_string(&payload) {
55            // validate-key always returns 200 (with meta.valid); machines returns 201.
56            Ok(resp) => resp
57                .into_json::<Value>()
58                // A 2xx with a non-JSON body is ambiguous (proxy/captive portal) → grace.
59                .map_err(|e| CheckErr::Offline(format!("decode: {e}"))),
60            Err(ureq::Error::Status(code, resp)) => {
61                let detail: String = resp
62                    .into_string()
63                    .unwrap_or_default()
64                    .chars()
65                    .take(200)
66                    .collect();
67                let msg = format!("HTTP {code}: {detail}");
68                // 408/429/5xx are transient/server-side → grace; other 4xx are an
69                // authoritative "no" (bad account/key/policy) → fail closed.
70                if code == 408 || code == 429 || code >= 500 {
71                    Err(CheckErr::Offline(msg))
72                } else {
73                    Err(CheckErr::Denied(msg))
74                }
75            }
76            Err(e) => Err(CheckErr::Offline(format!("network: {e}"))),
77        }
78    }
79
80    fn validate(&self, key: &str, fingerprint: &str) -> Result<Validation, CheckErr> {
81        let body = json!({ "meta": { "key": key, "scope": { "fingerprint": fingerprint } } });
82        let v = self.post("licenses/actions/validate-key", None, &body)?;
83        Ok(Validation {
84            valid: v["meta"]["valid"].as_bool().unwrap_or(false),
85            code: v["meta"]["code"].as_str().unwrap_or("UNKNOWN").to_string(),
86            license_id: v["data"]["id"].as_str().map(str::to_string),
87        })
88    }
89
90    fn activate_machine(&self, key: &str, fingerprint: &str, license_id: &str) -> Result<(), CheckErr> {
91        let body = json!({
92            "data": {
93                "type": "machines",
94                "attributes": { "fingerprint": fingerprint },
95                "relationships": { "license": { "data": { "type": "licenses", "id": license_id } } }
96            }
97        });
98        self.post("machines", Some(key), &body).map(|_| ())
99    }
100}
101
102struct Validation {
103    valid: bool,
104    code: String,
105    license_id: Option<String>,
106}
107
108impl LicenseProvider for KeygenProvider {
109    /// Validate, activating this machine first if a node-locked policy needs it, then
110    /// re-validate. Returns `Ok(valid)` for a definitive verdict.
111    fn check(
112        &self,
113        key: &str,
114        fingerprint: &str,
115        progress: &mut dyn FnMut(String),
116    ) -> Result<bool, CheckErr> {
117        progress("validating license…".into());
118        let r = self.validate(key, fingerprint)?;
119        if r.valid {
120            return Ok(true);
121        }
122        // Node-locked policy with no machine yet → register this device, then re-validate.
123        if matches!(
124            r.code.as_str(),
125            "NO_MACHINE" | "NO_MACHINES" | "FINGERPRINT_SCOPE_MISMATCH"
126        ) {
127            if let Some(id) = r.license_id {
128                progress("activating this device…".into());
129                let _ = self.activate_machine(key, fingerprint, &id); // ignore "already taken"
130                return Ok(self.validate(key, fingerprint)?.valid);
131            }
132        }
133        progress(format!("license not valid ({})", r.code));
134        Ok(false)
135    }
136}