use std::collections::{BTreeMap, BTreeSet};
use chrono::{DateTime, Duration, Utc};
use serde::Serialize;
use super::format::{LicencePayload, SignedLicence, TrustedKeys};
use super::hardware::{Binding, HardwareProfile};
use super::trial::{ClockStatus, TrialPolicy, TrialRecord, TrialStatus};
use super::LicenceError;
pub struct EvaluationContext<'a> {
pub product: &'a str,
pub variant: Option<&'a str>,
pub keys: &'a TrustedKeys,
pub hardware: &'a HardwareProfile,
pub now: DateTime<Utc>,
pub clock: ClockStatus,
pub require_binding: bool,
pub expiry_warning: Duration,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "reason", rename_all = "camelCase")]
pub enum RejectReason {
Format { detail: String },
UnknownKey { kid: String },
Signature,
Product { expected: String, found: String },
Variant { expected: Option<String>, found: String },
NoBinding,
HardwareMismatch { missing: Vec<Binding> },
#[serde(rename_all = "camelCase")]
NotYetValid { not_before: DateTime<Utc> },
#[serde(rename_all = "camelCase")]
Expired { not_after: DateTime<Utc> },
ClockRolledBack { mark: DateTime<Utc> },
Duplicate,
}
impl From<LicenceError> for RejectReason {
fn from(error: LicenceError) -> Self {
match error {
LicenceError::UnknownKey(kid) => Self::UnknownKey { kid },
LicenceError::Signature => Self::Signature,
other => Self::Format { detail: other.to_string() },
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "state", rename_all = "camelCase")]
pub enum LicenceState {
#[serde(rename_all = "camelCase")]
Valid { expires_at: Option<DateTime<Utc>>, expiring_soon: bool },
Rejected { reason: RejectReason },
}
impl LicenceState {
pub fn is_valid(&self) -> bool {
matches!(self, Self::Valid { .. })
}
}
pub fn evaluate_licence(licence: &SignedLicence, ctx: &EvaluationContext<'_>) -> LicenceState {
let reject = |reason| LicenceState::Rejected { reason };
if let Err(e) = licence.verify(ctx.keys) {
return reject(e.into());
}
let p: &LicencePayload = &licence.payload;
if p.product != ctx.product {
return reject(RejectReason::Product { expected: ctx.product.into(), found: p.product.clone() });
}
if let Some(variant) = &p.variant {
if ctx.variant != Some(variant.as_str()) {
return reject(RejectReason::Variant {
expected: ctx.variant.map(str::to_string),
found: variant.clone(),
});
}
}
if p.bind.is_empty() && ctx.require_binding {
return reject(RejectReason::NoBinding);
}
let missing: Vec<Binding> = p.bind.iter().filter(|b| !ctx.hardware.matches(b)).cloned().collect();
if !missing.is_empty() {
return reject(RejectReason::HardwareMismatch { missing });
}
if let Some(not_before) = p.not_before {
if ctx.now < not_before {
return reject(RejectReason::NotYetValid { not_before });
}
}
if let Some(not_after) = p.not_after {
if let ClockStatus::RolledBack { mark } = ctx.clock {
return reject(RejectReason::ClockRolledBack { mark });
}
if ctx.now >= not_after {
return reject(RejectReason::Expired { not_after });
}
}
LicenceState::Valid {
expires_at: p.not_after,
expiring_soon: p.not_after.is_some_and(|end| end - ctx.now <= ctx.expiry_warning),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum GrantMode {
Licensed,
Trial,
Unlicensed,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LicenceEvaluation {
pub id: String,
pub payload: LicencePayload,
#[serde(flatten)]
pub state: LicenceState,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Grant {
pub mode: GrantMode,
pub features: BTreeSet<String>,
pub quotas: BTreeMap<String, u64>,
pub licences: Vec<LicenceEvaluation>,
pub trial: Option<TrialStatus>,
pub next_change: Option<DateTime<Utc>>,
}
pub fn evaluate(
licences: &[SignedLicence],
trial: Option<&TrialRecord>,
policy: &TrialPolicy,
ctx: &EvaluationContext<'_>,
) -> Grant {
let mut features = BTreeSet::new();
let mut quotas: BTreeMap<String, u64> = BTreeMap::new();
let mut next_change: Option<DateTime<Utc>> = None;
let mut consider = |t: DateTime<Utc>| {
if t > ctx.now && next_change.is_none_or(|n| t < n) {
next_change = Some(t);
}
};
let mut evaluations = Vec::with_capacity(licences.len());
let mut seen = BTreeSet::new();
for licence in licences {
let state = if seen.insert(licence.payload.id.clone()) {
evaluate_licence(licence, ctx)
} else {
LicenceState::Rejected { reason: RejectReason::Duplicate }
};
match &state {
LicenceState::Valid { expires_at, .. } => {
features.extend(licence.payload.features.iter().cloned());
for (name, amount) in &licence.payload.quotas {
let slot = quotas.entry(name.clone()).or_default();
*slot = slot.saturating_add(*amount);
}
if let Some(end) = expires_at {
consider(*end);
consider(*end - ctx.expiry_warning);
}
}
LicenceState::Rejected { reason: RejectReason::NotYetValid { not_before } } => {
consider(*not_before);
}
LicenceState::Rejected { .. } => {}
}
evaluations.push(LicenceEvaluation {
id: licence.payload.id.clone(),
payload: licence.payload.clone(),
state,
});
}
let trial_status = trial.map(|t| t.status(policy, ctx.now, &ctx.clock));
let mode = if evaluations.iter().any(|e| e.state.is_valid()) {
GrantMode::Licensed
} else if trial_status.as_ref().is_some_and(|t| t.active) {
GrantMode::Trial
} else {
GrantMode::Unlicensed
};
if let Some(t) = &trial_status {
if t.active {
consider(t.expires_at);
}
}
if mode == GrantMode::Trial {
features = policy.features.iter().cloned().collect();
quotas = policy.quotas.clone();
}
Grant { mode, features, quotas, licences: evaluations, trial: trial_status, next_change }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::licence::format::tests::{payload, TEST_SEED};
use crate::licence::format::SigningKey;
use crate::licence::hardware::{HardwareIdentifier, IdentifierKind};
use chrono::TimeZone;
struct Fixture {
key: SigningKey,
keys: TrustedKeys,
hardware: HardwareProfile,
}
fn fixture() -> Fixture {
let key = SigningKey::from_seed_hex(TEST_SEED).unwrap();
let keys = TrustedKeys::from_hex(&[&key.public_hex()]).unwrap();
let hardware = HardwareProfile {
identifiers: vec![
HardwareIdentifier::new(IdentifierKind::Mac, "eth0", "e0:8f:4c:82:40:7e").unwrap(),
HardwareIdentifier::new(IdentifierKind::MachineId, "machine-id", "0cd9a1abe0b840bba8a4e848c070df47").unwrap(),
],
problems: vec![],
};
Fixture { key, keys, hardware }
}
fn ctx(f: &Fixture, now: DateTime<Utc>) -> EvaluationContext<'_> {
EvaluationContext {
product: "datastore-v2",
variant: Some("brand-a"),
keys: &f.keys,
hardware: &f.hardware,
now,
clock: ClockStatus::Ok,
require_binding: true,
expiry_warning: Duration::days(30),
}
}
fn signed(f: &Fixture, edit: impl FnOnce(&mut LicencePayload)) -> SignedLicence {
let mut p = payload(&f.key.kid());
edit(&mut p);
SignedLicence::parse(&f.key.sign(&p).unwrap()).unwrap()
}
fn now() -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 12, 1, 0, 0, 0).unwrap()
}
fn policy() -> TrialPolicy {
TrialPolicy {
duration: Duration::days(14),
features: vec!["base".into(), "all".into()],
quotas: BTreeMap::new(),
}
}
#[test]
fn valid_licence() {
let f = fixture();
let state = evaluate_licence(&signed(&f, |_| {}), &ctx(&f, now()));
assert_eq!(state, LicenceState::Valid { expires_at: payload("").not_after, expiring_soon: false });
}
#[test]
fn each_rejection_reason() {
let f = fixture();
let c = ctx(&f, now());
let reason = |l: SignedLicence| match evaluate_licence(&l, &c) {
LicenceState::Rejected { reason } => reason,
other => panic!("unexpected {other:?}"),
};
assert!(matches!(reason(signed(&f, |p| p.product = "other".into())), RejectReason::Product { .. }));
assert!(matches!(reason(signed(&f, |p| p.variant = Some("gmn".into()))), RejectReason::Variant { .. }));
assert!(matches!(reason(signed(&f, |p| p.bind.clear())), RejectReason::NoBinding));
let mut extra = payload("").bind[0].clone();
extra.sha256 = "00".repeat(32);
assert!(matches!(
reason(signed(&f, |p| p.bind.push(extra))),
RejectReason::HardwareMismatch { missing } if missing.len() == 1
));
assert!(matches!(
reason(signed(&f, |p| p.not_before = Some(now() + Duration::days(1)))),
RejectReason::NotYetValid { .. }
));
assert!(matches!(
reason(signed(&f, |p| p.not_after = Some(now()))),
RejectReason::Expired { .. }
));
let other = SigningKey::generate().unwrap();
let mut p = payload(&other.kid());
p.kid = other.kid();
let foreign = SignedLicence::parse(&other.sign(&p).unwrap()).unwrap();
assert!(matches!(reason(foreign), RejectReason::UnknownKey { .. }));
}
#[test]
fn any_variant_licence_and_unbound_when_allowed() {
let f = fixture();
assert!(evaluate_licence(&signed(&f, |p| p.variant = None), &ctx(&f, now())).is_valid());
let mut c = ctx(&f, now());
c.require_binding = false;
assert!(evaluate_licence(&signed(&f, |p| p.bind.clear()), &c).is_valid());
}
#[test]
fn rolled_back_clock_hits_only_time_limited_licences() {
let f = fixture();
let mut c = ctx(&f, now());
c.clock = ClockStatus::RolledBack { mark: now() + Duration::days(3) };
assert!(matches!(
evaluate_licence(&signed(&f, |_| {}), &c),
LicenceState::Rejected { reason: RejectReason::ClockRolledBack { .. } }
));
assert!(evaluate_licence(&signed(&f, |p| p.not_after = None), &c).is_valid());
}
#[test]
fn licences_or_together() {
let f = fixture();
let a = signed(&f, |p| { p.features = vec!["base".into()]; p.quotas = BTreeMap::from([("sources".into(), 2)]); });
let b = signed(&f, |p| { p.id = "b".into(); p.features = vec!["afc".into()]; p.quotas = BTreeMap::from([("sources".into(), 3)]); });
let dead = signed(&f, |p| { p.id = "c".into(); p.features = vec!["mde".into()]; p.not_after = Some(now()); });
let grant = evaluate(&[a, b, dead], None, &policy(), &ctx(&f, now()));
assert_eq!(grant.mode, GrantMode::Licensed);
assert_eq!(grant.features, BTreeSet::from(["afc".to_string(), "base".to_string()]));
assert_eq!(grant.quotas["sources"], 5);
assert_eq!(grant.licences.len(), 3);
}
#[test]
fn the_same_licence_twice_counts_once() {
let f = fixture();
let licence = signed(&f, |_| {});
let grant = evaluate(&[licence.clone(), licence], None, &policy(), &ctx(&f, now()));
assert_eq!(grant.quotas["sources"], 4);
assert_eq!(
grant.licences[1].state,
LicenceState::Rejected { reason: RejectReason::Duplicate }
);
}
#[test]
fn trial_then_unlicensed() {
let f = fixture();
let record = TrialRecord::start(now(), "id", &f.hardware);
let grant = evaluate(&[], Some(&record), &policy(), &ctx(&f, now() + Duration::days(1)));
assert_eq!(grant.mode, GrantMode::Trial);
assert!(grant.features.contains("all"));
assert_eq!(grant.next_change, Some(now() + Duration::days(14)));
let grant = evaluate(&[], Some(&record), &policy(), &ctx(&f, now() + Duration::days(14)));
assert_eq!(grant.mode, GrantMode::Unlicensed);
assert!(grant.features.is_empty());
assert_eq!(evaluate(&[], None, &policy(), &ctx(&f, now())).mode, GrantMode::Unlicensed);
}
#[test]
fn valid_licence_beats_trial_and_reports_next_change() {
let f = fixture();
let record = TrialRecord::start(now(), "id", &f.hardware);
let licence = signed(&f, |p| p.not_after = Some(now() + Duration::days(60)));
let grant = evaluate(&[licence], Some(&record), &policy(), &ctx(&f, now()));
assert_eq!(grant.mode, GrantMode::Licensed);
assert!(!grant.features.contains("all"));
assert_eq!(grant.next_change, Some(now() + Duration::days(14)));
}
}