[control] Previews: POST/GET/DELETE /api/v1/previews, tokens scoped to previews only, the upstream allow list, expiry; Windows drive paths in compile options (tests first)

This commit is contained in:
2026-11-17 13:46:33 +01:00
parent 83270e0746
commit fc9e16f1b2
21 changed files with 1677 additions and 43 deletions
+537
View File
@@ -0,0 +1,537 @@
// 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/.
//! Branch previews for Fabrica (Fabrica docs/32_coherence.md, T4). A preview is an ordinary
//! host file in the routes repository with a `[preview]` table, so it goes through the same
//! validation, compilers, differential tests and commit-confirmed apply as any host. This
//! module holds what is preview-only: the host body control writes, the upstream allow list
//! (a preview token is hostile: it must not be able to publish this machine's admin ports),
//! and the sweeper that closes expired previews.
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::Arc;
use std::time::Duration;
use crate::config::{Config, PreviewsConfig};
use crate::engine::{Change, Control, Fail};
use crate::hostspec::{HeaderRuleSpec, HostSpec, PreviewSpec};
use crate::messages::{self, Params};
use crate::util::now;
/// The actor name the sweeper's removals carry in the history.
pub const EXPIRY_ACTOR: &str = "Preview expiry";
/// One entry of `[previews] upstreams`.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Target {
Net(IpAddr, u8),
Name(String),
/// `*.suffix`: any name ending in `.suffix`.
Suffix(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Allowed {
target: Target,
ports: Option<(u16, u16)>,
}
fn parse_ports(p: &str) -> Option<(u16, u16)> {
let (lo, hi) = match p.split_once('-') {
Some((a, b)) => (a.parse().ok()?, b.parse().ok()?),
None => {
let x: u16 = p.parse().ok()?;
(x, x)
}
};
(lo >= 1 && lo <= hi).then_some((lo, hi))
}
fn parse_entry(e: &str) -> Option<Allowed> {
let e = e.trim();
// IPv6 networks carry no port (`fd00::/8`); everything else may end in `:port[-port]`.
if e.matches(':').count() > 1 {
let (ip, bits) = e.split_once('/').unwrap_or((e, "128"));
let ip: Ipv6Addr = ip.parse().ok()?;
let bits: u8 = bits.parse().ok().filter(|b| *b <= 128)?;
return Some(Allowed {
target: Target::Net(IpAddr::V6(ip), bits),
ports: None,
});
}
let (host, ports) = match e.rsplit_once(':') {
Some((h, p)) => (h, Some(parse_ports(p)?)),
None => (e, None),
};
if let Some((ip, bits)) = host.split_once('/') {
let ip: Ipv4Addr = ip.parse().ok()?;
let bits: u8 = bits.parse().ok().filter(|b| *b <= 32)?;
return Some(Allowed {
target: Target::Net(IpAddr::V4(ip), bits),
ports,
});
}
if let Ok(ip) = host.parse::<Ipv4Addr>() {
return Some(Allowed {
target: Target::Net(IpAddr::V4(ip), 32),
ports,
});
}
let name = host.to_ascii_lowercase();
let plain = |n: &str| {
!n.is_empty()
&& n.len() <= 253
&& n.split('.').all(|l| {
!l.is_empty()
&& l.len() <= 63
&& l.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
})
};
if let Some(suffix) = name.strip_prefix("*.") {
return plain(suffix).then(|| Allowed {
target: Target::Suffix(suffix.to_owned()),
ports,
});
}
plain(&name).then(|| Allowed {
target: Target::Name(name),
ports,
})
}
fn in_net(ip: IpAddr, net: IpAddr, bits: u8) -> bool {
match (ip, net) {
(IpAddr::V4(a), IpAddr::V4(n)) => {
let mask = if bits == 0 {
0
} else {
u32::MAX << (32 - u32::from(bits))
};
u32::from(a) & mask == u32::from(n) & mask
}
(IpAddr::V6(a), IpAddr::V6(n)) => {
let mask = if bits == 0 {
0
} else {
u128::MAX << (128 - u32::from(bits))
};
u128::from(a) & mask == u128::from(n) & mask
}
_ => false,
}
}
/// Addresses no preview may ever use, whatever the allow list says.
fn never(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v) => {
v.is_unspecified() || v.is_link_local() || v.is_multicast() || v.is_broadcast()
}
IpAddr::V6(v) => {
v.is_unspecified()
|| v.is_multicast()
|| (v.segments()[0] & 0xffc0) == 0xfe80
|| v.to_ipv4_mapped().is_some()
}
}
}
/// Check the `[previews]` section at start.
pub fn check_config(p: &PreviewsConfig, cfg: &Config) -> Result<(), String> {
ianitor_core::preview::hostname("p", "main", &p.domain)
.map_err(|e| format!("previews.domain: {e}"))?;
if !["domi", "letsencrypt"].contains(&p.tls.as_str()) {
return Err("previews.tls must be domi or letsencrypt".into());
}
if !["none", "forward-auth"].contains(&p.auth.as_str()) {
return Err("previews.auth must be none or forward-auth".into());
}
for u in &p.upstreams {
if parse_entry(u).is_none() {
return Err(format!(
"previews.upstreams: {u:?} is not a network (10.0.0.0/8), an address with ports (127.0.0.1:20000-29999) or a name (app.internal, *.svc.internal)"
));
}
}
if p.min_ttl_secs == 0
|| p.min_ttl_secs > p.max_ttl_secs
|| !(p.min_ttl_secs..=p.max_ttl_secs).contains(&p.default_ttl_secs)
{
return Err(
"previews: min_ttl_secs ≤ default_ttl_secs ≤ max_ttl_secs, and min_ttl_secs > 0".into(),
);
}
if !(1..=3600).contains(&p.sweep_secs) || !(1..=10_000).contains(&p.max_previews) {
return Err("previews: sweep_secs 1 to 3600, max_previews 1 to 10000".into());
}
let _ = cfg;
Ok(())
}
fn fail(status: u16, code: &str, params: Params) -> Fail {
Fail::new(status, code, params)
}
/// Whether a preview may send traffic to `upstream`; the parsed URL's host and port.
pub fn check_upstream(cfg: &Config, p: &PreviewsConfig, upstream: &str) -> Result<(), Fail> {
let bad = || fail(422, "preview.upstream", Params::new());
if upstream.is_empty()
|| upstream.len() > 512
|| !upstream.bytes().all(|c| c.is_ascii_graphic())
{
return Err(bad());
}
let u = url::Url::parse(upstream).map_err(|_| bad())?;
if !["http", "https"].contains(&u.scheme())
|| !u.username().is_empty()
|| u.password().is_some()
|| u.query().is_some()
|| u.fragment().is_some()
|| !(u.path().is_empty() || u.path() == "/")
{
return Err(bad());
}
let port = u.port_or_known_default().ok_or_else(bad)?;
let host = u.host().ok_or_else(bad)?;
let shown = || {
messages::params([
("upstream", upstream.to_owned()),
("allowed", {
if p.upstreams.is_empty() {
"nothing yet (set [previews] upstreams)".to_owned()
} else {
p.upstreams.join(", ")
}
}),
])
};
let not_allowed = || fail(403, "preview.upstream_not_allowed", shown());
let ip = match &host {
url::Host::Ipv4(v) => Some(IpAddr::V4(*v)),
url::Host::Ipv6(v) => Some(IpAddr::V6(*v)),
url::Host::Domain(_) => None,
};
if let Some(ip) = ip {
if never(ip) {
return Err(not_allowed());
}
// This machine's own control API and Caddy admin API, whatever the list says.
if ip.is_loopback() {
let admin_ports = std::iter::once(cfg.listen.port()).chain(
[cfg.compile.caddy_admin, cfg.caddy_compile().caddy_admin]
.into_iter()
.flatten()
.map(|a| a.port()),
);
if admin_ports.into_iter().any(|a| a == port) || port == 2019 {
return Err(not_allowed());
}
}
}
let name = match &host {
url::Host::Domain(d) => Some(d.to_ascii_lowercase()),
_ => None,
};
let ok = p.upstreams.iter().filter_map(|e| parse_entry(e)).any(|a| {
let port_ok = a.ports.is_none_or(|(lo, hi)| (lo..=hi).contains(&port));
let host_ok = match (&a.target, ip, &name) {
(Target::Net(net, bits), Some(ip), _) => in_net(ip, *net, *bits),
(Target::Name(n), _, Some(h)) => n == h,
(Target::Suffix(s), _, Some(h)) => h.ends_with(&format!(".{s}")),
_ => false,
};
port_ok && host_ok
});
if ok { Ok(()) } else { Err(not_allowed()) }
}
/// The host body of a branch's preview.
pub fn spec(
p: &PreviewsConfig,
hostname: &str,
project: &str,
branch: &str,
upstream: &str,
expires_at: u64,
) -> HostSpec {
HostSpec {
hostname: hostname.to_owned(),
upstreams: vec![upstream.trim_end_matches('/').to_owned()],
tls: p.tls.clone(),
auth: p.auth.clone(),
websockets: true,
share_links: false,
device_certs: false,
access_log: "off".into(),
health_check: None,
request_headers: Vec::new(),
// A preview is not for search engines.
response_headers: vec![HeaderRuleSpec {
action: "set".into(),
name: "X-Robots-Tag".into(),
value: Some("noindex, nofollow".into()),
secret: None,
}],
preview: Some(PreviewSpec {
project: project.to_owned(),
branch: branch.to_owned(),
expires_at: i64::try_from(expires_at).unwrap_or(i64::MAX),
}),
}
}
/// A preview's field problem as an API refusal.
pub fn name_fail(e: ianitor_core::preview::PreviewError) -> Fail {
use ianitor_core::preview::PreviewError as P;
let (code, problem) = match &e {
P::Branch(r) => ("preview.branch", (*r).to_owned()),
P::Project(r) => ("preview.project", (*r).to_owned()),
P::Domain(r) => ("preview.domain", r.clone()),
};
let mut f = fail(422, code, messages::params([("problem", problem)]));
f.reason.field = Some(
match e {
P::Branch(_) => "branch",
P::Project(_) => "project",
P::Domain(_) => "domain",
}
.into(),
);
f
}
/// What the previews screen and Fabrica see.
#[derive(Debug, Clone)]
pub struct Listed {
pub hostname: String,
pub project: String,
pub branch: String,
pub upstream: String,
pub expires_at: u64,
}
impl Control {
pub fn previews_cfg(&self) -> Result<&PreviewsConfig, Fail> {
self.cfg
.previews
.as_ref()
.ok_or_else(|| fail(409, "preview.off", Params::new()))
}
/// Every preview at the branch head, by host name.
pub fn previews(&self) -> Result<Vec<Listed>, Fail> {
let (_, _, model) = self.head_model()?;
Ok(model
.hosts()
.iter()
.filter_map(|h| {
let p = h.preview.as_ref()?;
Some(Listed {
hostname: h.hostname.to_string(),
project: p.project.clone(),
branch: p.branch.clone(),
upstream: h
.upstreams
.first()
.map(ToString::to_string)
.unwrap_or_default(),
expires_at: p.expires_at,
})
})
.collect())
}
/// Open (or move) a branch's preview.
pub fn open_preview(
&self,
project: &str,
branch: &str,
upstream: &str,
ttl: Option<u64>,
actor: &str,
) -> Result<(String, u64, crate::records::ApplyRecord), Fail> {
let p = self.previews_cfg()?;
let hostname =
ianitor_core::preview::hostname(project, branch, &p.domain).map_err(name_fail)?;
let ttl = ttl.unwrap_or(p.default_ttl_secs);
if !(p.min_ttl_secs..=p.max_ttl_secs).contains(&ttl) {
let mut f = fail(
422,
"preview.ttl",
messages::params([
("min", p.min_ttl_secs.to_string()),
("max", p.max_ttl_secs.to_string()),
]),
);
f.reason.field = Some("ttl".into());
return Err(f);
}
check_upstream(&self.cfg, p, upstream)?;
let previews = self.previews()?;
let (_, tree, model) = self.head_model()?;
let existing = model
.hosts()
.iter()
.find(|h| h.hostname.as_str() == hostname);
let create = match existing {
None => {
if previews.len() >= p.max_previews {
return Err(fail(
409,
"preview.too_many",
messages::params([("max", p.max_previews.to_string())]),
));
}
true
}
Some(h) => match &h.preview {
Some(pv) if pv.project == project && pv.branch == branch => false,
_ => {
return Err(fail(
409,
"preview.taken",
messages::params([("hostname", hostname.clone())]),
));
}
},
};
drop(tree);
let expires_at = now().saturating_add(ttl);
let spec = spec(p, &hostname, project, branch, upstream, expires_at);
let summary = format!(
"{} the preview of {branch} ({project})",
if create { "Opened" } else { "Moved" }
);
let rec = self.submit_as(Change::Put { spec, create }, None, actor, Some(summary))?;
Ok((hostname, expires_at, rec))
}
/// Close a preview by its host name. Only preview hosts.
pub fn close_preview(
&self,
hostname: &str,
actor: &str,
why: &str,
) -> Result<crate::records::ApplyRecord, Fail> {
self.previews_cfg()?;
let pv = self
.previews()?
.into_iter()
.find(|p| p.hostname == hostname)
.ok_or_else(|| fail(404, "preview.not_found", Params::new()))?;
let summary = format!("{why} preview of {} ({})", pv.branch, pv.project);
self.submit_as(
Change::Delete {
hostname: hostname.to_owned(),
},
None,
actor,
Some(summary),
)
}
/// Where a preview stands: `applying`, `live`, `failed` (with why), or not a preview.
pub fn preview_state(&self, hostname: &str) -> Option<(String, Option<String>)> {
let live = self.previews().ok()?.iter().any(|p| p.hostname == hostname);
let last = self
.records()
.into_iter()
.rev()
.find(|r| r.hosts.iter().any(|h| h == hostname));
let pending = last
.as_ref()
.is_some_and(|r| !["kept", "reverted", "failed"].contains(&r.state.as_str()));
if pending {
return Some(("applying".into(), None));
}
if live {
return Some(("live".into(), None));
}
let r = last?;
// A preview that never went live because its apply failed.
(r.summary.contains("the preview of") && r.state != "kept").then(|| {
(
"failed".into(),
r.reason.as_ref().map(|x| x.message.clone()),
)
})
}
/// Close expired previews, every `sweep_secs`.
pub async fn preview_sweeper(self: Arc<Self>) {
let Some(p) = self.cfg.previews.clone() else {
return;
};
loop {
tokio::time::sleep(Duration::from_secs(p.sweep_secs)).await;
let Ok(list) = self.previews() else {
continue;
};
let t = now();
let busy: Vec<String> = self
.records()
.into_iter()
.filter(|r| !["kept", "reverted", "failed"].contains(&r.state.as_str()))
.flat_map(|r| r.hosts)
.collect();
for pv in list.iter().filter(|p| p.expires_at <= t) {
if busy.contains(&pv.hostname) {
continue;
}
match self.close_preview(&pv.hostname, EXPIRY_ACTOR, "Closed the expired") {
Ok(_) => {
log::info!(target: "ianitor::previews", "the preview {} expired; closing it", pv.hostname)
}
Err(f) => {
log::warn!(target: "ianitor::previews", "cannot close the expired preview {}: {}", pv.hostname, f.reason.message)
}
}
}
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn allow_list_entries_parse() {
for ok in [
"10.0.0.0/8",
"127.0.0.1:20000-29999",
"192.168.1.5:8080",
"app.internal",
"app.internal:3000",
"*.svc.internal",
"fd00::/8",
] {
assert!(parse_entry(ok).is_some(), "{ok}");
}
for bad in [
"",
"10.0.0.0/33",
"a b",
"x:0",
"x:9-1",
"*.",
"http://x",
"1.2.3.4/8:70000",
] {
assert!(parse_entry(bad).is_none(), "{bad}");
}
}
#[test]
fn networks_match() {
let n = |s: &str| s.parse::<IpAddr>().unwrap();
assert!(in_net(n("10.1.2.3"), n("10.0.0.0"), 8));
assert!(!in_net(n("11.1.2.3"), n("10.0.0.0"), 8));
assert!(in_net(n("fd12::1"), n("fd00::"), 8));
assert!(in_net(n("1.2.3.4"), n("0.0.0.0"), 0));
assert!(never(n("0.0.0.0")) && never(n("169.254.169.254")) && never(n("::ffff:127.0.0.1")));
}
}