// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! Share links on control's side: minting, the list, stopping. //! //! Control keeps what it minted in `share-links.json` (never the token itself) and writes //! the revocation file edge reads (`{"epoch": n, "deny": [ids]}`): ids of stopped links that //! have not expired yet, and the epoch below which every token is refused ("stop all"). //! The file lives outside git, is written atomically, and edge re-reads it when control asks //! and on its own every 5 s. When control is down nothing can be stopped, but edge keeps //! refusing what is already on the list, also across its own restarts. use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use ianitor_core::share::{self, LinkSpec, ShareId, ShareKey}; use serde::{Deserialize, Serialize}; use crate::util::{now, random, read_json, write_json}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct LinkRecord { pub id: String, pub hostname: String, pub path_prefix: String, pub epoch: u32, pub created_at: u64, pub expires_at: u64, pub has_password: bool, pub created_by: String, pub stopped_at: Option, } impl LinkRecord { pub fn state(&self, epoch: u32, t: u64) -> &'static str { if self.stopped_at.is_some() || self.epoch < epoch { "stopped" } else if t >= self.expires_at { "expired" } else { "active" } } } #[derive(Debug, Default, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ShareFile { pub epoch: u32, pub links: Vec, } #[derive(Serialize)] struct RevocationFile { epoch: u32, deny: Vec, } /// Kept in the list this long after expiry or stop. const KEEP_SECS: u64 = 30 * 86_400; pub const MIN_EXPIRY: u64 = 3600; pub const MAX_EXPIRY: u64 = 90 * 86_400; /// Most active links at once. pub const MAX_ACTIVE: usize = 2000; /// Most ids edge takes on its deny list (edge refuses 10,000 and more). const MAX_DENY: usize = 9_999; pub struct Shares { path: PathBuf, revocations: PathBuf, lock: std::sync::Mutex<()>, } pub struct Minted { pub record: LinkRecord, pub token: String, } #[derive(Debug, PartialEq, Eq)] pub enum MintError { Prefix, Expiry, PasswordShort, PasswordLong, Replaces, /// More active links than [`MAX_ACTIVE`]. TooMany, Store(String), } impl Shares { pub fn new(state_dir: &Path, revocations: &Path) -> Shares { Shares { path: state_dir.join("share-links.json"), revocations: revocations.to_owned(), lock: std::sync::Mutex::new(()), } } pub fn load(&self) -> Result { Ok(read_json(&self.path)?.unwrap_or_default()) } /// The revocation file as edge has it now, if it can be read. fn published(&self) -> Option<(u32, BTreeSet)> { #[derive(Deserialize)] struct Published { epoch: u32, deny: Vec, } let p: Published = serde_json::from_slice(&std::fs::read(&self.revocations).ok()?).ok()?; Some((p.epoch, p.deny.into_iter().collect())) } /// The records, with the epoch never below the published one (records lost or restored /// from an older backup must not bring stopped links back). fn load_reconciled(&self) -> Result { let mut f = self.load()?; if let Some((epoch, _)) = self.published() && epoch > f.epoch { log::warn!(target: "ianitor::share", "share-link records are behind the published revocations (epoch {} < {epoch}); continuing from {epoch}", f.epoch); f.epoch = epoch; } Ok(f) } fn save(&self, f: &mut ShareFile) -> Result<(), String> { let t = now(); // Kept at least until they expire: a stopped link must stay on the deny list as long // as its token would otherwise work. f.links .retain(|l| t < l.expires_at.saturating_add(KEEP_SECS)); let deny = self.reconcile(f); write_json(&self.path, f)?; self.publish(f.epoch, deny) } /// The deny list for `f`, raising `f.epoch` when the list cannot be kept whole: /// - a published id that the records cannot account for (stopped link lost from the /// records) is never just dropped: the epoch goes up, which stops every older link; /// - a list longer than edge accepts also raises the epoch, instead of being cut short. fn reconcile(&self, f: &mut ShareFile) -> Vec { let t = now(); let published = self.published(); if let Some((epoch, _)) = &published { f.epoch = f.epoch.max(*epoch); } let deny_for = |f: &ShareFile| -> Vec { let mut d: Vec = f .links .iter() .filter(|l| l.stopped_at.is_some() && l.expires_at > t && l.epoch >= f.epoch) .map(|l| l.id.clone()) .collect(); d.sort(); d }; let mut deny = deny_for(f); if let Some((epoch, old)) = published && epoch == f.epoch { let accounted = |id: &String| { deny.binary_search(id).is_ok() || f.links .iter() .any(|l| &l.id == id && (l.expires_at <= t || l.epoch < f.epoch)) }; if !old.iter().all(accounted) { log::warn!(target: "ianitor::share", "stopped links are missing from the records; raising the epoch, which stops every earlier link"); f.epoch = f.epoch.saturating_add(1); deny = deny_for(f); } } if deny.len() > MAX_DENY { log::warn!(target: "ianitor::share", "more than {MAX_DENY} stopped links; raising the epoch, which stops every earlier link"); f.epoch = f.epoch.saturating_add(1); deny = deny_for(f); } deny } /// Write the revocation file edge reads. fn publish(&self, epoch: u32, deny: Vec) -> Result<(), String> { // Readable by edge (another user); it holds only random link ids. let text = serde_json::to_vec(&RevocationFile { epoch, deny }).map_err(|e| e.to_string())?; crate::util::write_atomic(&self.revocations, &text, 0o644) .map_err(|e| format!("cannot write {}: {e}", self.revocations.display())) } pub fn ensure_revocation_file(&self) -> Result<(), String> { let _g = self .lock .lock() .map_err(|_| "share store unavailable".to_owned())?; let mut f = self.load()?; self.save(&mut f) } #[allow(clippy::too_many_arguments)] pub fn mint( &self, key: &ShareKey, hostname: &str, prefix: &str, expires_in: u64, password: Option<&str>, replaces: Option<&str>, actor: &str, ) -> Result { let prefix = share::check_prefix(prefix).map_err(|_| MintError::Prefix)?; if !(MIN_EXPIRY..=MAX_EXPIRY).contains(&expires_in) { return Err(MintError::Expiry); } if let Some(p) = password { let n = p.chars().count(); if n < share::MIN_PASSWORD_CHARS { return Err(MintError::PasswordShort); } if n > share::MAX_PASSWORD_CHARS { return Err(MintError::PasswordLong); } } let _g = self .lock .lock() .map_err(|_| MintError::Store("share store unavailable".into()))?; let mut f = self.load_reconciled().map_err(MintError::Store)?; let t0 = now(); if f.links .iter() .filter(|l| l.stopped_at.is_none() && l.expires_at > t0) .count() >= MAX_ACTIVE { return Err(MintError::TooMany); } if let Some(r) = replaces { let Some(old) = f .links .iter_mut() .find(|l| l.id == r && l.hostname == hostname) else { return Err(MintError::Replaces); }; old.stopped_at.get_or_insert(now()); } // Settle the epoch first (lost records, an overflowing deny list): a link minted // below the epoch that is about to be published would be dead on arrival. let _ = self.reconcile(&mut f); let id = ShareId(random::<16>().map_err(|e| MintError::Store(e.to_string()))?); let t = now(); let spec = LinkSpec { id, epoch: f.epoch, expires_at: t + expires_in, prefix: &prefix, password, }; let token = share::mint(key, hostname, &spec).map_err(|e| MintError::Store(e.to_string()))?; let record = LinkRecord { id: id.to_hex(), hostname: hostname.to_owned(), path_prefix: prefix.clone(), epoch: f.epoch, created_at: t, expires_at: t + expires_in, has_password: password.is_some(), created_by: actor.to_owned(), stopped_at: None, }; f.links.push(record.clone()); self.save(&mut f).map_err(MintError::Store)?; Ok(Minted { record, token }) } /// Stop one link. `Ok(None)` when there is no such link. pub fn stop(&self, id: &str) -> Result, String> { let _g = self .lock .lock() .map_err(|_| "share store unavailable".to_owned())?; let mut f = self.load_reconciled()?; let Some(l) = f.links.iter_mut().find(|l| l.id == id) else { return Ok(None); }; l.stopped_at.get_or_insert(now()); let r = l.clone(); self.save(&mut f)?; Ok(Some(r)) } /// Stop every link minted so far by raising the epoch. pub fn stop_all(&self) -> Result { let _g = self .lock .lock() .map_err(|_| "share store unavailable".to_owned())?; let mut f = self.load_reconciled()?; f.epoch = f.epoch.saturating_add(1); let e = f.epoch; self.save(&mut f)?; Ok(e) } }