librnxengine 1.1.0

implement robust software licensing, activation, and validation systems.
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
use crate::{
    crypto::{KeyPair, PublicKey},
    error::LicenseError,
    license::{License, LicensePayload},
};
use chrono::Utc;
use ed25519_dalek::Signature;
use serde_cbor;
use std::convert::TryInto;
use tracing::{debug, error, info, instrument, warn};

/// Result of license validation containing detailed status information.
///
/// This struct provides comprehensive feedback about license validation,
/// including violations, warnings, expiration data, and enabled features.
/// Used by `LicenseEngine` to communicate validation results to callers.
#[derive(Debug, Clone)]
pub struct ValidationResult {
    /// Critical errors that invalidate the license
    pub violations: Vec<String>,
    /// Non-critical issues that don't affect license validity
    pub warnings: Vec<String>,
    /// When the license expires (None if expired or invalid)
    pub expires_at: Option<chrono::DateTime<Utc>>,
    /// Days remaining until expiration (negative if expired)
    pub days_remaining: Option<i64>,
    /// List of features enabled by this license
    pub features: Vec<String>,
}

impl ValidationResult {
    /// Creates a new empty validation result.
    ///
    /// # Returns
    /// A `ValidationResult` with empty collections and no expiration data.
    pub fn new() -> Self {
        Self {
            violations: Vec::new(),
            warnings: Vec::new(),
            expires_at: None,
            days_remaining: None,
            features: Vec::new(),
        }
    }

    /// Adds a critical violation that makes the license invalid.
    ///
    /// # Parameters
    /// - `msg`: Description of the violation
    pub fn add_violation(&mut self, msg: String) {
        self.violations.push(msg);
    }

    /// Adds a non-critical warning that doesn't affect license validity.
    ///
    /// # Parameters
    /// - `msg`: Description of the warning
    pub fn add_warning(&mut self, msg: String) {
        self.warnings.push(msg);
    }

    /// Checks if the license is valid (has no critical violations).
    ///
    /// # Returns
    /// - `true`: License has no violations (may have warnings)
    /// - `false`: License has one or more violations
    pub fn is_valid(&self) -> bool {
        self.violations.is_empty()
    }
}

/// Configuration for license validation and management behavior.
///
/// Controls various aspects of license validation, including grace periods,
/// hardware binding requirements, and revocation checks.
#[derive(Debug, Clone)]
pub struct LicenseConfig {
    /// Whether licenses can be validated without network access
    pub allow_offline: bool,
    /// Days of grace allowed after license expiration
    pub grace_period_days: u32,
    /// Maximum allowed clock skew between issuer and validator (seconds)
    pub max_clock_skew_seconds: i64,
    /// Whether licenses must be bound to specific hardware
    pub require_hardware_binding: bool,
    /// Whether to check license revocation status
    pub enable_revocation_check: bool,
}

impl Default for LicenseConfig {
    /// Provides sensible default configuration values.
    ///
    /// Defaults are chosen for balanced security and usability:
    /// - Offline validation allowed (for better UX)
    /// - 7-day grace period (standard business practice)
    /// - 5-minute clock skew tolerance (common for NTP sync)
    /// - No hardware binding (flexible deployment)
    /// - Revocation checks enabled (security)
    fn default() -> Self {
        Self {
            allow_offline: true,
            grace_period_days: 7,
            max_clock_skew_seconds: 300,
            require_hardware_binding: false,
            enable_revocation_check: true,
        }
    }
}

/// Core engine for license creation, validation, and management.
///
/// This is the main entry point for license operations. It provides:
/// - License creation with digital signatures
/// - Cryptographic verification of licenses
/// - Content validation against business rules
/// - Serialization/deserialization utilities
///
/// The engine uses Ed25519 digital signatures for security and
/// provides comprehensive validation with configurable rules.
pub struct LicenseEngine {
    config: LicenseConfig,
}

impl LicenseEngine {
    /// Creates a new license engine with the specified configuration.
    ///
    /// # Parameters
    /// - `config`: Validation and behavior configuration
    ///
    /// # Returns
    /// A new `LicenseEngine` instance
    ///
    /// # Example
    /// ```rust
    /// let config = LicenseConfig::default();
    /// let engine = LicenseEngine::new(config);
    /// ```
    pub fn new(config: LicenseConfig) -> Self {
        info!("Initializing LicenseEngine with config: {:?}", config);
        Self { config }
    }

    /// Creates a digitally signed license from a payload.
    ///
    /// This is the primary method for license issuance. It:
    /// 1. Validates the payload content
    /// 2. Serializes the payload to CBOR
    /// 3. Creates an Ed25519 digital signature
    /// 4. Packages everything into a complete license
    ///
    /// # Parameters
    /// - `keypair`: The cryptographic key pair for signing
    /// - `payload`: The license data to sign
    ///
    /// # Returns
    /// - `Ok(License)`: The signed, complete license
    /// - `Err(LicenseError)`: If validation or signing fails
    ///
    /// # Example
    /// ```rust
    /// let keypair = engine.generate_keypair()?;
    /// let payload = LicensePayload {
    ///     license_id: Uuid::new_v4(),
    ///     customer_id: "customer-123".to_string(),
    ///     // ... other fields
    /// };
    /// let license = engine.create_license(&keypair, payload)?;
    /// ```
    #[instrument(skip(self, keypair, payload), fields(license_id = %payload.license_id))]
    pub fn create_license(
        &self,
        keypair: &KeyPair,
        payload: LicensePayload,
    ) -> Result<License, LicenseError> {
        info!("Creating license for customer: {}", payload.customer_id);
        debug!("License payload: {:?}", payload);

        // Validate payload before signing
        self.validate_payload(&payload)?;

        // Serialize to CBOR for signing
        let serialized = serde_cbor::to_vec(&payload).map_err(|e| {
            error!("Failed to serialize license payload: {}", e);
            LicenseError::SerializationError(e.to_string())
        })?;
        debug!("Serialized payload size: {} bytes", serialized.len());

        // Create digital signature
        let signature = keypair.private.sign(&serialized)?;

        // Construct final license
        let license = License {
            version: 1,
            payload,
            signature: signature.to_bytes().to_vec(),
            algorithm: "ed25519".to_string(),
        };

        info!("License created successfully: {}", license.license_id());
        Ok(license)
    }

    /// Verifies a license's authenticity and validity.
    ///
    /// Performs comprehensive verification including:
    /// 1. Cryptographic signature verification
    /// 2. Content validation (expiration, grace period, etc.)
    /// 3. Clock skew detection
    ///
    /// # Parameters
    /// - `public_key`: The public key to verify the signature
    /// - `license`: The license to verify
    ///
    /// # Returns
    /// - `Ok(ValidationResult)`: Detailed validation results
    /// - `Err(LicenseError)`: If verification fails catastrophically
    ///
    /// # Security Note
    /// Always verify signatures before trusting license content.
    /// This method ensures cryptographic integrity.
    #[instrument(skip(self, public_key, license), fields(license_id = %license.license_id()))]
    pub fn verify_license(
        &self,
        public_key: &PublicKey,
        license: &License,
    ) -> Result<ValidationResult, LicenseError> {
        info!("Verifying license: {}", license.license_id());
        debug!("Using public key: {}", hex::encode(public_key.as_bytes()));

        // Serialize payload for signature verification
        let serialized = serde_cbor::to_vec(&license.payload)
            .map_err(|e| LicenseError::SerializationError(e.to_string()))?;

        // Convert signature bytes to Ed25519 signature object
        let sig_bytes: [u8; 64] = license
            .signature
            .as_slice()
            .try_into()
            .map_err(|_| LicenseError::SignatureValidationFailed)?;
        let signature = Signature::from_bytes(&sig_bytes);

        // Verify cryptographic signature
        public_key.verify(&serialized, &signature)?;

        // Validate license content against business rules
        let result = self.validate_license_content(license)?;

        // Log appropriate message based on validation outcome
        if result.is_valid() {
            info!("License validation successful: {}", license.license_id());
        } else {
            warn!("License validation failed: {:?}", result.violations);
        }

        Ok(result)
    }

    /// Validates license payload for correctness before signing.
    ///
    /// Ensures payload follows basic business rules to prevent
    /// creation of obviously invalid licenses.
    ///
    /// # Parameters
    /// - `payload`: The license payload to validate
    ///
    /// # Returns
    /// - `Ok(())`: Payload is valid
    /// - `Err(LicenseError)`: Payload violates rules
    ///
    /// # Validation Rules
    /// 1. Expiration must be after issue date
    /// 2. Must allow at least 1 activation
    fn validate_payload(&self, payload: &LicensePayload) -> Result<(), LicenseError> {
        debug!("Validating license payload");

        // Check expiration is after issue date
        if payload.expires_at <= payload.issued_at {
            error!("License expiration must be after issue date");
            return Err(LicenseError::InvalidLicense(
                "Expiration date must be after issue date".to_string(),
            ));
        }

        // Check reasonable activation limit
        if payload.max_activations == 0 {
            error!("License must allow at least 1 activation");
            return Err(LicenseError::InvalidLicense(
                "Max activations must be at least 1".to_string(),
            ));
        }

        Ok(())
    }

    /// Validates license content against current time and configuration.
    ///
    /// Performs time-based validations and applies configured rules
    /// like grace periods and clock skew tolerance.
    ///
    /// # Parameters
    /// - `license`: The license to validate
    ///
    /// # Returns
    /// - `Ok(ValidationResult)`: Validation results
    /// - `Err(LicenseError)`: If validation fails unexpectedly
    ///
    /// # Note
    /// This method assumes cryptographic verification has already passed.
    fn validate_license_content(
        &self,
        license: &License,
    ) -> Result<ValidationResult, LicenseError> {
        let mut result = ValidationResult::new();
        let now = Utc::now();

        // Check expiration
        if license.payload.expires_at < now {
            result.add_violation("License has expired".to_string());
        } else {
            // License is still valid, populate expiration info
            result.expires_at = Some(license.payload.expires_at);
            result.days_remaining = Some((license.payload.expires_at - now).num_days());
        }

        // Apply grace period if offline validation is allowed
        if self.config.allow_offline {
            let grace_end = license.payload.expires_at
                + chrono::Duration::days(self.config.grace_period_days as i64);
            if grace_end < now {
                result.add_violation("Grace period has ended".to_string());
            }
        }

        // Check for significant clock skew
        let skew = (now - license.payload.issued_at).num_seconds().abs();
        if skew > self.config.max_clock_skew_seconds {
            warn!("Large clock skew detected: {} seconds", skew);
            result.add_warning(format!("Large system clock skew: {} seconds", skew));
        }

        // Copy features to result for client inspection
        result.features = license.payload.features.clone();

        Ok(result)
    }

    /// Generates a new cryptographic key pair for license operations.
    ///
    /// Creates a new Ed25519 key pair suitable for signing and
    /// verifying licenses. Uses cryptographically secure random
    /// number generation.
    ///
    /// # Returns
    /// - `Ok(KeyPair)`: Newly generated key pair
    /// - `Err(LicenseError)`: If key generation fails
    ///
    /// # Security Note
    /// Store private keys securely. Public keys can be distributed
    /// for verification purposes.
    pub fn generate_keypair(&self) -> Result<KeyPair, LicenseError> {
        info!("Generating new key pair");
        let keypair = KeyPair::generate();
        debug!(
            "Generated public key: {}",
            hex::encode(keypair.public.as_bytes())
        );
        Ok(keypair)
    }

    /// Converts a license to pretty-printed JSON string.
    ///
    /// Useful for debugging, logging, or displaying licenses
    /// in human-readable format.
    ///
    /// # Parameters
    /// - `license`: The license to serialize
    ///
    /// # Returns
    /// - `Ok(String)`: JSON representation of the license
    /// - `Err(LicenseError)`: If serialization fails
    pub fn license_to_json(&self, license: &License) -> Result<String, LicenseError> {
        serde_json::to_string_pretty(license)
            .map_err(|e| LicenseError::SerializationError(e.to_string()))
    }

    /// Parses a license from a JSON string.
    ///
    /// # Parameters
    /// - `json`: JSON string containing license data
    ///
    /// # Returns
    /// - `Ok(License)`: Parsed license
    /// - `Err(LicenseError)`: If parsing fails
    ///
    /// # Note
    /// This only parses the data structure. Cryptographic
    /// verification must be performed separately.
    pub fn license_from_json(&self, json: &str) -> Result<License, LicenseError> {
        serde_json::from_str(json).map_err(|e| LicenseError::DeserializationError(e.to_string()))
    }

    /// Converts a license to compact binary CBOR format.
    ///
    /// CBOR is more compact than JSON and is the format used
    /// for digital signatures.
    ///
    /// # Parameters
    /// - `license`: The license to serialize
    ///
    /// # Returns
    /// - `Ok(Vec<u8>)`: CBOR-encoded license bytes
    /// - `Err(LicenseError)`: If serialization fails
    pub fn license_to_bytes(&self, license: &License) -> Result<Vec<u8>, LicenseError> {
        serde_cbor::to_vec(license).map_err(|e| LicenseError::SerializationError(e.to_string()))
    }

    /// Parses a license from CBOR binary data.
    ///
    /// # Parameters
    /// - `bytes`: CBOR-encoded license data
    ///
    /// # Returns
    /// - `Ok(License)`: Parsed license
    /// - `Err(LicenseError)`: If parsing fails
    pub fn license_from_bytes(&self, bytes: &[u8]) -> Result<License, LicenseError> {
        serde_cbor::from_slice(bytes).map_err(|e| LicenseError::DeserializationError(e.to_string()))
    }
}

// Note: The engine uses Ed25519 signatures for cryptographic security.
// Ed25519 provides:
// - Strong security with 128-bit security level
// - Fast verification
// - Small signature size (64 bytes)
// - Built-in resistance to several types of attacks

// Note: CBOR (Concise Binary Object Representation) is used for
// serialization during signing because:
// - It's deterministic (same data = same bytes)
// - More compact than JSON
// - Supports binary data natively
// - Standardized (RFC 7049)

// Note: Grace period logic is complex:
// - If `allow_offline` is true: Grace period applies
// - If `allow_offline` is false: Immediate expiration
// This allows flexible policies for different products.

// Note: Clock skew detection helps identify systems with
// incorrect time settings, which could affect validation.
// The default 300 seconds (5 minutes) is reasonable for
// systems using NTP time synchronization.

// Note: Hardware binding and revocation checks are configured
// but not implemented in this engine. They would require:
// - Hardware fingerprint comparison
// - Network calls to revocation lists
// - Additional validation logic

// Note: The engine is designed to be stateless (except for config).
// All operations are pure functions based on inputs.
// This makes it easy to test, parallelize, and use in different contexts.

// Note: Error handling is comprehensive:
// - Early validation prevents invalid licenses
// - Detailed error messages aid debugging
// - Appropriate logging levels for different situations
// - Structured logging with tracing spans

// Example usage pattern:
// ```
// // Setup
// let config = LicenseConfig::default();
// let engine = LicenseEngine::new(config);
// let keypair = engine.generate_keypair()?;
//
// // Create license
// let payload = create_payload();
// let license = engine.create_license(&keypair, payload)?;
//
// // Save license
// let json = engine.license_to_json(&license)?;
// std::fs::write("license.json", json)?;
//
// // Later: Load and verify
// let loaded_json = std::fs::read_to_string("license.json")?;
// let loaded_license = engine.license_from_json(&loaded_json)?;
// let result = engine.verify_license(&keypair.public, &loaded_license)?;
//
// if result.is_valid() {
//     println!("License valid, features: {:?}", result.features);
// }
// ```