rust-license-key 0.1.0

A production-grade Rust library for creating and validating offline software licenses using Ed25519 cryptography
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
# Architecture

Technical architecture documentation for developers contributing to or extending rust-license-key.

## Table of Contents

1. [Design Principles]#design-principles
2. [Module Structure]#module-structure
3. [Data Flow]#data-flow
4. [Type System Design]#type-system-design
5. [Error Handling Strategy]#error-handling-strategy
6. [Cryptographic Design]#cryptographic-design
7. [Serialization Format]#serialization-format
8. [Extension Points]#extension-points
9. [Testing Strategy]#testing-strategy

---

## Design Principles

### Core Principles

1. **Security First**: All design decisions prioritize security over convenience
2. **Explicit Over Implicit**: No hidden behavior; all operations are explicit
3. **Fail Safely**: Invalid input produces clear errors, never undefined behavior
4. **No Panics**: All fallible operations return `Result`
5. **Minimal Dependencies**: Only essential, well-audited crates
6. **Pure Functions**: Core logic is side-effect free (no I/O, no network)

### API Design Principles

1. **Hard to Misuse**: The API makes incorrect usage difficult
2. **Separation of Concerns**: Publisher and client code paths are distinct
3. **Builder Pattern**: Complex object construction uses builders
4. **Fluent Interfaces**: Method chaining for ergonomic configuration
5. **Progressive Disclosure**: Simple cases are simple; complex cases are possible

---

## Module Structure

```
src/
├── lib.rs           # Crate root: public API, re-exports, documentation
├── error.rs         # Error types: LicenseError, ValidationFailure
├── models.rs        # Data structures: payloads, constraints, results
├── crypto.rs        # Cryptography: key generation, signing, verification
├── builder.rs       # License creation: LicenseBuilder
├── parser.rs        # License loading: LicenseParser
└── validator.rs     # Validation logic: LicenseValidator
```

### Module Dependency Graph

```
                    ┌─────────────┐
                    │   lib.rs    │
                    │ (re-exports)│
                    └──────┬──────┘
        ┌──────────────────┼──────────────────┐
        │                  │                  │
        ▼                  ▼                  ▼
┌───────────────┐  ┌───────────────┐  ┌───────────────┐
│  builder.rs   │  │  parser.rs    │  │ validator.rs  │
│ (creation)    │  │ (loading)     │  │ (checking)    │
└───────┬───────┘  └───────┬───────┘  └───────┬───────┘
        │                  │                  │
        └──────────────────┼──────────────────┘
                   ┌───────────────┐
                   │  crypto.rs    │
                   │ (Ed25519)     │
                   └───────┬───────┘
        ┌──────────────────┼──────────────────┐
        │                  │                  │
        ▼                  ▼                  ▼
┌───────────────┐  ┌───────────────┐  ┌───────────────┐
│  models.rs    │  │  error.rs     │  │ (external)    │
│ (data types)  │  │ (errors)      │  │ ed25519-dalek │
└───────────────┘  └───────────────┘  └───────────────┘
```

### Module Responsibilities

| Module | Responsibility | Publisher | Client |
|--------|---------------|-----------|--------|
| `crypto` | Key management, signing, verification |||
| `builder` | License construction and signing || - |
| `parser` | License loading and signature verification | - ||
| `validator` | Constraint checking | - ||
| `models` | Shared data structures |||
| `error` | Error definitions |||

---

## Data Flow

### License Creation Flow (Publisher)

```
                    User Input
              ┌─────────────────┐
              │ LicenseBuilder  │
              │                 │
              │ • license_id()  │
              │ • customer_id() │
              │ • expires_in()  │
              │ • ...           │
              └────────┬────────┘
              ┌─────────────────┐
              │ build_payload() │
              │                 │
              │ Validates       │
              │ required fields │
              └────────┬────────┘
              ┌─────────────────┐
              │ LicensePayload  │
              │                 │
              │ • format_version│
              │ • license_id    │
              │ • constraints   │
              │ • ...           │
              └────────┬────────┘
              ┌─────────────────┐
              │ JSON serialize  │
              │ (serde_json)    │
              └────────┬────────┘
              ┌─────────────────┐
              │ Base64 encode   │
              │ (base64)        │
              └────────┬────────┘
              ┌─────────────────┐
              │ Ed25519 sign    │
              │ (ed25519-dalek) │
              │                 │
              │ Signs base64    │
              │ payload         │
              └────────┬────────┘
              ┌─────────────────┐
              │ SignedLicense   │
              │                 │
              │ • payload (b64) │
              │ • signature(b64)│
              └────────┬────────┘
              ┌─────────────────┐
              │ JSON output     │
              └─────────────────┘
```

### License Validation Flow (Client)

```
              License JSON File
              ┌─────────────────┐
              │ JSON parse      │
              │                 │
              │ → SignedLicense │
              └────────┬────────┘
              ┌─────────────────┐
              │ Verify Signature│
              │                 │
              │ public_key      │
              │   .verify()     │
              └────────┬────────┘
               ┌───────┴───────┐
               │               │
          INVALID           VALID
               │               │
               ▼               ▼
        ┌──────────┐   ┌─────────────────┐
        │ Return   │   │ Base64 decode   │
        │ failure  │   │ payload         │
        └──────────┘   └────────┬────────┘
                       ┌─────────────────┐
                       │ JSON parse      │
                       │                 │
                       │ → LicensePayload│
                       └────────┬────────┘
                       ┌─────────────────┐
                       │ Check version   │
                       │ compatibility   │
                       └────────┬────────┘
                       ┌─────────────────┐
                       │ Validate        │
                       │ constraints     │
                       │                 │
                       │ • expiration    │
                       │ • valid_from    │
                       │ • features      │
                       │ • hostname      │
                       │ • version       │
                       │ • connections   │
                       └────────┬────────┘
                       ┌─────────────────┐
                       │ ValidationResult│
                       │                 │
                       │ • is_valid      │
                       │ • failures[]    │
                       │ • payload       │
                       └─────────────────┘
```

---

## Type System Design

### Ownership and Lifetimes

The library uses owned types throughout the public API for simplicity:

```rust
// Owned strings in payload
pub struct LicensePayload {
    pub license_id: String,      // Owned
    pub customer_id: String,     // Owned
    // ...
}

// Builder consumes self for method chaining
impl LicenseBuilder {
    pub fn license_id(mut self, id: impl Into<String>) -> Self {
        self.license_id = Some(id.into());
        self
    }
}
```

### Generic Bounds

Flexible input types with `Into<String>`:

```rust
// Accepts &str, String, Cow<str>, etc.
pub fn license_id(self, id: impl Into<String>) -> Self

// Accepts any iterator of string-like items
pub fn allowed_features(self, features: impl IntoIterator<Item = impl Into<String>>) -> Self
```

### Optional vs Required Fields

```rust
// Required at build time (validated in build_payload)
license_id: Option<String>,    // Must be set
customer_id: Option<String>,   // Must be set

// Optional constraints (None means no restriction)
pub struct LicenseConstraints {
    pub expiration_date: Option<DateTime<Utc>>,
    pub allowed_features: Option<HashSet<String>>,
    // ...
}
```

### Newtype Patterns

Keys are wrapped in newtypes for type safety:

```rust
pub struct KeyPair {
    signing_key: SigningKey,  // Private, wrapped
}

pub struct PublicKey {
    verifying_key: VerifyingKey,  // Private, wrapped
}
```

---

## Error Handling Strategy

### Error Type Hierarchy

```rust
// Main error type with structured variants
pub enum LicenseError {
    // Cryptographic errors
    KeyGenerationFailed { reason: String },
    InvalidPrivateKey { reason: String },
    InvalidSignature,

    // Encoding errors
    Base64DecodingFailed { reason: String },
    JsonDeserializationFailed { reason: String },

    // Validation errors
    LicenseExpired { expiration_date: String },
    FeatureNotAllowed { feature: String },
    // ...
}

// Validation failures (not errors, but expected outcomes)
pub struct ValidationFailure {
    pub failure_type: ValidationFailureType,
    pub message: String,
    pub context: Option<String>,
}
```

### Error vs Failure

| Concept | Type | Meaning |
|---------|------|---------|
| Error | `LicenseError` | Unexpected condition, operation cannot proceed |
| Failure | `ValidationFailure` | Expected condition, license is invalid |

```rust
// Error: Cannot proceed
fn parse_json(&self, json: &str) -> Result<LicensePayload, LicenseError>

// Success with failures: Operation succeeded, license is invalid
fn validate_json(&self, json: &str, ctx: &ValidationContext) -> Result<ValidationResult, LicenseError>
```

### Error Context

Errors include context for debugging:

```rust
LicenseError::InvalidPublicKey {
    reason: format!("invalid key length: expected {} bytes, got {}",
                    PUBLIC_KEY_LENGTH, bytes.len())
}
```

---

## Cryptographic Design

### Algorithm Choice: Ed25519

| Property | Value | Rationale |
|----------|-------|-----------|
| Algorithm | Ed25519 | Fast, secure, widely audited |
| Library | ed25519-dalek | Pure Rust, well-maintained |
| Key Size | 32 bytes | Compact, easy to embed |
| Signature Size | 64 bytes | Compact |
| Security Level | 128-bit | Sufficient for licensing |

### Signing Process

```rust
// What gets signed
let payload_json = serde_json::to_string(&payload)?;
let encoded_payload = base64::encode(&payload_json);

// Signature is over the base64-encoded payload
// This ensures consistency across JSON formatting variations
let signature = signing_key.sign(encoded_payload.as_bytes());
```

### Verification Process

```rust
// Reconstruct what was signed
let encoded_payload = &signed_license.encoded_payload;

// Verify signature
verifying_key.verify(
    encoded_payload.as_bytes(),
    &signature
)?;
```

### Key Derivation

```rust
// Public key is deterministically derived from private key
let signing_key = SigningKey::from_bytes(&private_key_bytes);
let verifying_key = signing_key.verifying_key();
```

---

## Serialization Format

### License JSON Structure

```json
{
  "payload": "<base64-encoded-json>",
  "signature": "<base64-encoded-signature>"
}
```

### Payload JSON Structure

```json
{
  "v": 1,
  "id": "LIC-2024-001",
  "customer": "CUST-123",
  "customer_name": "Acme Corp",
  "issued_at": "2024-01-15T10:30:00Z",
  "constraints": {
    "expires_at": "2025-01-15T10:30:00Z",
    "allowed_features": ["basic", "premium"],
    "max_connections": 100
  },
  "metadata": {
    "custom_key": "custom_value"
  }
}
```

### Field Naming Convention

Compact JSON field names for smaller licenses:

```rust
#[serde(rename = "v")]
pub format_version: u32,

#[serde(rename = "id")]
pub license_id: String,

#[serde(rename = "expires_at", skip_serializing_if = "Option::is_none")]
pub expiration_date: Option<DateTime<Utc>>,
```

### Version Compatibility

```rust
pub const LICENSE_FORMAT_VERSION: u32 = 1;
pub const MIN_SUPPORTED_LICENSE_VERSION: u32 = 1;
pub const MAX_SUPPORTED_LICENSE_VERSION: u32 = 1;
```

Future versions will increment `LICENSE_FORMAT_VERSION` and extend the supported range.

---

## Extension Points

### Custom Constraints

Users can add application-specific constraints:

```rust
// In license
.custom_constraint("max_storage_gb", json!(100))

// In validation
let storage_limit = payload.constraints.custom_constraints
    .as_ref()
    .and_then(|c| c.get("max_storage_gb"))
    .and_then(|v| v.as_u64());
```

### Custom Validation

Applications can extend validation:

```rust
fn validate_with_custom_checks(
    license_json: &str,
    public_key: &str,
) -> Result<ValidationResult, LicenseError> {
    let mut result = validate_license(license_json, public_key, &ValidationContext::new())?;

    // Add custom validation
    if let Some(payload) = &result.payload {
        if let Some(custom) = &payload.constraints.custom_constraints {
            if let Some(region) = custom.get("region") {
                if region != "US" {
                    result.add_failure(ValidationFailure::new(
                        ValidationFailureType::CustomConstraint,
                        "Region not supported",
                    ));
                }
            }
        }
    }

    Ok(result)
}
```

### Custom Metadata

Metadata is stored but not validated:

```rust
// Store anything in metadata
.metadata("internal_id", json!("INT-123"))
.metadata("signed_by", json!("sales@company.com"))
.metadata("contract", json!({
    "id": "CNT-2024",
    "terms": "annual"
}))
```

---

## Testing Strategy

### Test Organization

```
src/
├── *.rs              # Unit tests in each module (#[cfg(test)] mod tests)
tests/
└── integration_tests.rs   # Integration tests
```

### Test Categories

| Category | Location | Purpose |
|----------|----------|---------|
| Unit Tests | `src/*.rs` | Test individual functions/methods |
| Integration Tests | `tests/` | Test complete workflows |
| Doc Tests | Rustdoc comments | Verify documentation examples |

### Test Patterns

```rust
// Unit test pattern
#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_key_pair() -> KeyPair {
        KeyPair::generate().expect("Key generation should succeed")
    }

    #[test]
    fn test_feature_name() {
        // Arrange
        let key_pair = create_test_key_pair();

        // Act
        let result = some_operation(&key_pair);

        // Assert
        assert!(result.is_ok());
    }
}
```

### Test Coverage Goals

| Area | Target Coverage |
|------|-----------------|
| Crypto operations | 100% of public API |
| Builder methods | All constraint types |
| Parser | Valid, invalid, and edge cases |
| Validator | All constraint types and combinations |
| Error paths | All error variants |

### Property-Based Testing (Future)

```rust
// Consider adding proptest for property-based tests
#[test]
fn prop_sign_verify_roundtrip(data: Vec<u8>) {
    let key_pair = KeyPair::generate().unwrap();
    let signature = key_pair.sign(&data);
    assert!(key_pair.public_key().verify(&data, &signature).is_ok());
}
```

---

**Previous:** [Examples]./examples.md | **Next:** [Contributing]./contributing.md