licenz-core 0.2.0

Offline software license verification with RSA signatures, hardware binding, and anti-tamper detection
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
//! Online license validation
//!
//! Configure via [`OnlineCheckConfig`]. **HTTPS** is required for `server_url`.
//! Responses from revocation and sync endpoints must be JSON `{"jws":"<compact-jws>"}`
//! with a verified payload (see `SECURITY.md`). Configure exactly one of
//! [`OnlineCheckConfig::jwks_url`] or [`OnlineCheckConfig::jws_verifying_key_pem`].

mod jws;

use crate::{LicenseError, Result, SignedLicense};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::io::Read;
use std::time::Duration;

/// License revocation status
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RevocationStatus {
    /// License is active and valid
    Active,
    /// License has been revoked
    Revoked,
    /// License has expired
    Expired,
    /// License was not found on server
    NotFound,
    /// Status string in a **verified** JWS payload was not recognized (not transport failure).
    Unknown,
}

/// Result of a revocation check
#[derive(Debug, Clone)]
pub struct RevocationCheckResult {
    pub serial: String,
    pub status: RevocationStatus,
    pub revoked_at: Option<DateTime<Utc>>,
    pub checked_at: DateTime<Utc>,
}

/// Sync report to send to the server
#[derive(Debug, Clone, Serialize)]
pub struct SyncReport {
    pub license_serial: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hardware_fingerprint: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub app_version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub features_used: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seats_in_use: Option<i32>,
}

/// Response from sync endpoint (JWS claims after verification)
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SyncResponse {
    pub status: String,
    pub message: Option<String>,
    pub server_time: DateTime<Utc>,
}

#[derive(Debug, Serialize)]
struct CheckRevocationRequest {
    serials: Vec<String>,
}

#[derive(Debug, Deserialize, Serialize)]
pub(super) struct CheckRevocationResponse {
    results: Vec<RevocationResult>,
    checked_at: DateTime<Utc>,
}

#[derive(Debug, Deserialize, Serialize)]
pub(super) struct RevocationResult {
    serial: String,
    status: String,
    revoked_at: Option<DateTime<Utc>>,
}

/// Configuration for online checks
#[derive(Debug, Clone)]
pub struct OnlineCheckConfig {
    pub server_url: String,
    pub api_key: String,
    pub timeout: Duration,
    pub max_response_bytes: usize,
    pub max_serials_per_request: usize,
    /// HTTPS URL returning a JWKS document (use this **or** `jws_verifying_key_pem`, not both).
    pub jwks_url: Option<String>,
    /// PEM-encoded RSA or Ed25519 public key (use this **or** `jwks_url`, not both).
    pub jws_verifying_key_pem: Option<String>,
    /// Expected JWT `aud` claim. When set, the JWS `aud` must match this value.
    pub expected_audience: Option<String>,
}

impl Default for OnlineCheckConfig {
    fn default() -> Self {
        Self {
            server_url: "https://api.licenz.io".to_string(),
            api_key: String::new(),
            timeout: Duration::from_secs(10),
            max_response_bytes: 512 * 1024,
            max_serials_per_request: 500,
            jwks_url: None,
            jws_verifying_key_pem: None,
            expected_audience: None,
        }
    }
}

impl OnlineCheckConfig {
    pub fn new(server_url: impl Into<String>, api_key: impl Into<String>) -> Self {
        Self {
            server_url: server_url.into(),
            api_key: api_key.into(),
            ..Default::default()
        }
    }

    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    pub fn with_max_response_bytes(mut self, max: usize) -> Self {
        self.max_response_bytes = max;
        self
    }

    pub fn with_max_serials_per_request(mut self, max: usize) -> Self {
        self.max_serials_per_request = max;
        self
    }

    pub fn with_jwks_url(mut self, url: impl Into<String>) -> Self {
        self.jwks_url = Some(url.into());
        self
    }

    pub fn with_jws_verifying_key_pem(mut self, pem: impl Into<String>) -> Self {
        self.jws_verifying_key_pem = Some(pem.into());
        self
    }
}

fn validate_config(config: &OnlineCheckConfig) -> Result<()> {
    let url_lower = config.server_url.to_ascii_lowercase();
    if !url_lower.starts_with("https://") {
        return Err(LicenseError::Validation(
            "HTTPS is required for online checks (server_url must start with https://)".into(),
        ));
    }
    if config.api_key.is_empty() {
        return Err(LicenseError::Validation(
            "API key must not be empty for online checks".into(),
        ));
    }
    let has_jwks = config
        .jwks_url
        .as_ref()
        .map(|s| !s.is_empty())
        .unwrap_or(false);
    let has_pem = config
        .jws_verifying_key_pem
        .as_ref()
        .map(|s| !s.trim().is_empty())
        .unwrap_or(false);
    match (has_jwks, has_pem) {
        (true, false) | (false, true) => Ok(()),
        (false, false) => Err(LicenseError::Validation(
            "Exactly one of jwks_url or jws_verifying_key_pem must be set for JWS verification"
                .into(),
        )),
        (true, true) => Err(LicenseError::Validation(
            "Set only one of jwks_url or jws_verifying_key_pem, not both".into(),
        )),
    }
}

fn build_client(config: &OnlineCheckConfig) -> Result<reqwest::blocking::Client> {
    reqwest::blocking::Client::builder()
        .timeout(config.timeout)
        .build()
        .map_err(|e| LicenseError::Validation(format!("Failed to create HTTP client: {}", e)))
}

fn read_body_limited(response: &mut reqwest::blocking::Response, limit: usize) -> Result<Vec<u8>> {
    let mut buf = Vec::new();
    let mut reader = response.take((limit as u64).saturating_add(1));
    reader
        .read_to_end(&mut buf)
        .map_err(|e| LicenseError::Validation(format!("Failed to read response body: {}", e)))?;
    if buf.len() > limit {
        return Err(LicenseError::Validation(format!(
            "Response body exceeds maximum of {} bytes",
            limit
        )));
    }
    Ok(buf)
}

fn truncate_body_for_error(body: &str, max: usize) -> String {
    if body.len() <= max {
        return body.to_string();
    }
    format!("{}… (truncated, {} bytes total)", &body[..max], body.len())
}

pub fn check_revocation(
    license: &SignedLicense,
    config: &OnlineCheckConfig,
) -> Result<RevocationCheckResult> {
    check_revocation_by_serial(&license.data.serial, config)
}

pub fn check_revocation_by_serial(
    serial: &str,
    config: &OnlineCheckConfig,
) -> Result<RevocationCheckResult> {
    let results = check_revocation_batch(&[serial.to_string()], config)?;
    results
        .into_iter()
        .next()
        .ok_or_else(|| LicenseError::Validation("No result returned from server".into()))
}

pub fn check_revocation_batch(
    serials: &[String],
    config: &OnlineCheckConfig,
) -> Result<Vec<RevocationCheckResult>> {
    validate_config(config)?;
    if serials.is_empty() {
        return Ok(Vec::new());
    }
    if serials.len() > config.max_serials_per_request {
        return Err(LicenseError::Validation(format!(
            "Too many serials: {} exceeds max_serials_per_request ({})",
            serials.len(),
            config.max_serials_per_request
        )));
    }

    let client = build_client(config)?;

    let url = format!(
        "{}/api/v1/licenses/check-revocation",
        config.server_url.trim_end_matches('/')
    );

    let request = CheckRevocationRequest {
        serials: serials.to_vec(),
    };

    let mut resp = client
        .post(&url)
        .header("Authorization", format!("Bearer {}", config.api_key))
        .json(&request)
        .send()
        .map_err(|e| LicenseError::Validation(format!("Revocation request failed: {}", e)))?;

    if !resp.status().is_success() {
        let status = resp.status();
        let body_raw = resp.text().unwrap_or_default();
        let snippet = truncate_body_for_error(&body_raw, 256);
        return Err(LicenseError::Validation(format!(
            "Revocation check failed with HTTP {}; truncated body preview: {:?}",
            status, snippet
        )));
    }

    let raw = read_body_limited(&mut resp, config.max_response_bytes)?;
    let parsed = parse_revocation_body(&raw, config, &client)?;
    let checked_at = parsed.checked_at;
    Ok(parsed
        .results
        .into_iter()
        .map(|r| RevocationCheckResult {
            serial: r.serial,
            status: parse_status(&r.status),
            revoked_at: r.revoked_at,
            checked_at,
        })
        .collect())
}

fn parse_revocation_body(
    body: &[u8],
    config: &OnlineCheckConfig,
    client: &reqwest::blocking::Client,
) -> Result<CheckRevocationResponse> {
    let v: serde_json::Value = serde_json::from_slice(body)
        .map_err(|e| LicenseError::Validation(format!("Failed to parse revocation JSON: {}", e)))?;
    let jws = v.get("jws").and_then(|x| x.as_str()).ok_or_else(|| {
        LicenseError::Validation("Revocation response missing top-level \"jws\" field".into())
    })?;
    jws::verify_revocation_jws(jws, config, client, config.timeout)
}

pub fn sync_report(report: &SyncReport, config: &OnlineCheckConfig) -> Result<SyncResponse> {
    validate_config(config)?;
    let client = build_client(config)?;

    let url = format!(
        "{}/api/v1/licenses/sync",
        config.server_url.trim_end_matches('/')
    );

    let mut response = client
        .post(&url)
        .header("Authorization", format!("Bearer {}", config.api_key))
        .json(report)
        .send()
        .map_err(|e| LicenseError::Validation(format!("Sync request failed: {}", e)))?;

    if !response.status().is_success() {
        let status = response.status();
        let body_raw = response.text().unwrap_or_default();
        let snippet = truncate_body_for_error(&body_raw, 256);
        return Err(LicenseError::Validation(format!(
            "Sync failed with HTTP {}; response body omitted from error (truncated preview: {:?})",
            status, snippet
        )));
    }

    let body = read_body_limited(&mut response, config.max_response_bytes)?;
    let v: serde_json::Value = serde_json::from_slice(&body).map_err(|e| {
        LicenseError::Validation(format!("Failed to parse sync response JSON: {}", e))
    })?;
    let jws = v.get("jws").and_then(|x| x.as_str()).ok_or_else(|| {
        LicenseError::Validation("Sync response missing top-level \"jws\" field".into())
    })?;
    jws::verify_sync_jws(jws, config, &client, config.timeout)
}

fn parse_status(status: &str) -> RevocationStatus {
    match status.to_lowercase().as_str() {
        "active" => RevocationStatus::Active,
        "revoked" => RevocationStatus::Revoked,
        "expired" => RevocationStatus::Expired,
        "not_found" => RevocationStatus::NotFound,
        _ => RevocationStatus::Unknown,
    }
}

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

    const TEST_PEM: &str = r#"-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo
4lgOEePzNm0tRgeLezV6ffAt0gunVTLw7onLRnrq0/IzW7yWR7QkPkblXN/KFhH
XuQgG6aMufVKA2cFFnTXka7s7ZWRfqJBXAJcpZMeKUFb7c4CdFIcfoiZFuVs8Un
k/6TmEYLOxOt17oZUKF8KCB8kWFuLLN24mTS7kbYB2gPpII5JadOxlAHfS6V0V2
MbuXg9qIfVu1Z1t456oiBOy2dPk2jAo1Pkr6N5wQrY1RG6VBX9J2T6dF9bR1QqQ
IDAQAB
-----END PUBLIC KEY-----"#;

    #[test]
    fn test_parse_status() {
        assert_eq!(parse_status("active"), RevocationStatus::Active);
        assert_eq!(parse_status("ACTIVE"), RevocationStatus::Active);
        assert_eq!(parse_status("revoked"), RevocationStatus::Revoked);
        assert_eq!(parse_status("expired"), RevocationStatus::Expired);
        assert_eq!(parse_status("not_found"), RevocationStatus::NotFound);
        assert_eq!(parse_status("unknown"), RevocationStatus::Unknown);
        assert_eq!(parse_status("something_else"), RevocationStatus::Unknown);
    }

    #[test]
    fn test_config_builder() {
        let config = OnlineCheckConfig::new("https://example.com", "test_key")
            .with_jws_verifying_key_pem(TEST_PEM)
            .with_timeout(Duration::from_secs(30));

        assert_eq!(config.server_url, "https://example.com");
        assert_eq!(config.api_key, "test_key");
        assert_eq!(config.timeout, Duration::from_secs(30));
    }

    #[test]
    fn test_validate_rejects_http() {
        let config =
            OnlineCheckConfig::new("http://example.com", "k").with_jws_verifying_key_pem(TEST_PEM);
        assert!(validate_config(&config).is_err());
    }

    #[test]
    fn test_validate_rejects_empty_key() {
        let config =
            OnlineCheckConfig::new("https://example.com", "").with_jws_verifying_key_pem(TEST_PEM);
        assert!(validate_config(&config).is_err());
    }

    #[test]
    fn test_validate_requires_exactly_one_jws_source() {
        let mut c = OnlineCheckConfig::new("https://a.com", "k");
        assert!(validate_config(&c).is_err());

        c.jws_verifying_key_pem = Some(TEST_PEM.into());
        assert!(validate_config(&c).is_ok());

        c.jwks_url = Some("https://a.com/jwks".into());
        assert!(validate_config(&c).is_err());
    }

    #[test]
    fn test_sync_report_serialization() {
        let report = SyncReport {
            license_serial: "LIC-TEST-123".to_string(),
            hardware_fingerprint: Some("abc123".to_string()),
            app_version: Some("1.0.0".to_string()),
            features_used: Some(vec!["premium".to_string()]),
            seats_in_use: Some(5),
        };

        let json = serde_json::to_string(&report).unwrap();
        assert!(json.contains("LIC-TEST-123"));
        assert!(json.contains("abc123"));
    }
}