Skip to main content

monetize_embed/
lib.rs

1//! **monetize-embed — what a product compiles in.** One struct, one question:
2//! *does this tenant get to do this, right now?* Answered from verified facts held in
3//! memory, in nanoseconds, with monetize down or not.
4//!
5//! ```text
6//!   monetize-server ──signed Snapshot file──▶ EntitlementCache::refresh   (start, catch-up)
7//!   monetize-server ──signed EntitlementFact─▶ EntitlementCache::push      (every change)
8//!   product choke point ──────────────────▶ EntitlementCache::allows     (every request)
9//! ```
10//!
11//! # The ladder table, as the product sees it
12//!
13//! | state | Write (push, LFS upload) | Read (owner clone/fetch) | AnonymousRead | Admin (UI) |
14//! |---|---|---|---|---|
15//! | Free, Paid | allow | allow | allow (product still applies Public) | allow |
16//! | Grace | allow, [`EntitlementCache::notice`] has the warning line | allow | allow | allow |
17//! | Suspended | **refuse**, named reason + URL | allow | **refuse** | refuse: pay page only |
18//! | Retention | refuse | allow (export) | refuse | refuse: pay page + export |
19//!
20//! Two rules, not negotiable: **never hold data hostage** — `Read` is allowed in every
21//! state, a lapsed tenant can always clone their own repositories; and **refuse before
22//! the bytes** — the product asks at `authorise_service`, before a pack is read, and
23//! puts [`Verdict::Refuse::reason_line`] in report-status.
24//!
25//! # What is, and is not, decided here
26//!
27//! * The `state` in a fact is monetize's verdict at push time. The cache does **not**
28//!   re-derive it as the clock moves — it does not know the policy's day counts, and the
29//!   product contract says a product keeps serving on its cached entitlement when
30//!   monetize is unreachable. Ladder transitions arrive as new pushes.
31//! * An unknown tenant is `Free`: the product's default, never a refusal.
32//! * Visibility (`Public`) and quotas (`caps`) are the product's own checks; this crate
33//!   only says whether the entitlement allows the *kind* of action.
34//!
35//! # Cost of the read path
36//!
37//! [`EntitlementCache::allows`] is one `ArcSwap::load` (an atomic increment on a
38//! debt-slot, ~2 ns, no lock, no allocation), one `BTreeMap` lookup on the tenant name,
39//! and a match. A refusal allocates its two strings; an allow allocates nothing. Writes
40//! (`push`, `refresh`) clone the map and swap the pointer — O(tenants), taken by the
41//! rare path on purpose so the hot path never contends.
42
43pub mod civil;
44pub mod signing;
45pub mod ticket;
46
47use std::collections::BTreeMap;
48use std::sync::Arc;
49
50use arc_swap::ArcSwap;
51/// Re-exported so a caller that must CHECK a signature — a product, or the
52/// operator console — links one crate and cannot end up on a different
53/// ed25519-dalek than the one the canonical form was verified against.
54pub use ed25519_dalek::VerifyingKey;
55pub use monetize_product::{EntitlementFact, State, TenantId};
56pub use signing::{SignatureError, Snapshot};
57/// The appliance→monetize direction of the seam: the product's own box vouching
58/// that a human may act for a tenant. See [`ticket`] for why it points that way.
59pub use ticket::{verify_ticket, ActorTicket, SeenNonces, PURPOSE_ORDER, PURPOSE_RENEW};
60
61/// What the product is about to do on behalf of (or to) a tenant.
62#[derive(Clone, Copy, PartialEq, Eq, Debug)]
63pub enum Action {
64    /// `git push`, LFS upload — anything that grows the tenant's data.
65    Write,
66    /// The owner's clone/fetch. Allowed in every state.
67    Read,
68    /// Anonymous browse/clone of a public repository.
69    AnonymousRead,
70    /// The tenant's own settings UI.
71    Admin,
72}
73
74#[derive(Clone, PartialEq, Eq, Debug)]
75pub enum Verdict {
76    Allow,
77    Refuse {
78        state: State,
79        /// Goes into report-status verbatim: `order … expired 2026-10-01; renew at …`.
80        reason_line: String,
81        /// The pay page for this tenant.
82        url: String,
83    },
84}
85
86impl Verdict {
87    pub fn is_allowed(&self) -> bool {
88        matches!(self, Verdict::Allow)
89    }
90}
91
92#[derive(Debug, thiserror::Error)]
93pub enum RefreshError {
94    #[error("snapshot is not valid JSON: {0}")]
95    Parse(#[from] serde_json::Error),
96    #[error(transparent)]
97    Signature(#[from] SignatureError),
98    #[error("snapshot issued at {offered} is older than the {held} the cache holds")]
99    Stale { offered: u64, held: u64 },
100}
101
102#[derive(Debug, thiserror::Error)]
103#[error("public key is not a valid Ed25519 point")]
104pub struct KeyError;
105
106struct Facts {
107    issued_unix_ms: u64,
108    by_tenant: BTreeMap<TenantId, EntitlementFact>,
109}
110
111pub struct EntitlementCache {
112    key: VerifyingKey,
113    /// `{tenant}` is replaced by the tenant name.
114    billing_url: String,
115    facts: ArcSwap<Facts>,
116}
117
118impl EntitlementCache {
119    /// `public_key` is monetize's 32-byte Ed25519 verifying key; `billing_url` is the
120    /// pay page template, e.g. `https://gunnar.rs/billing/{tenant}`.
121    pub fn new(public_key: &[u8; 32], billing_url: &str) -> Result<Self, KeyError> {
122        let key = VerifyingKey::from_bytes(public_key).map_err(|_| KeyError)?;
123        Ok(Self {
124            key,
125            billing_url: billing_url.to_string(),
126            facts: ArcSwap::from_pointee(Facts { issued_unix_ms: 0, by_tenant: BTreeMap::new() }),
127        })
128    }
129
130    pub fn public_key(&self) -> &VerifyingKey {
131        &self.key
132    }
133
134    /// The hot path. See the crate doc for its cost.
135    pub fn allows(&self, tenant: &TenantId, action: Action) -> Verdict {
136        let facts = self.facts.load();
137        let Some(fact) = facts.by_tenant.get(tenant) else {
138            return Verdict::Allow; // unknown tenant = Free = the product's default
139        };
140        match (fact.state, action) {
141            (State::Free | State::Paid | State::Grace, _) => Verdict::Allow,
142            (State::Suspended | State::Retention, Action::Read) => Verdict::Allow,
143            (state, action) => Verdict::Refuse {
144                state,
145                reason_line: self.reason_line(fact, action),
146                url: self.url_for(tenant),
147            },
148        }
149    }
150
151    /// The Grace banner / report-status warning, if the tenant is in Grace.
152    pub fn notice(&self, tenant: &TenantId) -> Option<String> {
153        let facts = self.facts.load();
154        let fact = facts.by_tenant.get(tenant)?;
155        if fact.state != State::Grace {
156            return None;
157        }
158        Some(format!("{}; renew at {}", self.expiry_phrase(fact), self.url_for(tenant)))
159    }
160
161    /// The state the cache holds for `tenant`; `Free` when unknown.
162    pub fn state(&self, tenant: &TenantId) -> State {
163        self.facts.load().by_tenant.get(tenant).map_or(State::Free, |f| f.state)
164    }
165
166    /// A copy of the whole fact (caps, paid_until, source) for the product's own checks.
167    pub fn fact(&self, tenant: &TenantId) -> Option<EntitlementFact> {
168        self.facts.load().by_tenant.get(tenant).cloned()
169    }
170
171    /// The issue time of the snapshot the cache holds (0 before the first refresh).
172    pub fn issued_unix_ms(&self) -> u64 {
173        self.facts.load().issued_unix_ms
174    }
175
176    pub fn len(&self) -> usize {
177        self.facts.load().by_tenant.len()
178    }
179
180    pub fn is_empty(&self) -> bool {
181        self.len() == 0
182    }
183
184    /// Replace everything with a signed [`Snapshot`] (its JSON bytes). Nothing changes
185    /// unless the envelope and every fact verify and the snapshot is not older than
186    /// the one held. Returns the number of tenants now known.
187    pub fn refresh(&self, snapshot_bytes: &[u8]) -> Result<usize, RefreshError> {
188        let snap: Snapshot = serde_json::from_slice(snapshot_bytes)?;
189        signing::verify_snapshot(&snap, &self.key)?;
190        let held = self.facts.load().issued_unix_ms;
191        if snap.issued_unix_ms < held {
192            return Err(RefreshError::Stale { offered: snap.issued_unix_ms, held });
193        }
194        let by_tenant: BTreeMap<TenantId, EntitlementFact> =
195            snap.facts.into_iter().map(|f| (f.tenant.clone(), f)).collect();
196        let n = by_tenant.len();
197        self.facts.store(Arc::new(Facts { issued_unix_ms: snap.issued_unix_ms, by_tenant }));
198        Ok(n)
199    }
200
201    /// One pushed fact. Verified before it replaces the tenant's current fact.
202    pub fn push(&self, fact: EntitlementFact) -> Result<(), SignatureError> {
203        signing::verify_fact(&fact, &self.key)?;
204        let current = self.facts.load_full();
205        let mut by_tenant = current.by_tenant.clone();
206        by_tenant.insert(fact.tenant.clone(), fact);
207        self.facts.store(Arc::new(Facts { issued_unix_ms: current.issued_unix_ms, by_tenant }));
208        Ok(())
209    }
210
211    fn url_for(&self, tenant: &TenantId) -> String {
212        self.billing_url.replace("{tenant}", &tenant.0)
213    }
214
215    /// `fact.plan` is the ORDER the verdict came from (a ledger reference), or
216    /// an operator's label, or nothing — the field keeps its wire name because
217    /// it is in the signed form; the sentence a user reads names the order.
218    fn expiry_phrase(&self, fact: &EntitlementFact) -> String {
219        let what = if fact.plan.is_empty() { "entitlement".to_owned() } else { format!("order {}", fact.plan) };
220        match fact.paid_until_unix_ms {
221            Some(until) => format!("{what} expired {}", civil::iso_date(until)),
222            None => format!("{what} suspended by operator"),
223        }
224    }
225
226    fn reason_line(&self, fact: &EntitlementFact, action: Action) -> String {
227        let url = self.url_for(&fact.tenant);
228        let expiry = self.expiry_phrase(fact);
229        let what = match (fact.state, action) {
230            (State::Retention, Action::Write) => "writes closed, data kept for export",
231            (_, Action::Write) => "writes closed",
232            (_, Action::AnonymousRead) => "anonymous access closed",
233            (_, Action::Admin) => "settings closed",
234            (_, Action::Read) => unreachable!("Read is allowed in every state"),
235        };
236        format!("{expiry}: {what}; renew at {url}")
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243    use ed25519_dalek::{Signer, SigningKey};
244
245    fn key() -> SigningKey {
246        SigningKey::generate(&mut rand::rngs::OsRng)
247    }
248
249    fn fact(tenant: &str, state: State, paid_until: Option<u64>) -> EntitlementFact {
250        EntitlementFact {
251            tenant: TenantId(tenant.into()),
252            plan: "10gb".into(),
253            state,
254            paid_until_unix_ms: paid_until,
255            caps: BTreeMap::from([("pack_bytes".to_string(), 10 << 30)]),
256            source: "payment:mock:gunnar/team/sub/2026-09-03".into(),
257            signature: vec![],
258            issued_unix_ms: None,
259            issued_signature: Vec::new(),
260        }
261    }
262
263    /// The V1 form — no issue time — which is what a fact signed before
264    /// 2026-09-17 looks like and what the cache must go on accepting.
265    fn signed(key: &SigningKey, mut f: EntitlementFact) -> EntitlementFact {
266        f.issued_unix_ms = None;
267        f.issued_signature = Vec::new();
268        f.signature = key.sign(&signing::fact_message(&f)).to_bytes().to_vec();
269        f
270    }
271
272    /// Both forms, stamped: what monetize mints now.
273    fn signed_at(key: &SigningKey, mut f: EntitlementFact, issued: u64) -> EntitlementFact {
274        f.issued_unix_ms = Some(issued);
275        f.signature = key.sign(&signing::fact_message(&f)).to_bytes().to_vec();
276        f.issued_signature = key.sign(&signing::fact_message_issued(&f)).to_bytes().to_vec();
277        f
278    }
279
280    fn snapshot(key: &SigningKey, issued: u64, facts: Vec<EntitlementFact>) -> Vec<u8> {
281        let signature = key.sign(&signing::snapshot_message(issued, &facts)).to_bytes().to_vec();
282        serde_json::to_vec(&Snapshot { issued_unix_ms: issued, facts, signature }).unwrap()
283    }
284
285    fn cache(key: &SigningKey) -> EntitlementCache {
286        EntitlementCache::new(&key.verifying_key().to_bytes(), "https://gunnar.rs/billing/{tenant}").unwrap()
287    }
288
289    const OCT_1_2026: u64 = 1_790_812_800_000;
290
291    #[test]
292    fn genuine_snapshot_is_accepted_and_answers() {
293        let k = key();
294        let c = cache(&k);
295        let bytes = snapshot(&k, 10, vec![signed(&k, fact("team/sub", State::Suspended, Some(OCT_1_2026)))]);
296        assert_eq!(c.refresh(&bytes).unwrap(), 1);
297        assert_eq!(c.state(&TenantId("team/sub".into())), State::Suspended);
298        assert_eq!(c.issued_unix_ms(), 10);
299    }
300
301    #[test]
302    fn forged_snapshot_is_rejected_and_changes_nothing() {
303        let k = key();
304        let forger = key();
305        let c = cache(&k);
306        let t = TenantId("team/sub".into());
307        // Envelope signed by the right key, one fact forged: the whole snapshot is refused.
308        let mut forged = signed(&forger, fact("team/sub", State::Paid, Some(OCT_1_2026)));
309        let bytes = snapshot(&k, 10, vec![forged.clone()]);
310        assert!(matches!(c.refresh(&bytes), Err(RefreshError::Signature(SignatureError::Fact(_)))));
311        // Envelope signed by the wrong key.
312        forged = signed(&k, forged);
313        let bytes = snapshot(&forger, 10, vec![forged.clone()]);
314        assert!(matches!(c.refresh(&bytes), Err(RefreshError::Signature(SignatureError::Envelope))));
315        // A genuine fact whose fields were edited after signing.
316        forged.state = State::Free;
317        assert!(matches!(c.push(forged), Err(SignatureError::Fact(_))));
318        // Garbage.
319        assert!(matches!(c.refresh(b"not json"), Err(RefreshError::Parse(_))));
320        assert!(c.is_empty());
321        assert_eq!(c.state(&t), State::Free);
322    }
323
324    #[test]
325    fn stale_snapshot_is_refused_newer_one_is_taken() {
326        let k = key();
327        let c = cache(&k);
328        c.refresh(&snapshot(&k, 20, vec![])).unwrap();
329        assert!(matches!(c.refresh(&snapshot(&k, 19, vec![])), Err(RefreshError::Stale { offered: 19, held: 20 })));
330        c.refresh(&snapshot(&k, 21, vec![])).unwrap();
331        assert_eq!(c.issued_unix_ms(), 21);
332    }
333
334    #[test]
335    fn push_replaces_one_tenant_and_keeps_the_rest() {
336        let k = key();
337        let c = cache(&k);
338        let a = TenantId("a".into());
339        let b = TenantId("b".into());
340        c.refresh(&snapshot(&k, 1, vec![signed(&k, fact("a", State::Paid, None)), signed(&k, fact("b", State::Paid, None))])).unwrap();
341        c.push(signed(&k, fact("a", State::Suspended, Some(OCT_1_2026)))).unwrap();
342        assert_eq!(c.state(&a), State::Suspended);
343        assert_eq!(c.state(&b), State::Paid);
344        assert_eq!(c.len(), 2);
345    }
346
347    /// The ladder table, row by row, column by column.
348    #[test]
349    fn verdict_table() {
350        use Action::*;
351        let k = key();
352        let c = cache(&k);
353        let t = TenantId("team/sub".into());
354        let rows: [(State, [bool; 4]); 5] = [
355            (State::Free, [true, true, true, true]),
356            (State::Paid, [true, true, true, true]),
357            (State::Grace, [true, true, true, true]),
358            (State::Suspended, [false, true, false, false]),
359            (State::Retention, [false, true, false, false]),
360        ];
361        for (state, expect) in rows {
362            c.push(signed(&k, fact("team/sub", state, Some(OCT_1_2026)))).unwrap();
363            for (action, allowed) in [Write, Read, AnonymousRead, Admin].into_iter().zip(expect) {
364                let v = c.allows(&t, action);
365                assert_eq!(v.is_allowed(), allowed, "{state:?} / {action:?} gave {v:?}");
366                if let Verdict::Refuse { state: s, reason_line, url } = &v {
367                    assert_eq!(*s, state);
368                    assert_eq!(url, "https://gunnar.rs/billing/team/sub");
369                    assert!(reason_line.contains("order 10gb expired 2026-10-01"), "{reason_line}");
370                    assert!(reason_line.ends_with("; renew at https://gunnar.rs/billing/team/sub"), "{reason_line}");
371                }
372            }
373            assert_eq!(c.notice(&t).is_some(), state == State::Grace, "{state:?} notice");
374        }
375    }
376
377    #[test]
378    fn refuse_twin_suspended_write_names_the_reason_and_unknown_tenant_is_free() {
379        let k = key();
380        let c = cache(&k);
381        let t = TenantId("team/sub".into());
382        c.push(signed(&k, fact("team/sub", State::Suspended, Some(OCT_1_2026)))).unwrap();
383        assert_eq!(
384            c.allows(&t, Action::Write),
385            Verdict::Refuse {
386                state: State::Suspended,
387                reason_line: "order 10gb expired 2026-10-01: writes closed; renew at https://gunnar.rs/billing/team/sub".into(),
388                url: "https://gunnar.rs/billing/team/sub".into(),
389            }
390        );
391        let op = signed(&k, fact("ops", State::Suspended, None));
392        c.push(op).unwrap();
393        assert!(matches!(c.allows(&TenantId("ops".into()), Action::Write), Verdict::Refuse { reason_line, .. } if reason_line.starts_with("order 10gb suspended by operator")));
394        assert_eq!(c.allows(&TenantId("nobody".into()), Action::Write), Verdict::Allow);
395        assert_eq!(c.state(&TenantId("nobody".into())), State::Free);
396    }
397}