brinkhaustools/licence/
format.rs

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
//! Wire format: licence payload, signed text block, signing keys, licence request.
//!
//! Text block = prefix + Crockford Base32 of `payload ‖ signature ‖ check`:
//! `payload` is canonical JSON, `signature` Ed25519 (64 bytes) over the payload
//! bytes, `check` the first 4 bytes of SHA-256 over `payload ‖ signature`. The check
//! tells a copy error ("incomplete") apart from a forgery ("signature invalid").
//! The verifier checks the transmitted bytes; it never re-serialises.

use std::collections::BTreeMap;

use chrono::{DateTime, Utc};
use ring::signature::{Ed25519KeyPair, KeyPair, UnparsedPublicKey, ED25519};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use super::codec::{base32_decode, base32_encode, canonical_json, hex_decode, hex_encode, wrap};
use super::hardware::Binding;
use super::LicenceError;

/// Prefix of a licence text block (format version 1).
pub const LICENCE_PREFIX: &str = "BLIC1-";
/// Prefix of a licence request block (format version 1).
pub const REQUEST_PREFIX: &str = "BLRQ1-";
/// Payload format version.
pub const FORMAT_VERSION: u32 = 1;
/// Line width of emitted blocks.
pub const LINE_WIDTH: usize = 64;

const SIGNATURE_LEN: usize = 64;
const CHECK_LEN: usize = 4;

/// Licensee named in a licence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Licensee {
    /// Customer slug (FleetManager).
    pub slug: String,
    /// Display name.
    pub name: String,
}

/// The signed content of a licence.
///
/// Unknown fields are rejected: a newer issuer that adds a restriction must bump
/// [`FORMAT_VERSION`], so an older verifier refuses loudly instead of ignoring it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LicencePayload {
    pub v: u32,
    /// Licence id (UUID, issued by the FleetManager).
    pub id: String,
    /// Id of the signing key ([`key_id`]).
    pub kid: String,
    /// Product the licence is for (each product checks its own name).
    pub product: String,
    /// Product variant (e.g. a branding stream); `None` = any.
    #[serde(default)]
    pub variant: Option<String>,
    pub licensee: Licensee,
    /// Hardware bindings; **all** must be present on the machine.
    pub bind: Vec<Binding>,
    #[serde(default)]
    pub not_before: Option<DateTime<Utc>>,
    /// End of validity; `None` = lifetime.
    #[serde(default)]
    pub not_after: Option<DateTime<Utc>>,
    /// Product-defined feature names (additive across licences).
    #[serde(default)]
    pub features: Vec<String>,
    /// Product-defined quotas (summed across licences).
    #[serde(default)]
    pub quotas: BTreeMap<String, u64>,
    pub issued_at: DateTime<Utc>,
    #[serde(default)]
    pub note: Option<String>,
}

/// A parsed (not yet verified) licence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedLicence {
    pub payload: LicencePayload,
    payload_bytes: Vec<u8>,
    signature: Vec<u8>,
    text: String,
}

impl SignedLicence {
    /// Parse a text block. Whitespace, line breaks and case do not matter.
    pub fn parse(text: &str) -> Result<Self, LicenceError> {
        let body = decode_block(text, LICENCE_PREFIX)?;
        if body.len() < SIGNATURE_LEN + 2 {
            return Err(LicenceError::Incomplete);
        }
        let split = body.len() - SIGNATURE_LEN;
        let (payload_bytes, signature) = body.split_at(split);
        // Version first: a newer format may carry fields this verifier does not
        // know, and the operator must read "update the software", not "invalid".
        let raw: serde_json::Value = serde_json::from_slice(payload_bytes)
            .map_err(|e| LicenceError::Payload(e.to_string()))?;
        let version = raw.get("v").and_then(serde_json::Value::as_u64);
        if let Some(v) = version.filter(|v| *v != u64::from(FORMAT_VERSION)) {
            return Err(LicenceError::UnsupportedVersion(u32::try_from(v).unwrap_or(u32::MAX)));
        }
        let payload: LicencePayload =
            serde_json::from_value(raw).map_err(|e| LicenceError::Payload(e.to_string()))?;
        Ok(Self {
            text: encode_block(LICENCE_PREFIX, &body),
            payload,
            payload_bytes: payload_bytes.to_vec(),
            signature: signature.to_vec(),
        })
    }

    /// Verify the signature against the trusted keys.
    pub fn verify(&self, keys: &TrustedKeys) -> Result<(), LicenceError> {
        let key = keys
            .get(&self.payload.kid)
            .ok_or_else(|| LicenceError::UnknownKey(self.payload.kid.clone()))?;
        UnparsedPublicKey::new(&ED25519, key)
            .verify(&self.payload_bytes, &self.signature)
            .map_err(|_| LicenceError::Signature)
    }

    /// Normalised text block (re-wrapped, upper case) — what to store and display.
    pub fn text(&self) -> &str {
        &self.text
    }
}

/// Key id: first 8 hex digits of SHA-256 over the raw public key.
pub fn key_id(public_key: &[u8]) -> String {
    hex_encode(&Sha256::digest(public_key))[..8].to_string()
}

/// Public keys a product trusts, by key id.
#[derive(Debug, Clone, Default)]
pub struct TrustedKeys {
    keys: BTreeMap<String, Vec<u8>>,
}

impl TrustedKeys {
    /// Build from hex-encoded raw Ed25519 public keys (32 bytes each).
    pub fn from_hex(public_keys: &[&str]) -> Result<Self, LicenceError> {
        let mut keys = BTreeMap::new();
        for hex in public_keys {
            let raw = hex_decode(hex)
                .filter(|k| k.len() == 32)
                .ok_or_else(|| LicenceError::Key(format!("not a 32-byte hex key: {hex}")))?;
            keys.insert(key_id(&raw), raw);
        }
        Ok(Self { keys })
    }

    /// Public key for `kid`.
    pub fn get(&self, kid: &str) -> Option<&[u8]> {
        self.keys.get(kid).map(Vec::as_slice)
    }

    /// All trusted key ids.
    pub fn ids(&self) -> Vec<String> {
        self.keys.keys().cloned().collect()
    }
}

/// An Ed25519 signing key, stored as its 32-byte seed in hex.
///
/// The seed file is the only secret of the scheme; it belongs on the issuing
/// server, never into a repository.
pub struct SigningKey {
    seed: [u8; 32],
    pair: Ed25519KeyPair,
}

impl SigningKey {
    /// Generate a new random key.
    pub fn generate() -> Result<Self, LicenceError> {
        let mut seed = [0u8; 32];
        ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut seed)
            .map_err(|_| LicenceError::Key("random source failed".to_string()))?;
        Self::from_seed(seed)
    }

    /// Load from a hex seed (64 hex digits).
    pub fn from_seed_hex(hex: &str) -> Result<Self, LicenceError> {
        let raw = hex_decode(hex)
            .filter(|s| s.len() == 32)
            .ok_or_else(|| LicenceError::Key("seed must be 64 hex digits".to_string()))?;
        let mut seed = [0u8; 32];
        seed.copy_from_slice(&raw);
        Self::from_seed(seed)
    }

    fn from_seed(seed: [u8; 32]) -> Result<Self, LicenceError> {
        let pair = Ed25519KeyPair::from_seed_unchecked(&seed)
            .map_err(|e| LicenceError::Key(e.to_string()))?;
        Ok(Self { seed, pair })
    }

    /// Seed as hex (for the key file).
    pub fn seed_hex(&self) -> String {
        hex_encode(&self.seed)
    }

    /// Raw public key as hex.
    pub fn public_hex(&self) -> String {
        hex_encode(self.pair.public_key().as_ref())
    }

    /// Key id of this key.
    pub fn kid(&self) -> String {
        key_id(self.pair.public_key().as_ref())
    }

    /// Sign a payload into a text block. `payload.kid` must be this key's id.
    pub fn sign(&self, payload: &LicencePayload) -> Result<String, LicenceError> {
        if payload.kid != self.kid() {
            return Err(LicenceError::Key(format!(
                "payload kid {} does not match signing key {}",
                payload.kid,
                self.kid()
            )));
        }
        let value =
            serde_json::to_value(payload).map_err(|e| LicenceError::Payload(e.to_string()))?;
        let mut body = canonical_json(&value).into_bytes();
        let signature = self.pair.sign(&body);
        body.extend_from_slice(signature.as_ref());
        Ok(encode_block(LICENCE_PREFIX, &body))
    }
}

/// A licence request: what a machine offers to bind to, copied from the product UI
/// into the FleetManager when the machine is offline. Not signed — it only
/// pre-fills the issuing form.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LicenceRequest {
    pub v: u32,
    pub product: String,
    #[serde(default)]
    pub variant: Option<String>,
    #[serde(default)]
    pub version: Option<String>,
    /// Installation id of the requesting software (recognition, not binding).
    pub installation_id: String,
    pub bind: Vec<Binding>,
    pub created_at: DateTime<Utc>,
}

impl LicenceRequest {
    /// Encode as a `BLRQ1-` text block.
    pub fn encode(&self) -> Result<String, LicenceError> {
        let value =
            serde_json::to_value(self).map_err(|e| LicenceError::Payload(e.to_string()))?;
        Ok(encode_block(REQUEST_PREFIX, canonical_json(&value).as_bytes()))
    }

    /// Decode a `BLRQ1-` text block.
    pub fn decode(text: &str) -> Result<Self, LicenceError> {
        let body = decode_block(text, REQUEST_PREFIX)?;
        let request: Self =
            serde_json::from_slice(&body).map_err(|e| LicenceError::Payload(e.to_string()))?;
        if request.v != FORMAT_VERSION {
            return Err(LicenceError::UnsupportedVersion(request.v));
        }
        Ok(request)
    }
}

/// `prefix ‖ base32(body ‖ check)`, wrapped.
pub(crate) fn encode_block(prefix: &str, body: &[u8]) -> String {
    let mut data = body.to_vec();
    data.extend_from_slice(&Sha256::digest(body)[..CHECK_LEN]);
    wrap(prefix, &base32_encode(&data), LINE_WIDTH)
}

/// Strip layout, check the prefix, decode, verify and strip the check bytes.
pub(crate) fn decode_block(text: &str, prefix: &str) -> Result<Vec<u8>, LicenceError> {
    let compact: String = text
        .chars()
        .filter(|c| !c.is_whitespace())
        .collect::<String>()
        .to_ascii_uppercase();
    let rest = compact
        .strip_prefix(prefix)
        .ok_or_else(|| LicenceError::Prefix(prefix.to_string()))?;
    let data = base32_decode(rest).map_err(LicenceError::Encoding)?;
    if data.len() <= CHECK_LEN {
        return Err(LicenceError::Incomplete);
    }
    let (body, check) = data.split_at(data.len() - CHECK_LEN);
    if Sha256::digest(body)[..CHECK_LEN] != *check {
        return Err(LicenceError::Incomplete);
    }
    Ok(body.to_vec())
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::licence::hardware::IdentifierKind;
    use chrono::TimeZone;

    pub(crate) const TEST_SEED: &str =
        "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60";

    pub(crate) fn payload(kid: &str) -> LicencePayload {
        LicencePayload {
            v: 1,
            id: "8a6e0804-2bd0-4672-b79d-d97027f9071a".into(),
            kid: kid.into(),
            product: "datastore-v2".into(),
            variant: Some("brand-a".into()),
            licensee: Licensee { slug: "acme".into(), name: "ACME Werkzeugbau GmbH".into() },
            bind: vec![Binding {
                kind: IdentifierKind::Mac,
                label: "eth0".into(),
                sha256: crate::licence::hardware::identifier_hash(
                    IdentifierKind::Mac,
                    "e0:8f:4c:82:40:7e",
                ),
            }],
            not_before: None,
            not_after: Some(Utc.with_ymd_and_hms(2027, 11, 5, 0, 0, 0).unwrap()),
            features: vec!["base".into(), "afc".into()],
            quotas: BTreeMap::from([("sources".into(), 4)]),
            issued_at: Utc.with_ymd_and_hms(2026, 11, 5, 10, 0, 0).unwrap(),
            note: Some("order 4711".into()),
        }
    }

    #[test]
    fn sign_parse_verify_roundtrip() {
        let key = SigningKey::from_seed_hex(TEST_SEED).unwrap();
        let text = key.sign(&payload(&key.kid())).unwrap();
        assert!(text.starts_with(LICENCE_PREFIX));
        assert!(text.lines().all(|l| l.len() <= LINE_WIDTH));
        let licence = SignedLicence::parse(&text.to_lowercase().replace('\n', "  \r\n")).unwrap();
        assert_eq!(licence.payload, payload(&key.kid()));
        assert_eq!(licence.text(), text);
        let keys = TrustedKeys::from_hex(&[&key.public_hex()]).unwrap();
        licence.verify(&keys).unwrap();
    }

    #[test]
    fn signing_is_deterministic() {
        let key = SigningKey::from_seed_hex(TEST_SEED).unwrap();
        assert_eq!(key.sign(&payload(&key.kid())).unwrap(), key.sign(&payload(&key.kid())).unwrap());
    }

    #[test]
    fn foreign_key_and_forgery_are_told_apart_from_copy_errors() {
        let key = SigningKey::from_seed_hex(TEST_SEED).unwrap();
        let other = SigningKey::generate().unwrap();
        let text = key.sign(&payload(&key.kid())).unwrap();
        let licence = SignedLicence::parse(&text).unwrap();
        let foreign = TrustedKeys::from_hex(&[&other.public_hex()]).unwrap();
        assert!(matches!(licence.verify(&foreign), Err(LicenceError::UnknownKey(_))));

        // A forger who keeps the check consistent still fails the signature.
        let mut forged = payload(&key.kid());
        forged.quotas.insert("sources".into(), 400);
        let forged_text = other.sign(&LicencePayload { kid: other.kid(), ..forged }).unwrap();
        let mut body = decode_block(&forged_text, LICENCE_PREFIX).unwrap();
        let p = body.len() - SIGNATURE_LEN;
        let mut payload_bytes = body[..p].to_vec();
        let text_payload = String::from_utf8(payload_bytes.clone()).unwrap();
        payload_bytes = text_payload.replace(&other.kid(), &key.kid()).into_bytes();
        body.splice(..p, payload_bytes);
        let tampered = SignedLicence::parse(&encode_block(LICENCE_PREFIX, &body)).unwrap();
        let trusted = TrustedKeys::from_hex(&[&key.public_hex()]).unwrap();
        assert!(matches!(tampered.verify(&trusted), Err(LicenceError::Signature)));

        // A truncated copy is "incomplete", not "forged".
        let cut = &text[..text.len() - 3];
        assert!(matches!(SignedLicence::parse(cut), Err(LicenceError::Incomplete | LicenceError::Encoding(_))));
        assert!(matches!(SignedLicence::parse("XYZ1-ABC"), Err(LicenceError::Prefix(_))));
    }

    #[test]
    fn unknown_payload_fields_are_refused() {
        let key = SigningKey::from_seed_hex(TEST_SEED).unwrap();
        let mut value = serde_json::to_value(payload(&key.kid())).unwrap();
        value["maxUsers"] = 3.into();
        let body = canonical_json(&value).into_bytes();
        let mut signed = body.clone();
        signed.extend_from_slice(key.pair.sign(&body).as_ref());
        let err = SignedLicence::parse(&encode_block(LICENCE_PREFIX, &signed)).unwrap_err();
        assert!(matches!(err, LicenceError::Payload(_)), "{err:?}");
    }

    #[test]
    fn kid_must_match_signing_key() {
        let key = SigningKey::from_seed_hex(TEST_SEED).unwrap();
        assert!(key.sign(&payload("deadbeef")).is_err());
    }

    #[test]
    fn request_roundtrip() {
        let request = LicenceRequest {
            v: 1,
            product: "datastore-v2".into(),
            variant: Some("brand-a".into()),
            version: Some("5.133.0".into()),
            installation_id: "3f0c7a52-0f7e-4b39-9a43-5d7a8c9b1e20".into(),
            bind: payload("x").bind,
            created_at: Utc.with_ymd_and_hms(2026, 11, 5, 10, 0, 0).unwrap(),
        };
        let text = request.encode().unwrap();
        assert!(text.starts_with(REQUEST_PREFIX));
        assert_eq!(LicenceRequest::decode(&text).unwrap(), request);
        assert!(matches!(LicenceRequest::decode(&text.replace(REQUEST_PREFIX, LICENCE_PREFIX)), Err(LicenceError::Prefix(_))));
    }

    #[test]
    fn trusted_keys_reject_bad_hex() {
        assert!(TrustedKeys::from_hex(&["abcd"]).is_err());
    }
}