From 83270e07466d6019418329958c486bd5d8327080 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 13:29:35 +0100 Subject: [PATCH] [core] Previews: branch and project names to one safe host label, and the [preview] table of a host file (tests first) --- crates/core/src/error.rs | 7 +- crates/core/src/lib.rs | 3 +- crates/core/src/model.rs | 14 ++ crates/core/src/preview.rs | 145 +++++++++++++++++++ crates/core/src/validate.rs | 43 +++++- crates/core/tests/preview.rs | 265 +++++++++++++++++++++++++++++++++++ 6 files changed, 474 insertions(+), 3 deletions(-) create mode 100644 crates/core/src/preview.rs create mode 100644 crates/core/tests/preview.rs diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index e4dbc84..bc3f8e0 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -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) -> 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, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 83e19de..75ca94d 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -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}; diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index b4822af..e4ad367 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -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, +} + +/// 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`). diff --git a/crates/core/src/preview.rs b/crates/core/src/preview.rs new file mode 100644 index 0000000..81db26d --- /dev/null +++ b/crates/core/src/preview.rs @@ -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 and project names come from a git host and +//! are hostile input; this module turns them into one safe DNS label. +//! +//! The label is `--`, 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 { + 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 { + 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) +} diff --git a/crates/core/src/validate.rs b/crates/core/src/validate.rs index d9fb9ac..2ff3b39 100644 --- a/crates/core/src/validate.rs +++ b/crates/core/src/validate.rs @@ -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, #[serde(default)] response_headers: Vec, + preview: Option, +} + +#[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 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 RawAccessLog::Off => AccessLog::Off, RawAccessLog::Truncated => AccessLog::Truncated, }, + preview, }) } diff --git a/crates/core/tests/preview.rs b/crates/core/tests/preview.rs new file mode 100644 index 0000000..4de5dfa --- /dev/null +++ b/crates/core/tests/preview.rs @@ -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 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&