[control] Phase 2 control plane: routes repo via git, journaled apply with trial/watch/revert, undo and restore, push with retry, share links, API tokens, REST API with OpenAPI, --dev
This commit is contained in:
@@ -0,0 +1,233 @@
|
||||
// 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::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<u64>,
|
||||
}
|
||||
|
||||
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<LinkRecord>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct RevocationFile {
|
||||
epoch: u32,
|
||||
deny: Vec<String>,
|
||||
}
|
||||
|
||||
/// 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;
|
||||
|
||||
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,
|
||||
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<ShareFile, String> {
|
||||
Ok(read_json(&self.path)?.unwrap_or_default())
|
||||
}
|
||||
|
||||
fn save(&self, f: &mut ShareFile) -> Result<(), String> {
|
||||
let t = now();
|
||||
f.links.retain(|l| {
|
||||
let end = l.stopped_at.unwrap_or(l.expires_at).min(l.expires_at);
|
||||
t < end.saturating_add(KEEP_SECS)
|
||||
});
|
||||
write_json(&self.path, f)?;
|
||||
self.write_revocations(f)
|
||||
}
|
||||
|
||||
/// Write the revocation file edge reads.
|
||||
pub fn write_revocations(&self, f: &ShareFile) -> Result<(), String> {
|
||||
let t = now();
|
||||
let mut deny: Vec<String> = f
|
||||
.links
|
||||
.iter()
|
||||
.filter(|l| l.stopped_at.is_some() && l.expires_at > t && l.epoch >= f.epoch)
|
||||
.map(|l| l.id.clone())
|
||||
.collect();
|
||||
deny.sort();
|
||||
deny.truncate(9_999);
|
||||
// Readable by edge (another user); it holds only random link ids.
|
||||
let text = serde_json::to_vec(&RevocationFile {
|
||||
epoch: f.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 f = self.load()?;
|
||||
self.write_revocations(&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<Minted, MintError> {
|
||||
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().map_err(MintError::Store)?;
|
||||
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());
|
||||
}
|
||||
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<Option<LinkRecord>, String> {
|
||||
let _g = self
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| "share store unavailable".to_owned())?;
|
||||
let mut f = self.load()?;
|
||||
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<u32, String> {
|
||||
let _g = self
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| "share store unavailable".to_owned())?;
|
||||
let mut f = self.load()?;
|
||||
f.epoch = f.epoch.saturating_add(1);
|
||||
let e = f.epoch;
|
||||
self.save(&mut f)?;
|
||||
Ok(e)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user