brinkhaustools/licence/
evaluate.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
//! Evaluation: which licences are valid on this machine now, and what they grant.

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;

/// Everything an evaluation depends on.
pub struct EvaluationContext<'a> {
    /// Product name a licence must name.
    pub product: &'a str,
    /// Active variant (e.g. branding stream); a licence naming another is refused.
    pub variant: Option<&'a str>,
    pub keys: &'a TrustedKeys,
    pub hardware: &'a HardwareProfile,
    pub now: DateTime<Utc>,
    pub clock: ClockStatus,
    /// Refuse licences without any binding.
    pub require_binding: bool,
    /// A valid licence ending within this span is flagged `expiringSoon`.
    pub expiry_warning: Duration,
}

/// Why a licence does not count.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "reason", rename_all = "camelCase")]
pub enum RejectReason {
    /// Not decodable (prefix, encoding, incomplete, payload, version).
    Format { detail: String },
    UnknownKey { kid: String },
    Signature,
    Product { expected: String, found: String },
    Variant { expected: Option<String>, found: String },
    NoBinding,
    /// Bindings not present on this machine.
    HardwareMismatch { missing: Vec<Binding> },
    #[serde(rename_all = "camelCase")]
    NotYetValid { not_before: DateTime<Utc> },
    #[serde(rename_all = "camelCase")]
    Expired { not_after: DateTime<Utc> },
    /// Time-limited licence while the clock is behind its mark.
    ClockRolledBack { mark: DateTime<Utc> },
    /// The same licence id was already counted: installing a licence twice
    /// must not double its quotas.
    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() },
        }
    }
}

/// State of one licence.
#[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 { .. })
    }
}

/// Check one licence against the context. Order: signature first — nothing in an
/// unauthenticated payload is reported as if it were true — then product, variant,
/// hardware, time.
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),
    }
}

/// Overall mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum GrantMode {
    /// At least one valid licence.
    Licensed,
    /// No valid licence, trial active.
    Trial,
    /// Neither.
    Unlicensed,
}

/// One evaluated licence.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LicenceEvaluation {
    pub id: String,
    pub payload: LicencePayload,
    #[serde(flatten)]
    pub state: LicenceState,
}

/// What all licences together grant.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Grant {
    pub mode: GrantMode,
    /// Union over valid licences (trial: the policy's features).
    pub features: BTreeSet<String>,
    /// Sum over valid licences (trial: the policy's quotas).
    pub quotas: BTreeMap<String, u64>,
    pub licences: Vec<LicenceEvaluation>,
    pub trial: Option<TrialStatus>,
    /// Earliest future instant at which the result changes by itself.
    pub next_change: Option<DateTime<Utc>>,
}

/// Evaluate all licences and the trial. Licences OR together: features are the
/// union, quotas the sum, over the **valid** licences only, each licence id
/// counted once (a repeat is [`RejectReason::Duplicate`]).
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"));
        // Earliest of: trial end (14 d) and warning start (60 - 30 d).
        assert_eq!(grant.next_change, Some(now() + Duration::days(14)));
    }
}