[core] Previews: branch and project names to one safe host label, and the [preview] table of a host file (tests first)

This commit is contained in:
2026-11-17 13:29:35 +01:00
parent 00b506670f
commit 83270e0746
6 changed files with 474 additions and 3 deletions
+6 -1
View File
@@ -178,6 +178,8 @@ pub enum ValidationError {
BadForwardAuth { file: String, reason: &'static str },
#[error("{file}: acme is not usable: {reason}")]
BadAcme { file: String, reason: &'static str },
#[error("{file}: the preview is not usable: {reason}")]
BadPreview { file: String, reason: String },
}
fn line_suffix(line: Option<usize>) -> String {
@@ -217,7 +219,8 @@ impl ValidationError {
| E::ForwardAuthNotConfigured { file }
| E::ProofWithoutSignIn { file }
| E::BadForwardAuth { file, .. }
| E::BadAcme { file, .. } => file,
| E::BadAcme { file, .. }
| E::BadPreview { file, .. } => file,
E::DuplicateHostname { second, .. } => second,
}
}
@@ -304,6 +307,7 @@ impl ValidationError {
E::ProofWithoutSignIn { .. } => "host.header.proof",
E::BadForwardAuth { .. } => "site.forward_auth",
E::BadAcme { .. } => "site.acme",
E::BadPreview { .. } => "host.preview",
}
}
@@ -338,6 +342,7 @@ impl ValidationError {
E::BadHealthCheck { .. } => Some("health_check.path".into()),
E::ForwardAuthNotConfigured { .. } => Some("auth".into()),
E::ProofWithoutSignIn { .. } => Some("auth".into()),
E::BadPreview { .. } => Some("preview".into()),
_ => None,
}
}
+2 -1
View File
@@ -13,6 +13,7 @@ pub mod edge_config;
mod error;
mod model;
pub mod pki;
pub mod preview;
pub mod routes;
pub mod share;
pub mod time;
@@ -22,7 +23,7 @@ pub use error::{ValidationError, ValidationErrors};
pub use model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, MAX_FILE_BYTES,
MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream,
MAX_UPSTREAMS, Model, Preview, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream,
UpstreamHost,
};
pub use validate::{SourceFile, load};
+14
View File
@@ -173,6 +173,20 @@ pub struct Host {
pub access_log: AccessLog,
/// Visitors must present a Domi device certificate (mTLS) that is on the allow list.
pub device_certs: bool,
/// Set when this host is a branch preview (see [`crate::preview`]). Control uses it; the
/// compilers never read it.
pub preview: Option<Preview>,
}
/// The `[preview]` table of a preview host: which branch of which project it shows, and
/// until when. Its host name's first label is always `preview::label(project, branch)`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Preview {
pub project: String,
pub branch: String,
/// Unix seconds; control removes the host after this.
pub expires_at: u64,
}
/// The forward-auth endpoint (Authelia's `/api/authz/forward-auth`).
+145
View File
@@ -0,0 +1,145 @@
// 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 (Fabrica docs/32_coherence.md, T4): every branch of a project gets the host
//! `<branch>--<project>.<preview domain>`. Branch and project names come from a git host and
//! are hostile input; this module turns them into one safe DNS label.
//!
//! The label is `<branch part>--<project part>`, at most 62 characters:
//! - each part is the name lowercased, with every run of other characters than `a-z0-9`
//! turned into one `-`, trimmed of dashes (the project part uses only the repository name,
//! the text after the last `/` or `:`);
//! - when that lost anything (case, a character, the owner, length) the part gets `-` and 6
//! hex digits of SHA-256 of the whole original name, so two names that would read the same
//! never share a host (`feature/login` and `feature-login`, `Main` and `main`);
//! - a branch part shorter than 3 characters is also suffixed, so `--` never lands in the
//! label's positions 3 and 4 (reserved for IDNA; Let's Encrypt refuses such labels).
//!
//! Parts never contain `--`, so the separator is unambiguous. Names that cannot be a git
//! branch or a Fabrica project (control characters, too long, empty) are refused, not mangled.
use std::fmt;
/// Longest branch name accepted, in bytes (git allows more; no real branch is near this).
pub const MAX_BRANCH_BYTES: usize = 255;
/// Longest project name accepted (Fabrica's `project` field).
pub const MAX_PROJECT_CHARS: usize = 128;
/// The branch part of the label is at most this long.
pub const BRANCH_PART: usize = 40;
/// The project part of the label is at most this long.
pub const PROJECT_PART: usize = 20;
const HASH_HEX: usize = 6;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PreviewError {
Branch(&'static str),
Project(&'static str),
Domain(String),
}
impl fmt::Display for PreviewError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PreviewError::Branch(r) => write!(f, "the branch name {r}"),
PreviewError::Project(r) => write!(f, "the project name {r}"),
PreviewError::Domain(r) => write!(f, "the preview host name is not usable: {r}"),
}
}
}
impl std::error::Error for PreviewError {}
fn check_branch(b: &str) -> Result<(), PreviewError> {
if b.is_empty() {
return Err(PreviewError::Branch("is empty"));
}
if b.len() > MAX_BRANCH_BYTES {
return Err(PreviewError::Branch("is longer than 255 bytes"));
}
if b.chars().any(char::is_control) {
return Err(PreviewError::Branch("contains a control character"));
}
Ok(())
}
fn check_project(p: &str) -> Result<(), PreviewError> {
if p.is_empty() || p.chars().count() > MAX_PROJECT_CHARS {
return Err(PreviewError::Project("must be 1 to 128 characters"));
}
if !p
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"._/:-".contains(&c))
{
return Err(PreviewError::Project(
"may only use letters, digits, '.', '_', '/', ':' and '-'",
));
}
if repo_name(p).bytes().all(|c| !c.is_ascii_alphanumeric()) {
return Err(PreviewError::Project("has no repository name"));
}
Ok(())
}
/// The repository name: what follows the last `/` or `:` (`github:acme/web` → `web`).
fn repo_name(p: &str) -> &str {
p.rsplit(['/', ':']).next().unwrap_or(p)
}
/// Lowercase LDH with dash runs collapsed and trimmed.
fn slug(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if c.is_ascii_alphanumeric() {
out.push(c.to_ascii_lowercase());
} else if !out.is_empty() && !out.ends_with('-') {
out.push('-');
}
}
while out.ends_with('-') {
out.pop();
}
out
}
fn short_hash(s: &str) -> String {
let d = ring::digest::digest(&ring::digest::SHA256, s.as_bytes());
let mut h = String::with_capacity(HASH_HEX);
for b in d.as_ref().iter().take(HASH_HEX / 2) {
h.push_str(&format!("{b:02x}"));
}
h
}
/// `slug` cut to `max`, with the hash of `original` appended when the slug is not exactly
/// `shown` or is shorter than `min`.
fn part(shown: &str, original: &str, max: usize, min: usize) -> String {
let s = slug(shown);
if s == shown && s.len() <= max && s.len() >= min && original == shown {
return s;
}
let keep = max - HASH_HEX - 1;
let mut cut: String = s.chars().take(keep).collect();
while cut.ends_with('-') {
cut.pop();
}
let h = short_hash(original);
if cut.is_empty() { h } else { format!("{cut}-{h}") }
}
/// The DNS label of a branch's preview.
pub fn label(project: &str, branch: &str) -> Result<String, PreviewError> {
check_branch(branch)?;
check_project(project)?;
let b = part(branch, branch, BRANCH_PART, 3);
let p = part(repo_name(project), project, PROJECT_PART, 1);
Ok(format!("{b}--{p}"))
}
/// The preview's host name under `domain`, checked like any host name.
pub fn hostname(project: &str, branch: &str, domain: &str) -> Result<String, PreviewError> {
crate::validate::check_hostname(domain).map_err(|r| PreviewError::Domain(r.to_owned()))?;
let h = format!("{}.{domain}", label(project, branch)?);
crate::validate::check_hostname(&h).map_err(|r| PreviewError::Domain(r.to_owned()))?;
Ok(h)
}
+42 -1
View File
@@ -15,7 +15,7 @@ use crate::error::{ValidationError as E, ValidationErrors, reason as r};
use crate::model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, MAX_FILE_BYTES, MAX_UPSTREAMS, Model,
Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream, UpstreamHost,
Preview, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream, UpstreamHost,
};
/// One route file handed in by the caller (core does no I/O).
@@ -129,6 +129,16 @@ struct RawHost {
request_headers: Vec<RawRule>,
#[serde(default)]
response_headers: Vec<RawRule>,
preview: Option<RawPreview>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawPreview {
project: String,
branch: String,
/// Signed so that 0 and negative numbers get a typed error instead of a serde one.
expires_at: i64,
}
// ------------------------------------------------------------------ entry point
@@ -511,6 +521,36 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
errors.push(E::ProofWithoutSignIn { file: f() });
}
let preview = raw.preview.and_then(|p| {
let bad = |reason: String| E::BadPreview { file: f(), reason };
let expires_at = match u64::try_from(p.expires_at) {
Ok(e) if e > 0 => e,
_ => {
errors.push(bad("expires_at must be a time in Unix seconds".into()));
return None;
}
};
match crate::preview::label(&p.project, &p.branch) {
Ok(label) => {
if raw.hostname.split('.').next() != Some(label.as_str()) {
errors.push(bad(format!(
"the host name of this branch's preview must start with \"{label}.\""
)));
return None;
}
}
Err(e) => {
errors.push(bad(e.to_string()));
return None;
}
}
Some(Preview {
project: p.project,
branch: p.branch,
expires_at,
})
});
if errors.len() != before {
return None;
}
@@ -533,6 +573,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
RawAccessLog::Off => AccessLog::Off,
RawAccessLog::Truncated => AccessLog::Truncated,
},
preview,
})
}
+265
View File
@@ -0,0 +1,265 @@
// 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/.
//! Preview host names (T4, written before the code): `<branch>--<project>.<preview domain>`.
//! Branch and project names come from a git host and are hostile: every one must map to a
//! safe DNS label, two different branches must never share a host, and the preview table of
//! a host file must agree with its host name.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::BTreeMap;
use ianitor_core::preview::{self, PreviewError};
use ianitor_core::{SourceFile, load};
/// A label a public CA and every resolver accept: LDH, 1–63, no leading or trailing dash, and
/// no `--` in positions 3 and 4 (reserved for IDNA A-labels, refused by Let's Encrypt).
fn assert_safe_label(l: &str) {
assert!(!l.is_empty() && l.len() <= 63, "length of {l:?}");
assert!(
l.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-'),
"{l:?} is not lowercase LDH"
);
assert!(!l.starts_with('-') && !l.ends_with('-'), "{l:?} has an edge dash");
assert!(l.get(2..4) != Some("--"), "{l:?} has -- in positions 3 and 4");
}
#[test]
fn plain_names_stay_readable() {
assert_eq!(preview::label("mnovak/Arca", "main").unwrap(), "main--arca-4a93cc");
assert_eq!(preview::label("shop", "fix-42").unwrap(), "fix-42--shop");
assert_eq!(
preview::hostname("shop", "fix-42", "preview.example.org").unwrap(),
"fix-42--shop.preview.example.org"
);
}
#[test]
fn hostile_branch_names_map_to_safe_labels() {
let long = "a".repeat(250);
let dots = "x.".repeat(100);
let hostile: &[&str] = &[
"main",
"Main",
"feature/login",
"feature//login",
"feature.login",
"..",
"...hidden",
"v1.2.3",
"ab",
"xn",
"a",
"-",
"--",
"_",
"fix/ünïcødé",
"日本語のブランチ",
"emoji-🦊-branch",
"Ⅻ-roman",
"fi-ligature",
"\u{200b}zero-width",
"right-to-left-\u{202e}gnp.exe",
"has space and ~^:?*[",
"semi;colon&amp<script>",
"../../etc/passwd",
"%2e%2e%2f",
"CAPS_AND_UNDERSCORES",
&long,
&dots,
"xn--80ak6aa92e",
"a--b",
"end-",
"-start",
];
for b in hostile {
let l = preview::label("team/web-app", b).unwrap_or_else(|e| panic!("{b:?}: {e}"));
assert_safe_label(&l);
let host = preview::hostname("team/web-app", b, "preview.example.org").unwrap();
assert!(host.ends_with(".preview.example.org"));
// The host is a valid host-file name: core accepts a preview file for it.
let text = preview_file(&host, "team/web-app", b);
load_one(&host, &text).unwrap_or_else(|e| panic!("{b:?}: {e}"));
}
}
#[test]
fn different_branches_never_share_a_label() {
// Pairs a naive slug would merge.
let pairs = [
("feature/login", "feature-login"),
("feature.login", "feature-login"),
("Main", "main"),
("fix/ü", "fix/ö"),
("a/b", "a_b"),
("x", "X"),
];
for (a, b) in pairs {
assert_ne!(
preview::label("p", a).unwrap(),
preview::label("p", b).unwrap(),
"{a:?} and {b:?}"
);
}
// Long branches that differ only after the cut.
let a = format!("{}-one", "release".repeat(10));
let b = format!("{}-two", "release".repeat(10));
assert_ne!(preview::label("p", &a).unwrap(), preview::label("p", &b).unwrap());
// And a broad sweep: many similar names, all distinct.
let mut seen = BTreeMap::new();
for i in 0..2000 {
for b in [format!("feature/{i}"), format!("feature-{i}"), format!("Feature/{i}")] {
let l = preview::label("p", &b).unwrap();
assert_safe_label(&l);
if let Some(prev) = seen.insert(l.clone(), b.clone()) {
panic!("{prev:?} and {b:?} both map to {l}");
}
}
}
}
#[test]
fn same_input_same_label() {
for b in ["main", "feature/ünï", "x".repeat(300).as_str()] {
if b.len() > preview::MAX_BRANCH_BYTES {
continue;
}
assert_eq!(preview::label("p/q", b).unwrap(), preview::label("p/q", b).unwrap());
}
}
#[test]
fn unusable_names_are_refused_not_mangled() {
let too_long = "b".repeat(preview::MAX_BRANCH_BYTES + 1);
let bad_branches = ["", "tab\there", "with\nnewline", "nul\0byte", "bell\u{7}", too_long.as_str()];
for b in bad_branches {
assert!(
matches!(preview::label("p", b), Err(PreviewError::Branch(_))),
"{b:?}"
);
}
let bad_projects = ["", "/", "owner/", "has space", "semi;colon", "ü/name", &"p".repeat(129)];
for p in bad_projects {
assert!(
matches!(preview::label(p, "main"), Err(PreviewError::Project(_))),
"{p:?}"
);
}
// A preview domain must be a hostname, and the whole name must fit DNS.
assert!(matches!(
preview::hostname("p", "main", "bad domain"),
Err(PreviewError::Domain(_))
));
let deep = format!("{}.example.org", "d".repeat(60).repeat(1) + &".d".repeat(90));
assert!(preview::hostname("p", "main", &deep).is_err());
}
#[test]
fn project_names_from_every_git_host_work() {
for p in [
"mnovak/Arca",
"github:acme/web",
"gitlab-work:group/sub/app",
"app",
"Org.Name/repo.js",
] {
let l = preview::label(p, "main").unwrap();
assert_safe_label(&l);
}
// Same repo name under two owners: different hosts.
assert_ne!(
preview::label("alice/app", "main").unwrap(),
preview::label("bob/app", "main").unwrap()
);
}
fn preview_file(host: &str, project: &str, branch: &str) -> String {
let mut t = toml::Table::new();
t.insert("hostname".into(), host.into());
t.insert(
"upstreams".into(),
toml::Value::Array(vec!["http://10.0.0.5:8080".into()]),
);
t.insert("tls".into(), "domi".into());
let mut p = toml::Table::new();
p.insert("project".into(), project.into());
p.insert("branch".into(), branch.into());
p.insert("expires_at".into(), toml::Value::Integer(1_900_000_000));
t.insert("preview".into(), toml::Value::Table(p));
toml::to_string(&t).unwrap()
}
fn load_one(host: &str, text: &str) -> Result<ianitor_core::Model, ianitor_core::ValidationErrors> {
let name = format!("hosts/{host}.toml");
load(
&SourceFile {
name: "ianitor.toml",
contents: "",
},
&[SourceFile {
name: &name,
contents: text,
}],
)
}
#[test]
fn the_model_carries_the_preview() {
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
let m = load_one(&host, &preview_file(&host, "shop", "fix-42")).unwrap();
let p = m.hosts()[0].preview.as_ref().expect("a preview");
assert_eq!((p.project.as_str(), p.branch.as_str(), p.expires_at), ("shop", "fix-42", 1_900_000_000));
}
#[test]
fn a_preview_table_must_match_its_host_name() {
// A file cannot claim to be another branch's preview, or name a host its label does not.
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
let e = load_one(&host, &preview_file(&host, "shop", "other")).unwrap_err();
assert!(e.to_string().contains("preview"), "{e}");
let e = load_one("plain.pv.example.org", &preview_file("plain.pv.example.org", "shop", "fix-42"))
.unwrap_err();
assert!(e.to_string().contains("preview"), "{e}");
// Unknown keys and bad values in the table are refused like everywhere else.
let text = preview_file(&host, "shop", "fix-42").replace("expires_at", "expires");
assert!(load_one(&host, &text).is_err());
let text = preview_file(&host, "shop", "fix-42").replace("1900000000", "0");
assert!(load_one(&host, &text).is_err());
}
#[test]
fn compilers_ignore_the_preview_table() {
// The preview metadata never reaches an engine: both outputs equal those of the same
// host without it.
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
let with = load_one(&host, &preview_file(&host, "shop", "fix-42")).unwrap();
let text = preview_file(&host, "shop", "fix-42");
let without_text: String = text
.split("[preview]")
.next()
.unwrap()
.to_owned();
let without = load_one(&host, &without_text).unwrap();
let o = ianitor_core::compile::CompileOptions {
http_listen: "0.0.0.0:80".parse().unwrap(),
https_listen: "0.0.0.0:443".parse().unwrap(),
cert_dir: "/var/lib/ianitor/certs".into(),
state_dir: "/var/lib/ianitor".into(),
access_log: "/var/log/ianitor/access.log".into(),
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
};
assert_eq!(
ianitor_core::compile::edge(&with, &o).unwrap(),
ianitor_core::compile::edge(&without, &o).unwrap()
);
assert_eq!(
ianitor_core::compile::caddy(&with, &o).unwrap(),
ianitor_core::compile::caddy(&without, &o).unwrap()
);
}