[core] Schema: tests first for validation and compiler determinism (red: 37+11 failing)

This commit is contained in:
2026-11-07 14:34:33 +01:00
parent c1abe88688
commit 9176cc63a4
12 changed files with 1231 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
// 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/.
//! Compilers from the validated [`Model`] to the two engines. Both are pure and deterministic:
//! the same model and options always give byte-identical output.
use std::net::SocketAddr;
use crate::Model;
/// Deployment facts that are not part of the routes repo (they change only with a rebuild).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompileOptions {
pub http_listen: SocketAddr,
pub https_listen: SocketAddr,
/// Absolute directory with Domi certificates: `<hostname>.crt` and `<hostname>.key`.
pub cert_dir: String,
/// Absolute state directory (edge ACME state, Caddy storage).
pub state_dir: String,
/// Absolute path of the access log file.
pub access_log: String,
/// `$CREDENTIALS_DIRECTORY` of the Caddy fallback unit, used in `{file.*}` placeholders.
pub caddy_credentials_dir: String,
/// Caddy admin endpoint; `None` disables the admin API.
pub caddy_admin: Option<SocketAddr>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum CompileError {
#[error("compile option `{option}` is not usable: {reason}")]
BadOption { option: &'static str, reason: &'static str },
#[error("could not serialise the compiled config: {0}")]
Serialize(String),
}
/// Compile to the Pingora runtime config read by ianitor-edge.
pub fn edge(model: &Model, options: &CompileOptions) -> Result<String, CompileError> {
let _ = (model, options);
Err(CompileError::Serialize("not implemented".into()))
}
/// Compile to Caddy JSON for the caddy-fallback unit.
pub fn caddy(model: &Model, options: &CompileOptions) -> Result<String, CompileError> {
let _ = (model, options);
Err(CompileError::Serialize("not implemented".into()))
}
+103
View File
@@ -0,0 +1,103 @@
// 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/.
//! The compiled runtime config read by ianitor-edge. Produced only by [`crate::compile::edge`].
//! Edge never decides policy: everything it does is spelled out here. Secret values are never
//! part of it, only secret names, resolved by edge from `$CREDENTIALS_DIRECTORY`.
use serde::{Deserialize, Serialize};
/// Bumped on any incompatible change; edge refuses other versions.
pub const EDGE_CONFIG_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeConfig {
pub version: u32,
/// Plain-HTTP listener: ACME HTTP-01 challenges and redirects to HTTPS.
pub http_listen: String,
/// TLS listener serving every host by SNI.
pub https_listen: String,
/// Port used in HTTP→HTTPS redirects (omitted from `Location` when 443).
pub https_port: u16,
/// Directory holding Domi certificates as `<hostname>.crt` / `<hostname>.key`.
pub cert_dir: String,
/// Edge state; ACME account and certificates live in `<state_dir>/acme`.
pub state_dir: String,
/// Access log file (JSON lines). Only hosts with `access_log` enabled write to it.
pub access_log: String,
pub acme: Option<EdgeAcme>,
pub forward_auth: Option<EdgeForwardAuth>,
/// Sorted by hostname.
pub hosts: Vec<EdgeHost>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeAcme {
pub directory: String,
pub email: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeForwardAuth {
pub upstream: EdgeUpstream,
pub path_and_query: String,
pub copy_headers: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeUpstream {
/// `host:port`, IPv6 in brackets.
pub address: String,
pub tls: bool,
/// SNI and certificate name when `tls` is set.
pub sni: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "source")]
pub enum EdgeTls {
/// Obtain and renew through ACME; stored under `<state_dir>/acme`.
Acme,
/// Load from files (Domi CA certificates).
Files { cert: String, key: String },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "kind")]
pub enum EdgeValue {
Literal { value: String },
Secret { name: String },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "op")]
pub enum EdgeHeaderOp {
Set { name: String, value: EdgeValue },
Remove { name: String },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeHealthCheck {
pub path: String,
pub interval_secs: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeHost {
pub hostname: String,
pub tls: EdgeTls,
pub upstreams: Vec<EdgeUpstream>,
pub forward_auth: bool,
pub websockets: bool,
pub request_headers: Vec<EdgeHeaderOp>,
pub response_headers: Vec<EdgeHeaderOp>,
pub health_check: Option<EdgeHealthCheck>,
pub access_log: bool,
}
+92
View File
@@ -0,0 +1,92 @@
// 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/.
//! Typed validation errors. Every message names the file and says what is wrong in plain English,
//! so the UI can show it as is.
use std::fmt;
/// One problem found in the route files.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ValidationError {
#[error("{file}: the file is not valid TOML{}: {message}", line_suffix(*line))]
Syntax { file: String, line: Option<usize>, message: String },
#[error("{file}: unknown field `{field}`")]
UnknownField { file: String, field: String },
#[error("{file}: required field `{field}` is missing")]
MissingField { file: String, field: String },
#[error("{file}: {message}")]
InvalidValue { file: String, message: String },
#[error("{file} appears twice in the routes")]
DuplicateFile { file: String },
#[error("{file}: `{hostname}` is not a valid hostname: {reason}")]
InvalidHostname { file: String, hostname: String, reason: &'static str },
#[error("hostname `{hostname}` is defined twice: in {first} and in {second}")]
DuplicateHostname { hostname: String, first: String, second: String },
#[error("{file}: at least one upstream is needed")]
NoUpstreams { file: String },
#[error("{file}: upstream `{url}` is not usable: {reason}")]
BadUpstreamUrl { file: String, url: String, reason: &'static str },
#[error("{file}: upstream `{url}` is listed twice")]
DuplicateUpstream { file: String, url: String },
#[error("{file}: secret `{secret}` is used but not declared in the site file")]
UndefinedSecret { file: String, secret: String },
#[error("{file}: response header `{header}` may not use a secret; secrets only go to upstreams")]
SecretInResponseHeader { file: String, header: String },
#[error("{file}: `{name}` is not a valid secret name (use a-z, 0-9, '_' and '-', at most 64 characters)")]
InvalidSecretName { file: String, name: String },
#[error("{file}: `{name}` is not a valid header name")]
InvalidHeaderName { file: String, name: String },
#[error("{file}: value for header `{header}` is not allowed: {reason}")]
InvalidHeaderValue { file: String, header: String, reason: &'static str },
#[error("{file}: header `{header}` is managed by the proxy and cannot be changed by a rule")]
ProtectedHeader { file: String, header: String },
#[error("{file}: header `{header}` has more than one rule in the same list")]
DuplicateHeaderRule { file: String, header: String },
#[error("{file}: rule for header `{header}` is incomplete: {reason}")]
BadHeaderRule { file: String, header: String, reason: &'static str },
#[error("{file}: health check is not usable: {reason}")]
BadHealthCheck { file: String, reason: &'static str },
#[error("{file}: auth = \"forward-auth\" needs a [forward_auth] section in the site file")]
ForwardAuthNotConfigured { file: String },
#[error("{file}: forward_auth is not usable: {reason}")]
BadForwardAuth { file: String, reason: &'static str },
#[error("{file}: acme is not usable: {reason}")]
BadAcme { file: String, reason: &'static str },
}
fn line_suffix(line: Option<usize>) -> String {
match line {
Some(l) => format!(" (line {l})"),
None => String::new(),
}
}
/// All problems found in one load, in a stable order (file by file, then hostname checks).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationErrors(pub(crate) Vec<ValidationError>);
impl ValidationErrors {
pub fn errors(&self) -> &[ValidationError] {
&self.0
}
pub fn into_errors(self) -> Vec<ValidationError> {
self.0
}
}
impl fmt::Display for ValidationErrors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, e) in self.0.iter().enumerate() {
if i > 0 {
writeln!(f)?;
}
write!(f, "{e}")?;
}
Ok(())
}
}
impl std::error::Error for ValidationErrors {}
+18
View File
@@ -3,3 +3,21 @@
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Ianitor core: host-file model, validation and compilers. Pure: no I/O, no network.
//!
//! The routes repo holds `ianitor.toml` (site settings) and one TOML file per host.
//! [`load`] turns them into a validated [`Model`]; [`compile::edge`] and [`compile::caddy`]
//! turn the model into the configs of the two engines.
pub mod compile;
pub mod edge_config;
mod error;
mod model;
mod validate;
pub use error::{ValidationError, ValidationErrors};
pub use model::{
AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, HealthCheck, Host, Hostname,
Model, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost, AUTHELIA_COPY_HEADERS,
LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING,
};
pub use validate::{load, SourceFile};
+225
View File
@@ -0,0 +1,225 @@
// 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/.
//! The validated model. Values of these types only come out of [`crate::load`], so every
//! compiler can rely on them being valid: the structs are `#[non_exhaustive]` and cannot be
//! built outside this crate.
use std::collections::BTreeSet;
use std::fmt;
/// A validated, lowercase DNS hostname (no wildcard, no trailing dot, not an IP address).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Hostname(pub(crate) String);
impl Hostname {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for Hostname {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
/// A validated secret name. It is also the credential file name under `$CREDENTIALS_DIRECTORY`,
/// so it can never contain a path separator.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SecretName(pub(crate) String);
impl SecretName {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for SecretName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl From<&str> for SecretName {
/// For tests and comparisons only; validation happens in [`crate::load`].
fn from(s: &str) -> Self {
SecretName(s.to_owned())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Scheme {
Http,
Https,
}
impl Scheme {
pub fn as_str(self) -> &'static str {
match self {
Scheme::Http => "http",
Scheme::Https => "https",
}
}
}
/// Where the upstream host is: a DNS name or an IP literal (IPv6 without brackets).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum UpstreamHost {
Name(String),
Ip(std::net::IpAddr),
}
/// A validated upstream: scheme, host and explicit port. No path, query, fragment or userinfo.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub struct Upstream {
pub scheme: Scheme,
pub host: UpstreamHost,
pub port: u16,
}
impl Upstream {
/// `host:port` as used for dialing, with IPv6 in brackets.
pub fn authority(&self) -> String {
match &self.host {
UpstreamHost::Name(n) => format!("{n}:{}", self.port),
UpstreamHost::Ip(std::net::IpAddr::V6(ip)) => format!("[{ip}]:{}", self.port),
UpstreamHost::Ip(ip) => format!("{ip}:{}", self.port),
}
}
/// The host part for TLS SNI and certificate verification.
pub fn host_str(&self) -> String {
match &self.host {
UpstreamHost::Name(n) => n.clone(),
UpstreamHost::Ip(ip) => ip.to_string(),
}
}
}
impl fmt::Display for Upstream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}://{}", self.scheme.as_str(), self.authority())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TlsMode {
/// Public certificate from Let's Encrypt via ACME (HTTP-01).
LetsEncrypt,
/// Certificate issued by the Domi CA, read from the certificate directory.
Domi,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthMode {
None,
/// Every request is first checked with the site's forward-auth endpoint (Authelia).
ForwardAuth,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccessLog {
Off,
/// Logged with IPv4 truncated to /24 and IPv6 to /48.
Truncated,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HeaderValue {
Literal(String),
/// Resolved by the engine at load time; never part of any compiled output.
Secret(SecretName),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HeaderRule {
Set { name: String, value: HeaderValue },
Remove { name: String },
}
impl HeaderRule {
pub fn name(&self) -> &str {
match self {
HeaderRule::Set { name, .. } | HeaderRule::Remove { name } => name,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HealthCheck {
pub path: String,
pub interval_secs: u32,
}
/// One validated host file.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Host {
pub hostname: Hostname,
/// The route file this host came from, for messages.
pub source: String,
pub upstreams: Vec<Upstream>,
pub tls: TlsMode,
pub auth: AuthMode,
pub request_headers: Vec<HeaderRule>,
pub response_headers: Vec<HeaderRule>,
pub websockets: bool,
pub health_check: Option<HealthCheck>,
pub share_links: bool,
pub access_log: AccessLog,
}
/// The forward-auth endpoint (Authelia's `/api/authz/forward-auth`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ForwardAuth {
pub upstream: Upstream,
/// Path plus optional query, e.g. `/api/authz/forward-auth`.
pub path_and_query: String,
/// Headers copied from a 2xx auth response onto the upstream request.
pub copy_headers: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Acme {
pub email: Option<String>,
pub directory: String,
}
/// Site-wide settings from `ianitor.toml`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Site {
pub secrets: BTreeSet<SecretName>,
pub forward_auth: Option<ForwardAuth>,
pub acme: Acme,
}
/// The whole validated routes tree. Hosts are sorted by hostname.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Model {
pub(crate) site: Site,
pub(crate) hosts: Vec<Host>,
}
impl Model {
pub fn site(&self) -> &Site {
&self.site
}
pub fn hosts(&self) -> &[Host] {
&self.hosts
}
}
/// Let's Encrypt production directory, the default when `[acme] directory` is not set.
pub const LETSENCRYPT_PRODUCTION: &str = "https://acme-v02.api.letsencrypt.org/directory";
/// Let's Encrypt staging directory.
pub const LETSENCRYPT_STAGING: &str = "https://acme-staging-v02.api.letsencrypt.org/directory";
/// Identity headers Authelia returns on success (Authelia's Caddy integration guide).
pub const AUTHELIA_COPY_HEADERS: [&str; 4] = ["Remote-User", "Remote-Groups", "Remote-Email", "Remote-Name"];
+20
View File
@@ -0,0 +1,20 @@
// 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/.
//! Parsing and validation of the routes tree.
use crate::{Model, ValidationErrors};
/// One route file handed in by the caller (core does no I/O).
#[derive(Debug, Clone, Copy)]
pub struct SourceFile<'a> {
pub name: &'a str,
pub contents: &'a str,
}
/// Parse and validate the site file and every host file.
pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result<Model, ValidationErrors> {
let _ = (site, hosts);
Err(ValidationErrors(Vec::new()))
}