brinkhaustools/licence/
trial.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
//! Trial licence, clock mark and installation id — the small persistent states of
//! the licence system. All three live in the product's data directory.
//!
//! None of them resists an operator who deletes the data directory: a new trial
//! starts, a new installation id appears. The countermeasure is visibility (the
//! product reports trial start and installation id to the FleetManager), not
//! cryptography — there is nothing on a general-purpose machine to anchor it to.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};

use super::codec::{hex_encode, write_atomic};
use super::hardware::HardwareProfile;
use super::LicenceError;

/// What a trial grants and for how long. Product-defined; the durations that
/// enforce a licence belong in the product's catalogue, not in its settings.
#[derive(Debug, Clone)]
pub struct TrialPolicy {
    pub duration: Duration,
    pub features: Vec<String>,
    pub quotas: BTreeMap<String, u64>,
}

/// A started trial.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TrialRecord {
    pub v: u32,
    pub started_at: DateTime<Utc>,
    pub installation_id: String,
    /// [`HardwareProfile::digest`] at trial start (lets the issuer recognise a
    /// trial restarted on the same hardware).
    pub hardware_digest: String,
}

/// Evaluated trial.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrialStatus {
    pub started_at: DateTime<Utc>,
    pub expires_at: DateTime<Utc>,
    pub active: bool,
    /// Whole days left (rounded up), 0 when ended.
    pub remaining_days: i64,
    /// Why the trial is not active, if it is not.
    pub ended: Option<TrialEnd>,
}

/// Why a trial is not active.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum TrialEnd {
    Expired,
    ClockRolledBack,
}

impl TrialRecord {
    /// Start a trial now.
    pub fn start(now: DateTime<Utc>, installation_id: &str, hardware: &HardwareProfile) -> Self {
        Self {
            v: 1,
            started_at: now,
            installation_id: installation_id.to_string(),
            hardware_digest: hardware.digest(),
        }
    }

    /// Merge two traces of the same trial (e.g. file and database): the earlier
    /// start wins, so deleting one trace never restarts the trial.
    pub fn earliest(a: Option<Self>, b: Option<Self>) -> Option<Self> {
        match (a, b) {
            (Some(a), Some(b)) => Some(if b.started_at < a.started_at { b } else { a }),
            (a, b) => a.or(b),
        }
    }

    /// Status at `now`. A clock set back before the trial start, or behind the
    /// clock mark, ends the trial — otherwise turning the clock back would extend it.
    pub fn status(&self, policy: &TrialPolicy, now: DateTime<Utc>, clock: &ClockStatus) -> TrialStatus {
        let expires_at = self.started_at + policy.duration;
        let ended = if matches!(clock, ClockStatus::RolledBack { .. }) || now < self.started_at {
            Some(TrialEnd::ClockRolledBack)
        } else if now >= expires_at {
            Some(TrialEnd::Expired)
        } else {
            None
        };
        let remaining_days = match ended {
            Some(_) => 0,
            None => {
                let left = expires_at - now;
                let days = left.num_days();
                if left > Duration::days(days) { days + 1 } else { days }
            }
        };
        TrialStatus {
            started_at: self.started_at,
            expires_at,
            active: ended.is_none(),
            remaining_days,
            ended,
        }
    }

    /// Load from a JSON file; `Ok(None)` if the file does not exist.
    pub fn load(path: &Path) -> Result<Option<Self>, LicenceError> {
        match std::fs::read(path) {
            Ok(bytes) => serde_json::from_slice(&bytes)
                .map(Some)
                .map_err(|e| LicenceError::State(format!("{}: {e}", path.display()))),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(LicenceError::State(format!("{}: {e}", path.display()))),
        }
    }

    /// Save atomically.
    pub fn save(&self, path: &Path) -> Result<(), LicenceError> {
        let json = serde_json::to_vec_pretty(self).map_err(|e| LicenceError::State(e.to_string()))?;
        write_atomic(path, &json).map_err(|e| LicenceError::State(format!("{}: {e}", path.display())))
    }
}

/// Result of the clock check.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "clock", rename_all = "camelCase")]
pub enum ClockStatus {
    Ok,
    /// The system time lies more than the guard behind the highest time seen.
    RolledBack { mark: DateTime<Utc> },
}

/// Highest system time ever seen, persisted. Detects a clock turned back to
/// stretch a time-limited licence. Recovery is correcting the clock; if the
/// clock had jumped into the future, the mark stays there until real time
/// passes it or [`ClockMark::reset`] is run.
#[derive(Debug, Clone)]
pub struct ClockMark {
    path: PathBuf,
    highest: Option<DateTime<Utc>>,
    guard: Duration,
}

impl ClockMark {
    /// Open the mark file (missing = no mark yet). `guard` is the tolerated step
    /// back (NTP corrections, a drifting RTC before sync).
    pub fn open(path: &Path, guard: Duration) -> Result<Self, LicenceError> {
        let highest = match std::fs::read_to_string(path) {
            Ok(text) => Some(
                DateTime::parse_from_rfc3339(text.trim())
                    .map_err(|e| LicenceError::State(format!("{}: {e}", path.display())))?
                    .with_timezone(&Utc),
            ),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => return Err(LicenceError::State(format!("{}: {e}", path.display()))),
        };
        Ok(Self { path: path.to_path_buf(), highest, guard })
    }

    /// Check `now` without persisting.
    pub fn check(&self, now: DateTime<Utc>) -> ClockStatus {
        match self.highest {
            Some(mark) if now + self.guard < mark => ClockStatus::RolledBack { mark },
            _ => ClockStatus::Ok,
        }
    }

    /// Check `now` and advance the mark if `now` is later.
    pub fn observe(&mut self, now: DateTime<Utc>) -> Result<ClockStatus, LicenceError> {
        let status = self.check(now);
        if self.highest.is_none_or(|h| now > h) {
            write_atomic(&self.path, now.to_rfc3339().as_bytes())
                .map_err(|e| LicenceError::State(format!("{}: {e}", self.path.display())))?;
            self.highest = Some(now);
        }
        Ok(status)
    }

    /// Reset the mark to `now` — the service action after a clock that once
    /// jumped into the future (faulty RTC or NTP): correcting the clock alone
    /// does not lower a mark that was already advanced. Products must not make
    /// this an operator setting, or it lifts every time-limited licence.
    pub fn reset(&mut self, now: DateTime<Utc>) -> Result<(), LicenceError> {
        write_atomic(&self.path, now.to_rfc3339().as_bytes())
            .map_err(|e| LicenceError::State(format!("{}: {e}", self.path.display())))?;
        self.highest = Some(now);
        Ok(())
    }

    /// Highest time seen.
    pub fn highest(&self) -> Option<DateTime<Utc>> {
        self.highest
    }
}

/// A random UUID v4 (licence ids, installation ids).
pub fn random_uuid() -> Result<String, LicenceError> {
    let mut raw = [0u8; 16];
    ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut raw)
        .map_err(|_| LicenceError::State("random source failed".to_string()))?;
    raw[6] = (raw[6] & 0x0f) | 0x40;
    raw[8] = (raw[8] & 0x3f) | 0x80;
    let h = hex_encode(&raw);
    Ok(format!("{}-{}-{}-{}-{}", &h[..8], &h[8..12], &h[12..16], &h[16..20], &h[20..]))
}

/// Load the installation id from `path`, creating it on first use.
/// Returns `(id, created)`. The id recognises an installation; it binds nothing.
pub fn installation_id(path: &Path) -> Result<(String, bool), LicenceError> {
    match std::fs::read_to_string(path) {
        Ok(text) if !text.trim().is_empty() => return Ok((text.trim().to_string(), false)),
        Ok(_) => {}
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => return Err(LicenceError::State(format!("{}: {e}", path.display()))),
    }
    let id = random_uuid()?;
    write_atomic(path, id.as_bytes())
        .map_err(|e| LicenceError::State(format!("{}: {e}", path.display())))?;
    Ok((id, true))
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::TimeZone;

    fn t(day: u32, hour: u32) -> DateTime<Utc> {
        Utc.with_ymd_and_hms(2026, 11, day, hour, 0, 0).unwrap()
    }

    fn policy() -> TrialPolicy {
        TrialPolicy { duration: Duration::days(14), features: vec![], quotas: BTreeMap::new() }
    }

    #[test]
    fn trial_runs_fourteen_days() {
        let record = TrialRecord::start(t(1, 12), "id", &HardwareProfile::default());
        let s = record.status(&policy(), t(1, 13), &ClockStatus::Ok);
        assert!(s.active);
        assert_eq!(s.remaining_days, 14);
        assert_eq!(record.status(&policy(), t(14, 13), &ClockStatus::Ok).remaining_days, 1);
        let end = record.status(&policy(), t(15, 12), &ClockStatus::Ok);
        assert!(!end.active);
        assert_eq!(end.ended, Some(TrialEnd::Expired));
    }

    #[test]
    fn clock_before_start_ends_trial() {
        let record = TrialRecord::start(t(10, 0), "id", &HardwareProfile::default());
        let s = record.status(&policy(), t(9, 0), &ClockStatus::Ok);
        assert_eq!(s.ended, Some(TrialEnd::ClockRolledBack));
        let s = record.status(&policy(), t(11, 0), &ClockStatus::RolledBack { mark: t(20, 0) });
        assert!(!s.active);
    }

    #[test]
    fn earliest_trace_wins() {
        let a = TrialRecord::start(t(5, 0), "a", &HardwareProfile::default());
        let b = TrialRecord::start(t(3, 0), "b", &HardwareProfile::default());
        assert_eq!(TrialRecord::earliest(Some(a.clone()), Some(b.clone())), Some(b.clone()));
        assert_eq!(TrialRecord::earliest(None, Some(a.clone())), Some(a));
        assert_eq!(TrialRecord::earliest(None, None), None);
    }

    #[test]
    fn trial_file_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("trial.mark");
        assert_eq!(TrialRecord::load(&path).unwrap(), None);
        let record = TrialRecord::start(t(1, 0), "id", &HardwareProfile::default());
        record.save(&path).unwrap();
        assert_eq!(TrialRecord::load(&path).unwrap(), Some(record));
        std::fs::write(&path, "garbage").unwrap();
        assert!(TrialRecord::load(&path).is_err());
    }

    #[test]
    fn clock_mark_detects_roll_back_beyond_guard() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("clock.mark");
        let mut mark = ClockMark::open(&path, Duration::hours(24)).unwrap();
        assert_eq!(mark.observe(t(10, 0)).unwrap(), ClockStatus::Ok);
        // Within the guard: tolerated, mark unchanged.
        assert_eq!(mark.observe(t(9, 12)).unwrap(), ClockStatus::Ok);
        assert_eq!(mark.highest(), Some(t(10, 0)));
        let reopened = ClockMark::open(&path, Duration::hours(24)).unwrap();
        assert_eq!(reopened.check(t(8, 0)), ClockStatus::RolledBack { mark: t(10, 0) });
        assert_eq!(reopened.check(t(11, 0)), ClockStatus::Ok);
        let mut reset = reopened;
        reset.reset(t(8, 0)).unwrap();
        assert_eq!(reset.check(t(8, 0)), ClockStatus::Ok);
    }

    #[test]
    fn installation_id_is_created_once() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("secrets/installation.id");
        let (id, created) = installation_id(&path).unwrap();
        assert!(created);
        assert_eq!(id.len(), 36);
        assert_eq!(installation_id(&path).unwrap(), (id, false));
    }
}