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;
pub const LICENCE_PREFIX: &str = "BLIC1-";
pub const REQUEST_PREFIX: &str = "BLRQ1-";
pub const FORMAT_VERSION: u32 = 1;
pub const LINE_WIDTH: usize = 64;
const SIGNATURE_LEN: usize = 64;
const CHECK_LEN: usize = 4;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Licensee {
pub slug: String,
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LicencePayload {
pub v: u32,
pub id: String,
pub kid: String,
pub product: String,
#[serde(default)]
pub variant: Option<String>,
pub licensee: Licensee,
pub bind: Vec<Binding>,
#[serde(default)]
pub not_before: Option<DateTime<Utc>>,
#[serde(default)]
pub not_after: Option<DateTime<Utc>>,
#[serde(default)]
pub features: Vec<String>,
#[serde(default)]
pub quotas: BTreeMap<String, u64>,
pub issued_at: DateTime<Utc>,
#[serde(default)]
pub note: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedLicence {
pub payload: LicencePayload,
payload_bytes: Vec<u8>,
signature: Vec<u8>,
text: String,
}
impl SignedLicence {
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);
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(),
})
}
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)
}
pub fn text(&self) -> &str {
&self.text
}
}
pub fn key_id(public_key: &[u8]) -> String {
hex_encode(&Sha256::digest(public_key))[..8].to_string()
}
#[derive(Debug, Clone, Default)]
pub struct TrustedKeys {
keys: BTreeMap<String, Vec<u8>>,
}
impl TrustedKeys {
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 })
}
pub fn get(&self, kid: &str) -> Option<&[u8]> {
self.keys.get(kid).map(Vec::as_slice)
}
pub fn ids(&self) -> Vec<String> {
self.keys.keys().cloned().collect()
}
}
pub struct SigningKey {
seed: [u8; 32],
pair: Ed25519KeyPair,
}
impl SigningKey {
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)
}
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 })
}
pub fn seed_hex(&self) -> String {
hex_encode(&self.seed)
}
pub fn public_hex(&self) -> String {
hex_encode(self.pair.public_key().as_ref())
}
pub fn kid(&self) -> String {
key_id(self.pair.public_key().as_ref())
}
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))
}
}
#[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>,
pub installation_id: String,
pub bind: Vec<Binding>,
pub created_at: DateTime<Utc>,
}
impl LicenceRequest {
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()))
}
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)
}
}
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)
}
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(_))));
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)));
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());
}
}