[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:
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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`).
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user