[repo] Merge: Phase 2 control plane (PR #3)
This commit was merged in pull request #3.
This commit is contained in:
@@ -65,8 +65,11 @@ expect_staged() {
|
||||
|
||||
B='-----BEGIN'
|
||||
E='-----END'
|
||||
mkdir -p "$WORK/../ianitor-hook-src.$$" && SRC="$WORK/../ianitor-hook-src.$$"
|
||||
trap 'rm -rf "$WORK" "$SRC"' EXIT INT TERM
|
||||
# An absolute path next to $WORK (not "$WORK/..", which no longer resolves once $WORK is gone),
|
||||
# removed first.
|
||||
SRC="$(dirname "$WORK")/ianitor-hook-src.$$"
|
||||
mkdir -p "$SRC" || exit 2
|
||||
trap 'rm -rf "$SRC" "$WORK"' EXIT INT TERM
|
||||
printf '%s RSA PRIVATE KEY-----\nMIIBOgIBAAJBAK\n%s RSA PRIVATE KEY-----\n' "$B" "$E" > "$SRC/pem"
|
||||
head -c 6291456 /dev/zero | tr '\000' 'a' > "$SRC/six-mb"
|
||||
|
||||
|
||||
Generated
+180
@@ -219,6 +219,56 @@ version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "axum"
|
||||
version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
|
||||
dependencies = [
|
||||
"axum-core",
|
||||
"bytes",
|
||||
"form_urlencoded",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"itoa",
|
||||
"matchit",
|
||||
"memchr",
|
||||
"mime",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"serde_core",
|
||||
"serde_json",
|
||||
"serde_path_to_error",
|
||||
"serde_urlencoded",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "axum-core"
|
||||
version = "0.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"mime",
|
||||
"pin-project-lite",
|
||||
"sync_wrapper",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
@@ -1005,15 +1055,37 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "ianitor-control"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"http",
|
||||
"ianitor-core",
|
||||
"ianitor-edge",
|
||||
"ianitor-testkit",
|
||||
"log",
|
||||
"rcgen",
|
||||
"ring",
|
||||
"rustls",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"toml",
|
||||
"utoipa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ianitor-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"ring",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"toml",
|
||||
"unicode-normalization",
|
||||
"url",
|
||||
]
|
||||
|
||||
@@ -1021,6 +1093,7 @@ dependencies = [
|
||||
name = "ianitor-diff"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"ianitor-control",
|
||||
"ianitor-core",
|
||||
"ianitor-edge",
|
||||
"ianitor-testkit",
|
||||
@@ -1036,12 +1109,17 @@ dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"form_urlencoded",
|
||||
"http",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"ianitor-core",
|
||||
"ianitor-testkit",
|
||||
"instant-acme",
|
||||
"log",
|
||||
"pingora",
|
||||
"ring",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"serde",
|
||||
@@ -1192,6 +1270,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown 0.17.1",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1343,6 +1423,12 @@ dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "matchit"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
@@ -1358,6 +1444,12 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1"
|
||||
|
||||
[[package]]
|
||||
name = "minimal-lexical"
|
||||
version = "0.2.1"
|
||||
@@ -2311,6 +2403,17 @@ dependencies = [
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_path_to_error"
|
||||
version = "0.1.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_spanned"
|
||||
version = "1.1.3"
|
||||
@@ -2320,6 +2423,18 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_urlencoded"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
|
||||
dependencies = [
|
||||
"form_urlencoded",
|
||||
"itoa",
|
||||
"ryu",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_yaml"
|
||||
version = "0.9.34+deprecated"
|
||||
@@ -2488,6 +2603,12 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sync_wrapper"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
|
||||
|
||||
[[package]]
|
||||
name = "synstructure"
|
||||
version = "0.13.2"
|
||||
@@ -2608,6 +2729,12 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec"
|
||||
version = "1.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.54.1"
|
||||
@@ -2733,6 +2860,27 @@ version = "1.2.0+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
|
||||
|
||||
[[package]]
|
||||
name = "tower"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"pin-project-lite",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-layer"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
|
||||
|
||||
[[package]]
|
||||
name = "tower-service"
|
||||
version = "0.3.3"
|
||||
@@ -2798,6 +2946,15 @@ version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-normalization"
|
||||
version = "0.1.26"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
|
||||
dependencies = [
|
||||
"tinyvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unsafe-libyaml"
|
||||
version = "0.2.11"
|
||||
@@ -2843,6 +3000,29 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6"
|
||||
|
||||
[[package]]
|
||||
name = "utoipa"
|
||||
version = "5.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8bde15df68e80b16c7d16b9616e80770ad158988daa56a27dccd1e55558b0160"
|
||||
dependencies = [
|
||||
"indexmap 2.14.2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"utoipa-gen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utoipa-gen"
|
||||
version = "5.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ba0b99ee52df3028635d93840c797102da61f8a7bb3cf751032455895b52ef8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
|
||||
+3
-1
@@ -5,7 +5,7 @@ members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
rust-version = "1.89"
|
||||
license = "MPL-2.0"
|
||||
publish = false
|
||||
|
||||
@@ -18,6 +18,8 @@ serde_json = "1.0.145"
|
||||
toml = "1.2.1"
|
||||
thiserror = "2.0.17"
|
||||
url = "2.5.7"
|
||||
ring = "0.17.14"
|
||||
base64 = "0.22.1"
|
||||
tokio = { version = "1.48", features = ["full"] }
|
||||
bytes = "1.10"
|
||||
http = "1.3"
|
||||
|
||||
@@ -1,15 +1,41 @@
|
||||
[package]
|
||||
name = "ianitor-control"
|
||||
description = "Ianitor Domi control plane (API, routes repo, apply/rollback). Placeholder until phase 2."
|
||||
description = "Ianitor Domi control plane: routes repo, apply with automatic rollback, share links, API tokens, REST API on loopback."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "ianitor_control"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ianitor-control"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ianitor-core.workspace = true
|
||||
axum = { version = "0.8.9", default-features = false, features = ["http1", "json", "query", "tokio", "matched-path"] }
|
||||
utoipa = "5"
|
||||
tokio.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
toml.workspace = true
|
||||
thiserror.workspace = true
|
||||
log.workspace = true
|
||||
ring.workspace = true
|
||||
base64.workspace = true
|
||||
http.workspace = true
|
||||
bytes.workspace = true
|
||||
# Dev mode only: a throw-away CA for the dev hosts (the Domi CA arrives in phase 3).
|
||||
rcgen.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
ianitor-testkit.workspace = true
|
||||
ianitor-edge.workspace = true
|
||||
rustls.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,521 @@
|
||||
// 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 REST + JSON API on loopback (`/api/v1`), with its OpenAPI document generated from the
|
||||
//! handlers (utoipa).
|
||||
//!
|
||||
//! Every request: the `Host` header must name this server (against DNS rebinding); a browser
|
||||
//! write without `X-Ianitor-UI: 1` is refused (CSRF); a valid `Authorization: Bearer` API
|
||||
//! token is required (nothing else identifies the caller: control trusts no `Remote-*`
|
||||
//! header); 120 requests a minute per token. Bodies are at most 64 KiB, JSON, with no
|
||||
//! unknown fields. Errors are one typed envelope with a plain-English message. Logs show
|
||||
//! method, route template, status and time only.
|
||||
|
||||
// An error answer is built once per failed request; boxing it buys nothing.
|
||||
#![allow(clippy::result_large_err)]
|
||||
|
||||
pub mod handlers;
|
||||
pub mod views;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Instant;
|
||||
|
||||
use axum::Router;
|
||||
use axum::body::{Body as AxumBody, Bytes};
|
||||
use axum::extract::{DefaultBodyLimit, FromRequest, MatchedPath, Request, State};
|
||||
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||
use axum::middleware::{self, Next};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{delete, get, post};
|
||||
use serde::de::DeserializeOwned;
|
||||
use utoipa::OpenApi;
|
||||
|
||||
pub use views::health_state;
|
||||
|
||||
use crate::engine::{Control, Fail};
|
||||
use crate::messages::{self, Params, message};
|
||||
use crate::tokens::Refusal;
|
||||
use crate::util::{hex, now, random, rfc3339, sha256_hex};
|
||||
use views::{ErrorBody, ErrorEnvelope};
|
||||
|
||||
pub const MAX_BODY: usize = 64 * 1024;
|
||||
const RATE_PER_MINUTE: u32 = 120;
|
||||
|
||||
/// Who is calling: the API token's id and name.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Actor {
|
||||
pub token_id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
pub enum Stored {
|
||||
/// The first request with this key is still being handled.
|
||||
Pending,
|
||||
Apply(String),
|
||||
Json(u16, serde_json::Value),
|
||||
}
|
||||
|
||||
/// Most Idempotency-Keys held at once (each for 24 h).
|
||||
const MAX_IDEM_KEYS: usize = 2000;
|
||||
|
||||
pub struct AppState {
|
||||
pub ctl: Arc<Control>,
|
||||
idem: Mutex<HashMap<String, (String, Stored, u64)>>,
|
||||
rate: Mutex<HashMap<String, (u64, u32)>>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(ctl: Arc<Control>) -> Arc<AppState> {
|
||||
Arc::new(AppState {
|
||||
ctl,
|
||||
idem: Mutex::new(HashMap::new()),
|
||||
rate: Mutex::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Count one request against `bucket`; `Err(seconds to wait)` over the limit.
|
||||
pub fn limit(&self, bucket: &str, per_window: u32, window: u64) -> Result<(), u64> {
|
||||
let Ok(mut m) = self.rate.lock() else {
|
||||
return Ok(());
|
||||
};
|
||||
let t = now();
|
||||
let slot = t / window;
|
||||
if m.len() > 10_000 {
|
||||
m.retain(|_, (s, _)| *s + 1 >= slot);
|
||||
}
|
||||
let e = m.entry(bucket.to_owned()).or_insert((slot, 0));
|
||||
if e.0 != slot {
|
||||
*e = (slot, 0);
|
||||
}
|
||||
if e.1 >= per_window {
|
||||
return Err((slot + 1) * window - t);
|
||||
}
|
||||
e.1 += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start a request with an Idempotency-Key, atomically: `Ok(Some)` replays an earlier
|
||||
/// answer, `Ok(None)` reserves the key (finish with [`AppState::idem_finish`]), `Err` when
|
||||
/// the key was used for another request, is still in progress, or no key can be held.
|
||||
pub fn idem_begin(&self, key: &str, fingerprint: &str) -> Result<Option<Stored>, ApiError> {
|
||||
let mut m = self
|
||||
.idem
|
||||
.lock()
|
||||
.map_err(|_| ApiError::internal("idempotency store"))?;
|
||||
let t = now();
|
||||
match m.get(key) {
|
||||
Some((fp, _, at)) if t.saturating_sub(*at) < 86_400 && fp != fingerprint => {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"request.idempotency",
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
Some((_, Stored::Pending, at)) if t.saturating_sub(*at) < 86_400 => {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::CONFLICT,
|
||||
"request.in_progress",
|
||||
Params::new(),
|
||||
)
|
||||
.retry(1));
|
||||
}
|
||||
Some((_, Stored::Apply(id), at)) if t.saturating_sub(*at) < 86_400 => {
|
||||
return Ok(Some(Stored::Apply(id.clone())));
|
||||
}
|
||||
Some((_, Stored::Json(s, v), at)) if t.saturating_sub(*at) < 86_400 => {
|
||||
return Ok(Some(Stored::Json(*s, v.clone())));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if m.len() >= MAX_IDEM_KEYS {
|
||||
m.retain(|_, (_, _, at)| t.saturating_sub(*at) < 86_400);
|
||||
}
|
||||
if m.len() >= MAX_IDEM_KEYS {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"rate.limited",
|
||||
Params::new(),
|
||||
)
|
||||
.retry(60));
|
||||
}
|
||||
m.insert(key.to_owned(), (fingerprint.to_owned(), Stored::Pending, t));
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Finish a reserved key: remember the answer, or (on `None`, a refusal) free the key.
|
||||
pub fn idem_finish(&self, key: &str, fingerprint: &str, s: Option<Stored>) {
|
||||
if let Ok(mut m) = self.idem.lock() {
|
||||
match s {
|
||||
Some(s) => {
|
||||
m.insert(key.to_owned(), (fingerprint.to_owned(), s, now()));
|
||||
}
|
||||
None => {
|
||||
m.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- errors
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ApiError {
|
||||
pub status: StatusCode,
|
||||
pub body: ErrorBody,
|
||||
pub errors: Vec<ErrorBody>,
|
||||
}
|
||||
|
||||
impl ApiError {
|
||||
pub fn new(status: StatusCode, code: &str, params: Params) -> ApiError {
|
||||
ApiError {
|
||||
status,
|
||||
body: ErrorBody {
|
||||
code: code.into(),
|
||||
message: message(code, ¶ms),
|
||||
field: params.get("field").cloned(),
|
||||
params,
|
||||
retry_after_s: None,
|
||||
detail: None,
|
||||
},
|
||||
errors: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn internal(detail: impl Into<String>) -> ApiError {
|
||||
let mut e = ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", Params::new());
|
||||
e.body.detail = Some(detail.into());
|
||||
e
|
||||
}
|
||||
|
||||
pub fn retry(mut self, secs: u64) -> ApiError {
|
||||
self.body.retry_after_s = Some(secs);
|
||||
self.body.params.insert("seconds".into(), secs.to_string());
|
||||
self.body.message = message(&self.body.code, &self.body.params);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Fail> for ApiError {
|
||||
fn from(f: Fail) -> ApiError {
|
||||
ApiError {
|
||||
status: StatusCode::from_u16(f.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
body: ErrorBody::from(&f.reason),
|
||||
errors: f.errors.iter().map(ErrorBody::from).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
let retry = self.body.retry_after_s;
|
||||
let env = ErrorEnvelope {
|
||||
error: self.body,
|
||||
errors: self.errors,
|
||||
request_id: String::new(),
|
||||
};
|
||||
let mut r = (self.status, axum::Json(env)).into_response();
|
||||
if let Some(s) = retry
|
||||
&& let Ok(v) = HeaderValue::from_str(&s.to_string())
|
||||
{
|
||||
r.headers_mut().insert(header::RETRY_AFTER, v);
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- JSON bodies
|
||||
|
||||
/// A JSON request body: at most 64 KiB, no unknown fields, errors that never echo values.
|
||||
pub struct Body<T> {
|
||||
pub value: T,
|
||||
pub raw: Bytes,
|
||||
}
|
||||
|
||||
impl<T: DeserializeOwned, S: Send + Sync> FromRequest<S> for Body<T> {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request(req: Request, state: &S) -> Result<Self, ApiError> {
|
||||
let json_type = req
|
||||
.headers()
|
||||
.get(header::CONTENT_TYPE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.is_some_and(|v| v.starts_with("application/json"));
|
||||
let raw = Bytes::from_request(req, state).await.map_err(|_| {
|
||||
ApiError::new(
|
||||
StatusCode::PAYLOAD_TOO_LARGE,
|
||||
"request.too_large",
|
||||
Params::new(),
|
||||
)
|
||||
})?;
|
||||
let text: &[u8] = if raw.is_empty() { b"{}" } else { &raw };
|
||||
if !raw.is_empty() && !json_type {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::UNSUPPORTED_MEDIA_TYPE,
|
||||
"request.body",
|
||||
messages::params([("problem", "send it as application/json.".into())]),
|
||||
));
|
||||
}
|
||||
match serde_json::from_slice::<T>(text) {
|
||||
Ok(value) => Ok(Body { value, raw }),
|
||||
Err(e) => Err(body_error(&e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn body_error(e: &serde_json::Error) -> ApiError {
|
||||
let m = e.to_string();
|
||||
let quoted = |prefix: &str| -> Option<String> {
|
||||
let rest = m.split(prefix).nth(1)?;
|
||||
Some(rest.split('`').next()?.to_owned())
|
||||
};
|
||||
if let Some(f) = quoted("unknown field `") {
|
||||
// The name is the sender's: repeat it only if it is a plain field name.
|
||||
let plain = !f.is_empty()
|
||||
&& f.len() <= 64
|
||||
&& f.bytes()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_');
|
||||
let shown = if plain {
|
||||
f
|
||||
} else {
|
||||
"(a field name)".to_owned()
|
||||
};
|
||||
let mut err = ApiError::new(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"request.body_unknown_field",
|
||||
messages::params([("field", shown.clone())]),
|
||||
);
|
||||
err.body.field = plain.then_some(shown);
|
||||
return err;
|
||||
}
|
||||
if let Some(f) = quoted("missing field `") {
|
||||
return ApiError::new(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"request.body",
|
||||
messages::params([
|
||||
("problem", format!("the field \"{f}\" is missing.")),
|
||||
("field", f),
|
||||
]),
|
||||
);
|
||||
}
|
||||
// Other serde messages can quote the value sent; say only where the problem is.
|
||||
let what = match e.classify() {
|
||||
serde_json::error::Category::Syntax | serde_json::error::Category::Eof => "it is not JSON",
|
||||
_ => "a value has the wrong type or form",
|
||||
};
|
||||
ApiError::new(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"request.body",
|
||||
messages::params([(
|
||||
"problem",
|
||||
format!("{what} (line {}, column {}).", e.line(), e.column()),
|
||||
)]),
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- middleware
|
||||
|
||||
fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
|
||||
let Some(host) = headers.get(header::HOST).and_then(|h| h.to_str().ok()) else {
|
||||
return false;
|
||||
};
|
||||
let port = ctl.cfg.listen.port();
|
||||
let ok = [
|
||||
ctl.cfg.listen.to_string(),
|
||||
format!("localhost:{port}"),
|
||||
format!("127.0.0.1:{port}"),
|
||||
format!("[::1]:{port}"),
|
||||
];
|
||||
ok.iter().any(|o| o.eq_ignore_ascii_case(host))
|
||||
|| ctl
|
||||
.cfg
|
||||
.allowed_hosts
|
||||
.iter()
|
||||
.any(|a| a.eq_ignore_ascii_case(host))
|
||||
}
|
||||
|
||||
/// Host check, CSRF check, token, rate limit; logs method, route template, status, time.
|
||||
async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) -> Response {
|
||||
let started = Instant::now();
|
||||
let method = req.method().clone();
|
||||
let route = req
|
||||
.extensions()
|
||||
.get::<MatchedPath>()
|
||||
.map(|p| p.as_str().to_owned())
|
||||
.unwrap_or_else(|| "(no route)".into());
|
||||
let resp = async {
|
||||
if !host_allowed(&st.ctl, req.headers()) {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
"request.host",
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
let browser = req.headers().contains_key(header::ORIGIN)
|
||||
|| req.headers().contains_key("sec-fetch-site");
|
||||
let write = !matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS");
|
||||
let ui = req
|
||||
.headers()
|
||||
.get("x-ianitor-ui")
|
||||
.is_some_and(|v| v.as_bytes() == b"1");
|
||||
if browser && write && !ui {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
"request.csrf",
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
let auth = req
|
||||
.headers()
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::to_owned);
|
||||
// The token store takes a file lock: off the async threads.
|
||||
let ctl = st.ctl.clone();
|
||||
let checked = tokio::task::spawn_blocking(move || ctl.tokens.check(auth.as_deref()))
|
||||
.await
|
||||
.unwrap_or(Err(Refusal::Unknown));
|
||||
let tok = checked.map_err(|r| {
|
||||
let (code, params) = match r {
|
||||
Refusal::Missing => ("token.missing", Params::new()),
|
||||
Refusal::Unknown => ("token.unknown", Params::new()),
|
||||
Refusal::Expired(t) => (
|
||||
"token.expired",
|
||||
messages::params([("date", ianitor_core::time::long_date(t))]),
|
||||
),
|
||||
Refusal::Revoked(t) => (
|
||||
"token.revoked",
|
||||
messages::params([("date", ianitor_core::time::long_date(t))]),
|
||||
),
|
||||
};
|
||||
ApiError::new(StatusCode::UNAUTHORIZED, code, params)
|
||||
})?;
|
||||
st.limit(&format!("token:{}", tok.id), RATE_PER_MINUTE, 60)
|
||||
.map_err(|s| {
|
||||
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
|
||||
})?;
|
||||
req.extensions_mut().insert(Actor {
|
||||
token_id: tok.id,
|
||||
name: tok.name,
|
||||
});
|
||||
Ok(next.run(req).await)
|
||||
}
|
||||
.await;
|
||||
let resp = resp.unwrap_or_else(IntoResponse::into_response);
|
||||
log::info!(target: "ianitor::api", "{method} {route} {} {} ms", resp.status().as_u16(), started.elapsed().as_millis());
|
||||
resp
|
||||
}
|
||||
|
||||
/// Adds `server_time` to every JSON object answer and `request_id` to error envelopes.
|
||||
async fn finish(req: Request, next: Next) -> Response {
|
||||
let request_id = random::<8>().map(|b| hex(&b)).unwrap_or_default();
|
||||
let resp = next.run(req).await;
|
||||
let json = resp
|
||||
.headers()
|
||||
.get(header::CONTENT_TYPE)
|
||||
.is_some_and(|v| v.as_bytes().starts_with(b"application/json"));
|
||||
let (mut parts, body) = resp.into_parts();
|
||||
if let Ok(v) = HeaderValue::from_str(&request_id) {
|
||||
parts.headers.insert("x-request-id", v);
|
||||
}
|
||||
if !json {
|
||||
return Response::from_parts(parts, body);
|
||||
}
|
||||
let Ok(bytes) = axum::body::to_bytes(body, 16 << 20).await else {
|
||||
return Response::from_parts(parts, AxumBody::empty());
|
||||
};
|
||||
let out = match serde_json::from_slice::<serde_json::Value>(&bytes) {
|
||||
Ok(serde_json::Value::Object(mut m)) => {
|
||||
m.insert("server_time".into(), rfc3339(now()).into());
|
||||
if m.contains_key("error") {
|
||||
m.insert("request_id".into(), request_id.into());
|
||||
}
|
||||
serde_json::to_vec(&m).unwrap_or_else(|_| bytes.to_vec())
|
||||
}
|
||||
_ => bytes.to_vec(),
|
||||
};
|
||||
parts.headers.remove(header::CONTENT_LENGTH);
|
||||
Response::from_parts(parts, AxumBody::from(out))
|
||||
}
|
||||
|
||||
async fn not_found() -> ApiError {
|
||||
ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
|
||||
}
|
||||
|
||||
async fn method_not_allowed() -> ApiError {
|
||||
ApiError::new(
|
||||
StatusCode::METHOD_NOT_ALLOWED,
|
||||
"request.method",
|
||||
Params::new(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn fingerprint(method: &str, path: &str, raw: &[u8]) -> String {
|
||||
sha256_hex(format!("{method} {path} {}", sha256_hex(raw)).as_bytes())
|
||||
}
|
||||
|
||||
pub fn router(st: Arc<AppState>) -> Router {
|
||||
use handlers as h;
|
||||
let api = Router::new()
|
||||
.route("/api/v1/overview", get(h::overview))
|
||||
.route("/api/v1/hosts", get(h::list_hosts).post(h::create_host))
|
||||
.route("/api/v1/hosts/validate", post(h::validate_host))
|
||||
.route(
|
||||
"/api/v1/hosts/{hostname}",
|
||||
get(h::get_host)
|
||||
.put(h::update_host)
|
||||
.patch(h::patch_host)
|
||||
.delete(h::delete_host),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/hosts/{hostname}/share-links",
|
||||
post(h::mint_share_link),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/hosts/{hostname}/certificate/retry",
|
||||
post(h::retry_certificate),
|
||||
)
|
||||
.route("/api/v1/applies", get(h::list_applies))
|
||||
.route(
|
||||
"/api/v1/applies/{id}",
|
||||
get(h::get_apply).delete(h::cancel_apply),
|
||||
)
|
||||
.route("/api/v1/history", get(h::history))
|
||||
.route("/api/v1/history/{change_id}", get(h::history_entry))
|
||||
.route(
|
||||
"/api/v1/history/{change_id}/restore-preview",
|
||||
get(h::restore_preview),
|
||||
)
|
||||
.route("/api/v1/undo", get(h::get_undo).post(h::undo))
|
||||
.route("/api/v1/restore", post(h::restore))
|
||||
.route("/api/v1/repo/push", post(h::push_now))
|
||||
.route("/api/v1/settings", get(h::settings))
|
||||
.route("/api/v1/tokens", get(h::list_tokens).post(h::create_token))
|
||||
.route(
|
||||
"/api/v1/tokens/{id}",
|
||||
delete(h::revoke_token).patch(h::rename_token),
|
||||
)
|
||||
.route("/api/v1/share-links", get(h::list_share_links))
|
||||
.route(
|
||||
"/api/v1/share-links/stop-all",
|
||||
post(h::stop_all_share_links),
|
||||
)
|
||||
.route("/api/v1/share-links/{id}", delete(h::stop_share_link))
|
||||
.route("/api/v1/health", get(h::health))
|
||||
.route("/api/v1/openapi.json", get(h::openapi))
|
||||
.method_not_allowed_fallback(method_not_allowed)
|
||||
.fallback(not_found)
|
||||
.layer(middleware::from_fn_with_state(st.clone(), guard))
|
||||
.layer(DefaultBodyLimit::max(MAX_BODY))
|
||||
.with_state(st);
|
||||
api.layer(middleware::from_fn(finish))
|
||||
}
|
||||
|
||||
/// The OpenAPI document.
|
||||
pub fn openapi_json() -> String {
|
||||
handlers::ApiDoc::openapi()
|
||||
.to_pretty_json()
|
||||
.unwrap_or_else(|_| "{}".into())
|
||||
}
|
||||
@@ -0,0 +1,797 @@
|
||||
// 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/.
|
||||
|
||||
//! Response shapes (docs/ui-api.md §1, §2), built from control's state. Times are RFC 3339
|
||||
//! UTC; every JSON object answer also gets `server_time` from the API layer.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::edgelink::{EdgeStatus, HostStatus};
|
||||
use crate::engine::Control;
|
||||
use crate::hostspec::HostSpec;
|
||||
use crate::messages::{self, message};
|
||||
use crate::records::{ApplyRecord, FieldError, Reason, Step, WatchHost};
|
||||
use crate::util::{now, rfc3339};
|
||||
|
||||
fn t(x: Option<u64>) -> Option<String> {
|
||||
x.map(rfc3339)
|
||||
}
|
||||
|
||||
fn short(id: &Option<String>) -> Option<String> {
|
||||
id.as_ref().map(|c| c.chars().take(7).collect())
|
||||
}
|
||||
|
||||
/// One error, as the UI shows it (docs/ui-api.md §0).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
|
||||
pub struct ErrorBody {
|
||||
/// Stable code, e.g. `host.upstream.no_port`.
|
||||
pub code: String,
|
||||
/// Plain English, shown as is.
|
||||
pub message: String,
|
||||
/// The form field, e.g. `upstreams[0]`.
|
||||
pub field: Option<String>,
|
||||
pub params: BTreeMap<String, String>,
|
||||
pub retry_after_s: Option<u64>,
|
||||
/// Technical detail, behind "Show details". Never a secret.
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
|
||||
impl From<&FieldError> for ErrorBody {
|
||||
fn from(e: &FieldError) -> Self {
|
||||
ErrorBody {
|
||||
code: e.code.clone(),
|
||||
message: e.message.clone(),
|
||||
field: e.field.clone(),
|
||||
params: e.params.clone(),
|
||||
retry_after_s: None,
|
||||
detail: e.detail.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Reason> for ErrorBody {
|
||||
fn from(r: &Reason) -> Self {
|
||||
ErrorBody {
|
||||
code: r.code.clone(),
|
||||
message: r.message.clone(),
|
||||
field: r.field.clone(),
|
||||
params: r.params.clone(),
|
||||
retry_after_s: None,
|
||||
detail: r.detail.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct ErrorEnvelope {
|
||||
pub error: ErrorBody,
|
||||
pub errors: Vec<ErrorBody>,
|
||||
pub request_id: String,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- applies
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct WaitingFor {
|
||||
pub apply_id: String,
|
||||
pub summary: String,
|
||||
pub seconds_left: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct QueueView {
|
||||
pub position: usize,
|
||||
pub waiting_for: Option<WaitingFor>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct WatchView {
|
||||
pub ends_at: String,
|
||||
pub seconds_left: u64,
|
||||
pub hosts: Vec<WatchHost>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct PushView {
|
||||
/// `pushed`, `pending` or `failed`.
|
||||
pub state: String,
|
||||
pub at: Option<String>,
|
||||
pub error_code: Option<String>,
|
||||
pub next_try_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct ApplyView {
|
||||
pub id: String,
|
||||
pub change_id: String,
|
||||
/// `add`, `edit`, `remove`, `undo`, `restore` or `share_links`.
|
||||
pub kind: String,
|
||||
pub summary: String,
|
||||
pub hosts: Vec<String>,
|
||||
/// `queued`, `validating`, `applying`, `watching`, `kept`, `reverted`, `failed` or
|
||||
/// `needs_attention`.
|
||||
pub state: String,
|
||||
pub created_at: String,
|
||||
pub started_at: Option<String>,
|
||||
pub finished_at: Option<String>,
|
||||
pub steps: Vec<Step>,
|
||||
pub queue: Option<QueueView>,
|
||||
pub watch: Option<WatchView>,
|
||||
pub reason: Option<Reason>,
|
||||
pub errors: Vec<ErrorBody>,
|
||||
pub commit_short: Option<String>,
|
||||
pub commit: Option<String>,
|
||||
pub push: Option<PushView>,
|
||||
pub undo_of: Option<String>,
|
||||
pub restore_of: Option<String>,
|
||||
pub effect: Option<String>,
|
||||
pub attempted_host: Option<HostSpec>,
|
||||
pub actor: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct ApplyAccepted {
|
||||
pub apply: ApplyView,
|
||||
}
|
||||
|
||||
pub fn apply_view(c: &Control, r: &ApplyRecord) -> ApplyView {
|
||||
let n = now();
|
||||
let queue = (r.state == "queued").then(|| {
|
||||
let position = c.queue_position(&r.id).unwrap_or(1);
|
||||
let running = c.records().into_iter().rev().find(|x| x.is_running());
|
||||
QueueView {
|
||||
position,
|
||||
waiting_for: running.map(|x| WaitingFor {
|
||||
apply_id: x.id.clone(),
|
||||
summary: x.summary.clone(),
|
||||
seconds_left: x.watch.as_ref().map(|w| w.ends.saturating_sub(n)),
|
||||
}),
|
||||
}
|
||||
});
|
||||
let push = (r.state == "kept" && r.commit.is_some()).then(|| {
|
||||
let p = c.push_state();
|
||||
let step = r
|
||||
.steps
|
||||
.iter()
|
||||
.find(|s| s.key == "push")
|
||||
.map(|s| s.state.as_str())
|
||||
.unwrap_or("pending");
|
||||
PushView {
|
||||
state: match step {
|
||||
"done" => "pushed",
|
||||
"failed" => "failed",
|
||||
_ if c.cfg.routes.remote.is_none() => "pending",
|
||||
_ if p.error_code.is_some() => "failed",
|
||||
_ => "pending",
|
||||
}
|
||||
.into(),
|
||||
at: t(p.last_push_at),
|
||||
error_code: p.error_code.clone(),
|
||||
next_try_at: t(p.next_try_at),
|
||||
}
|
||||
});
|
||||
ApplyView {
|
||||
id: r.id.clone(),
|
||||
change_id: r.id.clone(),
|
||||
kind: r.kind.clone(),
|
||||
summary: r.summary.clone(),
|
||||
hosts: r.hosts.clone(),
|
||||
state: r.state.clone(),
|
||||
created_at: rfc3339(r.created),
|
||||
started_at: t(r.started),
|
||||
finished_at: t(r.finished),
|
||||
steps: r.steps.clone(),
|
||||
queue,
|
||||
watch: r.watch.as_ref().map(|w| WatchView {
|
||||
ends_at: rfc3339(w.ends),
|
||||
seconds_left: if r.state == "watching" {
|
||||
w.ends.saturating_sub(n)
|
||||
} else {
|
||||
0
|
||||
},
|
||||
hosts: w.hosts.clone(),
|
||||
}),
|
||||
reason: r.reason.clone(),
|
||||
errors: r.errors.iter().map(ErrorBody::from).collect(),
|
||||
commit_short: short(&r.commit),
|
||||
commit: r.commit.clone(),
|
||||
push,
|
||||
undo_of: r.undo_of.clone(),
|
||||
restore_of: r.restore_of.clone(),
|
||||
effect: r.effect.clone(),
|
||||
attempted_host: r.attempted_host.clone(),
|
||||
actor: r.actor.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- health
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct Failure {
|
||||
pub kind: String,
|
||||
pub upstream: String,
|
||||
pub count: u32,
|
||||
pub of: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct UpstreamHealth {
|
||||
pub url: String,
|
||||
/// `healthy`, `down` or `pending`.
|
||||
pub state: String,
|
||||
pub last_check_at: Option<String>,
|
||||
pub latency_ms: Option<u64>,
|
||||
pub failure_kind: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct HealthView {
|
||||
/// `healthy`, `degraded`, `down`, `unknown` or `pending`.
|
||||
pub state: String,
|
||||
pub last_check_at: Option<String>,
|
||||
pub latency_ms: Option<u64>,
|
||||
pub since: Option<String>,
|
||||
pub failure: Option<Failure>,
|
||||
pub upstreams: Vec<UpstreamHealth>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct CertView {
|
||||
/// `ok`, `pending` or `failed`.
|
||||
pub state: String,
|
||||
pub not_after: Option<String>,
|
||||
pub error_code: Option<String>,
|
||||
}
|
||||
|
||||
/// The health word for a host (docs/ui-api.md §1.1): `unknown` without a health check,
|
||||
/// `pending` before the first check, `healthy` when every upstream passed its last check and
|
||||
/// its recent ones, `degraded` when some fail or results are mixed, `down` when none passed.
|
||||
pub fn health_state(h: &HostStatus) -> &'static str {
|
||||
if !h.health_check {
|
||||
return "unknown";
|
||||
}
|
||||
let checks: Vec<Vec<&crate::edgelink::Check>> = h
|
||||
.upstreams
|
||||
.iter()
|
||||
.map(|u| {
|
||||
u.checks
|
||||
.iter()
|
||||
.filter(|c| c.source == "health_check")
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
if checks.iter().all(|c| c.is_empty()) {
|
||||
return "pending";
|
||||
}
|
||||
let last_ok: Vec<bool> = checks
|
||||
.iter()
|
||||
.map(|c| c.last().is_some_and(|x| x.ok))
|
||||
.collect();
|
||||
if !last_ok.iter().any(|x| *x) {
|
||||
return "down";
|
||||
}
|
||||
let mixed = checks
|
||||
.iter()
|
||||
.any(|c| c.iter().any(|x| x.ok) && c.iter().any(|x| !x.ok));
|
||||
if last_ok.iter().all(|x| *x) && !mixed {
|
||||
"healthy"
|
||||
} else {
|
||||
"degraded"
|
||||
}
|
||||
}
|
||||
|
||||
fn scheme_url(spec: Option<&HostSpec>, address: &str) -> String {
|
||||
let scheme = spec
|
||||
.and_then(|s| s.upstreams.first())
|
||||
.and_then(|u| u.split_once("://").map(|(s, _)| s.to_owned()))
|
||||
.unwrap_or_else(|| "http".into());
|
||||
format!("{scheme}://{address}")
|
||||
}
|
||||
|
||||
pub fn health_view(
|
||||
status: Option<&HostStatus>,
|
||||
spec: Option<&HostSpec>,
|
||||
since: Option<(&'static str, u64)>,
|
||||
) -> HealthView {
|
||||
let Some(h) = status else {
|
||||
return HealthView {
|
||||
state: if spec.is_some_and(|s| s.health_check.is_none()) {
|
||||
"unknown"
|
||||
} else {
|
||||
"pending"
|
||||
}
|
||||
.into(),
|
||||
last_check_at: None,
|
||||
latency_ms: None,
|
||||
since: None,
|
||||
failure: None,
|
||||
upstreams: Vec::new(),
|
||||
};
|
||||
};
|
||||
let state = health_state(h);
|
||||
let mut last_at = None;
|
||||
let mut latency = None;
|
||||
let mut failure: Option<Failure> = None;
|
||||
let ups = h
|
||||
.upstreams
|
||||
.iter()
|
||||
.map(|u| {
|
||||
let checks: Vec<_> = u
|
||||
.checks
|
||||
.iter()
|
||||
.filter(|c| c.source == "health_check")
|
||||
.collect();
|
||||
let last = checks.last();
|
||||
if let Some(l) = last {
|
||||
last_at = last_at.max(Some(l.at));
|
||||
if l.ok {
|
||||
latency = match (latency, l.latency_ms) {
|
||||
(Some(a), Some(b)) => Some(u64::min(a, b)),
|
||||
(a, b) => a.or(b),
|
||||
};
|
||||
} else if failure.is_none() {
|
||||
failure = Some(Failure {
|
||||
kind: l.kind.clone().unwrap_or_else(|| "bad_answer".into()),
|
||||
upstream: scheme_url(spec, &u.address),
|
||||
count: checks.iter().filter(|c| !c.ok).count() as u32,
|
||||
of: checks.len() as u32,
|
||||
});
|
||||
}
|
||||
}
|
||||
UpstreamHealth {
|
||||
url: scheme_url(spec, &u.address),
|
||||
state: match last {
|
||||
None => "pending",
|
||||
Some(l) if l.ok => "healthy",
|
||||
Some(_) => "down",
|
||||
}
|
||||
.into(),
|
||||
last_check_at: last.map(|l| rfc3339(l.at)),
|
||||
latency_ms: last.and_then(|l| l.latency_ms),
|
||||
failure_kind: last.and_then(|l| l.kind.clone()),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
HealthView {
|
||||
state: state.into(),
|
||||
last_check_at: t(last_at),
|
||||
latency_ms: latency,
|
||||
since: since
|
||||
.filter(|(s, _)| *s == state)
|
||||
.map(|(_, at)| rfc3339(at)),
|
||||
failure: if matches!(state, "down" | "degraded") {
|
||||
failure
|
||||
} else {
|
||||
None
|
||||
},
|
||||
upstreams: if h.health_check { ups } else { Vec::new() },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cert_view(status: Option<&HostStatus>, spec: Option<&HostSpec>) -> CertView {
|
||||
match status {
|
||||
Some(h) => CertView {
|
||||
state: h.certificate.state.clone(),
|
||||
not_after: h
|
||||
.certificate
|
||||
.not_after
|
||||
.and_then(|x| u64::try_from(x).ok())
|
||||
.map(rfc3339),
|
||||
error_code: (h.certificate.state == "failed").then(|| "cert.failed".into()),
|
||||
},
|
||||
None => CertView {
|
||||
state: if spec.is_some_and(|s| s.tls == "domi") {
|
||||
"ok"
|
||||
} else {
|
||||
"pending"
|
||||
}
|
||||
.into(),
|
||||
not_after: None,
|
||||
error_code: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- hosts and overview
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct HostRow {
|
||||
pub hostname: String,
|
||||
pub upstreams: Vec<String>,
|
||||
pub tls: String,
|
||||
pub auth: String,
|
||||
pub websockets: bool,
|
||||
pub share_links: bool,
|
||||
pub added_at: Option<String>,
|
||||
pub health: HealthView,
|
||||
pub certificate: CertView,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct HostDetail {
|
||||
pub host: HostSpec,
|
||||
/// The routes commit this was read from; send it back as `base_rev`.
|
||||
pub rev: String,
|
||||
/// The host file as committed.
|
||||
pub toml: String,
|
||||
pub health: HealthView,
|
||||
pub certificate: CertView,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct HostList {
|
||||
pub rev: String,
|
||||
pub hosts: Vec<HostRow>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, ToSchema)]
|
||||
pub struct Counts {
|
||||
pub hosts: usize,
|
||||
pub healthy: usize,
|
||||
pub degraded: usize,
|
||||
pub down: usize,
|
||||
pub unknown: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct EngineView {
|
||||
/// `pingora` (the Caddy switch waits on Mark, ROADMAP §10 (b)).
|
||||
pub running: String,
|
||||
/// `running` or `stopped` (control cannot reach it).
|
||||
pub state: String,
|
||||
pub since: Option<String>,
|
||||
#[schema(value_type = Option<Object>)]
|
||||
pub fallback_ready: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct UndoTarget {
|
||||
pub change_id: String,
|
||||
pub summary: String,
|
||||
pub kept_at: Option<String>,
|
||||
pub commit_short: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct Blocked {
|
||||
pub code: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct UndoView {
|
||||
pub available: bool,
|
||||
pub target: Option<UndoTarget>,
|
||||
/// What Undo does, e.g. "Removes recipes.home.example".
|
||||
pub effect: Option<String>,
|
||||
pub blocked: Option<Blocked>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct ActiveApply {
|
||||
pub id: String,
|
||||
pub state: String,
|
||||
pub summary: String,
|
||||
pub seconds_left: Option<u64>,
|
||||
pub queued: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct RepoView {
|
||||
pub name: String,
|
||||
pub last_push_at: Option<String>,
|
||||
pub unpushed: u64,
|
||||
pub push_error_code: Option<String>,
|
||||
pub remote_configured: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct SiteView {
|
||||
pub forward_auth_configured: bool,
|
||||
pub acme_configured: bool,
|
||||
pub secrets: Vec<String>,
|
||||
pub watch_seconds: u64,
|
||||
pub share_links_available: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct Overview {
|
||||
pub counts: Counts,
|
||||
pub hosts: Vec<HostRow>,
|
||||
pub engine: EngineView,
|
||||
pub last_apply: Option<ApplyView>,
|
||||
pub undo: UndoView,
|
||||
pub active_apply: Option<ActiveApply>,
|
||||
pub repo: Option<RepoView>,
|
||||
/// The Domi intermediate; arrives in phase 3.
|
||||
#[schema(value_type = Option<Object>)]
|
||||
pub intermediate: Option<serde_json::Value>,
|
||||
pub site: Option<SiteView>,
|
||||
pub paused: Option<Blocked>,
|
||||
/// Set when control cannot read health from edge (`health.unavailable`).
|
||||
pub health_error: Option<Blocked>,
|
||||
pub rev: Option<String>,
|
||||
}
|
||||
|
||||
pub fn added_at(c: &Control, hostname: &str) -> Option<String> {
|
||||
c.records()
|
||||
.iter()
|
||||
.find(|r| r.kind == "add" && r.state == "kept" && r.hosts.iter().any(|h| h == hostname))
|
||||
.and_then(|r| r.finished)
|
||||
.map(rfc3339)
|
||||
}
|
||||
|
||||
pub fn undo_view(c: &Control) -> UndoView {
|
||||
let blocked = if let Some(p) = c.paused() {
|
||||
Some(Blocked {
|
||||
code: "undo.paused".into(),
|
||||
message: message("undo.paused", &messages::Params::new()) + " " + &p.message,
|
||||
})
|
||||
} else {
|
||||
c.records()
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|r| r.is_running() && r.kind == "undo")
|
||||
.map(|r| {
|
||||
let left = r
|
||||
.watch
|
||||
.as_ref()
|
||||
.map(|w| w.ends.saturating_sub(now()))
|
||||
.unwrap_or(0);
|
||||
Blocked {
|
||||
code: "undo.watching".into(),
|
||||
message: message(
|
||||
"undo.watching",
|
||||
&messages::params([("seconds", left.to_string())]),
|
||||
),
|
||||
}
|
||||
})
|
||||
};
|
||||
match c.undo_target() {
|
||||
None => UndoView {
|
||||
available: false,
|
||||
target: None,
|
||||
effect: None,
|
||||
blocked: Some(blocked.unwrap_or(Blocked {
|
||||
code: "undo.nothing".into(),
|
||||
message: message("undo.nothing", &messages::Params::new()),
|
||||
})),
|
||||
},
|
||||
Some(t) => {
|
||||
let effect = undo_effect(c, &t);
|
||||
UndoView {
|
||||
available: blocked.is_none(),
|
||||
target: Some(UndoTarget {
|
||||
change_id: t.id.clone(),
|
||||
summary: t.summary.clone(),
|
||||
kept_at: t.finished.map(rfc3339),
|
||||
commit_short: short(&t.commit),
|
||||
}),
|
||||
effect,
|
||||
blocked,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What undoing `t` would do: from its tree back to the tree before it.
|
||||
pub fn undo_effect(c: &Control, t: &ApplyRecord) -> Option<String> {
|
||||
let (commit, base) = (t.commit.as_ref()?, t.base.as_ref()?);
|
||||
let from = c.repo.tree(commit).ok()?;
|
||||
let to = c.repo.tree(base).ok()?;
|
||||
let mut parts = Vec::new();
|
||||
let mut names: std::collections::BTreeSet<String> = from.hostnames().into_iter().collect();
|
||||
names.extend(to.hostnames());
|
||||
for h in names {
|
||||
match (from.host(&h), to.host(&h)) {
|
||||
(Some(a), Some(b)) if a != b => parts.push(format!("Changes {h} back")),
|
||||
(Some(_), None) => parts.push(format!("Removes {h}")),
|
||||
(None, Some(_)) => parts.push(format!("Adds {h} back")),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some(if parts.is_empty() {
|
||||
"Changes the site settings back".into()
|
||||
} else {
|
||||
parts.join("; ")
|
||||
})
|
||||
}
|
||||
|
||||
pub fn host_rows(
|
||||
c: &Control,
|
||||
tree: &crate::repo::RouteTree,
|
||||
status: Option<&EdgeStatus>,
|
||||
since: &std::collections::HashMap<String, (&'static str, u64)>,
|
||||
) -> Vec<HostRow> {
|
||||
tree.hostnames()
|
||||
.into_iter()
|
||||
.map(|h| {
|
||||
let spec = tree.host(&h).and_then(|t| HostSpec::from_toml(t).ok());
|
||||
let st = status.and_then(|s| s.hosts.iter().find(|x| x.hostname == h));
|
||||
HostRow {
|
||||
upstreams: spec
|
||||
.as_ref()
|
||||
.map(|s| s.upstreams.clone())
|
||||
.unwrap_or_default(),
|
||||
tls: spec.as_ref().map(|s| s.tls.clone()).unwrap_or_default(),
|
||||
auth: spec.as_ref().map(|s| s.auth.clone()).unwrap_or_default(),
|
||||
websockets: spec.as_ref().is_none_or(|s| s.websockets),
|
||||
share_links: spec.as_ref().is_some_and(|s| s.share_links),
|
||||
added_at: added_at(c, &h),
|
||||
health: health_view(st, spec.as_ref(), since.get(&h).copied()),
|
||||
certificate: cert_view(st, spec.as_ref()),
|
||||
hostname: h,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- history
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct HistoryEntry {
|
||||
pub change_id: String,
|
||||
pub summary: String,
|
||||
pub kind: String,
|
||||
pub state: String,
|
||||
pub at: String,
|
||||
pub commit_short: Option<String>,
|
||||
pub hosts: Vec<String>,
|
||||
pub reason_short: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct History {
|
||||
pub entries: Vec<HistoryEntry>,
|
||||
/// Pass as `before` for older entries.
|
||||
pub next_before: Option<String>,
|
||||
}
|
||||
|
||||
pub fn history_row(r: &ApplyRecord) -> HistoryEntry {
|
||||
HistoryEntry {
|
||||
change_id: r.id.clone(),
|
||||
summary: r.summary.clone(),
|
||||
kind: r.kind.clone(),
|
||||
state: r.state.clone(),
|
||||
at: rfc3339(r.finished.unwrap_or(r.created)),
|
||||
commit_short: short(&r.commit),
|
||||
hosts: r.hosts.clone(),
|
||||
reason_short: r.reason.as_ref().filter(|_| r.state != "kept").map(|x| {
|
||||
x.params
|
||||
.get("kind")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| x.code.rsplit('.').next().unwrap_or("").replace('_', " "))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct FieldChange {
|
||||
pub field: String,
|
||||
pub from: String,
|
||||
pub to: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct HostChange {
|
||||
pub hostname: String,
|
||||
/// `added`, `removed` or `changed`.
|
||||
pub effect: String,
|
||||
pub fields: Vec<FieldChange>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct RestorePreview {
|
||||
pub restorable: bool,
|
||||
pub same_as_current: bool,
|
||||
pub changes: Vec<HostChange>,
|
||||
pub blocked: Option<Blocked>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- tokens, shares, settings
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct TokenView {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub created_at: String,
|
||||
pub last_used_at: Option<String>,
|
||||
pub expires_at: Option<String>,
|
||||
pub revoked_at: Option<String>,
|
||||
}
|
||||
|
||||
impl From<&crate::tokens::TokenRecord> for TokenView {
|
||||
fn from(r: &crate::tokens::TokenRecord) -> Self {
|
||||
TokenView {
|
||||
id: r.id.clone(),
|
||||
name: r.name.clone(),
|
||||
created_at: rfc3339(r.created_at),
|
||||
last_used_at: t(r.last_used_at),
|
||||
expires_at: t(r.expires_at),
|
||||
revoked_at: t(r.revoked_at),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct TokenList {
|
||||
pub items: Vec<TokenView>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct CreatedToken {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// Shown once; Ianitor keeps only its hash.
|
||||
pub token: String,
|
||||
pub expires_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct ShareLinkView {
|
||||
pub id: String,
|
||||
pub hostname: String,
|
||||
pub path_prefix: String,
|
||||
pub created_at: String,
|
||||
pub expires_at: String,
|
||||
pub has_password: bool,
|
||||
/// `active`, `expired` or `stopped`.
|
||||
pub state: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct ShareLinkList {
|
||||
pub items: Vec<ShareLinkView>,
|
||||
pub epoch: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct MintedLink {
|
||||
pub id: String,
|
||||
/// Contains the token; shown once.
|
||||
pub url: String,
|
||||
pub expires_at: String,
|
||||
pub path_prefix: String,
|
||||
pub has_password: bool,
|
||||
/// `host.share.no_signin` when the host needs no sign-in anyway.
|
||||
pub warning: Option<Blocked>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct StoppedAll {
|
||||
pub epoch: u32,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct Settings {
|
||||
pub repo: RepoView,
|
||||
pub watch_seconds: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct EdgeHealth {
|
||||
pub attached: bool,
|
||||
pub reachable: bool,
|
||||
pub config_sha256: Option<String>,
|
||||
pub trial_running: bool,
|
||||
pub error: Option<String>,
|
||||
pub read_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct HealthReport {
|
||||
pub edge: EdgeHealth,
|
||||
pub paused: Option<Blocked>,
|
||||
pub queued: usize,
|
||||
pub hosts: Vec<HostRow>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct Done {
|
||||
pub message: String,
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
// 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/.
|
||||
|
||||
//! `control.toml`: where control keeps its state, the routes repository, the files it writes
|
||||
//! for edge and Caddy, and the deployment facts both compilers need. Written by the NixOS
|
||||
//! module; never holds a secret (secrets are credential *names* in `$CREDENTIALS_DIRECTORY`).
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use ianitor_core::compile::CompileOptions;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Config {
|
||||
/// The API listens here. Only loopback addresses are accepted.
|
||||
#[serde(default = "default_listen")]
|
||||
pub listen: SocketAddr,
|
||||
/// Extra `Host` header values the API accepts (besides the listen address, `localhost`
|
||||
/// and `127.0.0.1` on its port), e.g. the admin host edge forwards to control in phase 3.
|
||||
#[serde(default)]
|
||||
pub allowed_hosts: Vec<String>,
|
||||
/// Tokens, share links, apply records, the apply journal.
|
||||
pub state_dir: PathBuf,
|
||||
/// Overrides `$CREDENTIALS_DIRECTORY` (dev mode and tests only).
|
||||
pub credentials_dir: Option<PathBuf>,
|
||||
/// The `git` binary.
|
||||
#[serde(default = "default_git")]
|
||||
pub git: PathBuf,
|
||||
/// How long the health watch after an apply lasts.
|
||||
#[serde(default = "default_watch")]
|
||||
pub watch_secs: u64,
|
||||
/// How often watched hosts are probed during the watch.
|
||||
#[serde(default = "default_every")]
|
||||
pub watch_every_secs: u64,
|
||||
/// Extra time edge waits for a confirmation after the watch before it reverts by itself.
|
||||
#[serde(default = "default_margin")]
|
||||
pub trial_margin_secs: u64,
|
||||
/// How often control reads health from edge for the overview.
|
||||
#[serde(default = "default_poll")]
|
||||
pub health_poll_secs: u64,
|
||||
pub routes: Routes,
|
||||
pub edge: Edge,
|
||||
pub caddy: Caddy,
|
||||
/// Deployment facts for both compilers.
|
||||
pub compile: Compile,
|
||||
/// Different facts for the Caddy output (only tests need this: both engines side by side).
|
||||
pub compile_caddy: Option<Compile>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Routes {
|
||||
/// The routes repository (bare). Created with an empty `ianitor.toml` when missing.
|
||||
pub repo: PathBuf,
|
||||
#[serde(default = "default_branch")]
|
||||
pub branch: String,
|
||||
/// Where kept changes are pushed (a URL or a path); none means no push.
|
||||
pub remote: Option<String>,
|
||||
/// Shown in the UI ("Last pushed to <name>").
|
||||
#[serde(default = "default_remote_name")]
|
||||
pub remote_name: String,
|
||||
/// User name for HTTPS pushes.
|
||||
#[serde(default = "default_push_user")]
|
||||
pub push_username: String,
|
||||
/// Credential (file name in `$CREDENTIALS_DIRECTORY`) holding the push password or token.
|
||||
pub push_credential: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Edge {
|
||||
/// The edge config file; only ever holds a config that passed its watch.
|
||||
pub config: PathBuf,
|
||||
/// The trial file edge loads during an apply (default `<config>.trial`).
|
||||
pub trial: Option<PathBuf>,
|
||||
/// Edge's admin socket; without it control applies without reload or health watch
|
||||
/// (dev mode without an edge).
|
||||
pub admin_socket: Option<PathBuf>,
|
||||
/// The share-link revocation file edge reads.
|
||||
pub share_revocations: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Caddy {
|
||||
/// The Caddy JSON the caddy-fallback unit reads.
|
||||
pub config: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Compile {
|
||||
pub http_listen: SocketAddr,
|
||||
pub https_listen: SocketAddr,
|
||||
pub cert_dir: String,
|
||||
pub state_dir: String,
|
||||
pub access_log: String,
|
||||
pub caddy_credentials_dir: String,
|
||||
pub caddy_admin: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
impl Compile {
|
||||
pub fn options(&self) -> CompileOptions {
|
||||
CompileOptions {
|
||||
http_listen: self.http_listen,
|
||||
https_listen: self.https_listen,
|
||||
cert_dir: self.cert_dir.clone(),
|
||||
state_dir: self.state_dir.clone(),
|
||||
access_log: self.access_log.clone(),
|
||||
caddy_credentials_dir: self.caddy_credentials_dir.clone(),
|
||||
caddy_admin: self.caddy_admin,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_listen() -> SocketAddr {
|
||||
SocketAddr::from(([127, 0, 0, 1], 7878))
|
||||
}
|
||||
fn default_git() -> PathBuf {
|
||||
PathBuf::from("git")
|
||||
}
|
||||
fn default_watch() -> u64 {
|
||||
60
|
||||
}
|
||||
fn default_every() -> u64 {
|
||||
5
|
||||
}
|
||||
fn default_margin() -> u64 {
|
||||
30
|
||||
}
|
||||
fn default_poll() -> u64 {
|
||||
2
|
||||
}
|
||||
fn default_branch() -> String {
|
||||
"main".into()
|
||||
}
|
||||
fn default_remote_name() -> String {
|
||||
"Gitea".into()
|
||||
}
|
||||
fn default_push_user() -> String {
|
||||
"ianitor".into()
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConfigError {
|
||||
#[error("cannot read {path}: {source}")]
|
||||
Read {
|
||||
path: PathBuf,
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("{path} is not a valid control config: {message}")]
|
||||
Parse { path: PathBuf, message: String },
|
||||
#[error("control config: {0}")]
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn load(path: &Path) -> Result<Config, ConfigError> {
|
||||
let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read {
|
||||
path: path.to_owned(),
|
||||
source,
|
||||
})?;
|
||||
let c: Config = toml::from_str(&text).map_err(|e| ConfigError::Parse {
|
||||
path: path.to_owned(),
|
||||
message: e.message().to_owned(),
|
||||
})?;
|
||||
c.check()?;
|
||||
Ok(c)
|
||||
}
|
||||
|
||||
pub fn check(&self) -> Result<(), ConfigError> {
|
||||
if !self.listen.ip().is_loopback() {
|
||||
return Err(ConfigError::Invalid(format!(
|
||||
"listen = {} is not a loopback address; ianitor-control only listens on 127.0.0.1 or ::1",
|
||||
self.listen
|
||||
)));
|
||||
}
|
||||
if !(1..=3600).contains(&self.watch_secs) {
|
||||
return Err(ConfigError::Invalid("watch_secs must be 1 to 3600".into()));
|
||||
}
|
||||
if !(1..=60).contains(&self.watch_every_secs)
|
||||
|| !(1..=600).contains(&self.trial_margin_secs)
|
||||
{
|
||||
return Err(ConfigError::Invalid(
|
||||
"watch_every_secs must be 1 to 60 and trial_margin_secs 1 to 600".into(),
|
||||
));
|
||||
}
|
||||
if self.routes.branch.is_empty()
|
||||
|| !self
|
||||
.routes
|
||||
.branch
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || b"-_./".contains(&c))
|
||||
|| self.routes.branch.starts_with(['-', '.', '/'])
|
||||
|| self.routes.branch.contains("..")
|
||||
{
|
||||
return Err(ConfigError::Invalid(
|
||||
"routes.branch is not a plain branch name".into(),
|
||||
));
|
||||
}
|
||||
if let Some(r) = &self.routes.remote
|
||||
&& (r.starts_with('-') || r.is_empty())
|
||||
{
|
||||
return Err(ConfigError::Invalid("routes.remote is not usable".into()));
|
||||
}
|
||||
if let Some(c) = &self.routes.push_credential
|
||||
&& !valid_credential_name(c)
|
||||
{
|
||||
return Err(ConfigError::Invalid(
|
||||
"routes.push_credential must be a plain credential name".into(),
|
||||
));
|
||||
}
|
||||
if let Some(m) = empty_model() {
|
||||
for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) {
|
||||
ianitor_core::compile::edge(&m, &c.options())
|
||||
.map_err(|e| ConfigError::Invalid(e.to_string()))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn trial_path(&self) -> PathBuf {
|
||||
self.edge
|
||||
.trial
|
||||
.clone()
|
||||
.unwrap_or_else(|| suffixed(&self.edge.config, ".trial"))
|
||||
}
|
||||
|
||||
pub fn caddy_trial_path(&self) -> PathBuf {
|
||||
suffixed(&self.caddy.config, ".trial")
|
||||
}
|
||||
|
||||
pub fn caddy_compile(&self) -> &Compile {
|
||||
self.compile_caddy.as_ref().unwrap_or(&self.compile)
|
||||
}
|
||||
|
||||
pub fn credentials_dir(&self) -> Option<PathBuf> {
|
||||
self.credentials_dir
|
||||
.clone()
|
||||
.or_else(|| std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from))
|
||||
}
|
||||
|
||||
/// Read a credential by name (trailing newline dropped). Never logged.
|
||||
pub fn credential(&self, name: &str) -> Option<Vec<u8>> {
|
||||
if !valid_credential_name(name) {
|
||||
return None;
|
||||
}
|
||||
let raw = std::fs::read(self.credentials_dir()?.join(name)).ok()?;
|
||||
let t = raw
|
||||
.strip_suffix(b"\r\n")
|
||||
.or_else(|| raw.strip_suffix(b"\n"))
|
||||
.unwrap_or(&raw);
|
||||
(!t.is_empty()).then(|| t.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn valid_credential_name(n: &str) -> bool {
|
||||
!n.is_empty()
|
||||
&& n.len() <= 64
|
||||
&& n.bytes()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_' || c == b'-')
|
||||
}
|
||||
|
||||
fn suffixed(p: &Path, suffix: &str) -> PathBuf {
|
||||
let mut name = p.file_name().unwrap_or_default().to_os_string();
|
||||
name.push(suffix);
|
||||
p.with_file_name(name)
|
||||
}
|
||||
|
||||
fn empty_model() -> Option<ianitor_core::Model> {
|
||||
ianitor_core::load(
|
||||
&ianitor_core::SourceFile {
|
||||
name: "ianitor.toml",
|
||||
contents: "",
|
||||
},
|
||||
&[],
|
||||
)
|
||||
.ok()
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// 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/.
|
||||
|
||||
//! Crash points for the crash-safety tests: with `IANITOR_TEST_CRASH_AT=<stage>` in its
|
||||
//! environment, control aborts (no cleanup, like a kill -9) when an apply reaches that stage.
|
||||
//! Without the variable this does nothing; the NixOS unit never sets it.
|
||||
//!
|
||||
//! `IANITOR_TEST_FAIL_WRITE=<file name>` makes every write of a state file with that name
|
||||
//! fail, as on a full disk (fault injection for the same tests).
|
||||
|
||||
/// The stages, in order.
|
||||
pub const STAGES: [&str; 9] = [
|
||||
"prepared",
|
||||
"committed",
|
||||
"trial_written",
|
||||
"trial_loaded",
|
||||
"watching",
|
||||
"watched",
|
||||
"confirmed",
|
||||
"promoted",
|
||||
"reverting",
|
||||
];
|
||||
|
||||
pub fn point(stage: &str) {
|
||||
if std::env::var("IANITOR_TEST_CRASH_AT").as_deref() == Ok(stage) {
|
||||
log::error!(target: "ianitor::crash", "IANITOR_TEST_CRASH_AT={stage}: aborting on purpose");
|
||||
std::process::abort();
|
||||
}
|
||||
}
|
||||
|
||||
/// Fail a state-file write when `IANITOR_TEST_FAIL_WRITE` names this file.
|
||||
pub fn fail_write(path: &std::path::Path) -> Result<(), String> {
|
||||
match (
|
||||
std::env::var_os("IANITOR_TEST_FAIL_WRITE"),
|
||||
path.file_name(),
|
||||
) {
|
||||
(Some(want), Some(name)) if want == name => Err(format!(
|
||||
"cannot write {}: IANITOR_TEST_FAIL_WRITE (injected)",
|
||||
path.display()
|
||||
)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
// 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/.
|
||||
|
||||
//! `ianitor-control --dev`: everything temporary, on 127.0.0.1. A fresh routes repository, a
|
||||
//! state directory, a share-link key and one API token printed once. If an `ianitor-edge`
|
||||
//! binary is found (`--edge-bin`, `$IANITOR_EDGE_BIN`, or next to this binary), it runs as
|
||||
//! the dev proxy on 127.0.0.1:18080/18443 with an admin socket, so applies are loaded and
|
||||
//! watched for real; otherwise applies are only written. Everything is removed on Ctrl-C.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::time::Duration;
|
||||
|
||||
use ianitor_control::config::{Caddy, Compile, Config, Edge, Routes};
|
||||
use ianitor_control::repo::Repo;
|
||||
use ianitor_control::tokens::Tokens;
|
||||
use ianitor_control::util::{hex, random, write_atomic};
|
||||
|
||||
/// Hosts that get a certificate from the dev CA, so `tls = "domi"` works for them.
|
||||
const DEV_HOSTS: [&str; 3] = ["app.dev.test", "wiki.dev.test", "photos.dev.test"];
|
||||
|
||||
/// A throw-away CA and certificates for [`DEV_HOSTS`] in `certs/`; the CA as `dev-ca.crt`.
|
||||
fn dev_certs(dir: &Path) -> Result<(), String> {
|
||||
use rcgen::{
|
||||
BasicConstraints, CertificateParams, DnType, IsCa, Issuer, KeyPair, KeyUsagePurpose,
|
||||
};
|
||||
let e = |x: rcgen::Error| x.to_string();
|
||||
let ca_key = KeyPair::generate().map_err(e)?;
|
||||
let mut ca = CertificateParams::new(Vec::<String>::new()).map_err(e)?;
|
||||
ca.distinguished_name
|
||||
.push(DnType::CommonName, "Ianitor dev CA");
|
||||
ca.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
|
||||
ca.key_usages = vec![
|
||||
KeyUsagePurpose::KeyCertSign,
|
||||
KeyUsagePurpose::DigitalSignature,
|
||||
];
|
||||
let ca_cert = ca.self_signed(&ca_key).map_err(e)?;
|
||||
std::fs::write(dir.join("certs/dev-ca.crt"), ca_cert.pem()).map_err(|x| x.to_string())?;
|
||||
let issuer = Issuer::new(ca, ca_key);
|
||||
for h in DEV_HOSTS {
|
||||
let key = KeyPair::generate().map_err(e)?;
|
||||
let mut p = CertificateParams::new(vec![h.to_owned()]).map_err(e)?;
|
||||
p.distinguished_name.push(DnType::CommonName, h);
|
||||
let cert = p.signed_by(&key, &issuer).map_err(e)?;
|
||||
std::fs::write(dir.join(format!("certs/{h}.crt")), cert.pem())
|
||||
.map_err(|x| x.to_string())?;
|
||||
write_atomic(
|
||||
&dir.join(format!("certs/{h}.key")),
|
||||
key.serialize_pem().as_bytes(),
|
||||
0o600,
|
||||
)
|
||||
.map_err(|x| x.to_string())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const SITE: &str = "# Dev site settings. Sign-in goes to an Authelia that may not run here.\n\
|
||||
[forward_auth]\nurl = \"http://127.0.0.1:9091/api/authz/forward-auth\"\n";
|
||||
|
||||
struct Cleanup {
|
||||
dir: PathBuf,
|
||||
edge: Option<Child>,
|
||||
}
|
||||
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
if let Some(c) = &mut self.edge {
|
||||
let _ = c.kill();
|
||||
let _ = c.wait();
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&self.dir);
|
||||
}
|
||||
}
|
||||
|
||||
fn find_edge(args: &[String]) -> Option<PathBuf> {
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
if a == "--edge-bin" {
|
||||
return it.next().map(PathBuf::from);
|
||||
}
|
||||
}
|
||||
if let Some(p) = std::env::var_os("IANITOR_EDGE_BIN") {
|
||||
return Some(PathBuf::from(p));
|
||||
}
|
||||
let me = std::env::current_exe().ok()?;
|
||||
let sibling = me.with_file_name(if cfg!(windows) {
|
||||
"ianitor-edge.exe"
|
||||
} else {
|
||||
"ianitor-edge"
|
||||
});
|
||||
sibling.is_file().then_some(sibling)
|
||||
}
|
||||
|
||||
fn arg(args: &[String], name: &str) -> Option<String> {
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
if a == name {
|
||||
return it.next().cloned();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub async fn run(args: &[String]) -> Result<(), String> {
|
||||
let listen: SocketAddr = arg(args, "--listen")
|
||||
.unwrap_or_else(|| "127.0.0.1:7878".into())
|
||||
.parse()
|
||||
.map_err(|_| "--listen must be an address like 127.0.0.1:7878")?;
|
||||
if !listen.ip().is_loopback() {
|
||||
return Err("--dev listens on loopback only".into());
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("ianitor-dev-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let mut cleanup = Cleanup {
|
||||
dir: dir.clone(),
|
||||
edge: None,
|
||||
};
|
||||
for d in [
|
||||
"state",
|
||||
"edge",
|
||||
"caddy",
|
||||
"certs",
|
||||
"creds",
|
||||
"logs",
|
||||
"edge-state",
|
||||
] {
|
||||
std::fs::create_dir_all(dir.join(d)).map_err(|e| e.to_string())?;
|
||||
}
|
||||
dev_certs(&dir)?;
|
||||
let key = hex(&random::<32>().map_err(|e| e.to_string())?);
|
||||
write_atomic(&dir.join("creds/share-link-key"), key.as_bytes(), 0o600)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let edge_bin = if cfg!(unix) { find_edge(args) } else { None };
|
||||
let s = |p: &str| dir.join(p).to_string_lossy().into_owned();
|
||||
let cfg = Config {
|
||||
listen,
|
||||
allowed_hosts: Vec::new(),
|
||||
state_dir: dir.join("state"),
|
||||
credentials_dir: Some(dir.join("creds")),
|
||||
git: PathBuf::from("git"),
|
||||
watch_secs: arg(args, "--watch-secs")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(10),
|
||||
watch_every_secs: 2,
|
||||
trial_margin_secs: 20,
|
||||
health_poll_secs: 2,
|
||||
routes: Routes {
|
||||
repo: dir.join("routes.git"),
|
||||
branch: "main".into(),
|
||||
remote: None,
|
||||
remote_name: "Gitea".into(),
|
||||
push_username: "ianitor".into(),
|
||||
push_credential: None,
|
||||
},
|
||||
edge: Edge {
|
||||
config: dir.join("edge/edge.json"),
|
||||
trial: None,
|
||||
admin_socket: edge_bin.as_ref().map(|_| dir.join("edge/admin.sock")),
|
||||
share_revocations: dir.join("edge/share-revocations.json"),
|
||||
},
|
||||
caddy: Caddy {
|
||||
config: dir.join("caddy/caddy.json"),
|
||||
},
|
||||
compile: Compile {
|
||||
http_listen: "127.0.0.1:18080".parse().map_err(|_| "bad address")?,
|
||||
https_listen: "127.0.0.1:18443".parse().map_err(|_| "bad address")?,
|
||||
cert_dir: s("certs"),
|
||||
state_dir: s("edge-state"),
|
||||
access_log: s("logs/access.log"),
|
||||
caddy_credentials_dir: s("creds"),
|
||||
caddy_admin: None,
|
||||
},
|
||||
compile_caddy: None,
|
||||
};
|
||||
cfg.check().map_err(|e| e.to_string())?;
|
||||
Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None)?;
|
||||
|
||||
// Control writes edge.json first; then edge can start from it.
|
||||
let ctl_cfg = cfg.clone();
|
||||
let opened = ianitor_control::Control::open(ctl_cfg).await?;
|
||||
drop(opened);
|
||||
if let Some(bin) = &edge_bin {
|
||||
cleanup.edge = Some(start_edge(bin, &dir, &cfg)?);
|
||||
}
|
||||
|
||||
println!("Ianitor control (dev) on http://{listen}/api/v1");
|
||||
println!("Routes repository: {}", cfg.routes.repo.display());
|
||||
match &edge_bin {
|
||||
Some(b) => println!(
|
||||
"Dev proxy: {} on https://127.0.0.1:18443 (HTTP 18080). tls = \"domi\" works for {}; CA: {}",
|
||||
b.display(),
|
||||
DEV_HOSTS.join(", "),
|
||||
dir.join("certs/dev-ca.crt").display()
|
||||
),
|
||||
None => println!(
|
||||
"No ianitor-edge found: applies are written but not loaded or watched (use --edge-bin)."
|
||||
),
|
||||
}
|
||||
println!("API token (shown once): {token}");
|
||||
println!("Press Ctrl-C to stop and remove {}", dir.display());
|
||||
let r = ianitor_control::serve(cfg, ianitor_control::stop_signal()).await;
|
||||
drop(cleanup);
|
||||
r
|
||||
}
|
||||
|
||||
fn start_edge(bin: &Path, dir: &Path, cfg: &Config) -> Result<Child, String> {
|
||||
let log = std::fs::File::create(dir.join("logs/edge.log")).map_err(|e| e.to_string())?;
|
||||
let log2 = log.try_clone().map_err(|e| e.to_string())?;
|
||||
let child = Command::new(bin)
|
||||
.arg("--config")
|
||||
.arg(&cfg.edge.config)
|
||||
.arg("--admin-socket")
|
||||
.arg(dir.join("edge/admin.sock"))
|
||||
.arg("--share-revocations")
|
||||
.arg(&cfg.edge.share_revocations)
|
||||
.env("CREDENTIALS_DIRECTORY", dir.join("creds"))
|
||||
.stdout(Stdio::from(log))
|
||||
.stderr(Stdio::from(log2))
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start {}: {e}", bin.display()))?;
|
||||
let sock = dir.join("edge/admin.sock");
|
||||
for _ in 0..100 {
|
||||
if sock.exists() {
|
||||
return Ok(child);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
Err(format!(
|
||||
"the dev proxy did not start; see {}",
|
||||
dir.join("logs/edge.log").display()
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// 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/.
|
||||
|
||||
//! Control's side of edge's admin socket (see `ianitor_edge::admin`).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EdgeLinkError {
|
||||
/// Edge did not answer (not running, socket missing, timeout).
|
||||
#[error("edge cannot be reached: {0}")]
|
||||
Unreachable(String),
|
||||
/// Edge answered with an error.
|
||||
#[error("{message}")]
|
||||
Refused { status: u16, message: String },
|
||||
}
|
||||
|
||||
/// One probe result as edge reports it.
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
pub struct Check {
|
||||
pub seq: u64,
|
||||
pub at: u64,
|
||||
pub ok: bool,
|
||||
pub source: String,
|
||||
pub kind: Option<String>,
|
||||
pub status: Option<u16>,
|
||||
pub latency_ms: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct UpstreamStatus {
|
||||
pub address: String,
|
||||
pub healthy: bool,
|
||||
pub checks: Vec<Check>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct CertStatus {
|
||||
pub state: String,
|
||||
pub not_after: Option<i64>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct HostStatus {
|
||||
pub hostname: String,
|
||||
pub health_check: bool,
|
||||
pub upstreams: Vec<UpstreamStatus>,
|
||||
pub certificate: CertStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct TrialStatus {
|
||||
pub config_sha256: String,
|
||||
pub seconds_left: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct EdgeStatus {
|
||||
pub generation: u64,
|
||||
pub config_sha256: String,
|
||||
pub started_at: u64,
|
||||
pub trial: Option<TrialStatus>,
|
||||
pub hosts: Vec<HostStatus>,
|
||||
}
|
||||
|
||||
/// How control reaches edge. `None` in dev mode without an edge: applies are written but
|
||||
/// not loaded or watched.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum EdgeLink {
|
||||
Unix(PathBuf),
|
||||
None,
|
||||
}
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
impl EdgeLink {
|
||||
pub fn attached(&self) -> bool {
|
||||
matches!(self, EdgeLink::Unix(_))
|
||||
}
|
||||
|
||||
async fn call(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<Value>,
|
||||
) -> Result<Value, EdgeLinkError> {
|
||||
let EdgeLink::Unix(socket) = self else {
|
||||
return Err(EdgeLinkError::Unreachable("no edge is attached".into()));
|
||||
};
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let body = body.map(|b| b.to_string()).unwrap_or_default();
|
||||
let req = format!(
|
||||
"{method} {path} HTTP/1.1\r\nHost: edge\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
let exchange = async {
|
||||
let mut s = tokio::net::UnixStream::connect(socket).await?;
|
||||
s.write_all(req.as_bytes()).await?;
|
||||
let mut buf = Vec::new();
|
||||
s.read_to_end(&mut buf).await?;
|
||||
Ok::<_, std::io::Error>(buf)
|
||||
};
|
||||
let buf = tokio::time::timeout(TIMEOUT, exchange)
|
||||
.await
|
||||
.map_err(|_| EdgeLinkError::Unreachable("no answer within 10 s".into()))?
|
||||
.map_err(|e| EdgeLinkError::Unreachable(e.to_string()))?;
|
||||
let (status, json) = parse(&buf).map_err(EdgeLinkError::Unreachable)?;
|
||||
if (200..300).contains(&status) {
|
||||
Ok(json)
|
||||
} else {
|
||||
Err(EdgeLinkError::Refused {
|
||||
status,
|
||||
message: json["error"].as_str().unwrap_or("edge refused").to_owned(),
|
||||
})
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = (socket, method, path, body);
|
||||
Err(EdgeLinkError::Unreachable(
|
||||
"the admin socket needs Unix".into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn status(&self) -> Result<EdgeStatus, EdgeLinkError> {
|
||||
let v = self.call("GET", "/v1/status", None).await?;
|
||||
serde_json::from_value(v)
|
||||
.map_err(|e| EdgeLinkError::Unreachable(format!("odd status: {e}")))
|
||||
}
|
||||
|
||||
/// Load the trial file; returns its SHA-256 as edge computed it.
|
||||
pub async fn trial(
|
||||
&self,
|
||||
confirm_within: u64,
|
||||
watch_hosts: &[String],
|
||||
every: u64,
|
||||
) -> Result<String, EdgeLinkError> {
|
||||
let v = self
|
||||
.call(
|
||||
"POST",
|
||||
"/v1/trial",
|
||||
Some(json!({
|
||||
"confirm_within_secs": confirm_within,
|
||||
"watch_hosts": watch_hosts,
|
||||
"watch_every_secs": every,
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned())
|
||||
}
|
||||
|
||||
pub async fn confirm(&self, sha: &str) -> Result<(), EdgeLinkError> {
|
||||
self.call("POST", "/v1/confirm", Some(json!({ "config_sha256": sha })))
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
pub async fn abort(&self) -> Result<bool, EdgeLinkError> {
|
||||
let v = self.call("POST", "/v1/abort", None).await?;
|
||||
Ok(v["reverted"].as_bool().unwrap_or(false))
|
||||
}
|
||||
|
||||
pub async fn reload(&self) -> Result<String, EdgeLinkError> {
|
||||
let v = self.call("POST", "/v1/reload", None).await?;
|
||||
Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned())
|
||||
}
|
||||
|
||||
pub async fn reload_revocations(&self) -> Result<(), EdgeLinkError> {
|
||||
self.call("POST", "/v1/share-revocations/reload", None)
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
pub async fn acme_retry(&self) -> Result<(), EdgeLinkError> {
|
||||
self.call("POST", "/v1/acme/retry", None).await.map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(raw: &[u8]) -> Result<(u16, Value), String> {
|
||||
let end = raw
|
||||
.windows(4)
|
||||
.position(|w| w == b"\r\n\r\n")
|
||||
.ok_or("no complete answer from edge")?;
|
||||
let head = String::from_utf8_lossy(&raw[..end]);
|
||||
let status: u16 = head
|
||||
.split(' ')
|
||||
.nth(1)
|
||||
.and_then(|s| s.parse().ok())
|
||||
.ok_or("no status from edge")?;
|
||||
let chunked = head
|
||||
.to_ascii_lowercase()
|
||||
.contains("transfer-encoding: chunked");
|
||||
let mut body = raw[end + 4..].to_vec();
|
||||
if chunked {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = &body[..];
|
||||
while let Some(p) = rest.windows(2).position(|w| w == b"\r\n") {
|
||||
let size = usize::from_str_radix(String::from_utf8_lossy(&rest[..p]).trim(), 16)
|
||||
.map_err(|_| "odd chunk from edge")?;
|
||||
rest = &rest[p + 2..];
|
||||
if size == 0 || rest.len() < size {
|
||||
break;
|
||||
}
|
||||
out.extend_from_slice(&rest[..size]);
|
||||
rest = &rest[(size + 2).min(rest.len())..];
|
||||
}
|
||||
body = out;
|
||||
}
|
||||
let json = serde_json::from_slice(&body).unwrap_or(Value::Null);
|
||||
Ok((status, json))
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,187 @@
|
||||
// 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 host body of the API. It mirrors the host TOML file field for field (docs/ui-api.md
|
||||
//! §1.2), so control writes exactly what Mark would write by hand. Core validates the TOML
|
||||
//! control writes; this type only carries it.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct HostSpec {
|
||||
/// Lowercase DNS name, e.g. `wiki.home.example`.
|
||||
pub hostname: String,
|
||||
/// Where traffic goes, e.g. `http://10.0.0.23:3000`. Same scheme for all.
|
||||
pub upstreams: Vec<String>,
|
||||
/// `letsencrypt` or `domi`.
|
||||
#[serde(default = "letsencrypt")]
|
||||
pub tls: String,
|
||||
/// `none` or `forward-auth`.
|
||||
#[serde(default = "auth_none")]
|
||||
pub auth: String,
|
||||
#[serde(default = "yes")]
|
||||
pub websockets: bool,
|
||||
#[serde(default)]
|
||||
pub share_links: bool,
|
||||
/// `off` or `truncated`.
|
||||
#[serde(default = "off")]
|
||||
pub access_log: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub health_check: Option<HealthCheckSpec>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub request_headers: Vec<HeaderRuleSpec>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub response_headers: Vec<HeaderRuleSpec>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct HealthCheckSpec {
|
||||
pub path: String,
|
||||
#[serde(default = "ten")]
|
||||
pub interval_secs: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct HeaderRuleSpec {
|
||||
/// `set` or `remove`.
|
||||
pub action: String,
|
||||
pub name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub value: Option<String>,
|
||||
/// Name of a secret declared in `ianitor.toml`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub secret: Option<String>,
|
||||
}
|
||||
|
||||
fn letsencrypt() -> String {
|
||||
"letsencrypt".into()
|
||||
}
|
||||
fn auth_none() -> String {
|
||||
"none".into()
|
||||
}
|
||||
fn off() -> String {
|
||||
"off".into()
|
||||
}
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
fn ten() -> i64 {
|
||||
10
|
||||
}
|
||||
|
||||
impl HostSpec {
|
||||
/// The TOML file control commits for this host. Every field is written out, so the file
|
||||
/// says exactly what the form said.
|
||||
pub fn to_toml(&self) -> Result<String, String> {
|
||||
let body = toml::to_string(self).map_err(|e| e.to_string())?;
|
||||
Ok(format!(
|
||||
"# Written by Ianitor control. Edit through the web UI or the API.\n{body}"
|
||||
))
|
||||
}
|
||||
|
||||
pub fn from_toml(text: &str) -> Result<HostSpec, String> {
|
||||
toml::from_str(text).map_err(|e| e.message().to_owned())
|
||||
}
|
||||
|
||||
/// Field-level differences, labelled for the restore preview (docs/ui-api.md §1.4).
|
||||
pub fn diff(&self, to: &HostSpec) -> Vec<(String, String, String)> {
|
||||
let mut out = Vec::new();
|
||||
let mut push = |f: &str, a: String, b: String| {
|
||||
if a != b {
|
||||
out.push((f.to_owned(), a, b));
|
||||
}
|
||||
};
|
||||
push("hostname", self.hostname.clone(), to.hostname.clone());
|
||||
push(
|
||||
"upstreams",
|
||||
self.upstreams.join(", "),
|
||||
to.upstreams.join(", "),
|
||||
);
|
||||
push("tls", self.tls.clone(), to.tls.clone());
|
||||
push("auth", self.auth.clone(), to.auth.clone());
|
||||
push(
|
||||
"websockets",
|
||||
self.websockets.to_string(),
|
||||
to.websockets.to_string(),
|
||||
);
|
||||
push(
|
||||
"share_links",
|
||||
self.share_links.to_string(),
|
||||
to.share_links.to_string(),
|
||||
);
|
||||
push("access_log", self.access_log.clone(), to.access_log.clone());
|
||||
let hc =
|
||||
|h: &Option<HealthCheckSpec>| h.as_ref().map(|h| (h.path.clone(), h.interval_secs));
|
||||
let (a, b) = (hc(&self.health_check), hc(&to.health_check));
|
||||
push(
|
||||
"health_check.path",
|
||||
a.as_ref().map(|x| x.0.clone()).unwrap_or_default(),
|
||||
b.as_ref().map(|x| x.0.clone()).unwrap_or_default(),
|
||||
);
|
||||
push(
|
||||
"health_check.interval_secs",
|
||||
a.map(|x| x.1.to_string()).unwrap_or_default(),
|
||||
b.map(|x| x.1.to_string()).unwrap_or_default(),
|
||||
);
|
||||
let rules =
|
||||
|r: &[HeaderRuleSpec], q: &[HeaderRuleSpec]| format!("{} rules", r.len() + q.len());
|
||||
if self.request_headers != to.request_headers
|
||||
|| self.response_headers != to.response_headers
|
||||
{
|
||||
out.push((
|
||||
"headers".into(),
|
||||
rules(&self.request_headers, &self.response_headers),
|
||||
rules(&to.request_headers, &to.response_headers),
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips_and_core_accepts_it() {
|
||||
let h = HostSpec {
|
||||
hostname: "wiki.home.test".into(),
|
||||
upstreams: vec!["http://10.0.0.2:3000".into()],
|
||||
tls: "domi".into(),
|
||||
auth: "none".into(),
|
||||
websockets: false,
|
||||
share_links: true,
|
||||
access_log: "truncated".into(),
|
||||
health_check: Some(HealthCheckSpec {
|
||||
path: "/health".into(),
|
||||
interval_secs: 15,
|
||||
}),
|
||||
request_headers: vec![HeaderRuleSpec {
|
||||
action: "set".into(),
|
||||
name: "X-A".into(),
|
||||
value: Some("1".into()),
|
||||
secret: None,
|
||||
}],
|
||||
response_headers: vec![],
|
||||
};
|
||||
let text = h.to_toml().unwrap();
|
||||
assert_eq!(HostSpec::from_toml(&text).unwrap(), h);
|
||||
let m = ianitor_core::load(
|
||||
&ianitor_core::SourceFile {
|
||||
name: "ianitor.toml",
|
||||
contents: "",
|
||||
},
|
||||
&[ianitor_core::SourceFile {
|
||||
name: "hosts/wiki.home.test.toml",
|
||||
contents: &text,
|
||||
}],
|
||||
);
|
||||
assert!(m.is_ok(), "{m:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// 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/.
|
||||
|
||||
//! Ianitor control: the routes repository, apply with automatic rollback, share links, API
|
||||
//! tokens and the REST API, on loopback only. It never serves public traffic; if it stops,
|
||||
//! edge keeps serving the last good config.
|
||||
|
||||
pub mod api;
|
||||
pub mod config;
|
||||
pub mod crash;
|
||||
pub mod edgelink;
|
||||
pub mod engine;
|
||||
pub mod hostspec;
|
||||
pub mod logger;
|
||||
pub mod messages;
|
||||
pub mod records;
|
||||
pub mod repo;
|
||||
pub mod shares;
|
||||
pub mod tokens;
|
||||
pub mod util;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use config::Config;
|
||||
pub use engine::Control;
|
||||
|
||||
/// Open control, start its background tasks and serve the API until `shutdown` resolves.
|
||||
pub async fn serve(
|
||||
cfg: Config,
|
||||
shutdown: impl std::future::Future<Output = ()> + Send + 'static,
|
||||
) -> Result<(), String> {
|
||||
cfg.check().map_err(|e| e.to_string())?;
|
||||
let listen = cfg.listen;
|
||||
let ctl = Control::open(cfg).await?;
|
||||
tokio::spawn(ctl.clone().worker());
|
||||
tokio::spawn(ctl.clone().health_poller());
|
||||
tokio::spawn(ctl.clone().pusher());
|
||||
let app = api::router(api::AppState::new(ctl.clone()));
|
||||
if !listen.ip().is_loopback() {
|
||||
return Err("ianitor-control only listens on loopback".into());
|
||||
}
|
||||
let listener = tokio::net::TcpListener::bind(listen)
|
||||
.await
|
||||
.map_err(|e| format!("cannot listen on {listen}: {e}"))?;
|
||||
log::info!(target: "ianitor::control", "API on http://{listen}/api/v1");
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(shutdown)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
drop(ctl);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Wait for Ctrl-C or SIGTERM.
|
||||
pub async fn stop_signal() {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
let mut term = match signal(SignalKind::terminate()) {
|
||||
Ok(s) => s,
|
||||
Err(_) => {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => {}
|
||||
_ = term.recv() => {}
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// For tests: the router over an opened control.
|
||||
pub fn app(ctl: Arc<Control>) -> axum::Router {
|
||||
api::router(api::AppState::new(ctl))
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// 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/.
|
||||
|
||||
//! Error log on stderr (journald under systemd). Control never logs request headers, bodies,
|
||||
//! query strings, tokens, passwords or share links: request lines are logged as method and
|
||||
//! route only, by the API layer.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use log::{Level, LevelFilter, Log, Metadata, Record};
|
||||
|
||||
struct Stderr {
|
||||
own: LevelFilter,
|
||||
}
|
||||
|
||||
impl Log for Stderr {
|
||||
fn enabled(&self, m: &Metadata<'_>) -> bool {
|
||||
let limit = if m.target().starts_with("ianitor") {
|
||||
self.own
|
||||
} else {
|
||||
self.own.min(LevelFilter::Info)
|
||||
};
|
||||
m.level() <= limit
|
||||
}
|
||||
|
||||
fn log(&self, r: &Record<'_>) {
|
||||
if self.enabled(r.metadata()) {
|
||||
let lvl = match r.level() {
|
||||
Level::Error => "ERROR",
|
||||
Level::Warn => "WARN",
|
||||
Level::Info => "INFO",
|
||||
Level::Debug => "DEBUG",
|
||||
Level::Trace => "TRACE",
|
||||
};
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
"{lvl} {}: {}",
|
||||
r.target(),
|
||||
r.args()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {
|
||||
let _ = std::io::stderr().flush();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(level: Option<&str>) {
|
||||
let own = match level.map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("error") => LevelFilter::Error,
|
||||
Some("warn") => LevelFilter::Warn,
|
||||
Some("debug") => LevelFilter::Debug,
|
||||
Some("trace") => LevelFilter::Trace,
|
||||
_ => LevelFilter::Info,
|
||||
};
|
||||
if log::set_boxed_logger(Box::new(Stderr { own })).is_ok() {
|
||||
log::set_max_level(own);
|
||||
}
|
||||
}
|
||||
+235
-5
@@ -2,11 +2,241 @@
|
||||
// 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/.
|
||||
|
||||
//! Placeholder for ianitor-control (ROADMAP phase 2). It deliberately opens no socket.
|
||||
//! ```text
|
||||
//! ianitor-control --config <control.toml> run the control plane
|
||||
//! ianitor-control --dev [--edge-bin <ianitor-edge>] temporary everything on 127.0.0.1
|
||||
//! ianitor-control token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>)
|
||||
//! ianitor-control token list (--config <c> | --state-dir <d>)
|
||||
//! ianitor-control token revoke <id> (--config <c> | --state-dir <d>)
|
||||
//! ianitor-control openapi print the OpenAPI document
|
||||
//! ianitor-control check --config <control.toml> check the config and exit
|
||||
//! ```
|
||||
//! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`),
|
||||
//! the binary answers git's prompt from the push credential file.
|
||||
|
||||
fn main() {
|
||||
println!(
|
||||
"ianitor-control {}: placeholder. The control plane (API on 127.0.0.1) arrives in phase 2.",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use ianitor_control::{Config, logger, tokens::Tokens};
|
||||
|
||||
mod dev;
|
||||
|
||||
fn usage() -> ExitCode {
|
||||
eprintln!(
|
||||
"usage: ianitor-control --config <control.toml> | --dev [--edge-bin <path>] | \
|
||||
token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>) | \
|
||||
token list (...) | token revoke <id> (...) | openapi | check --config <c>"
|
||||
);
|
||||
ExitCode::from(2)
|
||||
}
|
||||
|
||||
fn askpass() -> ExitCode {
|
||||
// git asks "Username for 'https://…':" and "Password for 'https://…':".
|
||||
let prompt = std::env::args().nth(1).unwrap_or_default();
|
||||
if prompt.starts_with("Username") {
|
||||
println!(
|
||||
"{}",
|
||||
std::env::var("IANITOR_ASKPASS_USER").unwrap_or_default()
|
||||
);
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
// Answer only the password prompt; anything else (a passphrase, a host key question)
|
||||
// gets no answer, so the push fails instead of handing out the token.
|
||||
if !prompt.starts_with("Password for") {
|
||||
eprintln!("ianitor-control askpass: not answering {prompt:?}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
let Some(file) = std::env::var_os("IANITOR_ASKPASS_FILE") else {
|
||||
return ExitCode::FAILURE;
|
||||
};
|
||||
match std::fs::read_to_string(file) {
|
||||
Ok(v) => {
|
||||
println!("{}", v.trim_end_matches(['\r', '\n']));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(_) => ExitCode::FAILURE,
|
||||
}
|
||||
}
|
||||
|
||||
fn state_dir(args: &[String]) -> Result<PathBuf, String> {
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--state-dir" => {
|
||||
return it
|
||||
.next()
|
||||
.map(PathBuf::from)
|
||||
.ok_or("--state-dir needs a path".into());
|
||||
}
|
||||
"--config" => {
|
||||
let p = it.next().ok_or("--config needs a path")?;
|
||||
return Config::load(&PathBuf::from(p))
|
||||
.map(|c| c.state_dir)
|
||||
.map_err(|e| e.to_string());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Err("give --config <control.toml> or --state-dir <dir>".into())
|
||||
}
|
||||
|
||||
/// The token files must stay owned by the user control runs as: refuse to touch them as
|
||||
/// anyone else (typically root), instead of leaving root-owned files control cannot open.
|
||||
#[cfg(unix)]
|
||||
fn same_owner(dir: &std::path::Path) -> Result<(), String> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let existing = dir
|
||||
.ancestors()
|
||||
.find(|p| p.is_dir())
|
||||
.ok_or_else(|| format!("no part of {} exists", dir.display()))?;
|
||||
let owner = std::fs::metadata(existing)
|
||||
.map_err(|e| format!("cannot read {}: {e}", existing.display()))?
|
||||
.uid();
|
||||
// Who we are, without libc: the owner of a file we create (in the temp dir, so nothing is
|
||||
// created in the state dir by the wrong user).
|
||||
let probe = std::env::temp_dir().join(format!(".ianitor-owner-probe-{}", std::process::id()));
|
||||
// create_new: never follows or reuses a file someone else put there.
|
||||
let me = std::fs::File::create_new(&probe)
|
||||
.and_then(|f| f.metadata())
|
||||
.map(|m| m.uid());
|
||||
if me.is_ok() {
|
||||
let _ = std::fs::remove_file(&probe);
|
||||
}
|
||||
let me = me.map_err(|e| format!("cannot create a probe file to learn who runs this: {e}"))?;
|
||||
if me == 0 && !dir.is_dir() {
|
||||
return Err(format!(
|
||||
"{} does not exist; create it as the user control runs as (or run this as that user), not as root",
|
||||
dir.display()
|
||||
));
|
||||
}
|
||||
if me != owner {
|
||||
return Err(format!(
|
||||
"{} belongs to uid {owner}, but this runs as uid {me}; run it as that user (e.g. sudo -u ianitor ianitor-control token ...)",
|
||||
existing.display()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn same_owner(_: &std::path::Path) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn token(args: &[String]) -> Result<(), String> {
|
||||
let dir = state_dir(args)?;
|
||||
// Check the owner before creating anything: the nearest existing ancestor must belong to
|
||||
// whoever runs this (so root does not create a state dir control cannot use).
|
||||
same_owner(&dir)?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
||||
let tokens = Tokens::new(&dir);
|
||||
match args.first().map(String::as_str) {
|
||||
Some("create") => {
|
||||
let mut name = None;
|
||||
let mut expires = Some(ianitor_control::util::now() + 365 * 86_400);
|
||||
let mut it = args.iter().skip(1);
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--name" => name = it.next().cloned(),
|
||||
"--never" => expires = None,
|
||||
"--expires-days" => {
|
||||
let d: u64 = it
|
||||
.next()
|
||||
.and_then(|d| d.parse().ok())
|
||||
.filter(|d| (1..=3650).contains(d))
|
||||
.ok_or("--expires-days must be 1 to 3650")?;
|
||||
expires = Some(ianitor_control::util::now() + d * 86_400);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let name = name.ok_or("--name <name> is required")?;
|
||||
let (rec, value) = tokens.create(&name, expires).map_err(|e| {
|
||||
if e == "token.name" {
|
||||
"the name must be 1 to 64 letters, digits, spaces, dots, dashes or underscores"
|
||||
.to_owned()
|
||||
} else {
|
||||
e
|
||||
}
|
||||
})?;
|
||||
eprintln!(
|
||||
"Token {} ({}) created. It is shown once; save it in Custos now:",
|
||||
rec.id, rec.name
|
||||
);
|
||||
println!("{value}");
|
||||
Ok(())
|
||||
}
|
||||
Some("list") => {
|
||||
for t in tokens.list()? {
|
||||
println!(
|
||||
"{} {} created {}{}{}",
|
||||
t.id,
|
||||
t.name,
|
||||
ianitor_control::util::rfc3339(t.created_at),
|
||||
t.expires_at
|
||||
.map(|e| format!(" expires {}", ianitor_control::util::rfc3339(e)))
|
||||
.unwrap_or_default(),
|
||||
t.revoked_at
|
||||
.map(|e| format!(" REVOKED {}", ianitor_control::util::rfc3339(e)))
|
||||
.unwrap_or_default()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Some("revoke") => {
|
||||
let id = args.get(1).ok_or("token revoke <id>")?;
|
||||
match tokens.revoke(id)? {
|
||||
Some(_) => {
|
||||
eprintln!("Token {id} revoked.");
|
||||
Ok(())
|
||||
}
|
||||
None => Err(format!("there is no token {id}")),
|
||||
}
|
||||
}
|
||||
_ => Err("token create | list | revoke".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") {
|
||||
return askpass();
|
||||
}
|
||||
logger::init(std::env::var("IANITOR_LOG").ok().as_deref());
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let rt = match tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
{
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
eprintln!("ianitor-control: cannot start: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let result = match args.first().map(String::as_str) {
|
||||
Some("token") => token(&args[1..]),
|
||||
Some("openapi") => {
|
||||
println!("{}", ianitor_control::api::openapi_json());
|
||||
Ok(())
|
||||
}
|
||||
Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")),
|
||||
Some("--dev") => rt.block_on(dev::run(&args[1..])),
|
||||
Some("--config") => match args.get(1) {
|
||||
Some(p) => match Config::load(&PathBuf::from(p)) {
|
||||
Ok(cfg) => rt.block_on(ianitor_control::serve(cfg, ianitor_control::stop_signal())),
|
||||
Err(e) => Err(e.to_string()),
|
||||
},
|
||||
None => return usage(),
|
||||
},
|
||||
Some("--help" | "-h") | None => return usage(),
|
||||
Some(_) => return usage(),
|
||||
};
|
||||
match result {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
log::error!(target: "ianitor::control", "{e}");
|
||||
eprintln!("ianitor-control: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
// 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/.
|
||||
|
||||
//! Every user-facing message, by code, in the words of docs/ui-api.md §3. `{x}` is filled from
|
||||
//! the params; a missing param leaves a plain gap rather than a placeholder.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub type Params = BTreeMap<String, String>;
|
||||
|
||||
fn template(code: &str) -> &'static str {
|
||||
match code {
|
||||
// 3.1 host form
|
||||
"host.hostname.missing" => "Enter the address people will type, like wiki.home.example.",
|
||||
"host.hostname.uppercase" => "Use lowercase letters only: {suggestion}.",
|
||||
"host.hostname.characters" => "Use only letters a–z, digits, dots and dashes.",
|
||||
"host.hostname.spaces" => "Remove the spaces from the address.",
|
||||
"host.hostname.wildcard" => {
|
||||
"Addresses with * are not supported yet. Add each name as its own host."
|
||||
}
|
||||
"host.hostname.trailing_dot" => "Remove the dot at the end.",
|
||||
"host.hostname.empty_label" => "There are two dots in a row. Remove one.",
|
||||
"host.hostname.label_dash" => "A part of the address cannot start or end with a dash.",
|
||||
"host.hostname.label_long" => "Each part between dots can be at most 63 characters.",
|
||||
"host.hostname.too_long" => "The address can be at most 253 characters.",
|
||||
"host.hostname.numeric" => {
|
||||
"That looks like an IP address. Use a name, like wiki.home.example."
|
||||
}
|
||||
"host.hostname.taken" => "{hostname} is already a host.",
|
||||
"host.hostname.mismatch" => {
|
||||
"The address in the form ({hostname}) is not the host you are editing ({path_hostname})."
|
||||
}
|
||||
"host.file_name" => "The address does not match the file it is stored in.",
|
||||
"host.upstreams.missing" => {
|
||||
"Enter where Ianitor should send traffic, like http://10.0.0.23:3000."
|
||||
}
|
||||
"host.upstream.not_url" => "Write it as a full address, like http://10.0.0.23:3000.",
|
||||
"host.upstream.scheme" => "Start the address with http:// or https://.",
|
||||
"host.upstream.no_host" => "Add the server's name or IP address after http://.",
|
||||
"host.upstream.host_name" => {
|
||||
"The server name is not usable. Use letters a–z, digits, dots and dashes, or an IP address."
|
||||
}
|
||||
"host.upstream.no_port" => "Add the port at the end, like :3000.",
|
||||
"host.upstream.port_zero" => {
|
||||
"Port 0 cannot be used. Enter the port the service listens on."
|
||||
}
|
||||
"host.upstream.path" => "Leave out the path after the port. Visitors keep their own path.",
|
||||
"host.upstream.query" | "host.upstream.fragment" => "Leave out everything after ? or #.",
|
||||
"host.upstream.credentials" => {
|
||||
"Leave out the user name and password. Put them in a header rule with a secret instead."
|
||||
}
|
||||
"host.upstream.duplicate" => "This address is listed twice.",
|
||||
"host.upstream.mixed_schemes" => {
|
||||
"All addresses for one host must start the same way: all http:// or all https://."
|
||||
}
|
||||
"host.upstream.too_many" => "One host can send traffic to at most {max} addresses.",
|
||||
"host.auth.not_configured" => {
|
||||
"Sign-in is not set up on this server yet, so choose Anyone for now. To set it up, add the Authelia address to ianitor.toml in the routes repository."
|
||||
}
|
||||
"host.header.name" => "\"{name}\" cannot be a header name. Use letters, digits and dashes.",
|
||||
"host.header.value" => {
|
||||
"This value has characters a header cannot carry. Use visible characters and spaces only."
|
||||
}
|
||||
"host.header.empty" => "Enter a value, or choose Remove to drop the header.",
|
||||
"host.header.protected" => "Ianitor sets {name} itself, so a rule cannot change it.",
|
||||
"host.header.duplicate" => "{name} already has a rule in this list.",
|
||||
"host.header.both" => "Choose a fixed value or a secret, not both.",
|
||||
"host.header.remove_value" => "Remove needs only the header name.",
|
||||
"host.header.secret_unknown" => {
|
||||
"There is no secret named {secret}. Secrets are listed in ianitor.toml and loaded from the server's credentials."
|
||||
}
|
||||
"host.header.secret_response" => {
|
||||
"Secrets can only be sent to your service, never back to visitors."
|
||||
}
|
||||
"host.health.path" => "Start with / and use plain characters, like /health.",
|
||||
"host.health.interval" => "Check every 1 to 3600 seconds.",
|
||||
"host.field.unknown" => "Ianitor does not know the setting \"{field}\".",
|
||||
"host.field.invalid" | "file.field.invalid" => {
|
||||
"One of the settings has a value Ianitor cannot use. Show details to see which."
|
||||
}
|
||||
"file.field.missing" => "The setting \"{field}\" is missing.",
|
||||
"change.conflict" => {
|
||||
"{hostname} was changed at {time} (\"{summary}\") after you opened it. Your edits are still here. Check them, then Apply again."
|
||||
}
|
||||
"change.unchanged" => "This is the same as what is live now, so nothing changed.",
|
||||
"host.not_found" => "{hostname} is no longer a host.",
|
||||
"host.share.no_signin" => {
|
||||
"Anyone can already open {hostname}, so a share link changes nothing."
|
||||
}
|
||||
// 3.2 apply, undo, restore, repository
|
||||
"apply.queued" => "Waiting for \"{summary}\" to finish, about {seconds} s.",
|
||||
"apply.kept" => "{hostname} is live. Health checks passed for {seconds} s.",
|
||||
"apply.kept.no_watch" => {
|
||||
"{hostname} is live. It has no health check, so Ianitor only checked that it answers."
|
||||
}
|
||||
"apply.kept.removed" => "{hostname} is removed.",
|
||||
"apply.kept.no_edge" => {
|
||||
"Saved. No proxy is attached (development mode), so nothing was checked."
|
||||
}
|
||||
"apply.reverted.refused" => {
|
||||
"{hostname} was not {verb}. {upstream} refused the connection on {count} of {of} checks. Ianitor undid the change; every other host kept running."
|
||||
}
|
||||
"apply.reverted.timeout" => {
|
||||
"{hostname} was not {verb}. {upstream} did not answer within 5 seconds on {count} of {of} checks. Ianitor undid the change."
|
||||
}
|
||||
"apply.reverted.not_found" => {
|
||||
"{hostname} was not {verb}. {upstream} says {path} does not exist. Check the health check address. Ianitor undid the change."
|
||||
}
|
||||
"apply.reverted.server_error" => {
|
||||
"{hostname} was not {verb}. {upstream} answered with an error page on {count} of {of} checks. Ianitor undid the change."
|
||||
}
|
||||
"apply.reverted.redirect" => {
|
||||
"{hostname} was not {verb}. {upstream} sent visitors elsewhere instead of answering {path}. Use an address that answers directly, like /health."
|
||||
}
|
||||
"apply.reverted.sign_in" => {
|
||||
"{hostname} was not {verb}. {upstream} asked for a sign-in on {path}. Use an address that answers without signing in."
|
||||
}
|
||||
"apply.reverted.name" => {
|
||||
"{hostname} was not {verb}. The name {upstream_host} could not be found on this network."
|
||||
}
|
||||
"apply.reverted.tls" => {
|
||||
"{hostname} was not {verb}. {upstream} uses https://, but its certificate could not be checked."
|
||||
}
|
||||
"apply.reverted.no_answer" => {
|
||||
"{hostname} was not {verb}. No health check finished within {seconds} s. Ianitor undid the change."
|
||||
}
|
||||
"apply.reverted.edge_lost" => {
|
||||
"The proxy restarted during the check, so it went back to the last good settings. Ianitor undid the change to match."
|
||||
}
|
||||
"apply.failed.reload" => {
|
||||
"{engine} did not take the new settings, so nothing changed. Every host kept running."
|
||||
}
|
||||
"apply.failed.build" => {
|
||||
"Ianitor could not build the settings for this change, so nothing changed."
|
||||
}
|
||||
"apply.failed.validation" => {
|
||||
"This change no longer fits with the routes: {first_error} Nothing changed."
|
||||
}
|
||||
"apply.failed.edge_unreachable" => {
|
||||
"Ianitor cannot reach the proxy right now, so nothing changed. Traffic is not affected."
|
||||
}
|
||||
"apply.interrupted" => {
|
||||
"Ianitor restarted during the check, so it undid the change to be safe."
|
||||
}
|
||||
"apply.interrupted.queued" => {
|
||||
"Ianitor restarted before this change ran, so nothing changed. Try again."
|
||||
}
|
||||
"apply.cancelled" => "Cancelled before it started. Nothing changed.",
|
||||
"apply.needs_attention" => {
|
||||
"The change failed its check, and Ianitor could not undo it by itself. Visitors are served the last good settings, but the routes repository still has the change."
|
||||
}
|
||||
"push.failed.unreachable" => {
|
||||
"Kept, but not yet saved to {remote}: {remote} did not answer. Ianitor tries again at {time}."
|
||||
}
|
||||
"push.failed.rejected" => {
|
||||
"Kept, but {remote} has changes Ianitor does not have, so nothing was sent. Nothing is lost on this server."
|
||||
}
|
||||
"push.failed.auth" => {
|
||||
"Kept, but {remote} refused Ianitor's access key. Check the key in Custos."
|
||||
}
|
||||
"undo.nothing" => "Nothing to undo yet.",
|
||||
"undo.watching" => "Wait for the check to finish ({seconds} s).",
|
||||
"undo.paused" => "Changes are paused, so Undo is not available.",
|
||||
"undo.target_moved" => {
|
||||
"The last change is now \"{summary}\", so Undo did nothing. Look again and choose."
|
||||
}
|
||||
"restore.same" => "This version is the same as the current one. Nothing to restore.",
|
||||
"restore.not_kept" => {
|
||||
"This change was undone at the time, so there is nothing to go back to."
|
||||
}
|
||||
"change.not_found" => "There is no change with that id.",
|
||||
"repo.unreadable" => {
|
||||
"{file} in the routes repository cannot be read. Changes are paused until it is fixed."
|
||||
}
|
||||
"repo.unexpected_file" => "{file} does not belong in the routes repository.",
|
||||
"repo.no_remote" => "No place to push to is set up.",
|
||||
// 3.4 share links
|
||||
"share.disabled" => {
|
||||
"Share links are off for {hostname}. Turning them on is a change to the host, checked like any other."
|
||||
}
|
||||
"share.prefix" => "Start with /, like /share/summer-2026. / shares the whole site.",
|
||||
"share.expiry" => "Choose between 1 hour and 90 days.",
|
||||
"share.password_short" => "Use at least 8 characters.",
|
||||
"share.password_long" => "Use at most 128 characters.",
|
||||
"share.stopped" => "Stopped. The link stops working within a few seconds.",
|
||||
"share.stopped_all" => "All share links are stopped. New ones work as usual.",
|
||||
"share.unavailable" => {
|
||||
"Share links are not set up on this server: the share-link key is missing from the credentials."
|
||||
}
|
||||
"share.too_many" => {
|
||||
"There are 2,000 active share links already. Stop some, or stop all, then try again."
|
||||
}
|
||||
"share.not_found" => "There is no share link with that id.",
|
||||
"share.replaces" => "The link to replace is not a link for {hostname}.",
|
||||
// 3.5 tokens, limits
|
||||
"token.missing" => "This request needs an API token. Make one in Settings, API.",
|
||||
"token.unknown" => {
|
||||
"This API token is not one Ianitor issued, or it was copied incompletely."
|
||||
}
|
||||
"token.expired" => {
|
||||
"This API token expired on {date}. Make a new one in Settings, API, then revoke this one."
|
||||
}
|
||||
"token.revoked" => "This API token was revoked on {date}.",
|
||||
"token.not_found" => "There is no API token with that id.",
|
||||
"token.name" => "Use 1 to 64 letters, digits, spaces, dots, dashes or underscores.",
|
||||
"token.expiry" => "Choose between 1 and 3650 days, or never.",
|
||||
"rate.limited" => "Too many requests in a short time. Try again in {seconds} s.",
|
||||
"control.files_unwritten" => {
|
||||
"The change is live, but Ianitor could not save the proxy settings to disk. Changes are paused until Ianitor restarts and saves them."
|
||||
}
|
||||
"control.paused" => "Changes are paused: {reason} Traffic keeps flowing.",
|
||||
// request shape
|
||||
"request.body" => "The request body is not valid: {problem}",
|
||||
"request.body_unknown_field" => "Ianitor does not know the field \"{field}\".",
|
||||
"request.too_large" => "The request body is too large.",
|
||||
"request.csrf" => {
|
||||
"This request came from a browser page without Ianitor's UI header, so it was refused."
|
||||
}
|
||||
"request.host" => "This request was sent to an address Ianitor does not answer on.",
|
||||
"request.not_found" => "There is no such API call.",
|
||||
"request.method" => "This API call does not take that method.",
|
||||
"request.in_progress" => {
|
||||
"The first request with this Idempotency-Key is still being handled. Try again in a moment."
|
||||
}
|
||||
"request.idempotency" => "This Idempotency-Key was already used for a different request.",
|
||||
"request.base_rev" => "base_rev is not a commit in the routes history.",
|
||||
"health.unavailable" => {
|
||||
"Ianitor cannot read health from {engine} right now. Traffic is not affected."
|
||||
}
|
||||
"internal" => "Something went wrong inside Ianitor control. Show details for more.",
|
||||
_ => "Something went wrong.",
|
||||
}
|
||||
}
|
||||
|
||||
/// The message for `code`, with params filled in.
|
||||
pub fn message(code: &str, params: &Params) -> String {
|
||||
let t = template(code);
|
||||
let mut out = String::with_capacity(t.len() + 32);
|
||||
let mut rest = t;
|
||||
while let Some(start) = rest.find('{') {
|
||||
out.push_str(&rest[..start]);
|
||||
let after = &rest[start + 1..];
|
||||
match after.find('}') {
|
||||
Some(end) => {
|
||||
let key = &after[..end];
|
||||
if let Some(v) = params.get(key) {
|
||||
out.push_str(v);
|
||||
}
|
||||
rest = &after[end + 1..];
|
||||
}
|
||||
None => {
|
||||
out.push_str(&rest[start..]);
|
||||
rest = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
pub fn params<const N: usize>(pairs: [(&str, String); N]) -> Params {
|
||||
pairs.into_iter().map(|(k, v)| (k.to_owned(), v)).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn placeholders_are_filled() {
|
||||
let p = params([("hostname", "a.test".into()), ("max", "64".into())]);
|
||||
assert_eq!(
|
||||
message("host.hostname.taken", &p),
|
||||
"a.test is already a host."
|
||||
);
|
||||
assert_eq!(
|
||||
message("host.upstream.too_many", &p),
|
||||
"One host can send traffic to at most 64 addresses."
|
||||
);
|
||||
assert!(!message("token.revoked", &Params::new()).contains('{'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
// 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/.
|
||||
|
||||
//! Apply records (one per user action: the history the UI shows, docs/ui-api.md §2.1) and the
|
||||
//! apply journal (what a crash interrupted).
|
||||
//!
|
||||
//! The journal (`journal.json`) is written, atomically and durably, before every step that
|
||||
//! changes the outside world, so after a crash control knows how far an apply got:
|
||||
//!
|
||||
//! | stage | what has happened | recovery |
|
||||
//! |:--|:--|:--|
|
||||
//! | `prepared` | commit object made, branch not moved | branch at base: nothing to undo; at the commit: as `committed` |
|
||||
//! | `committed` | branch moved to the commit | revert commit, abort trial, drop trial files |
|
||||
//! | `trial_written` | trial files written | same |
|
||||
//! | `trial_loaded` | edge serves the trial (and reverts by itself at its deadline) | same |
|
||||
//! | `confirmed` | edge confirmed the trial | promote trial files, record kept |
|
||||
//! | `promoted` | files promoted | record kept |
|
||||
//! | `reverting` | revert started | finish the revert |
|
||||
//!
|
||||
//! Throughout, `edge.json` and `caddy.json` only ever hold a config that passed its watch.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::hostspec::HostSpec;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
|
||||
pub struct Step {
|
||||
/// `validate`, `compile`, `write`, `reload`, `watch` or `push`.
|
||||
pub key: String,
|
||||
/// `pending`, `running`, `done`, `failed` or `skipped`.
|
||||
pub state: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, ToSchema)]
|
||||
pub struct WatchHost {
|
||||
pub hostname: String,
|
||||
pub passed: u32,
|
||||
pub failed: u32,
|
||||
pub total: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
|
||||
pub struct Watch {
|
||||
/// Unix seconds.
|
||||
pub ends: u64,
|
||||
pub hosts: Vec<WatchHost>,
|
||||
}
|
||||
|
||||
/// Why an apply did not stay (or a detail of why it did).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, ToSchema)]
|
||||
pub struct Reason {
|
||||
pub code: String,
|
||||
/// Plain English, from `messages`.
|
||||
pub message: String,
|
||||
pub hostname: Option<String>,
|
||||
pub upstream: Option<String>,
|
||||
pub field: Option<String>,
|
||||
pub count: Option<u32>,
|
||||
pub of: Option<u32>,
|
||||
/// Technical detail (core's text, edge's error); never a secret.
|
||||
pub detail: Option<String>,
|
||||
#[serde(default)]
|
||||
pub params: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// One field problem, in the API error shape.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
|
||||
pub struct FieldError {
|
||||
pub code: String,
|
||||
pub message: String,
|
||||
pub field: Option<String>,
|
||||
pub params: BTreeMap<String, String>,
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct ApplyRecord {
|
||||
pub id: String,
|
||||
/// `add`, `edit`, `remove`, `undo`, `restore` or `share_links`.
|
||||
pub kind: String,
|
||||
pub summary: String,
|
||||
pub hosts: Vec<String>,
|
||||
/// `queued`, `validating`, `applying`, `watching`, `kept`, `reverted`, `failed` or
|
||||
/// `needs_attention`.
|
||||
pub state: String,
|
||||
pub steps: Vec<Step>,
|
||||
pub created: u64,
|
||||
pub started: Option<u64>,
|
||||
pub finished: Option<u64>,
|
||||
pub watch: Option<Watch>,
|
||||
pub reason: Option<Reason>,
|
||||
#[serde(default)]
|
||||
pub errors: Vec<FieldError>,
|
||||
/// Branch head when the apply started.
|
||||
pub base: Option<String>,
|
||||
/// The commit of this change (none if it never got one).
|
||||
pub commit: Option<String>,
|
||||
/// The commit that undid it, for reverted applies.
|
||||
pub revert_commit: Option<String>,
|
||||
pub undo_of: Option<String>,
|
||||
pub restore_of: Option<String>,
|
||||
/// Token name of whoever asked.
|
||||
pub actor: String,
|
||||
/// What was tried, for "Edit and try again".
|
||||
pub attempted_host: Option<HostSpec>,
|
||||
/// For undo: what it does ("Removes x").
|
||||
pub effect: Option<String>,
|
||||
}
|
||||
|
||||
pub const STEP_KEYS: [&str; 6] = ["validate", "compile", "write", "reload", "watch", "push"];
|
||||
|
||||
impl ApplyRecord {
|
||||
pub fn new(
|
||||
id: String,
|
||||
kind: &str,
|
||||
summary: String,
|
||||
hosts: Vec<String>,
|
||||
actor: &str,
|
||||
t: u64,
|
||||
) -> ApplyRecord {
|
||||
ApplyRecord {
|
||||
id,
|
||||
kind: kind.into(),
|
||||
summary,
|
||||
hosts,
|
||||
state: "queued".into(),
|
||||
steps: STEP_KEYS
|
||||
.iter()
|
||||
.map(|k| Step {
|
||||
key: (*k).into(),
|
||||
state: "pending".into(),
|
||||
})
|
||||
.collect(),
|
||||
created: t,
|
||||
started: None,
|
||||
finished: None,
|
||||
watch: None,
|
||||
reason: None,
|
||||
errors: Vec::new(),
|
||||
base: None,
|
||||
commit: None,
|
||||
revert_commit: None,
|
||||
undo_of: None,
|
||||
restore_of: None,
|
||||
actor: actor.into(),
|
||||
attempted_host: None,
|
||||
effect: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn step(&mut self, key: &str, state: &str) {
|
||||
if let Some(s) = self.steps.iter_mut().find(|s| s.key == key) {
|
||||
s.state = state.into();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_active(&self) -> bool {
|
||||
matches!(
|
||||
self.state.as_str(),
|
||||
"queued" | "validating" | "applying" | "watching"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn is_running(&self) -> bool {
|
||||
matches!(self.state.as_str(), "validating" | "applying" | "watching")
|
||||
}
|
||||
|
||||
/// A kept change with a commit: something Undo can target.
|
||||
pub fn is_kept_change(&self) -> bool {
|
||||
self.state == "kept" && self.commit.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Journal {
|
||||
pub apply_id: String,
|
||||
pub stage: String,
|
||||
pub base: String,
|
||||
pub commit: String,
|
||||
pub edge_sha256: Option<String>,
|
||||
pub reason: Option<Reason>,
|
||||
}
|
||||
|
||||
/// Push state, in `push.json`.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PushState {
|
||||
pub pushed: Option<String>,
|
||||
pub last_push_at: Option<u64>,
|
||||
pub last_attempt_at: Option<u64>,
|
||||
pub next_try_at: Option<u64>,
|
||||
pub error_code: Option<String>,
|
||||
pub error_detail: Option<String>,
|
||||
#[serde(default)]
|
||||
pub failures: u32,
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
// 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 routes repository: a bare git repository driven through the `git` binary.
|
||||
//!
|
||||
//! Why the `git` binary (not git2 or gix): pushing to Gitea over HTTPS or SSH is required,
|
||||
//! and gix cannot push yet; git2 would bring libgit2 plus OpenSSL/libssh2 as C dependencies
|
||||
//! into the Nix build, while `git` is one store path Mark already uses, with the same
|
||||
//! behaviour he sees by hand. Control only uses plumbing with fixed arguments: commit ids are
|
||||
//! checked to be hex before they reach a command line, file content goes through stdin, the
|
||||
//! environment is cleared (no user or system git config, no hooks, no prompts), and objects
|
||||
//! and refs are fsync'ed so a crash cannot lose a commit edge already runs.
|
||||
//!
|
||||
//! Control never reads a working tree: trees are read from git objects, so symbolic links or
|
||||
//! files outside the repository cannot be smuggled in. A tree must have exactly the shape
|
||||
//! `ianitor_core::routes` allows.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use ianitor_core::routes::{self, EntryKind, SITE_FILE};
|
||||
use ianitor_core::{MAX_FILE_BYTES, ValidationError};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RepoError {
|
||||
#[error("git {op} failed: {message}")]
|
||||
Git { op: String, message: String },
|
||||
#[error("the routes repository has files that do not belong there")]
|
||||
Shape(Vec<ValidationError>),
|
||||
#[error("{0} is not a commit in the routes history")]
|
||||
UnknownCommit(String),
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// A commit id: 40 (SHA-1) or 64 (SHA-256) lowercase hex digits.
|
||||
pub fn is_commit_id(s: &str) -> bool {
|
||||
(s.len() == 40 || s.len() == 64)
|
||||
&& s.bytes()
|
||||
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
|
||||
}
|
||||
|
||||
/// The files of one routes tree: path → content. Paths are exactly `ianitor.toml` and
|
||||
/// `hosts/<hostname>.toml`.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct RouteTree {
|
||||
pub files: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl RouteTree {
|
||||
pub fn site(&self) -> &str {
|
||||
self.files.get(SITE_FILE).map_or("", String::as_str)
|
||||
}
|
||||
|
||||
pub fn host(&self, hostname: &str) -> Option<&str> {
|
||||
self.files
|
||||
.get(&routes::host_path(hostname))
|
||||
.map(String::as_str)
|
||||
}
|
||||
|
||||
pub fn hostnames(&self) -> Vec<String> {
|
||||
self.files
|
||||
.keys()
|
||||
.filter_map(|p| p.strip_prefix("hosts/")?.strip_suffix(".toml"))
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn set_host(&mut self, hostname: &str, contents: String) {
|
||||
self.files.insert(routes::host_path(hostname), contents);
|
||||
}
|
||||
|
||||
pub fn remove_host(&mut self, hostname: &str) -> bool {
|
||||
self.files.remove(&routes::host_path(hostname)).is_some()
|
||||
}
|
||||
|
||||
/// Load and validate with core.
|
||||
pub fn model(&self) -> Result<ianitor_core::Model, ianitor_core::ValidationErrors> {
|
||||
let hosts: Vec<ianitor_core::SourceFile> = self
|
||||
.files
|
||||
.iter()
|
||||
.filter(|(p, _)| p.as_str() != SITE_FILE)
|
||||
.map(|(p, c)| ianitor_core::SourceFile {
|
||||
name: p,
|
||||
contents: c,
|
||||
})
|
||||
.collect();
|
||||
ianitor_core::load(
|
||||
&ianitor_core::SourceFile {
|
||||
name: SITE_FILE,
|
||||
contents: self.site(),
|
||||
},
|
||||
&hosts,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Facts about one commit.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CommitInfo {
|
||||
pub id: String,
|
||||
pub parents: Vec<String>,
|
||||
pub time: u64,
|
||||
pub subject: String,
|
||||
}
|
||||
|
||||
pub struct Repo {
|
||||
git: PathBuf,
|
||||
dir: PathBuf,
|
||||
home: PathBuf,
|
||||
branch: String,
|
||||
cache: Mutex<Option<(String, Arc<RouteTree>)>>,
|
||||
}
|
||||
|
||||
fn null_device() -> &'static str {
|
||||
if cfg!(windows) { "NUL" } else { "/dev/null" }
|
||||
}
|
||||
|
||||
impl Repo {
|
||||
/// Open (or create, with an empty `ianitor.toml`) the bare repository at `dir`.
|
||||
pub fn open(git: &Path, dir: &Path, home: &Path, branch: &str) -> Result<Repo, RepoError> {
|
||||
Repo::open_seeded(git, dir, home, branch, "")
|
||||
}
|
||||
|
||||
/// Like [`Repo::open`]; a new repository starts with `site` as its `ianitor.toml`.
|
||||
pub fn open_seeded(
|
||||
git: &Path,
|
||||
dir: &Path,
|
||||
home: &Path,
|
||||
branch: &str,
|
||||
site: &str,
|
||||
) -> Result<Repo, RepoError> {
|
||||
let repo = Repo {
|
||||
git: git.to_owned(),
|
||||
dir: dir.to_owned(),
|
||||
home: home.to_owned(),
|
||||
branch: branch.to_owned(),
|
||||
cache: Mutex::new(None),
|
||||
};
|
||||
if !dir.join("HEAD").exists() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| RepoError::Other(e.to_string()))?;
|
||||
repo.run_in(
|
||||
None,
|
||||
&[
|
||||
"init",
|
||||
"--bare",
|
||||
"--quiet",
|
||||
&format!("--initial-branch={branch}"),
|
||||
],
|
||||
Some(dir),
|
||||
None,
|
||||
&[],
|
||||
)?;
|
||||
}
|
||||
if repo.head()?.is_none() {
|
||||
let mut t = RouteTree::default();
|
||||
t.files.insert(SITE_FILE.into(), site.to_owned());
|
||||
let tree = repo.write_tree(&t, None)?;
|
||||
let c = repo.commit(&tree, &[], "Start the routes repository", "Ianitor control")?;
|
||||
repo.update_ref(&c, None)?;
|
||||
}
|
||||
Ok(repo)
|
||||
}
|
||||
|
||||
pub fn dir(&self) -> &Path {
|
||||
&self.dir
|
||||
}
|
||||
|
||||
fn command(&self) -> Command {
|
||||
let mut c = Command::new(&self.git);
|
||||
c.env_clear();
|
||||
if let Some(p) = std::env::var_os("PATH") {
|
||||
c.env("PATH", p);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
for v in ["SYSTEMROOT", "TEMP", "TMP"] {
|
||||
if let Some(x) = std::env::var_os(v) {
|
||||
c.env(v, x);
|
||||
}
|
||||
}
|
||||
c.env("HOME", &self.home)
|
||||
.env("LC_ALL", "C")
|
||||
.env("GIT_CONFIG_NOSYSTEM", "1")
|
||||
.env("GIT_CONFIG_GLOBAL", null_device())
|
||||
.env("GIT_TERMINAL_PROMPT", "0")
|
||||
.args([
|
||||
"-c",
|
||||
&format!("core.hooksPath={}", null_device()),
|
||||
"-c",
|
||||
"core.fsync=all",
|
||||
"-c",
|
||||
"core.fsyncMethod=fsync",
|
||||
]);
|
||||
c
|
||||
}
|
||||
|
||||
fn run_in(
|
||||
&self,
|
||||
git_dir: Option<&Path>,
|
||||
args: &[&str],
|
||||
cwd: Option<&Path>,
|
||||
stdin: Option<&[u8]>,
|
||||
env: &[(&str, &str)],
|
||||
) -> Result<Vec<u8>, RepoError> {
|
||||
let mut c = self.command();
|
||||
if let Some(d) = git_dir {
|
||||
c.env("GIT_DIR", d);
|
||||
}
|
||||
if let Some(d) = cwd {
|
||||
c.current_dir(d);
|
||||
}
|
||||
for (k, v) in env {
|
||||
c.env(k, v);
|
||||
}
|
||||
c.args(args)
|
||||
.stdin(if stdin.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::null()
|
||||
})
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
let op = args.first().copied().unwrap_or("").to_owned();
|
||||
let mut child = c.spawn().map_err(|e| RepoError::Git {
|
||||
op: op.clone(),
|
||||
message: format!("cannot run {}: {e}", self.git.display()),
|
||||
})?;
|
||||
if let (Some(data), Some(mut si)) = (stdin, child.stdin.take()) {
|
||||
si.write_all(data).map_err(|e| RepoError::Git {
|
||||
op: op.clone(),
|
||||
message: e.to_string(),
|
||||
})?;
|
||||
}
|
||||
let out = child.wait_with_output().map_err(|e| RepoError::Git {
|
||||
op: op.clone(),
|
||||
message: e.to_string(),
|
||||
})?;
|
||||
if !out.status.success() {
|
||||
return Err(RepoError::Git {
|
||||
op,
|
||||
message: String::from_utf8_lossy(&out.stderr)
|
||||
.trim()
|
||||
.chars()
|
||||
.take(500)
|
||||
.collect(),
|
||||
});
|
||||
}
|
||||
Ok(out.stdout)
|
||||
}
|
||||
|
||||
fn git(&self, args: &[&str], stdin: Option<&[u8]>) -> Result<Vec<u8>, RepoError> {
|
||||
self.run_in(Some(&self.dir), args, None, stdin, &[])
|
||||
}
|
||||
|
||||
fn git_str(&self, args: &[&str]) -> Result<String, RepoError> {
|
||||
Ok(String::from_utf8_lossy(&self.git(args, None)?)
|
||||
.trim()
|
||||
.to_owned())
|
||||
}
|
||||
|
||||
fn reference(&self) -> String {
|
||||
format!("refs/heads/{}", self.branch)
|
||||
}
|
||||
|
||||
/// The current commit of the branch.
|
||||
pub fn head(&self) -> Result<Option<String>, RepoError> {
|
||||
match self.git(
|
||||
&["rev-parse", "--verify", "--quiet", &self.reference()],
|
||||
None,
|
||||
) {
|
||||
Ok(out) => {
|
||||
let s = String::from_utf8_lossy(&out).trim().to_owned();
|
||||
Ok(is_commit_id(&s).then_some(s))
|
||||
}
|
||||
Err(RepoError::Git { .. }) => Ok(None),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn head_required(&self) -> Result<String, RepoError> {
|
||||
self.head()?
|
||||
.ok_or_else(|| RepoError::Other("the routes branch has no commit".into()))
|
||||
}
|
||||
|
||||
/// Is `id` a commit reachable from the branch head?
|
||||
pub fn in_history(&self, id: &str) -> Result<bool, RepoError> {
|
||||
if !is_commit_id(id) {
|
||||
return Ok(false);
|
||||
}
|
||||
let head = self.head_required()?;
|
||||
let mut c = self.command();
|
||||
c.env("GIT_DIR", &self.dir)
|
||||
.args(["merge-base", "--is-ancestor", id, &head])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
let st = c.status().map_err(|e| RepoError::Git {
|
||||
op: "merge-base".into(),
|
||||
message: e.to_string(),
|
||||
})?;
|
||||
Ok(st.success())
|
||||
}
|
||||
|
||||
pub fn info(&self, id: &str) -> Result<CommitInfo, RepoError> {
|
||||
if !is_commit_id(id) {
|
||||
return Err(RepoError::UnknownCommit(id.chars().take(64).collect()));
|
||||
}
|
||||
let out = self
|
||||
.git(
|
||||
&[
|
||||
"show",
|
||||
"-s",
|
||||
"--format=%H%x00%P%x00%at%x00%s",
|
||||
"--end-of-options",
|
||||
id,
|
||||
],
|
||||
None,
|
||||
)
|
||||
.map_err(|_| RepoError::UnknownCommit(id.to_owned()))?;
|
||||
let text = String::from_utf8_lossy(&out);
|
||||
let mut f = text.trim_end_matches('\n').split('\0');
|
||||
let (Some(h), Some(p), Some(t), Some(s)) = (f.next(), f.next(), f.next(), f.next()) else {
|
||||
return Err(RepoError::UnknownCommit(id.to_owned()));
|
||||
};
|
||||
Ok(CommitInfo {
|
||||
id: h.to_owned(),
|
||||
parents: p
|
||||
.split(' ')
|
||||
.filter(|x| !x.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect(),
|
||||
time: t.parse().unwrap_or(0),
|
||||
subject: s.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Read the tree of a commit, checking its shape. Cached for the last commit read.
|
||||
pub fn tree(&self, commit: &str) -> Result<Arc<RouteTree>, RepoError> {
|
||||
if !is_commit_id(commit) {
|
||||
return Err(RepoError::UnknownCommit(commit.chars().take(64).collect()));
|
||||
}
|
||||
if let Ok(c) = self.cache.lock()
|
||||
&& let Some((id, t)) = c.as_ref()
|
||||
&& id == commit
|
||||
{
|
||||
return Ok(t.clone());
|
||||
}
|
||||
let listing = self.git(&["ls-tree", "-r", "-z", "--full-tree", "-l", commit], None)?;
|
||||
let mut entries = Vec::new();
|
||||
for rec in listing.split(|b| *b == 0).filter(|r| !r.is_empty()) {
|
||||
let rec = String::from_utf8_lossy(rec);
|
||||
let (meta, path) = rec
|
||||
.split_once('\t')
|
||||
.ok_or_else(|| RepoError::Other("unexpected ls-tree output".into()))?;
|
||||
let mut m = meta.split_whitespace();
|
||||
let (mode, kind, sha, size) = (m.next(), m.next(), m.next(), m.next());
|
||||
let entry_kind = match (mode, kind) {
|
||||
(Some("100644"), Some("blob")) => EntryKind::File,
|
||||
(Some("100755"), Some("blob")) => EntryKind::Executable,
|
||||
(Some("120000"), _) => EntryKind::Symlink,
|
||||
_ => EntryKind::Submodule,
|
||||
};
|
||||
let size: usize = size.and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
entries.push((
|
||||
path.to_owned(),
|
||||
entry_kind,
|
||||
sha.unwrap_or("").to_owned(),
|
||||
size,
|
||||
));
|
||||
}
|
||||
routes::check_tree(entries.iter().map(|(p, k, _, _)| (p.as_str(), *k)))
|
||||
.map_err(RepoError::Shape)?;
|
||||
let mut tree = RouteTree::default();
|
||||
for (path, _, sha, size) in entries {
|
||||
if size > MAX_FILE_BYTES {
|
||||
return Err(RepoError::Shape(vec![ValidationError::FileTooLarge {
|
||||
file: path,
|
||||
max: MAX_FILE_BYTES,
|
||||
}]));
|
||||
}
|
||||
if !is_commit_id(&sha) {
|
||||
return Err(RepoError::Other("unexpected object id".into()));
|
||||
}
|
||||
let blob = self.git(&["cat-file", "blob", &sha], None)?;
|
||||
let text = String::from_utf8(blob).map_err(|_| {
|
||||
RepoError::Shape(vec![ValidationError::Syntax {
|
||||
file: path.clone(),
|
||||
line: None,
|
||||
message: "the file is not UTF-8 text".into(),
|
||||
}])
|
||||
})?;
|
||||
tree.files.insert(path, text);
|
||||
}
|
||||
let tree = Arc::new(tree);
|
||||
if let Ok(mut c) = self.cache.lock() {
|
||||
*c = Some((commit.to_owned(), tree.clone()));
|
||||
}
|
||||
Ok(tree)
|
||||
}
|
||||
|
||||
/// Write the tree objects for `tree`; returns the tree id.
|
||||
pub fn write_tree(&self, tree: &RouteTree, _base: Option<&str>) -> Result<String, RepoError> {
|
||||
let mut hosts = Vec::new();
|
||||
let mut root = Vec::new();
|
||||
for (path, content) in &tree.files {
|
||||
let sha = self.git_str_in(&["hash-object", "-w", "--stdin"], content.as_bytes())?;
|
||||
if let Some(name) = path.strip_prefix("hosts/") {
|
||||
hosts.extend_from_slice(format!("100644 blob {sha}\t{name}\0").as_bytes());
|
||||
} else {
|
||||
root.extend_from_slice(format!("100644 blob {sha}\t{path}\0").as_bytes());
|
||||
}
|
||||
}
|
||||
if !hosts.is_empty() {
|
||||
let sub = self.git_str_in(&["mktree", "-z"], &hosts)?;
|
||||
root.extend_from_slice(format!("040000 tree {sub}\thosts\0").as_bytes());
|
||||
}
|
||||
self.git_str_in(&["mktree", "-z"], &root)
|
||||
}
|
||||
|
||||
fn git_str_in(&self, args: &[&str], stdin: &[u8]) -> Result<String, RepoError> {
|
||||
let out = self.git(args, Some(stdin))?;
|
||||
let s = String::from_utf8_lossy(&out).trim().to_owned();
|
||||
if !is_commit_id(&s) {
|
||||
return Err(RepoError::Other(format!(
|
||||
"git {} gave no object id",
|
||||
args[0]
|
||||
)));
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// Create a commit object (not yet on the branch).
|
||||
pub fn commit(
|
||||
&self,
|
||||
tree: &str,
|
||||
parents: &[&str],
|
||||
message: &str,
|
||||
author: &str,
|
||||
) -> Result<String, RepoError> {
|
||||
let mut args = vec!["commit-tree", tree];
|
||||
for p in parents {
|
||||
args.push("-p");
|
||||
args.push(p);
|
||||
}
|
||||
args.extend(["-F", "-"]);
|
||||
let author: String = author
|
||||
.chars()
|
||||
.filter(|c| !c.is_control() && !"<>".contains(*c))
|
||||
.take(64)
|
||||
.collect();
|
||||
let author = if author.trim().is_empty() {
|
||||
"Ianitor control".to_owned()
|
||||
} else {
|
||||
author
|
||||
};
|
||||
let env = [
|
||||
("GIT_AUTHOR_NAME", author.as_str()),
|
||||
("GIT_AUTHOR_EMAIL", "ianitor@localhost"),
|
||||
("GIT_COMMITTER_NAME", "Ianitor control"),
|
||||
("GIT_COMMITTER_EMAIL", "ianitor@localhost"),
|
||||
];
|
||||
let out = self.run_in(Some(&self.dir), &args, None, Some(message.as_bytes()), &env)?;
|
||||
let s = String::from_utf8_lossy(&out).trim().to_owned();
|
||||
if !is_commit_id(&s) {
|
||||
return Err(RepoError::Other("git commit-tree gave no commit id".into()));
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
pub fn tree_id(&self, commit: &str) -> Result<String, RepoError> {
|
||||
if !is_commit_id(commit) {
|
||||
return Err(RepoError::UnknownCommit(commit.to_owned()));
|
||||
}
|
||||
self.git_str(&["rev-parse", "--verify", &format!("{commit}^{{tree}}")])
|
||||
}
|
||||
|
||||
/// Move the branch to `new` only if it is still at `old` (compare and swap).
|
||||
pub fn update_ref(&self, new: &str, old: Option<&str>) -> Result<(), RepoError> {
|
||||
let zero = "0".repeat(new.len());
|
||||
let old = old.unwrap_or(&zero);
|
||||
self.git(&["update-ref", &self.reference(), new, old], None)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// Number of commits in `to` that are not in `from` (`from` none: all of `to`).
|
||||
pub fn count_between(&self, from: Option<&str>, to: &str) -> Result<u64, RepoError> {
|
||||
let range = match from {
|
||||
Some(f) if is_commit_id(f) => format!("{f}..{to}"),
|
||||
_ => to.to_owned(),
|
||||
};
|
||||
Ok(self
|
||||
.git_str(&["rev-list", "--count", &range])?
|
||||
.parse()
|
||||
.unwrap_or(0))
|
||||
}
|
||||
|
||||
/// Push `commit` to the branch on `remote`. Credentials come through `GIT_ASKPASS`
|
||||
/// (this binary's `askpass` mode), never on a command line or in a file.
|
||||
pub async fn push(
|
||||
&self,
|
||||
remote: &str,
|
||||
commit: &str,
|
||||
askpass: Option<(PathBuf, String, PathBuf)>,
|
||||
timeout: std::time::Duration,
|
||||
) -> Result<(), RepoError> {
|
||||
if !is_commit_id(commit) {
|
||||
return Err(RepoError::UnknownCommit(commit.to_owned()));
|
||||
}
|
||||
let std_cmd = self.command();
|
||||
let mut c = tokio::process::Command::from(std_cmd);
|
||||
c.env("GIT_DIR", &self.dir);
|
||||
if let Some((exe, user, file)) = askpass {
|
||||
c.env("GIT_ASKPASS", exe)
|
||||
.env("IANITOR_ASKPASS", "1")
|
||||
.env("IANITOR_ASKPASS_USER", user)
|
||||
.env("IANITOR_ASKPASS_FILE", file);
|
||||
}
|
||||
c.args([
|
||||
"push",
|
||||
"--porcelain",
|
||||
"--",
|
||||
remote,
|
||||
&format!("{commit}:{}", self.reference()),
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
let child = c.spawn().map_err(|e| RepoError::Git {
|
||||
op: "push".into(),
|
||||
message: e.to_string(),
|
||||
})?;
|
||||
let out = tokio::time::timeout(timeout, child.wait_with_output())
|
||||
.await
|
||||
.map_err(|_| RepoError::Git {
|
||||
op: "push".into(),
|
||||
message: format!("no answer within {} s", timeout.as_secs()),
|
||||
})?
|
||||
.map_err(|e| RepoError::Git {
|
||||
op: "push".into(),
|
||||
message: e.to_string(),
|
||||
})?;
|
||||
if out.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
let text = format!(
|
||||
"{} {}",
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
Err(RepoError::Git {
|
||||
op: "push".into(),
|
||||
message: text.trim().chars().take(500).collect(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
// 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/.
|
||||
|
||||
//! Share links on control's side: minting, the list, stopping.
|
||||
//!
|
||||
//! Control keeps what it minted in `share-links.json` (never the token itself) and writes
|
||||
//! the revocation file edge reads (`{"epoch": n, "deny": [ids]}`): ids of stopped links that
|
||||
//! have not expired yet, and the epoch below which every token is refused ("stop all").
|
||||
//! The file lives outside git, is written atomically, and edge re-reads it when control asks
|
||||
//! and on its own every 5 s. When control is down nothing can be stopped, but edge keeps
|
||||
//! refusing what is already on the list, also across its own restarts.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use ianitor_core::share::{self, LinkSpec, ShareId, ShareKey};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::util::{now, random, read_json, write_json};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct LinkRecord {
|
||||
pub id: String,
|
||||
pub hostname: String,
|
||||
pub path_prefix: String,
|
||||
pub epoch: u32,
|
||||
pub created_at: u64,
|
||||
pub expires_at: u64,
|
||||
pub has_password: bool,
|
||||
pub created_by: String,
|
||||
pub stopped_at: Option<u64>,
|
||||
}
|
||||
|
||||
impl LinkRecord {
|
||||
pub fn state(&self, epoch: u32, t: u64) -> &'static str {
|
||||
if self.stopped_at.is_some() || self.epoch < epoch {
|
||||
"stopped"
|
||||
} else if t >= self.expires_at {
|
||||
"expired"
|
||||
} else {
|
||||
"active"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ShareFile {
|
||||
pub epoch: u32,
|
||||
pub links: Vec<LinkRecord>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct RevocationFile {
|
||||
epoch: u32,
|
||||
deny: Vec<String>,
|
||||
}
|
||||
|
||||
/// Kept in the list this long after expiry or stop.
|
||||
const KEEP_SECS: u64 = 30 * 86_400;
|
||||
pub const MIN_EXPIRY: u64 = 3600;
|
||||
pub const MAX_EXPIRY: u64 = 90 * 86_400;
|
||||
/// Most active links at once.
|
||||
pub const MAX_ACTIVE: usize = 2000;
|
||||
/// Most ids edge takes on its deny list (edge refuses 10,000 and more).
|
||||
const MAX_DENY: usize = 9_999;
|
||||
|
||||
pub struct Shares {
|
||||
path: PathBuf,
|
||||
revocations: PathBuf,
|
||||
lock: std::sync::Mutex<()>,
|
||||
}
|
||||
|
||||
pub struct Minted {
|
||||
pub record: LinkRecord,
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum MintError {
|
||||
Prefix,
|
||||
Expiry,
|
||||
PasswordShort,
|
||||
PasswordLong,
|
||||
Replaces,
|
||||
/// More active links than [`MAX_ACTIVE`].
|
||||
TooMany,
|
||||
Store(String),
|
||||
}
|
||||
|
||||
impl Shares {
|
||||
pub fn new(state_dir: &Path, revocations: &Path) -> Shares {
|
||||
Shares {
|
||||
path: state_dir.join("share-links.json"),
|
||||
revocations: revocations.to_owned(),
|
||||
lock: std::sync::Mutex::new(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load(&self) -> Result<ShareFile, String> {
|
||||
Ok(read_json(&self.path)?.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The revocation file as edge has it now, if it can be read.
|
||||
fn published(&self) -> Option<(u32, BTreeSet<String>)> {
|
||||
#[derive(Deserialize)]
|
||||
struct Published {
|
||||
epoch: u32,
|
||||
deny: Vec<String>,
|
||||
}
|
||||
let p: Published = serde_json::from_slice(&std::fs::read(&self.revocations).ok()?).ok()?;
|
||||
Some((p.epoch, p.deny.into_iter().collect()))
|
||||
}
|
||||
|
||||
/// The records, with the epoch never below the published one (records lost or restored
|
||||
/// from an older backup must not bring stopped links back).
|
||||
fn load_reconciled(&self) -> Result<ShareFile, String> {
|
||||
let mut f = self.load()?;
|
||||
if let Some((epoch, _)) = self.published()
|
||||
&& epoch > f.epoch
|
||||
{
|
||||
log::warn!(target: "ianitor::share", "share-link records are behind the published revocations (epoch {} < {epoch}); continuing from {epoch}", f.epoch);
|
||||
f.epoch = epoch;
|
||||
}
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
fn save(&self, f: &mut ShareFile) -> Result<(), String> {
|
||||
let t = now();
|
||||
// Kept at least until they expire: a stopped link must stay on the deny list as long
|
||||
// as its token would otherwise work.
|
||||
f.links
|
||||
.retain(|l| t < l.expires_at.saturating_add(KEEP_SECS));
|
||||
let deny = self.reconcile(f);
|
||||
write_json(&self.path, f)?;
|
||||
self.publish(f.epoch, deny)
|
||||
}
|
||||
|
||||
/// The deny list for `f`, raising `f.epoch` when the list cannot be kept whole:
|
||||
/// - a published id that the records cannot account for (stopped link lost from the
|
||||
/// records) is never just dropped: the epoch goes up, which stops every older link;
|
||||
/// - a list longer than edge accepts also raises the epoch, instead of being cut short.
|
||||
fn reconcile(&self, f: &mut ShareFile) -> Vec<String> {
|
||||
let t = now();
|
||||
let published = self.published();
|
||||
if let Some((epoch, _)) = &published {
|
||||
f.epoch = f.epoch.max(*epoch);
|
||||
}
|
||||
let deny_for = |f: &ShareFile| -> Vec<String> {
|
||||
let mut d: Vec<String> = f
|
||||
.links
|
||||
.iter()
|
||||
.filter(|l| l.stopped_at.is_some() && l.expires_at > t && l.epoch >= f.epoch)
|
||||
.map(|l| l.id.clone())
|
||||
.collect();
|
||||
d.sort();
|
||||
d
|
||||
};
|
||||
let mut deny = deny_for(f);
|
||||
if let Some((epoch, old)) = published
|
||||
&& epoch == f.epoch
|
||||
{
|
||||
let accounted = |id: &String| {
|
||||
deny.binary_search(id).is_ok()
|
||||
|| f.links
|
||||
.iter()
|
||||
.any(|l| &l.id == id && (l.expires_at <= t || l.epoch < f.epoch))
|
||||
};
|
||||
if !old.iter().all(accounted) {
|
||||
log::warn!(target: "ianitor::share", "stopped links are missing from the records; raising the epoch, which stops every earlier link");
|
||||
f.epoch = f.epoch.saturating_add(1);
|
||||
deny = deny_for(f);
|
||||
}
|
||||
}
|
||||
if deny.len() > MAX_DENY {
|
||||
log::warn!(target: "ianitor::share", "more than {MAX_DENY} stopped links; raising the epoch, which stops every earlier link");
|
||||
f.epoch = f.epoch.saturating_add(1);
|
||||
deny = deny_for(f);
|
||||
}
|
||||
deny
|
||||
}
|
||||
|
||||
/// Write the revocation file edge reads.
|
||||
fn publish(&self, epoch: u32, deny: Vec<String>) -> Result<(), String> {
|
||||
// Readable by edge (another user); it holds only random link ids.
|
||||
let text =
|
||||
serde_json::to_vec(&RevocationFile { epoch, deny }).map_err(|e| e.to_string())?;
|
||||
crate::util::write_atomic(&self.revocations, &text, 0o644)
|
||||
.map_err(|e| format!("cannot write {}: {e}", self.revocations.display()))
|
||||
}
|
||||
|
||||
pub fn ensure_revocation_file(&self) -> Result<(), String> {
|
||||
let _g = self
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| "share store unavailable".to_owned())?;
|
||||
let mut f = self.load()?;
|
||||
self.save(&mut f)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn mint(
|
||||
&self,
|
||||
key: &ShareKey,
|
||||
hostname: &str,
|
||||
prefix: &str,
|
||||
expires_in: u64,
|
||||
password: Option<&str>,
|
||||
replaces: Option<&str>,
|
||||
actor: &str,
|
||||
) -> Result<Minted, MintError> {
|
||||
let prefix = share::check_prefix(prefix).map_err(|_| MintError::Prefix)?;
|
||||
if !(MIN_EXPIRY..=MAX_EXPIRY).contains(&expires_in) {
|
||||
return Err(MintError::Expiry);
|
||||
}
|
||||
if let Some(p) = password {
|
||||
let n = p.chars().count();
|
||||
if n < share::MIN_PASSWORD_CHARS {
|
||||
return Err(MintError::PasswordShort);
|
||||
}
|
||||
if n > share::MAX_PASSWORD_CHARS {
|
||||
return Err(MintError::PasswordLong);
|
||||
}
|
||||
}
|
||||
let _g = self
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| MintError::Store("share store unavailable".into()))?;
|
||||
let mut f = self.load_reconciled().map_err(MintError::Store)?;
|
||||
let t0 = now();
|
||||
if f.links
|
||||
.iter()
|
||||
.filter(|l| l.stopped_at.is_none() && l.expires_at > t0)
|
||||
.count()
|
||||
>= MAX_ACTIVE
|
||||
{
|
||||
return Err(MintError::TooMany);
|
||||
}
|
||||
if let Some(r) = replaces {
|
||||
let Some(old) = f
|
||||
.links
|
||||
.iter_mut()
|
||||
.find(|l| l.id == r && l.hostname == hostname)
|
||||
else {
|
||||
return Err(MintError::Replaces);
|
||||
};
|
||||
old.stopped_at.get_or_insert(now());
|
||||
}
|
||||
// Settle the epoch first (lost records, an overflowing deny list): a link minted
|
||||
// below the epoch that is about to be published would be dead on arrival.
|
||||
let _ = self.reconcile(&mut f);
|
||||
let id = ShareId(random::<16>().map_err(|e| MintError::Store(e.to_string()))?);
|
||||
let t = now();
|
||||
let spec = LinkSpec {
|
||||
id,
|
||||
epoch: f.epoch,
|
||||
expires_at: t + expires_in,
|
||||
prefix: &prefix,
|
||||
password,
|
||||
};
|
||||
let token =
|
||||
share::mint(key, hostname, &spec).map_err(|e| MintError::Store(e.to_string()))?;
|
||||
let record = LinkRecord {
|
||||
id: id.to_hex(),
|
||||
hostname: hostname.to_owned(),
|
||||
path_prefix: prefix.clone(),
|
||||
epoch: f.epoch,
|
||||
created_at: t,
|
||||
expires_at: t + expires_in,
|
||||
has_password: password.is_some(),
|
||||
created_by: actor.to_owned(),
|
||||
stopped_at: None,
|
||||
};
|
||||
f.links.push(record.clone());
|
||||
self.save(&mut f).map_err(MintError::Store)?;
|
||||
Ok(Minted { record, token })
|
||||
}
|
||||
|
||||
/// Stop one link. `Ok(None)` when there is no such link.
|
||||
pub fn stop(&self, id: &str) -> Result<Option<LinkRecord>, String> {
|
||||
let _g = self
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| "share store unavailable".to_owned())?;
|
||||
let mut f = self.load_reconciled()?;
|
||||
let Some(l) = f.links.iter_mut().find(|l| l.id == id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
l.stopped_at.get_or_insert(now());
|
||||
let r = l.clone();
|
||||
self.save(&mut f)?;
|
||||
Ok(Some(r))
|
||||
}
|
||||
|
||||
/// Stop every link minted so far by raising the epoch.
|
||||
pub fn stop_all(&self) -> Result<u32, String> {
|
||||
let _g = self
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| "share store unavailable".to_owned())?;
|
||||
let mut f = self.load_reconciled()?;
|
||||
f.epoch = f.epoch.saturating_add(1);
|
||||
let e = f.epoch;
|
||||
self.save(&mut f)?;
|
||||
Ok(e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
// 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/.
|
||||
|
||||
//! API tokens. A token is `ian_<id>_<secret>`: a 16-hex-digit id (for listing and lookup)
|
||||
//! and 32 random bytes. Control stores only SHA-256 of the whole token, in `tokens.json`
|
||||
//! (mode 0600), and compares in constant time.
|
||||
//!
|
||||
//! A fast hash is enough here: the secret has 256 bits of entropy, so nobody can find a
|
||||
//! preimage by guessing, slow or fast; slow password hashes only help low-entropy secrets
|
||||
//! that people pick. The comparison is constant-time anyway (it compares hashes of the
|
||||
//! presented value, so even a timing leak would say nothing about a stored hash's preimage).
|
||||
//!
|
||||
//! The value is shown once, in the response that creates it (or by `ianitor-control token
|
||||
//! create`), and never logged. Revoked and expired tokens stay listed so a script gets a
|
||||
//! precise message ("revoked on …").
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TokenRecord {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub sha256: String,
|
||||
pub created_at: u64,
|
||||
pub expires_at: Option<u64>,
|
||||
pub last_used_at: Option<u64>,
|
||||
pub revoked_at: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct TokenFile {
|
||||
tokens: Vec<TokenRecord>,
|
||||
}
|
||||
|
||||
/// Why a presented token was refused.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Refusal {
|
||||
Missing,
|
||||
Unknown,
|
||||
Expired(u64),
|
||||
Revoked(u64),
|
||||
}
|
||||
|
||||
pub const MAX_TOKENS: usize = 200;
|
||||
const LAST_USED_GRANULARITY: u64 = 60;
|
||||
|
||||
pub struct Tokens {
|
||||
path: PathBuf,
|
||||
/// Serialises read-modify-write of the file inside this process.
|
||||
lock: std::sync::Mutex<()>,
|
||||
}
|
||||
|
||||
struct StoreGuard<'a> {
|
||||
_m: std::sync::MutexGuard<'a, ()>,
|
||||
_f: std::fs::File,
|
||||
}
|
||||
|
||||
pub fn valid_name(n: &str) -> bool {
|
||||
let n = n.trim();
|
||||
!n.is_empty()
|
||||
&& n.chars().count() <= 64
|
||||
&& n.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || " ._-".contains(c))
|
||||
}
|
||||
|
||||
impl Tokens {
|
||||
pub fn new(state_dir: &Path) -> Tokens {
|
||||
Tokens {
|
||||
path: state_dir.join("tokens.json"),
|
||||
lock: std::sync::Mutex::new(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Exclusive access to `tokens.json` for one read-modify-write: a mutex inside this
|
||||
/// process and an advisory lock on `tokens.lock` across processes (the CLI and the
|
||||
/// server), released when the guard is dropped, also if the process dies.
|
||||
fn guard(&self) -> Result<StoreGuard<'_>, String> {
|
||||
let m = self
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| "token store unavailable".to_owned())?;
|
||||
let path = self.path.with_file_name("tokens.lock");
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)
|
||||
.map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
||||
}
|
||||
let f = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
||||
f.lock()
|
||||
.map_err(|e| format!("cannot lock {}: {e}", path.display()))?;
|
||||
Ok(StoreGuard { _m: m, _f: f })
|
||||
}
|
||||
|
||||
fn load(&self) -> Result<TokenFile, String> {
|
||||
Ok(read_json(&self.path)?.unwrap_or_default())
|
||||
}
|
||||
|
||||
fn save(&self, f: &TokenFile) -> Result<(), String> {
|
||||
write_json(&self.path, f)
|
||||
}
|
||||
|
||||
/// Create a token; returns the record and the value (shown once).
|
||||
pub fn create(
|
||||
&self,
|
||||
name: &str,
|
||||
expires_at: Option<u64>,
|
||||
) -> Result<(TokenRecord, String), String> {
|
||||
let _g = self.guard()?;
|
||||
if !valid_name(name) {
|
||||
return Err("token.name".into());
|
||||
}
|
||||
let mut f = self.load()?;
|
||||
if f.tokens.iter().filter(|t| t.revoked_at.is_none()).count() >= MAX_TOKENS {
|
||||
return Err("too many tokens; revoke some first".into());
|
||||
}
|
||||
let id = hex(&random::<8>().map_err(|e| e.to_string())?);
|
||||
let secret = URL_SAFE_NO_PAD.encode(random::<32>().map_err(|e| e.to_string())?);
|
||||
let value = format!("ian_{id}_{secret}");
|
||||
let rec = TokenRecord {
|
||||
id,
|
||||
name: name.trim().to_owned(),
|
||||
sha256: sha256_hex(value.as_bytes()),
|
||||
created_at: now(),
|
||||
expires_at,
|
||||
last_used_at: None,
|
||||
revoked_at: None,
|
||||
};
|
||||
f.tokens.push(rec.clone());
|
||||
self.save(&f)?;
|
||||
Ok((rec, value))
|
||||
}
|
||||
|
||||
pub fn list(&self) -> Result<Vec<TokenRecord>, String> {
|
||||
let _g = self.guard()?;
|
||||
Ok(self.load()?.tokens)
|
||||
}
|
||||
|
||||
pub fn revoke(&self, id: &str) -> Result<Option<TokenRecord>, String> {
|
||||
let _g = self.guard()?;
|
||||
let mut f = self.load()?;
|
||||
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if t.revoked_at.is_none() {
|
||||
t.revoked_at = Some(now());
|
||||
}
|
||||
let r = t.clone();
|
||||
self.save(&f)?;
|
||||
Ok(Some(r))
|
||||
}
|
||||
|
||||
pub fn rename(&self, id: &str, name: &str) -> Result<Option<TokenRecord>, String> {
|
||||
let _g = self.guard()?;
|
||||
if !valid_name(name) {
|
||||
return Err("token.name".into());
|
||||
}
|
||||
let mut f = self.load()?;
|
||||
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
t.name = name.trim().to_owned();
|
||||
let r = t.clone();
|
||||
self.save(&f)?;
|
||||
Ok(Some(r))
|
||||
}
|
||||
|
||||
/// Check a presented `Authorization` value. The token never appears in an error.
|
||||
pub fn check(&self, header: Option<&str>) -> Result<TokenRecord, Refusal> {
|
||||
let Some(h) = header else {
|
||||
return Err(Refusal::Missing);
|
||||
};
|
||||
let Some(value) = h.strip_prefix("Bearer ").map(str::trim) else {
|
||||
return Err(Refusal::Unknown);
|
||||
};
|
||||
let id = value
|
||||
.strip_prefix("ian_")
|
||||
.and_then(|r| r.split_once('_'))
|
||||
.map(|(id, _)| id)
|
||||
.filter(|id| id.len() == 16)
|
||||
.ok_or(Refusal::Unknown)?;
|
||||
let _g = self.guard().map_err(|_| Refusal::Unknown)?;
|
||||
let mut f = self.load().map_err(|_| Refusal::Unknown)?;
|
||||
let presented = sha256_hex(value.as_bytes());
|
||||
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {
|
||||
return Err(Refusal::Unknown);
|
||||
};
|
||||
if !ct_eq(t.sha256.as_bytes(), presented.as_bytes()) {
|
||||
return Err(Refusal::Unknown);
|
||||
}
|
||||
if let Some(r) = t.revoked_at {
|
||||
return Err(Refusal::Revoked(r));
|
||||
}
|
||||
let n = now();
|
||||
if let Some(e) = t.expires_at
|
||||
&& n >= e
|
||||
{
|
||||
return Err(Refusal::Expired(e));
|
||||
}
|
||||
let rec = t.clone();
|
||||
if t.last_used_at
|
||||
.is_none_or(|l| n.saturating_sub(l) >= LAST_USED_GRANULARITY)
|
||||
{
|
||||
t.last_used_at = Some(n);
|
||||
if let Err(e) = self.save(&f) {
|
||||
log::warn!(target: "ianitor::tokens", "cannot record token use: {e}");
|
||||
}
|
||||
}
|
||||
Ok(rec)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn create_check_revoke() {
|
||||
let d = std::env::temp_dir().join(format!("ianitor-tokens-{}", std::process::id()));
|
||||
let t = Tokens::new(&d);
|
||||
let (rec, value) = t.create("laptop", None).unwrap();
|
||||
assert!(value.starts_with("ian_"));
|
||||
let stored = std::fs::read_to_string(d.join("tokens.json")).unwrap();
|
||||
assert!(!stored.contains(&value[21..]), "only the hash is stored");
|
||||
assert_eq!(
|
||||
t.check(Some(&format!("Bearer {value}"))).unwrap().id,
|
||||
rec.id
|
||||
);
|
||||
assert_eq!(t.check(None).unwrap_err(), Refusal::Missing);
|
||||
assert_eq!(t.check(Some(&value)).unwrap_err(), Refusal::Unknown);
|
||||
let mut wrong = value.clone();
|
||||
wrong.pop();
|
||||
wrong.push('x');
|
||||
assert_eq!(
|
||||
t.check(Some(&format!("Bearer {wrong}"))).unwrap_err(),
|
||||
Refusal::Unknown
|
||||
);
|
||||
t.revoke(&rec.id).unwrap();
|
||||
assert!(matches!(
|
||||
t.check(Some(&format!("Bearer {value}"))).unwrap_err(),
|
||||
Refusal::Revoked(_)
|
||||
));
|
||||
let (_, v2) = t.create("old", Some(1)).unwrap();
|
||||
assert_eq!(
|
||||
t.check(Some(&format!("Bearer {v2}"))).unwrap_err(),
|
||||
Refusal::Expired(1)
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// 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/.
|
||||
|
||||
//! Small shared helpers: time, randomness, hashing, atomic file writes.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use ring::rand::{SecureRandom, SystemRandom};
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
pub fn now() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn rfc3339(t: u64) -> String {
|
||||
ianitor_core::time::rfc3339(t)
|
||||
}
|
||||
|
||||
pub fn random<const N: usize>() -> Result<[u8; N], std::io::Error> {
|
||||
let mut b = [0u8; N];
|
||||
SystemRandom::new()
|
||||
.fill(&mut b)
|
||||
.map_err(|_| std::io::Error::other("the system random generator failed"))?;
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
pub fn hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
pub fn sha256_hex(data: &[u8]) -> String {
|
||||
hex(ring::digest::digest(&ring::digest::SHA256, data).as_ref())
|
||||
}
|
||||
|
||||
/// Compare two byte strings in time that depends only on their length.
|
||||
pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
let mut d = 0u8;
|
||||
for (x, y) in a.iter().zip(b) {
|
||||
d |= x ^ y;
|
||||
}
|
||||
std::hint::black_box(d) == 0
|
||||
}
|
||||
|
||||
/// Write `data` to `path` so that readers see the old or the new content, never a mix, and
|
||||
/// the new content survives a crash once this returns: temporary file in the same directory,
|
||||
/// fsync, rename, fsync of the directory.
|
||||
pub fn write_atomic(path: &Path, data: &[u8], mode: u32) -> std::io::Result<()> {
|
||||
crate::crash::fail_write(path).map_err(std::io::Error::other)?;
|
||||
let dir = path
|
||||
.parent()
|
||||
.filter(|p| !p.as_os_str().is_empty())
|
||||
.unwrap_or(Path::new("."));
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let mut name = path.file_name().unwrap_or_default().to_os_string();
|
||||
// Unique per write (process, counter, random), so two writers of the same file never
|
||||
// share a temporary file.
|
||||
static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let n = WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let r = random::<4>().map(|b| hex(&b))?;
|
||||
name.push(format!(".tmp-{}-{n}-{r}", std::process::id()));
|
||||
let tmp = dir.join(name);
|
||||
{
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.write(true).create(true).truncate(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut opts, mode);
|
||||
#[cfg(not(unix))]
|
||||
let _ = mode;
|
||||
let mut f = opts.open(&tmp)?;
|
||||
f.write_all(data)?;
|
||||
f.sync_all()?;
|
||||
}
|
||||
std::fs::rename(&tmp, path)?;
|
||||
sync_dir(dir)
|
||||
}
|
||||
|
||||
/// Rename `from` to `to` atomically and durably.
|
||||
pub fn rename_durable(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
crate::crash::fail_write(to).map_err(std::io::Error::other)?;
|
||||
std::fs::rename(from, to)?;
|
||||
sync_dir(to.parent().unwrap_or(Path::new(".")))
|
||||
}
|
||||
|
||||
pub fn sync_dir(dir: &Path) -> std::io::Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::fs::File::open(dir)?.sync_all()?;
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = dir;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_if_exists(path: &Path) -> std::io::Result<()> {
|
||||
match std::fs::remove_file(path) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a JSON state file; `Ok(None)` when it does not exist.
|
||||
pub fn read_json<T: DeserializeOwned>(path: &Path) -> Result<Option<T>, String> {
|
||||
match std::fs::read(path) {
|
||||
Ok(b) => serde_json::from_slice(&b)
|
||||
.map(Some)
|
||||
.map_err(|e| format!("{} is damaged: {e}", path.display())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(format!("cannot read {}: {e}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a JSON state file atomically, readable by its owner only.
|
||||
pub fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
|
||||
let mut text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?;
|
||||
text.push(b'\n');
|
||||
write_atomic(path, &text, 0o600).map_err(|e| format!("cannot write {}: {e}", path.display()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn constant_time_compare() {
|
||||
assert!(ct_eq(b"abc", b"abc"));
|
||||
assert!(!ct_eq(b"abc", b"abd"));
|
||||
assert!(!ct_eq(b"abc", b"ab"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_atomic_writes_of_one_file_all_succeed() {
|
||||
let d = std::env::temp_dir().join(format!("ianitor-util-c-{}", std::process::id()));
|
||||
let p = d.join("paused.json");
|
||||
let threads: Vec<_> = (0..16)
|
||||
.map(|i| {
|
||||
let p = p.clone();
|
||||
std::thread::spawn(move || {
|
||||
(0..50).all(|_| write_atomic(&p, format!("{i}").as_bytes(), 0o600).is_ok())
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for t in threads {
|
||||
assert!(t.join().unwrap(), "a write failed");
|
||||
}
|
||||
let left: Vec<_> = std::fs::read_dir(&d).unwrap().collect();
|
||||
assert_eq!(left.len(), 1, "no temporary files left");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atomic_write_replaces() {
|
||||
let d = std::env::temp_dir().join(format!("ianitor-util-{}", std::process::id()));
|
||||
let p = d.join("f.json");
|
||||
write_atomic(&p, b"one", 0o600).unwrap();
|
||||
write_atomic(&p, b"two", 0o600).unwrap();
|
||||
assert_eq!(std::fs::read(&p).unwrap(), b"two");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,543 @@
|
||||
// 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 API's edges (ROADMAP §6 phase 2, tests first): requests without a valid token are
|
||||
//! rejected on every route and tokens never reach a log, an error or a state file; request
|
||||
//! bodies are hostile input; the routes repository holds only host files; control only
|
||||
//! listens on loopback; the OpenAPI document covers the API.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
#[cfg(unix)]
|
||||
mod common;
|
||||
|
||||
#[cfg(not(unix))]
|
||||
#[test]
|
||||
fn skipped_on_windows() {
|
||||
eprintln!(
|
||||
"SKIPPED on Windows: {} needs Linux (edge admin socket); run it in WSL2",
|
||||
file!()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
mod unix {
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::common::{Env, EnvSpec, host};
|
||||
use ianitor_testkit::more::tcp_raw;
|
||||
use ianitor_testkit::upstream::Echo;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Every (method, path) in the OpenAPI document, with path parameters filled in.
|
||||
fn routes(doc: &Value) -> Vec<(String, String)> {
|
||||
let mut out = Vec::new();
|
||||
for (path, item) in doc["paths"].as_object().unwrap() {
|
||||
for method in ["get", "post", "put", "patch", "delete"] {
|
||||
if item.get(method).is_some() {
|
||||
let p = path
|
||||
.replace("{hostname}", "a.test")
|
||||
.replace("{id}", "x")
|
||||
.replace("{change_id}", "x");
|
||||
out.push((method.to_uppercase(), p));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn requests_without_a_valid_token_are_rejected_and_tokens_are_never_logged() {
|
||||
let good = Echo::start("good").await;
|
||||
let mut env = Env::new(EnvSpec::default()).await;
|
||||
env.start_control(None);
|
||||
let doc = env.call("GET", "/api/v1/openapi.json", None).await;
|
||||
assert_eq!(doc.status, 200, "{}", doc.text);
|
||||
let routes = routes(&doc.json);
|
||||
assert!(routes.len() >= 25, "{routes:?}");
|
||||
|
||||
// Make a second token through the API and revoke it, to test a revoked one too.
|
||||
let made = env
|
||||
.call("POST", "/api/v1/tokens", Some(json!({ "name": "script" })))
|
||||
.await;
|
||||
assert_eq!(made.status, 201, "{}", made.text);
|
||||
let revoked = made.json["token"].as_str().unwrap().to_owned();
|
||||
let rid = made.json["id"].as_str().unwrap().to_owned();
|
||||
assert_eq!(
|
||||
env.call("DELETE", &format!("/api/v1/tokens/{rid}"), None)
|
||||
.await
|
||||
.status,
|
||||
204
|
||||
);
|
||||
// A listing never shows values or hashes.
|
||||
let list = env.call("GET", "/api/v1/tokens", None).await;
|
||||
assert!(
|
||||
!list.text.contains(&revoked) && !list.text.contains("sha256"),
|
||||
"{}",
|
||||
list.text
|
||||
);
|
||||
assert!(!list.text.contains(&env.token));
|
||||
|
||||
let mut wrong = env.token.clone();
|
||||
wrong.pop();
|
||||
wrong.push(if env.token.ends_with('A') { 'B' } else { 'A' });
|
||||
type Case = (String, Vec<(String, String)>, &'static str);
|
||||
let cases: Vec<Case> = vec![
|
||||
("no header".into(), vec![], "token.missing"),
|
||||
(
|
||||
"not bearer".into(),
|
||||
vec![("Authorization".into(), env.token.clone())],
|
||||
"token.unknown",
|
||||
),
|
||||
(
|
||||
"basic".into(),
|
||||
vec![("Authorization".into(), "Basic YWRtaW46YWRtaW4=".into())],
|
||||
"token.unknown",
|
||||
),
|
||||
(
|
||||
"one char off".into(),
|
||||
vec![("Authorization".into(), format!("Bearer {wrong}"))],
|
||||
"token.unknown",
|
||||
),
|
||||
(
|
||||
"made up".into(),
|
||||
vec![(
|
||||
"Authorization".into(),
|
||||
"Bearer ian_0000000000000000_xxxxxxxx".into(),
|
||||
)],
|
||||
"token.unknown",
|
||||
),
|
||||
(
|
||||
"revoked".into(),
|
||||
vec![("Authorization".into(), format!("Bearer {revoked}"))],
|
||||
"token.revoked",
|
||||
),
|
||||
(
|
||||
"empty bearer".into(),
|
||||
vec![("Authorization".into(), "Bearer ".into())],
|
||||
"token.unknown",
|
||||
),
|
||||
// Identity headers do not authenticate (docs/ui-api.md G14).
|
||||
(
|
||||
"remote-user".into(),
|
||||
vec![
|
||||
("Remote-User".into(), "mark".into()),
|
||||
("Remote-Groups".into(), "admins".into()),
|
||||
],
|
||||
"token.missing",
|
||||
),
|
||||
];
|
||||
for (what, headers, code) in &cases {
|
||||
let hs: Vec<(&str, &str)> = headers
|
||||
.iter()
|
||||
.map(|(a, b)| (a.as_str(), b.as_str()))
|
||||
.collect();
|
||||
for (method, path) in &routes {
|
||||
let body = (method != "GET" && method != "DELETE").then(|| json!({}));
|
||||
let r = env.call_with(method, path, &hs, body).await;
|
||||
assert_eq!(r.status, 401, "{what}: {method} {path}: {}", r.text);
|
||||
assert_eq!(r.json["error"]["code"], *code, "{what}: {method} {path}");
|
||||
assert!(r.json["error"]["message"].as_str().unwrap().len() > 10);
|
||||
assert!(r.json["request_id"].is_string() && r.json["server_time"].is_string());
|
||||
}
|
||||
}
|
||||
// Unknown paths are refused the same way, before anything else.
|
||||
assert_eq!(
|
||||
env.call_with("GET", "/api/v1/nope", &[], None).await.status,
|
||||
401
|
||||
);
|
||||
assert_eq!(env.call_with("GET", "/", &[], None).await.status, 401);
|
||||
|
||||
// A wrong Host header (DNS rebinding) is refused even with a good token.
|
||||
let auth = format!("Bearer {}", env.token);
|
||||
let raw = format!(
|
||||
"GET /api/v1/overview HTTP/1.1\r\nHost: evil.example\r\nAuthorization: {auth}\r\nConnection: close\r\n\r\n"
|
||||
);
|
||||
let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap();
|
||||
assert_eq!(r.status, 403, "{}", r.text());
|
||||
// A browser write without the UI header is refused (CSRF).
|
||||
let r = env
|
||||
.call_with(
|
||||
"POST",
|
||||
"/api/v1/hosts",
|
||||
&[("Authorization", &auth), ("Origin", "https://evil.example")],
|
||||
Some(json!({ "host": host("a.test", &good.url(), false) })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 403, "{}", r.text);
|
||||
assert_eq!(r.json["error"]["code"], "request.csrf");
|
||||
let r = env
|
||||
.call_with(
|
||||
"POST",
|
||||
"/api/v1/hosts",
|
||||
&[
|
||||
("Authorization", &auth),
|
||||
("Origin", "http://127.0.0.1"),
|
||||
("X-Ianitor-UI", "1"),
|
||||
],
|
||||
Some(json!({ "host": host("a.test", &good.url(), false) })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
env.wait_apply(r.json["apply"]["id"].as_str().unwrap())
|
||||
.await;
|
||||
|
||||
// Exercise the rest with the good token, then look for any token anywhere.
|
||||
for (method, path) in &routes {
|
||||
if method == "GET" {
|
||||
env.call(method, path, None).await;
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
env.kill_control();
|
||||
let mut everything = env.control_log();
|
||||
for f in [
|
||||
"applies.json",
|
||||
"push.json",
|
||||
"share-links.json",
|
||||
"journal.json",
|
||||
] {
|
||||
everything.push_str(&env.file(&format!("state/{f}")));
|
||||
}
|
||||
everything.push_str(&env.file("edge/edge.json"));
|
||||
everything.push_str(&env.git(&["log", "-p", "--all"]));
|
||||
// `ian_<16 hex>_<secret>`; the secret itself may contain '_'.
|
||||
let secret_part = |t: &str| {
|
||||
assert!(t.starts_with("ian_") && t.as_bytes()[20] == b'_');
|
||||
t[21..].to_owned()
|
||||
};
|
||||
for t in [&env.token, &revoked] {
|
||||
assert!(
|
||||
!everything.contains(secret_part(t).as_str()),
|
||||
"a token leaked"
|
||||
);
|
||||
}
|
||||
let stored = env.file("state/tokens.json");
|
||||
for t in [&env.token, &revoked] {
|
||||
assert!(
|
||||
!stored.contains(secret_part(t).as_str()),
|
||||
"tokens.json holds a value, not a hash"
|
||||
);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(env.dir.join("state/tokens.json"))
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode();
|
||||
assert_eq!(mode & 0o077, 0, "tokens.json is private");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn bodies_are_hostile_input() {
|
||||
let good = Echo::start("good").await;
|
||||
let mut env = Env::new(EnvSpec::default()).await;
|
||||
env.start_control(None);
|
||||
let auth = format!("Bearer {}", env.token);
|
||||
|
||||
// Unknown fields, at the top and inside the host.
|
||||
let r = env
|
||||
.call(
|
||||
"POST",
|
||||
"/api/v1/hosts",
|
||||
Some(json!({ "host": host("a.test", &good.url(), false), "colour": 1 })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 422, "{}", r.text);
|
||||
assert_eq!(r.json["error"]["code"], "request.body_unknown_field");
|
||||
assert_eq!(r.json["error"]["field"], "colour");
|
||||
let mut h = host("a.test", &good.url(), false);
|
||||
h["upstream"] = json!("typo");
|
||||
let r = env
|
||||
.call("POST", "/api/v1/hosts", Some(json!({ "host": h })))
|
||||
.await;
|
||||
assert_eq!(
|
||||
r.json["error"]["code"], "request.body_unknown_field",
|
||||
"{}",
|
||||
r.text
|
||||
);
|
||||
// Wrong types never echo the value sent.
|
||||
let r = env
|
||||
.call(
|
||||
"POST",
|
||||
"/api/v1/tokens",
|
||||
Some(json!({ "name": ["secret-ish-value"] })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 400, "{}", r.text);
|
||||
assert!(!r.text.contains("secret-ish-value"), "{}", r.text);
|
||||
// Nor do odd field names, path parameters or credentials in an upstream URL.
|
||||
let r = env
|
||||
.call("POST", "/api/v1/tokens", Some(json!({ "pass:hunter2": 1 })))
|
||||
.await;
|
||||
assert_eq!(r.status, 422, "{}", r.text);
|
||||
assert!(!r.text.contains("hunter2"), "{}", r.text);
|
||||
let r = env.call("GET", "/api/v1/hosts/x%3Chunter2%3E", None).await;
|
||||
assert_eq!(r.status, 404, "{}", r.text);
|
||||
assert!(!r.text.contains("hunter2"), "{}", r.text);
|
||||
let mut leaky = host("a.test", "http://admin:hunter2@10.0.0.2:3000", false);
|
||||
leaky["upstreams"] = json!(["http://admin:hunter2@10.0.0.2:3000", "ftp://u:hunter2@x"]);
|
||||
let r = env
|
||||
.call("POST", "/api/v1/hosts", Some(json!({ "host": leaky })))
|
||||
.await;
|
||||
assert_eq!(r.status, 422, "{}", r.text);
|
||||
assert!(!r.text.contains("hunter2"), "{}", r.text);
|
||||
// Not JSON, wrong content type, too large.
|
||||
let raw = format!(
|
||||
"POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: application/json\r\nContent-Length: 5\r\nConnection: close\r\n\r\n{{{{{{{{{{",
|
||||
env.api
|
||||
);
|
||||
let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap();
|
||||
assert_eq!(r.status, 400, "{}", r.text());
|
||||
let raw = format!(
|
||||
"POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}",
|
||||
env.api
|
||||
);
|
||||
let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap();
|
||||
assert_eq!(r.status, 415, "{}", r.text());
|
||||
let big = "x".repeat(70 * 1024);
|
||||
let r = env
|
||||
.call("POST", "/api/v1/tokens", Some(json!({ "name": big })))
|
||||
.await;
|
||||
assert_eq!(r.status, 413, "{}", &r.text[..r.text.len().min(300)]);
|
||||
|
||||
// Field errors come back as one envelope with codes and field paths.
|
||||
let mut bad = host("a.test", "ftp://x", true);
|
||||
bad["health_check"]["interval_secs"] = json!(0);
|
||||
let r = env
|
||||
.call("POST", "/api/v1/hosts", Some(json!({ "host": bad })))
|
||||
.await;
|
||||
assert_eq!(r.status, 422, "{}", r.text);
|
||||
let fields: Vec<&str> = r.json["errors"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|e| e["field"].as_str())
|
||||
.collect();
|
||||
assert!(fields.contains(&"upstreams[0]"), "{fields:?}");
|
||||
assert!(fields.contains(&"health_check.interval_secs"), "{fields:?}");
|
||||
assert_eq!(r.json["error"]["code"], "apply.failed.validation");
|
||||
let codes: Vec<&str> = r.json["errors"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|e| e["code"].as_str())
|
||||
.collect();
|
||||
assert!(codes.contains(&"host.upstream.scheme"), "{codes:?}");
|
||||
let msg = r.json["errors"][0]["message"].as_str().unwrap();
|
||||
assert!(
|
||||
!msg.contains("TOML") && !msg.contains("hosts/"),
|
||||
"plain English: {msg}"
|
||||
);
|
||||
// Validate without applying.
|
||||
let r = env
|
||||
.call(
|
||||
"POST",
|
||||
"/api/v1/hosts/validate?mode=create",
|
||||
Some(host("a.test", &good.url(), false)),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
// A hostname that does not match the path, a host that does not exist.
|
||||
let r = env
|
||||
.call(
|
||||
"PUT",
|
||||
"/api/v1/hosts/b.test",
|
||||
Some(json!({ "host": host("a.test", &good.url(), false) })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
r.json["error"]["code"], "host.hostname.mismatch",
|
||||
"{}",
|
||||
r.text
|
||||
);
|
||||
let r = env.call("DELETE", "/api/v1/hosts/nope.test", None).await;
|
||||
assert_eq!(r.status, 404);
|
||||
let r = env.call("GET", "/api/v1/hosts/..%2f..%2fetc", None).await;
|
||||
assert_eq!(r.status, 404);
|
||||
// base_rev must be a commit of the history.
|
||||
let r = env.call("POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false), "base_rev": "0".repeat(40) }))).await;
|
||||
assert_eq!(r.json["error"]["code"], "request.base_rev", "{}", r.text);
|
||||
let r = env.call("POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false), "base_rev": "--upload-pack=touch /tmp/x" }))).await;
|
||||
assert_eq!(r.status, 422, "{}", r.text);
|
||||
|
||||
// Idempotency-Key: a retry returns the same apply; another body with it is refused.
|
||||
let body = json!({ "host": host("a.test", &good.url(), false) });
|
||||
let k = [
|
||||
("Authorization", auth.as_str()),
|
||||
("Idempotency-Key", "click-1"),
|
||||
];
|
||||
let first = env
|
||||
.call_with("POST", "/api/v1/hosts", &k, Some(body.clone()))
|
||||
.await;
|
||||
assert_eq!(first.status, 202, "{}", first.text);
|
||||
let again = env.call_with("POST", "/api/v1/hosts", &k, Some(body)).await;
|
||||
assert_eq!(again.status, 202, "{}", again.text);
|
||||
assert_eq!(again.json["apply"]["id"], first.json["apply"]["id"]);
|
||||
let other = env
|
||||
.call_with(
|
||||
"POST",
|
||||
"/api/v1/hosts",
|
||||
&k,
|
||||
Some(json!({ "host": host("b.test", &good.url(), false) })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(other.status, 422);
|
||||
assert_eq!(other.json["error"]["code"], "request.idempotency");
|
||||
env.wait_apply(first.json["apply"]["id"].as_str().unwrap())
|
||||
.await;
|
||||
// Taken hostname.
|
||||
let r = env
|
||||
.call(
|
||||
"POST",
|
||||
"/api/v1/hosts",
|
||||
Some(json!({ "host": host("a.test", &good.url(), false) })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.json["error"]["code"], "host.hostname.taken", "{}", r.text);
|
||||
assert_eq!(r.json["error"]["field"], "hostname");
|
||||
// The overview answers 304 to its own ETag.
|
||||
let o = env.call("GET", "/api/v1/overview", None).await;
|
||||
let etag = o.header("etag").unwrap().to_owned();
|
||||
let r = env
|
||||
.call_with(
|
||||
"GET",
|
||||
"/api/v1/overview",
|
||||
&[("Authorization", &auth), ("If-None-Match", &etag)],
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 304);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn the_routes_repository_holds_only_host_files() {
|
||||
let good = Echo::start("good").await;
|
||||
let mut env = Env::new(EnvSpec::default()).await;
|
||||
env.start_control(None);
|
||||
assert_eq!(
|
||||
env.add_host(host("a.test", &good.url(), false)).await["state"],
|
||||
"kept"
|
||||
);
|
||||
let good_edge = env.file("edge/edge.json");
|
||||
env.kill_control();
|
||||
// Someone pushes a stray file and a nested folder straight into the repository.
|
||||
let work = env.dir.join("work");
|
||||
let git = |args: &[&str], cwd: &std::path::Path| {
|
||||
let o = std::process::Command::new("git")
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
o.status.success(),
|
||||
"{args:?} {}",
|
||||
String::from_utf8_lossy(&o.stderr)
|
||||
);
|
||||
};
|
||||
git(
|
||||
&[
|
||||
"clone",
|
||||
"--quiet",
|
||||
&env.repo().to_string_lossy(),
|
||||
&work.to_string_lossy(),
|
||||
],
|
||||
&env.dir.join("."),
|
||||
);
|
||||
std::fs::create_dir_all(work.join("hosts/sub")).unwrap();
|
||||
std::fs::write(work.join("README.md"), "hello").unwrap();
|
||||
std::fs::write(
|
||||
work.join("hosts/sub/b.test.toml"),
|
||||
"hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||
)
|
||||
.unwrap();
|
||||
git(&["add", "-A"], &work);
|
||||
git(&["commit", "--quiet", "-m", "stray"], &work);
|
||||
git(&["push", "--quiet", "origin", "HEAD:main"], &work);
|
||||
|
||||
env.start_control(None);
|
||||
let o = env.call("GET", "/api/v1/overview", None).await;
|
||||
assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text);
|
||||
let r = env
|
||||
.call(
|
||||
"POST",
|
||||
"/api/v1/hosts",
|
||||
Some(json!({ "host": host("c.test", &good.url(), false) })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 409, "{}", r.text);
|
||||
assert_eq!(r.json["error"]["code"], "control.paused");
|
||||
// Edge keeps the last good config; nothing stray was compiled.
|
||||
assert_eq!(env.file("edge/edge.json"), good_edge);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn control_only_listens_on_loopback() {
|
||||
let env = Env::new(EnvSpec::default()).await;
|
||||
let text = std::fs::read_to_string(env.config_path()).unwrap();
|
||||
let open = text.replace(
|
||||
&format!("listen = \"{}\"", env.api),
|
||||
"listen = \"0.0.0.0:7979\"",
|
||||
);
|
||||
std::fs::write(env.config_path(), open).unwrap();
|
||||
let out = std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control"))
|
||||
.arg("--config")
|
||||
.arg(env.config_path())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!out.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&out.stderr).contains("loopback"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
assert!(std::net::TcpStream::connect("127.0.0.1:7979").is_err());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn the_overview_has_everything_the_main_screen_needs() {
|
||||
let good = Echo::start("good").await;
|
||||
let mut env = Env::new(EnvSpec::default()).await;
|
||||
env.start_control(None);
|
||||
env.add_host(host("a.test", &good.url(), true)).await;
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
let o = env.call("GET", "/api/v1/overview", None).await;
|
||||
assert_eq!(o.status, 200, "{}", o.text);
|
||||
for k in [
|
||||
"counts",
|
||||
"hosts",
|
||||
"engine",
|
||||
"last_apply",
|
||||
"undo",
|
||||
"repo",
|
||||
"site",
|
||||
"server_time",
|
||||
"rev",
|
||||
] {
|
||||
assert!(o.json.get(k).is_some(), "{k} missing: {}", o.text);
|
||||
}
|
||||
assert_eq!(o.json["counts"]["hosts"], 1);
|
||||
assert_eq!(o.json["counts"]["healthy"], 1, "{}", o.text);
|
||||
let h = &o.json["hosts"][0];
|
||||
assert_eq!(h["health"]["state"], "healthy");
|
||||
assert!(h["health"]["latency_ms"].is_u64());
|
||||
assert_eq!(h["certificate"]["state"], "ok");
|
||||
assert_eq!(o.json["engine"]["running"], "pingora");
|
||||
assert_eq!(o.json["engine"]["state"], "running");
|
||||
assert_eq!(o.json["last_apply"]["state"], "kept");
|
||||
assert_eq!(o.json["undo"]["available"], true);
|
||||
assert!(o.json["intermediate"].is_null());
|
||||
// The CLI lists tokens without values.
|
||||
let out = std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control"))
|
||||
.args(["token", "list", "--config"])
|
||||
.arg(env.config_path())
|
||||
.output()
|
||||
.unwrap();
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(text.contains("test") && !text.contains(&env.token[21..]));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,565 @@
|
||||
// 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/.
|
||||
|
||||
//! A control-plane test environment on 127.0.0.1: an edge running in this process (with its
|
||||
//! admin socket), the real `ianitor-control` binary as a child process (so a test can kill it
|
||||
//! or make it abort at a crash point), a bare routes repository, test upstreams and a test CA.
|
||||
//! The first API token comes from `ianitor-control token create`, as in production.
|
||||
|
||||
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use ianitor_core::compile::{self, CompileOptions};
|
||||
use ianitor_core::{SourceFile, load};
|
||||
use ianitor_testkit::more::{JsonResp, tcp_json, unix_json};
|
||||
use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port};
|
||||
use ianitor_testkit::tls::TestCa;
|
||||
use rustls::RootCertStore;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub const HOSTS: [&str; 7] = [
|
||||
"a.test",
|
||||
"b.test",
|
||||
"c.test",
|
||||
"d.test",
|
||||
"e.test",
|
||||
"f.test",
|
||||
"share.test",
|
||||
];
|
||||
pub const SHARE_KEY: &str = "control-test-share-key-0123456789abcdef0123456789";
|
||||
|
||||
pub struct Edge {
|
||||
stop: Option<tokio::sync::oneshot::Sender<()>>,
|
||||
pub http: SocketAddr,
|
||||
pub https: SocketAddr,
|
||||
pub admin: PathBuf,
|
||||
}
|
||||
|
||||
impl Drop for Edge {
|
||||
fn drop(&mut self) {
|
||||
if let Some(s) = self.stop.take() {
|
||||
let _ = s.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Env {
|
||||
pub dir: TempDir,
|
||||
pub ca: TestCa,
|
||||
pub edge: Option<Edge>,
|
||||
pub control: Option<ChildGuard>,
|
||||
pub api: SocketAddr,
|
||||
pub token: String,
|
||||
pub opts: CompileOptions,
|
||||
pub watch_secs: u64,
|
||||
pub remote: Option<String>,
|
||||
log_n: u32,
|
||||
}
|
||||
|
||||
pub struct EnvSpec {
|
||||
pub watch_secs: u64,
|
||||
pub site: String,
|
||||
pub remote: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for EnvSpec {
|
||||
fn default() -> Self {
|
||||
EnvSpec {
|
||||
watch_secs: 2,
|
||||
site: String::new(),
|
||||
remote: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn s(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
impl Env {
|
||||
pub async fn new(spec: EnvSpec) -> Env {
|
||||
let dir = TempDir::new("ctl");
|
||||
for d in [
|
||||
"state",
|
||||
"edge",
|
||||
"caddy",
|
||||
"certs",
|
||||
"creds",
|
||||
"logs",
|
||||
"edge-state",
|
||||
] {
|
||||
std::fs::create_dir_all(dir.join(d)).unwrap();
|
||||
}
|
||||
let ca = TestCa::new("Ianitor Control Test CA");
|
||||
for h in HOSTS {
|
||||
let leaf = ca.issue(&[h]);
|
||||
std::fs::write(dir.join(&format!("certs/{h}.crt")), leaf.cert_pem).unwrap();
|
||||
std::fs::write(dir.join(&format!("certs/{h}.key")), leaf.key_pem).unwrap();
|
||||
}
|
||||
std::fs::write(dir.join("creds/share-link-key"), SHARE_KEY).unwrap();
|
||||
let opts = CompileOptions {
|
||||
http_listen: local(free_port()),
|
||||
https_listen: local(free_port()),
|
||||
cert_dir: dir.str("certs"),
|
||||
state_dir: dir.str("edge-state"),
|
||||
access_log: dir.str("logs/access.log"),
|
||||
caddy_credentials_dir: dir.str("creds"),
|
||||
caddy_admin: None,
|
||||
};
|
||||
// Edge starts from an empty config; control brings it in line on its first start.
|
||||
let empty = load(
|
||||
&SourceFile {
|
||||
name: "ianitor.toml",
|
||||
contents: "",
|
||||
},
|
||||
&[],
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
dir.join("edge/edge.json"),
|
||||
compile::edge(&empty, &opts).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
dir.join("edge/share-revocations.json"),
|
||||
"{\"epoch\":0,\"deny\":[]}",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let api = local(free_port());
|
||||
let mut env = Env {
|
||||
edge: None,
|
||||
control: None,
|
||||
api,
|
||||
token: String::new(),
|
||||
opts,
|
||||
watch_secs: spec.watch_secs,
|
||||
remote: spec.remote.clone(),
|
||||
ca,
|
||||
dir,
|
||||
log_n: 0,
|
||||
};
|
||||
env.write_config(&spec);
|
||||
env.start_edge();
|
||||
// Seed the routes repository with the site file, then make the first token.
|
||||
if !spec.site.is_empty() {
|
||||
env.seed_site(&spec.site);
|
||||
}
|
||||
env.token = env.cli_token("test");
|
||||
env
|
||||
}
|
||||
|
||||
fn write_config(&self, spec: &EnvSpec) {
|
||||
let d = |p: &str| s(&self.dir.join(p));
|
||||
let remote = spec
|
||||
.remote
|
||||
.as_ref()
|
||||
.map(|r| format!("remote = \"{r}\"\n"))
|
||||
.unwrap_or_default();
|
||||
let text = format!(
|
||||
r#"listen = "{api}"
|
||||
state_dir = "{state}"
|
||||
credentials_dir = "{creds}"
|
||||
watch_secs = {watch}
|
||||
watch_every_secs = 1
|
||||
trial_margin_secs = 2
|
||||
health_poll_secs = 1
|
||||
|
||||
[routes]
|
||||
repo = "{repo}"
|
||||
{remote}
|
||||
[edge]
|
||||
config = "{edge}/edge.json"
|
||||
admin_socket = "{edge}/admin.sock"
|
||||
share_revocations = "{edge}/share-revocations.json"
|
||||
|
||||
[caddy]
|
||||
config = "{caddy}/caddy.json"
|
||||
|
||||
[compile]
|
||||
http_listen = "{http}"
|
||||
https_listen = "{https}"
|
||||
cert_dir = "{certs}"
|
||||
state_dir = "{edge_state}"
|
||||
access_log = "{log}"
|
||||
caddy_credentials_dir = "{creds}"
|
||||
"#,
|
||||
api = self.api,
|
||||
state = d("state"),
|
||||
creds = d("creds"),
|
||||
watch = spec.watch_secs,
|
||||
repo = d("routes.git"),
|
||||
edge = d("edge"),
|
||||
caddy = d("caddy"),
|
||||
http = self.opts.http_listen,
|
||||
https = self.opts.https_listen,
|
||||
certs = d("certs"),
|
||||
edge_state = d("edge-state"),
|
||||
log = d("logs/access.log"),
|
||||
);
|
||||
std::fs::write(self.dir.join("control.toml"), text).unwrap();
|
||||
}
|
||||
|
||||
pub fn config_path(&self) -> PathBuf {
|
||||
self.dir.join("control.toml")
|
||||
}
|
||||
|
||||
pub fn repo(&self) -> PathBuf {
|
||||
self.dir.join("routes.git")
|
||||
}
|
||||
|
||||
pub fn start_edge(&mut self) {
|
||||
let opts = ianitor_edge::Options {
|
||||
config: self.dir.join("edge/edge.json"),
|
||||
admin_socket: Some(self.dir.join("edge/admin.sock")),
|
||||
share_revocations: Some(self.dir.join("edge/share-revocations.json")),
|
||||
credentials_dir: Some(self.dir.join("creds")),
|
||||
..Default::default()
|
||||
};
|
||||
let shared = ianitor_edge::prepare(&opts).expect("edge config");
|
||||
let server = ianitor_edge::server(shared, &opts).expect("edge server");
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
std::thread::spawn(move || ianitor_edge::run_until(server, rx));
|
||||
assert!(wait_for_port(
|
||||
self.opts.https_listen,
|
||||
Duration::from_secs(20)
|
||||
));
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !self.dir.join("edge/admin.sock").exists() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
self.edge = Some(Edge {
|
||||
stop: Some(tx),
|
||||
http: self.opts.http_listen,
|
||||
https: self.opts.https_listen,
|
||||
admin: self.dir.join("edge/admin.sock"),
|
||||
});
|
||||
}
|
||||
|
||||
/// Stop the in-process edge (and wait until its listeners are gone).
|
||||
pub fn stop_edge(&mut self) {
|
||||
self.edge = None;
|
||||
let deadline = Instant::now() + Duration::from_secs(15);
|
||||
while std::net::TcpStream::connect(self.opts.https_listen).is_ok()
|
||||
&& Instant::now() < deadline
|
||||
{
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
|
||||
fn command(&self) -> Command {
|
||||
let mut c = Command::new(env!("CARGO_BIN_EXE_ianitor-control"));
|
||||
c.env_remove("IANITOR_TEST_CRASH_AT");
|
||||
c.env_remove("IANITOR_TEST_FAIL_WRITE");
|
||||
c
|
||||
}
|
||||
|
||||
pub fn cli_token(&self, name: &str) -> String {
|
||||
let out = self
|
||||
.command()
|
||||
.args(["token", "create", "--name", name, "--config"])
|
||||
.arg(self.config_path())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
let t = String::from_utf8_lossy(&out.stdout).trim().to_owned();
|
||||
assert!(t.starts_with("ian_"), "{t}");
|
||||
t
|
||||
}
|
||||
|
||||
/// Put an `ianitor.toml` into a fresh repository (before control first starts).
|
||||
fn seed_site(&self, site: &str) {
|
||||
let work = self.dir.join("seed");
|
||||
std::fs::create_dir_all(&work).unwrap();
|
||||
let git = |args: &[&str], cwd: &Path| {
|
||||
let o = Command::new("git")
|
||||
.args([
|
||||
"-c",
|
||||
"user.name=test",
|
||||
"-c",
|
||||
"user.email=t@t",
|
||||
"-c",
|
||||
"init.defaultBranch=main",
|
||||
])
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
o.status.success(),
|
||||
"git {args:?}: {}",
|
||||
String::from_utf8_lossy(&o.stderr)
|
||||
);
|
||||
};
|
||||
git(
|
||||
&["init", "--bare", "--quiet", &s(&self.repo())],
|
||||
&self.dir.join("."),
|
||||
);
|
||||
git(&["init", "--quiet"], &work);
|
||||
std::fs::write(work.join("ianitor.toml"), site).unwrap();
|
||||
git(&["add", "ianitor.toml"], &work);
|
||||
git(&["commit", "--quiet", "-m", "Site settings"], &work);
|
||||
git(
|
||||
&["push", "--quiet", &s(&self.repo()), "HEAD:refs/heads/main"],
|
||||
&work,
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
pub fn control_log(&self) -> String {
|
||||
let mut out = String::new();
|
||||
for i in 0..=self.log_n {
|
||||
out.push_str(
|
||||
&std::fs::read_to_string(self.dir.join(&format!("logs/control-{i}.log")))
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Start the control binary; with `crash_at`, it aborts when an apply reaches that stage.
|
||||
pub fn start_control(&mut self, crash_at: Option<&str>) {
|
||||
self.start_control_env(crash_at, &[]);
|
||||
}
|
||||
|
||||
/// Like [`Env::start_control`], with extra environment (fault injection).
|
||||
pub fn start_control_env(&mut self, crash_at: Option<&str>, envs: &[(&str, &str)]) {
|
||||
self.log_n += 1;
|
||||
let log = std::fs::File::create(self.dir.join(&format!("logs/control-{}.log", self.log_n)))
|
||||
.unwrap();
|
||||
let mut c = self.command();
|
||||
c.arg("--config").arg(self.config_path());
|
||||
c.env("IANITOR_LOG", "debug");
|
||||
if let Some(stage) = crash_at {
|
||||
c.env("IANITOR_TEST_CRASH_AT", stage);
|
||||
}
|
||||
for (k, v) in envs {
|
||||
c.env(k, v);
|
||||
}
|
||||
c.stdout(Stdio::from(log.try_clone().unwrap()))
|
||||
.stderr(Stdio::from(log));
|
||||
self.control = Some(ChildGuard(c.spawn().unwrap()));
|
||||
if !wait_for_port(self.api, Duration::from_secs(30)) {
|
||||
panic!("control did not start:\n{}", self.control_log());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kill_control(&mut self) {
|
||||
self.control = None;
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while std::net::TcpStream::connect(self.api).is_ok() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for control to exit by itself (a crash point).
|
||||
pub fn wait_control_exit(&mut self, timeout: Duration) -> Option<std::process::ExitStatus> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
while Instant::now() < deadline {
|
||||
if let Some(c) = &mut self.control
|
||||
&& let Some(st) = c.0.try_wait().unwrap()
|
||||
{
|
||||
self.control = None;
|
||||
return Some(st);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub async fn call(&self, method: &str, path: &str, body: Option<Value>) -> JsonResp {
|
||||
let auth = format!("Bearer {}", self.token);
|
||||
self.call_with(method, path, &[("Authorization", &auth)], body)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn call_with(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
headers: &[(&str, &str)],
|
||||
body: Option<Value>,
|
||||
) -> JsonResp {
|
||||
tcp_json(self.api, method, path, headers, body.as_ref())
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{method} {path}: {e}\n{}", self.control_log()))
|
||||
}
|
||||
|
||||
/// Wait for an apply to end; returns its record.
|
||||
pub async fn wait_apply(&self, id: &str) -> Value {
|
||||
let deadline = Instant::now() + Duration::from_secs(90);
|
||||
loop {
|
||||
let r = self
|
||||
.call("GET", &format!("/api/v1/applies/{id}"), None)
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
let st = r.json["state"].as_str().unwrap_or("").to_owned();
|
||||
if ["kept", "reverted", "failed", "needs_attention"].contains(&st.as_str()) {
|
||||
return r.json;
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
panic!("apply {id} still {st}:\n{}", self.control_log());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Submit and wait.
|
||||
pub async fn apply(&self, method: &str, path: &str, body: Option<Value>) -> Value {
|
||||
let r = self.call(method, path, body).await;
|
||||
assert_eq!(r.status, 202, "{method} {path}: {}", r.text);
|
||||
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
|
||||
self.wait_apply(&id).await
|
||||
}
|
||||
|
||||
pub async fn add_host(&self, host: Value) -> Value {
|
||||
self.apply("POST", "/api/v1/hosts", Some(json!({ "host": host })))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn edge_status(&self) -> Value {
|
||||
let r = unix_json(&self.dir.join("edge/admin.sock"), "GET", "/v1/status", None)
|
||||
.await
|
||||
.unwrap();
|
||||
r.json
|
||||
}
|
||||
|
||||
pub fn roots(&self) -> Arc<RootCertStore> {
|
||||
self.ca.roots()
|
||||
}
|
||||
|
||||
pub fn git(&self, args: &[&str]) -> String {
|
||||
let o = Command::new("git")
|
||||
.env("GIT_DIR", self.repo())
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
o.status.success(),
|
||||
"git {args:?}: {}",
|
||||
String::from_utf8_lossy(&o.stderr)
|
||||
);
|
||||
String::from_utf8_lossy(&o.stdout).trim().to_owned()
|
||||
}
|
||||
|
||||
pub fn head(&self) -> String {
|
||||
self.git(&["rev-parse", "refs/heads/main"])
|
||||
}
|
||||
|
||||
/// The routes files at the branch head.
|
||||
pub fn head_files(&self) -> Vec<(String, String)> {
|
||||
let list = self.git(&["ls-tree", "-r", "--name-only", "refs/heads/main"]);
|
||||
list.lines()
|
||||
.map(|p| {
|
||||
(
|
||||
p.to_owned(),
|
||||
self.git(&["show", &format!("refs/heads/main:{p}")]) + "\n",
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What edge.json and caddy.json must hold for the branch head.
|
||||
pub fn expected_configs(&self) -> (String, String) {
|
||||
let files = self.head_files();
|
||||
let site = files
|
||||
.iter()
|
||||
.find(|(p, _)| p == "ianitor.toml")
|
||||
.map(|(_, c)| c.clone())
|
||||
.unwrap_or_default();
|
||||
let hosts: Vec<SourceFile> = files
|
||||
.iter()
|
||||
.filter(|(p, _)| p != "ianitor.toml")
|
||||
.map(|(p, c)| SourceFile {
|
||||
name: p,
|
||||
contents: c,
|
||||
})
|
||||
.collect();
|
||||
let model = load(
|
||||
&SourceFile {
|
||||
name: "ianitor.toml",
|
||||
contents: &site,
|
||||
},
|
||||
&hosts,
|
||||
)
|
||||
.expect("head validates");
|
||||
(
|
||||
compile::edge(&model, &self.opts).unwrap(),
|
||||
compile::caddy(&model, &self.opts).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn file(&self, p: &str) -> String {
|
||||
std::fs::read_to_string(self.dir.join(p)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The repository, both files and edge agree, and nothing is left half done.
|
||||
pub async fn assert_consistent(&self) {
|
||||
let (edge_text, caddy_text) = self.expected_configs();
|
||||
assert_eq!(
|
||||
self.file("edge/edge.json"),
|
||||
edge_text,
|
||||
"edge.json matches the branch head"
|
||||
);
|
||||
assert_eq!(
|
||||
self.file("caddy/caddy.json"),
|
||||
caddy_text,
|
||||
"caddy.json matches the branch head"
|
||||
);
|
||||
let st = self.edge_status().await;
|
||||
assert!(st["trial"].is_null(), "no trial left running: {st}");
|
||||
assert_eq!(
|
||||
st["config_sha256"],
|
||||
sha256(&edge_text),
|
||||
"edge runs edge.json"
|
||||
);
|
||||
assert!(
|
||||
!self.dir.join("edge/edge.json.trial").exists(),
|
||||
"no trial file left"
|
||||
);
|
||||
assert!(
|
||||
!self.dir.join("caddy/caddy.json.trial").exists(),
|
||||
"no Caddy trial file left"
|
||||
);
|
||||
assert!(
|
||||
!self.dir.join("state/journal.json").exists(),
|
||||
"no journal left"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sha256(text: &str) -> String {
|
||||
ring::digest::digest(&ring::digest::SHA256, text.as_bytes())
|
||||
.as_ref()
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A host body for the API.
|
||||
pub fn host(name: &str, upstream: &str, health: bool) -> Value {
|
||||
let mut h = json!({
|
||||
"hostname": name,
|
||||
"upstreams": [upstream],
|
||||
"tls": "domi",
|
||||
"auth": "none",
|
||||
"websockets": true,
|
||||
"share_links": false,
|
||||
"access_log": "off",
|
||||
});
|
||||
if health {
|
||||
h["health_check"] = json!({ "path": "/healthz", "interval_secs": 1 });
|
||||
}
|
||||
h
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
// 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/.
|
||||
|
||||
//! Token and share-link stores (QC fix round 1, M2 and M4): a CLI revoke is never lost to the
|
||||
//! server recording token use at the same time, and losing `share-links.json` never revives a
|
||||
//! stopped link.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use ianitor_control::shares::Shares;
|
||||
use ianitor_control::tokens::{Refusal, Tokens};
|
||||
use ianitor_core::share::ShareKey;
|
||||
use ianitor_testkit::proc::TempDir;
|
||||
use serde_json::Value;
|
||||
|
||||
fn revocations(p: &std::path::Path) -> Value {
|
||||
serde_json::from_slice(&std::fs::read(p).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cli_revoke_is_not_lost_while_the_server_records_token_use() {
|
||||
let bin = env!("CARGO_BIN_EXE_ianitor-control");
|
||||
let rounds = 20;
|
||||
let mut lost = 0;
|
||||
for _ in 0..rounds {
|
||||
let d = TempDir::new("tok-race");
|
||||
let server = Tokens::new(d.path());
|
||||
let values: Vec<_> = (0..150)
|
||||
.map(|i| server.create(&format!("t{i}"), None).unwrap())
|
||||
.collect();
|
||||
let victim = values[75].0.id.clone();
|
||||
let mut cli = std::process::Command::new(bin)
|
||||
.args(["token", "revoke", &victim, "--state-dir"])
|
||||
.arg(d.path())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
for (_, v) in &values {
|
||||
let _ = server.check(Some(&format!("Bearer {v}")));
|
||||
}
|
||||
assert!(cli.wait().unwrap().success());
|
||||
if !matches!(
|
||||
server.check(Some(&format!("Bearer {}", values[75].1))),
|
||||
Err(Refusal::Revoked(_))
|
||||
) {
|
||||
lost += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
lost, 0,
|
||||
"the CLI said revoked but the token still worked in {lost}/{rounds} rounds"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_creates_from_the_cli_and_the_server_all_survive() {
|
||||
let bin = env!("CARGO_BIN_EXE_ianitor-control");
|
||||
let d = TempDir::new("tok-create");
|
||||
let server = Tokens::new(d.path());
|
||||
let mut clis: Vec<_> = (0..8)
|
||||
.map(|i| {
|
||||
std::process::Command::new(bin)
|
||||
.args([
|
||||
"token",
|
||||
"create",
|
||||
"--name",
|
||||
&format!("cli{i}"),
|
||||
"--state-dir",
|
||||
])
|
||||
.arg(d.path())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.unwrap()
|
||||
})
|
||||
.collect();
|
||||
for i in 0..40 {
|
||||
server.create(&format!("srv{i}"), None).unwrap();
|
||||
}
|
||||
for c in &mut clis {
|
||||
assert!(c.wait().unwrap().success());
|
||||
}
|
||||
assert_eq!(server.list().unwrap().len(), 48);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn losing_share_links_json_never_lowers_the_revocation_epoch() {
|
||||
let d = TempDir::new("epoch");
|
||||
let rev = d.join("share-revocations.json");
|
||||
let s = Shares::new(d.path(), &rev);
|
||||
let key = ShareKey::new(&[9u8; 32]).unwrap();
|
||||
let m = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
|
||||
s.stop(&m.record.id).unwrap();
|
||||
s.stop_all().unwrap();
|
||||
s.stop_all().unwrap();
|
||||
assert_eq!(revocations(&rev)["epoch"], 2);
|
||||
std::fs::remove_file(d.join("share-links.json")).unwrap();
|
||||
Shares::new(d.path(), &rev)
|
||||
.ensure_revocation_file()
|
||||
.unwrap();
|
||||
assert!(
|
||||
revocations(&rev)["epoch"].as_u64().unwrap() >= 2,
|
||||
"{}",
|
||||
revocations(&rev)
|
||||
);
|
||||
// Minting after the loss continues from there.
|
||||
let m2 = Shares::new(d.path(), &rev)
|
||||
.mint(&key, "a.test", "/", 3600, None, None, "t")
|
||||
.unwrap();
|
||||
assert!(m2.record.epoch >= 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lost_deny_list_raises_the_epoch_instead_of_shrinking() {
|
||||
let d = TempDir::new("deny");
|
||||
let rev = d.join("share-revocations.json");
|
||||
let s = Shares::new(d.path(), &rev);
|
||||
let key = ShareKey::new(&[9u8; 32]).unwrap();
|
||||
let a = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
|
||||
let _b = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
|
||||
s.stop(&a.record.id).unwrap();
|
||||
let before = revocations(&rev);
|
||||
assert_eq!(before["deny"][0], a.record.id);
|
||||
assert_eq!(before["epoch"], 0);
|
||||
// The records are gone (or an older backup without the stop is restored).
|
||||
std::fs::remove_file(d.join("share-links.json")).unwrap();
|
||||
Shares::new(d.path(), &rev)
|
||||
.ensure_revocation_file()
|
||||
.unwrap();
|
||||
let after = revocations(&rev);
|
||||
let still_denied = after["deny"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|x| x == &before["deny"][0]);
|
||||
assert!(
|
||||
still_denied || after["epoch"].as_u64().unwrap() > 0,
|
||||
"stopped link {} works again: {after}",
|
||||
a.record.id
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deny_list_that_would_overflow_raises_the_epoch() {
|
||||
let d = TempDir::new("overflow");
|
||||
let rev = d.join("share-revocations.json");
|
||||
let s = Shares::new(d.path(), &rev);
|
||||
let t = ianitor_control::util::now();
|
||||
let links: Vec<Value> = (0..10_050u32)
|
||||
.map(|i| {
|
||||
serde_json::json!({
|
||||
"id": format!("{:032x}", i + 1), "hostname": "a.test", "path_prefix": "/", "epoch": 0,
|
||||
"created_at": t, "expires_at": t + 3600, "has_password": false, "created_by": "t",
|
||||
"stopped_at": t
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
std::fs::write(
|
||||
d.join("share-links.json"),
|
||||
serde_json::json!({ "epoch": 0, "links": links }).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
s.ensure_revocation_file().unwrap();
|
||||
let r = revocations(&rev);
|
||||
assert!(
|
||||
r["epoch"].as_u64().unwrap() >= 1,
|
||||
"an overflowing deny list must raise the epoch: {}",
|
||||
r["epoch"]
|
||||
);
|
||||
assert!(r["deny"].as_array().unwrap().len() < 10_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_minted_after_the_records_were_lost_works() {
|
||||
let d = TempDir::new("doa");
|
||||
let rev = d.join("share-revocations.json");
|
||||
let s = Shares::new(d.path(), &rev);
|
||||
let key = ShareKey::new(&[9u8; 32]).unwrap();
|
||||
let a = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
|
||||
s.stop(&a.record.id).unwrap();
|
||||
std::fs::remove_file(d.join("share-links.json")).unwrap();
|
||||
let b = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
|
||||
let published = revocations(&rev);
|
||||
assert!(
|
||||
u64::from(b.record.epoch) >= published["epoch"].as_u64().unwrap(),
|
||||
"dead on arrival: link epoch {} < published {}",
|
||||
b.record.epoch,
|
||||
published["epoch"]
|
||||
);
|
||||
let list = s.load().unwrap();
|
||||
let rec = list.links.iter().find(|l| l.id == b.record.id).unwrap();
|
||||
assert_eq!(
|
||||
rec.state(list.epoch, ianitor_control::util::now()),
|
||||
"active"
|
||||
);
|
||||
}
|
||||
@@ -13,6 +13,9 @@ serde_json.workspace = true
|
||||
toml.workspace = true
|
||||
thiserror.workspace = true
|
||||
url.workspace = true
|
||||
ring.workspace = true
|
||||
base64.workspace = true
|
||||
unicode-normalization = "0.1.24"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -54,6 +54,7 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig {
|
||||
interval_secs: hc.interval_secs,
|
||||
}),
|
||||
access_log: h.access_log == AccessLog::Truncated,
|
||||
share_links: h.share_links,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Bumped on any incompatible change; edge refuses other versions.
|
||||
pub const EDGE_CONFIG_VERSION: u32 = 1;
|
||||
pub const EDGE_CONFIG_VERSION: u32 = 2;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -103,4 +103,7 @@ pub struct EdgeHost {
|
||||
pub response_headers: Vec<EdgeHeaderOp>,
|
||||
pub health_check: Option<EdgeHealthCheck>,
|
||||
pub access_log: bool,
|
||||
/// Share-link tokens (see `ianitor_core::share`) let visitors in on this host without
|
||||
/// forward-auth. Checked against the key credential and the revocation file.
|
||||
pub share_links: bool,
|
||||
}
|
||||
|
||||
+314
-9
@@ -2,11 +2,67 @@
|
||||
// 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.
|
||||
//! Typed validation errors. Every message names the file and says what is wrong in plain English.
|
||||
//!
|
||||
//! Each error also has a stable [`ValidationError::code`], the form field it is about
|
||||
//! ([`ValidationError::field`], e.g. `upstreams[1]`) and the values the UI shows in bold
|
||||
//! ([`ValidationError::params`]). The control API maps the code to the UI's copy
|
||||
//! (docs/ui-api.md §3.1) and keeps the `Display` text below as the technical detail.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
|
||||
/// The reasons carried in `&'static str` fields. [`ValidationError::code`] compares them by
|
||||
/// value, so every reason is written once, here.
|
||||
pub(crate) mod reason {
|
||||
pub const HOST_EMPTY: &str = "it is empty";
|
||||
pub const HOST_TOO_LONG: &str = "it is longer than 253 characters";
|
||||
pub const HOST_IP: &str = "IP addresses are not hostnames";
|
||||
pub const HOST_WILDCARD: &str = "wildcards are not supported";
|
||||
pub const HOST_TRAILING_DOT: &str = "it must not end with a dot";
|
||||
pub const HOST_UPPERCASE: &str = "it must be lowercase";
|
||||
pub const HOST_SPACES: &str = "it must not contain spaces";
|
||||
pub const HOST_EMPTY_LABEL: &str = "it has an empty label";
|
||||
pub const HOST_LABEL_LONG: &str = "a label is longer than 63 characters";
|
||||
pub const HOST_CHARACTERS: &str = "only a-z, 0-9, '-' and '.' are allowed";
|
||||
pub const HOST_LABEL_DASH: &str = "a label must not start or end with '-'";
|
||||
pub const HOST_NUMERIC: &str = "the last label must not be numeric";
|
||||
|
||||
pub const URL_ASCII: &str = "it must be plain ASCII without spaces";
|
||||
pub const URL_NOT_URL: &str = "it is not a URL like http://127.0.0.1:8080";
|
||||
pub const URL_SCHEME: &str = "only http:// and https:// are supported";
|
||||
pub const URL_CREDENTIALS: &str = "credentials in the URL are not allowed";
|
||||
pub const URL_FRAGMENT: &str = "a #fragment is not allowed";
|
||||
pub const URL_NO_HOST: &str = "it has no host";
|
||||
pub const URL_HOST_NAME: &str = "the host name is not valid";
|
||||
pub const URL_NO_PORT: &str = "it has no port";
|
||||
pub const URL_PORT_ZERO: &str = "port 0 is not usable";
|
||||
pub const URL_PATH: &str = "a path is not allowed; requests keep their own path";
|
||||
pub const URL_QUERY: &str = "a ?query is not allowed";
|
||||
pub const URL_BRACES: &str = "'{' and '}' are not allowed";
|
||||
pub const URL_MIXED: &str = "all upstreams of a host must use the same scheme";
|
||||
|
||||
pub const VALUE_EMPTY: &str = "an empty value is not allowed; use action = \"remove\"";
|
||||
pub const VALUE_LONG: &str = "it is longer than 4096 characters";
|
||||
pub const VALUE_ASCII: &str = "only visible ASCII characters and spaces are allowed";
|
||||
pub const VALUE_BRACES: &str = "'{' and '}' are not allowed (they are placeholders in Caddy)";
|
||||
pub const VALUE_EDGE_SPACE: &str = "it must not start or end with a space";
|
||||
|
||||
pub const RULE_REMOVE_VALUE: &str = "remove takes no value or secret";
|
||||
pub const RULE_BOTH: &str = "give either value or secret, not both";
|
||||
pub const RULE_NEITHER: &str = "set needs a value or a secret";
|
||||
|
||||
pub const HEALTH_PATH: &str =
|
||||
"path must start with '/' and contain only visible ASCII without '{', '}' or '#'";
|
||||
pub const HEALTH_INTERVAL: &str = "interval_secs must be between 1 and 3600";
|
||||
|
||||
pub const PATH_LAYOUT: &str =
|
||||
"only ianitor.toml and hosts/<hostname>.toml belong in the routes repository";
|
||||
pub const PATH_SUBDIR: &str = "folders inside hosts/ are not allowed";
|
||||
pub const PATH_NAME: &str = "the file name must be a lowercase hostname followed by .toml";
|
||||
pub const PATH_KIND: &str = "symbolic links, executables and submodules are not allowed";
|
||||
}
|
||||
|
||||
/// One problem found in the route files.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ValidationError {
|
||||
@@ -26,8 +82,10 @@ pub enum ValidationError {
|
||||
DuplicateFile { file: String },
|
||||
#[error("{file} is larger than {max} bytes")]
|
||||
FileTooLarge { file: String, max: usize },
|
||||
#[error("{file} must be named after its hostname: {hostname}.toml")]
|
||||
#[error("{file} must be named after its hostname: hosts/{hostname}.toml")]
|
||||
FileNameMismatch { file: String, hostname: String },
|
||||
#[error("{file}: {reason}")]
|
||||
UnexpectedFile { file: String, reason: &'static str },
|
||||
#[error("{file}: at most {max} upstreams per host")]
|
||||
TooManyUpstreams { file: String, max: usize },
|
||||
#[error("{file}: `{hostname}` is not a valid hostname: {reason}")]
|
||||
@@ -49,36 +107,64 @@ pub enum ValidationError {
|
||||
file: String,
|
||||
url: String,
|
||||
reason: &'static str,
|
||||
/// Position in `upstreams`; `None` when the problem is about the list as a whole.
|
||||
index: Option<usize>,
|
||||
},
|
||||
#[error("{file}: upstream `{url}` is listed twice")]
|
||||
DuplicateUpstream { file: String, url: String },
|
||||
DuplicateUpstream {
|
||||
file: String,
|
||||
url: String,
|
||||
index: usize,
|
||||
},
|
||||
#[error("{file}: secret `{secret}` is used but not declared in the site file")]
|
||||
UndefinedSecret { file: String, secret: String },
|
||||
UndefinedSecret {
|
||||
file: String,
|
||||
secret: String,
|
||||
field: String,
|
||||
},
|
||||
#[error(
|
||||
"{file}: response header `{header}` may not use a secret; secrets only go to upstreams"
|
||||
)]
|
||||
SecretInResponseHeader { file: String, header: String },
|
||||
SecretInResponseHeader {
|
||||
file: String,
|
||||
header: String,
|
||||
field: 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 },
|
||||
InvalidHeaderName {
|
||||
file: String,
|
||||
name: String,
|
||||
field: String,
|
||||
},
|
||||
#[error("{file}: value for header `{header}` is not allowed: {reason}")]
|
||||
InvalidHeaderValue {
|
||||
file: String,
|
||||
header: String,
|
||||
reason: &'static str,
|
||||
field: String,
|
||||
},
|
||||
#[error("{file}: header `{header}` is managed by the proxy and cannot be changed by a rule")]
|
||||
ProtectedHeader { file: String, header: String },
|
||||
ProtectedHeader {
|
||||
file: String,
|
||||
header: String,
|
||||
field: String,
|
||||
},
|
||||
#[error("{file}: header `{header}` has more than one rule in the same list")]
|
||||
DuplicateHeaderRule { file: String, header: String },
|
||||
DuplicateHeaderRule {
|
||||
file: String,
|
||||
header: String,
|
||||
field: String,
|
||||
},
|
||||
#[error("{file}: rule for header `{header}` is incomplete: {reason}")]
|
||||
BadHeaderRule {
|
||||
file: String,
|
||||
header: String,
|
||||
reason: &'static str,
|
||||
field: String,
|
||||
},
|
||||
#[error("{file}: health check is not usable: {reason}")]
|
||||
BadHealthCheck { file: String, reason: &'static str },
|
||||
@@ -97,6 +183,220 @@ fn line_suffix(line: Option<usize>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
impl ValidationError {
|
||||
/// The file the problem is in (for a duplicate hostname: the second file).
|
||||
pub fn file(&self) -> &str {
|
||||
use ValidationError as E;
|
||||
match self {
|
||||
E::Syntax { file, .. }
|
||||
| E::UnknownField { file, .. }
|
||||
| E::MissingField { file, .. }
|
||||
| E::InvalidValue { file, .. }
|
||||
| E::DuplicateFile { file }
|
||||
| E::FileTooLarge { file, .. }
|
||||
| E::FileNameMismatch { file, .. }
|
||||
| E::UnexpectedFile { file, .. }
|
||||
| E::TooManyUpstreams { file, .. }
|
||||
| E::InvalidHostname { file, .. }
|
||||
| E::NoUpstreams { file }
|
||||
| E::BadUpstreamUrl { file, .. }
|
||||
| E::DuplicateUpstream { file, .. }
|
||||
| E::UndefinedSecret { file, .. }
|
||||
| E::SecretInResponseHeader { file, .. }
|
||||
| E::InvalidSecretName { file, .. }
|
||||
| E::InvalidHeaderName { file, .. }
|
||||
| E::InvalidHeaderValue { file, .. }
|
||||
| E::ProtectedHeader { file, .. }
|
||||
| E::DuplicateHeaderRule { file, .. }
|
||||
| E::BadHeaderRule { file, .. }
|
||||
| E::BadHealthCheck { file, .. }
|
||||
| E::ForwardAuthNotConfigured { file }
|
||||
| E::BadForwardAuth { file, .. }
|
||||
| E::BadAcme { file, .. } => file,
|
||||
E::DuplicateHostname { second, .. } => second,
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the problem is in the site file (or a stray file), not in a host file.
|
||||
pub fn in_site_file(&self) -> bool {
|
||||
!self.file().starts_with("hosts/")
|
||||
}
|
||||
|
||||
/// A stable code the UI switches on, e.g. `host.upstream.no_port` (docs/ui-api.md §3.1).
|
||||
pub fn code(&self) -> &'static str {
|
||||
use ValidationError as E;
|
||||
use reason as r;
|
||||
let site = self.in_site_file();
|
||||
match self {
|
||||
E::Syntax { .. } => "file.syntax",
|
||||
E::UnknownField { .. } if site => "site.field.unknown",
|
||||
E::UnknownField { .. } => "host.field.unknown",
|
||||
E::MissingField { field, .. } if !site && field == "hostname" => {
|
||||
"host.hostname.missing"
|
||||
}
|
||||
E::MissingField { field, .. } if !site && field == "upstreams" => {
|
||||
"host.upstreams.missing"
|
||||
}
|
||||
E::MissingField { .. } => "file.field.missing",
|
||||
E::InvalidValue { .. } => "file.field.invalid",
|
||||
E::DuplicateFile { .. } => "repo.duplicate_file",
|
||||
E::FileTooLarge { .. } => "file.too_large",
|
||||
E::FileNameMismatch { .. } => "host.file_name",
|
||||
E::UnexpectedFile { .. } => "repo.unexpected_file",
|
||||
E::TooManyUpstreams { .. } => "host.upstream.too_many",
|
||||
E::InvalidHostname { reason, .. } => match *reason {
|
||||
x if x == r::HOST_EMPTY => "host.hostname.missing",
|
||||
x if x == r::HOST_TOO_LONG => "host.hostname.too_long",
|
||||
x if x == r::HOST_IP || x == r::HOST_NUMERIC => "host.hostname.numeric",
|
||||
x if x == r::HOST_WILDCARD => "host.hostname.wildcard",
|
||||
x if x == r::HOST_TRAILING_DOT => "host.hostname.trailing_dot",
|
||||
x if x == r::HOST_UPPERCASE => "host.hostname.uppercase",
|
||||
x if x == r::HOST_SPACES => "host.hostname.spaces",
|
||||
x if x == r::HOST_EMPTY_LABEL => "host.hostname.empty_label",
|
||||
x if x == r::HOST_LABEL_LONG => "host.hostname.label_long",
|
||||
x if x == r::HOST_LABEL_DASH => "host.hostname.label_dash",
|
||||
_ => "host.hostname.characters",
|
||||
},
|
||||
E::DuplicateHostname { .. } => "host.hostname.taken",
|
||||
E::NoUpstreams { .. } => "host.upstreams.missing",
|
||||
E::BadUpstreamUrl { reason, .. } => match *reason {
|
||||
x if x == r::URL_SCHEME => "host.upstream.scheme",
|
||||
x if x == r::URL_CREDENTIALS => "host.upstream.credentials",
|
||||
x if x == r::URL_FRAGMENT => "host.upstream.fragment",
|
||||
x if x == r::URL_NO_HOST => "host.upstream.no_host",
|
||||
x if x == r::URL_HOST_NAME => "host.upstream.host_name",
|
||||
x if x == r::URL_NO_PORT => "host.upstream.no_port",
|
||||
x if x == r::URL_PORT_ZERO => "host.upstream.port_zero",
|
||||
x if x == r::URL_PATH => "host.upstream.path",
|
||||
x if x == r::URL_QUERY => "host.upstream.query",
|
||||
x if x == r::URL_MIXED => "host.upstream.mixed_schemes",
|
||||
_ => "host.upstream.not_url",
|
||||
},
|
||||
E::DuplicateUpstream { .. } => "host.upstream.duplicate",
|
||||
E::UndefinedSecret { .. } => "host.header.secret_unknown",
|
||||
E::SecretInResponseHeader { .. } => "host.header.secret_response",
|
||||
E::InvalidSecretName { .. } => "site.secret.name",
|
||||
E::InvalidHeaderName { .. } | E::ProtectedHeader { .. } if site => {
|
||||
"site.forward_auth.header"
|
||||
}
|
||||
E::InvalidHeaderName { .. } => "host.header.name",
|
||||
E::InvalidHeaderValue { reason, .. } if *reason == r::VALUE_EMPTY => {
|
||||
"host.header.empty"
|
||||
}
|
||||
E::InvalidHeaderValue { .. } => "host.header.value",
|
||||
E::ProtectedHeader { .. } => "host.header.protected",
|
||||
E::DuplicateHeaderRule { .. } => "host.header.duplicate",
|
||||
E::BadHeaderRule { reason, .. } => match *reason {
|
||||
x if x == r::RULE_BOTH => "host.header.both",
|
||||
x if x == r::RULE_REMOVE_VALUE => "host.header.remove_value",
|
||||
_ => "host.header.empty",
|
||||
},
|
||||
E::BadHealthCheck { reason, .. } if *reason == r::HEALTH_INTERVAL => {
|
||||
"host.health.interval"
|
||||
}
|
||||
E::BadHealthCheck { .. } => "host.health.path",
|
||||
E::ForwardAuthNotConfigured { .. } => "host.auth.not_configured",
|
||||
E::BadForwardAuth { .. } => "site.forward_auth",
|
||||
E::BadAcme { .. } => "site.acme",
|
||||
}
|
||||
}
|
||||
|
||||
/// The form field the problem is about, as a path into the host body (`hostname`,
|
||||
/// `upstreams[0]`, `request_headers[2].name`, `health_check.path`), or `None`.
|
||||
pub fn field(&self) -> Option<String> {
|
||||
use ValidationError as E;
|
||||
if self.in_site_file() {
|
||||
return None;
|
||||
}
|
||||
match self {
|
||||
E::UnknownField { field, .. } | E::MissingField { field, .. } => Some(field.clone()),
|
||||
E::FileNameMismatch { .. }
|
||||
| E::InvalidHostname { .. }
|
||||
| E::DuplicateHostname { .. } => Some("hostname".into()),
|
||||
E::TooManyUpstreams { .. } | E::NoUpstreams { .. } => Some("upstreams".into()),
|
||||
E::BadUpstreamUrl { index, .. } => Some(match index {
|
||||
Some(i) => format!("upstreams[{i}]"),
|
||||
None => "upstreams".into(),
|
||||
}),
|
||||
E::DuplicateUpstream { index, .. } => Some(format!("upstreams[{index}]")),
|
||||
E::UndefinedSecret { field, .. }
|
||||
| E::SecretInResponseHeader { field, .. }
|
||||
| E::InvalidHeaderName { field, .. }
|
||||
| E::InvalidHeaderValue { field, .. }
|
||||
| E::ProtectedHeader { field, .. }
|
||||
| E::DuplicateHeaderRule { field, .. }
|
||||
| E::BadHeaderRule { field, .. } => Some(field.clone()),
|
||||
E::BadHealthCheck { reason, .. } if *reason == reason::HEALTH_INTERVAL => {
|
||||
Some("health_check.interval_secs".into())
|
||||
}
|
||||
E::BadHealthCheck { .. } => Some("health_check.path".into()),
|
||||
E::ForwardAuthNotConfigured { .. } => Some("auth".into()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The values a message shows: always `file`, plus `line`, `field`, `max`, `hostname`,
|
||||
/// `suggestion`, `url`, `name` or `secret` where they apply.
|
||||
pub fn params(&self) -> BTreeMap<&'static str, String> {
|
||||
use ValidationError as E;
|
||||
let mut p = BTreeMap::new();
|
||||
p.insert("file", self.file().to_owned());
|
||||
match self {
|
||||
E::Syntax { line: Some(l), .. } => {
|
||||
p.insert("line", l.to_string());
|
||||
}
|
||||
E::UnknownField { field, .. } | E::MissingField { field, .. } => {
|
||||
p.insert("field", field.clone());
|
||||
}
|
||||
E::FileTooLarge { max, .. } | E::TooManyUpstreams { max, .. } => {
|
||||
p.insert("max", max.to_string());
|
||||
}
|
||||
E::FileNameMismatch { hostname, .. } | E::DuplicateHostname { hostname, .. } => {
|
||||
p.insert("hostname", hostname.clone());
|
||||
}
|
||||
E::InvalidHostname {
|
||||
hostname, reason, ..
|
||||
} => {
|
||||
p.insert("hostname", hostname.clone());
|
||||
if *reason == reason::HOST_UPPERCASE || *reason == reason::HOST_TRAILING_DOT {
|
||||
p.insert(
|
||||
"suggestion",
|
||||
hostname.trim_end_matches('.').to_ascii_lowercase(),
|
||||
);
|
||||
}
|
||||
}
|
||||
E::BadUpstreamUrl { url, reason, .. } => {
|
||||
p.insert("url", url.clone());
|
||||
if [reason::URL_PATH, reason::URL_QUERY, reason::URL_FRAGMENT].contains(reason)
|
||||
&& let Ok(u) = url::Url::parse(url)
|
||||
&& let Some(host) = u.host_str()
|
||||
{
|
||||
let port = u.port().map(|p| format!(":{p}")).unwrap_or_default();
|
||||
p.insert("suggestion", format!("{}://{host}{port}", u.scheme()));
|
||||
}
|
||||
}
|
||||
E::DuplicateUpstream { url, .. } => {
|
||||
p.insert("url", url.clone());
|
||||
}
|
||||
E::UndefinedSecret { secret, .. } => {
|
||||
p.insert("secret", secret.clone());
|
||||
}
|
||||
E::InvalidSecretName { name, .. } | E::InvalidHeaderName { name, .. } => {
|
||||
p.insert("name", name.clone());
|
||||
}
|
||||
E::SecretInResponseHeader { header, .. }
|
||||
| E::InvalidHeaderValue { header, .. }
|
||||
| E::ProtectedHeader { header, .. }
|
||||
| E::DuplicateHeaderRule { header, .. }
|
||||
| E::BadHeaderRule { header, .. } => {
|
||||
p.insert("name", header.clone());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>);
|
||||
@@ -109,6 +409,11 @@ impl ValidationErrors {
|
||||
pub fn into_errors(self) -> Vec<ValidationError> {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Wrap errors found outside [`crate::load`] (e.g. by [`crate::routes::check_path`]).
|
||||
pub fn from_errors(errors: Vec<ValidationError>) -> ValidationErrors {
|
||||
ValidationErrors(errors)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ValidationErrors {
|
||||
|
||||
@@ -12,12 +12,15 @@ pub mod compile;
|
||||
pub mod edge_config;
|
||||
mod error;
|
||||
mod model;
|
||||
pub mod routes;
|
||||
pub mod share;
|
||||
pub mod time;
|
||||
mod validate;
|
||||
|
||||
pub use error::{ValidationError, ValidationErrors};
|
||||
pub use model::{
|
||||
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
|
||||
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, Model, Scheme,
|
||||
SecretName, Site, TlsMode, Upstream, UpstreamHost,
|
||||
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, MAX_FILE_BYTES,
|
||||
MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost,
|
||||
};
|
||||
pub use validate::{SourceFile, load};
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// 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 shape of the routes repository: exactly `ianitor.toml` and `hosts/<hostname>.toml`,
|
||||
//! regular files only. Anything else (other names, folders inside `hosts/`, symbolic links,
|
||||
//! submodules, executables) is refused, so the repository can never hold something the
|
||||
//! compilers do not read.
|
||||
|
||||
use crate::error::{ValidationError, reason};
|
||||
use crate::validate::check_hostname;
|
||||
|
||||
/// The site file at the root of the repository.
|
||||
pub const SITE_FILE: &str = "ianitor.toml";
|
||||
/// The folder holding one file per host.
|
||||
pub const HOSTS_DIR: &str = "hosts";
|
||||
/// Most host files one repository may hold.
|
||||
pub const MAX_HOST_FILES: usize = 1000;
|
||||
|
||||
/// What a tree entry is, as git reports it (`git ls-tree` modes).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EntryKind {
|
||||
/// Mode 100644.
|
||||
File,
|
||||
/// Mode 100755.
|
||||
Executable,
|
||||
/// Mode 120000.
|
||||
Symlink,
|
||||
/// Mode 160000.
|
||||
Submodule,
|
||||
}
|
||||
|
||||
/// A path the repository may hold.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RoutePath {
|
||||
Site,
|
||||
Host { hostname: String },
|
||||
}
|
||||
|
||||
/// The path of the file for `hostname`.
|
||||
pub fn host_path(hostname: &str) -> String {
|
||||
format!("{HOSTS_DIR}/{hostname}.toml")
|
||||
}
|
||||
|
||||
/// Check one path of the repository tree (as listed recursively, `/`-separated).
|
||||
pub fn check_path(path: &str, kind: EntryKind) -> Result<RoutePath, ValidationError> {
|
||||
let bad = |reason| ValidationError::UnexpectedFile {
|
||||
file: path.to_owned(),
|
||||
reason,
|
||||
};
|
||||
if kind != EntryKind::File {
|
||||
return Err(bad(reason::PATH_KIND));
|
||||
}
|
||||
if path == SITE_FILE {
|
||||
return Ok(RoutePath::Site);
|
||||
}
|
||||
let Some(rest) = path.strip_prefix("hosts/") else {
|
||||
return Err(bad(reason::PATH_LAYOUT));
|
||||
};
|
||||
if rest.contains(['/', '\\']) {
|
||||
return Err(bad(reason::PATH_SUBDIR));
|
||||
}
|
||||
let Some(hostname) = rest.strip_suffix(".toml") else {
|
||||
return Err(bad(reason::PATH_NAME));
|
||||
};
|
||||
if check_hostname(hostname).is_err() {
|
||||
return Err(bad(reason::PATH_NAME));
|
||||
}
|
||||
Ok(RoutePath::Host {
|
||||
hostname: hostname.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Check a whole tree listing. Returns every problem; at most [`MAX_HOST_FILES`] host files.
|
||||
pub fn check_tree<'a>(
|
||||
entries: impl IntoIterator<Item = (&'a str, EntryKind)>,
|
||||
) -> Result<(), Vec<ValidationError>> {
|
||||
let mut errors = Vec::new();
|
||||
let mut hosts = 0usize;
|
||||
let mut site = false;
|
||||
for (path, kind) in entries {
|
||||
match check_path(path, kind) {
|
||||
Ok(RoutePath::Site) => site = true,
|
||||
Ok(RoutePath::Host { .. }) => hosts += 1,
|
||||
Err(e) => errors.push(e),
|
||||
}
|
||||
}
|
||||
if !site {
|
||||
errors.push(ValidationError::MissingField {
|
||||
file: SITE_FILE.into(),
|
||||
field: "(the file itself)".into(),
|
||||
});
|
||||
}
|
||||
if hosts > MAX_HOST_FILES {
|
||||
errors.push(ValidationError::UnexpectedFile {
|
||||
file: HOSTS_DIR.into(),
|
||||
reason: "more than 1000 host files",
|
||||
});
|
||||
}
|
||||
if errors.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(errors)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
// 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/.
|
||||
|
||||
//! Share links: stateless tokens minted by control and checked by edge.
|
||||
//!
|
||||
//! A link token is `ish1.` + base64url(payload ‖ mac):
|
||||
//!
|
||||
//! ```text
|
||||
//! payload = version (1) ‖ id (16) ‖ epoch (u32 BE) ‖ expires_at (u64 BE, Unix s) ‖ flags (1) ‖ path prefix
|
||||
//! mac = HMAC-SHA256(key, "ianitor share link v1" 0 host 0 payload [0 HMAC-SHA256(key, "ianitor share password v1" 0 id password)])
|
||||
//! ```
|
||||
//!
|
||||
//! - The host is not in the token but in the MAC, so a token for one host fails on another.
|
||||
//! - With a password (flag bit 0), the MAC can only be checked by someone who has both the key
|
||||
//! and the password: the token carries no password hash, so holding a link does not allow
|
||||
//! guessing its password offline. Edge rate-limits guesses.
|
||||
//! - The session cookie edge sets after a successful check is `iss1.` + base64url(payload ‖
|
||||
//! HMAC(key, "ianitor share session v1" 0 host 0 payload)): a different domain, so a link
|
||||
//! token is never accepted as a cookie and a cookie never as a link (and a cookie for a
|
||||
//! password link proves the password was given).
|
||||
//! - Revocation: every token carries the epoch it was minted in; edge refuses tokens from an
|
||||
//! older epoch ("stop all") and ids on the deny list ("stop this link").
|
||||
//!
|
||||
//! [`path_within`] decides whether a raw request path lies under a link's prefix. It refuses
|
||||
//! anything an upstream might read differently from a plain byte comparison.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fmt;
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use ring::hmac;
|
||||
|
||||
/// Name of the credential (`$CREDENTIALS_DIRECTORY/<name>`) holding the share-link key, read by
|
||||
/// both edge and control.
|
||||
pub const KEY_CREDENTIAL: &str = "share-link-key";
|
||||
/// Shortest key accepted, in bytes.
|
||||
pub const MIN_KEY_LEN: usize = 32;
|
||||
/// Query parameter carrying a link token. Edge only takes values that start with
|
||||
/// [`LINK_PREFIX`]; anything else is left to the upstream.
|
||||
pub const QUERY_PARAM: &str = "share";
|
||||
/// Start of every link token.
|
||||
pub const LINK_PREFIX: &str = "ish1.";
|
||||
/// Start of every session cookie value.
|
||||
pub const SESSION_PREFIX: &str = "iss1.";
|
||||
/// Session cookie name (`__Secure-`: browsers only accept it with `Secure`).
|
||||
pub const COOKIE_NAME: &str = "__Secure-ianitor-share";
|
||||
/// Path the password form posts to, on hosts with share links.
|
||||
pub const PASSWORD_PATH: &str = "/.well-known/ianitor/share";
|
||||
/// Longest path prefix.
|
||||
pub const MAX_PREFIX_LEN: usize = 256;
|
||||
/// Password length limits, in characters.
|
||||
pub const MIN_PASSWORD_CHARS: usize = 8;
|
||||
pub const MAX_PASSWORD_CHARS: usize = 128;
|
||||
|
||||
const VERSION: u8 = 1;
|
||||
const FLAG_PASSWORD: u8 = 1;
|
||||
const FIXED_LEN: usize = 1 + 16 + 4 + 8 + 1;
|
||||
const MAC_LEN: usize = 32;
|
||||
/// Longest token or cookie accepted before decoding.
|
||||
const MAX_ENCODED_LEN: usize = 1024;
|
||||
|
||||
/// A link id: 16 random bytes, written as 32 lowercase hex digits.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct ShareId(pub [u8; 16]);
|
||||
|
||||
impl ShareId {
|
||||
pub fn to_hex(&self) -> String {
|
||||
self.0.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
pub fn from_hex(s: &str) -> Option<ShareId> {
|
||||
if s.len() != 32
|
||||
|| !s
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut out = [0u8; 16];
|
||||
for (i, o) in out.iter_mut().enumerate() {
|
||||
*o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?;
|
||||
}
|
||||
Some(ShareId(out))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ShareId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.to_hex())
|
||||
}
|
||||
}
|
||||
|
||||
/// The HMAC key. Never printed.
|
||||
pub struct ShareKey(hmac::Key);
|
||||
|
||||
impl fmt::Debug for ShareKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("ShareKey(<redacted>)")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ShareError {
|
||||
#[error("the share-link key must be at least {MIN_KEY_LEN} bytes")]
|
||||
KeyTooShort,
|
||||
#[error("the path prefix is not usable: {0}")]
|
||||
Prefix(&'static str),
|
||||
#[error("the password must be {MIN_PASSWORD_CHARS} to {MAX_PASSWORD_CHARS} characters")]
|
||||
Password,
|
||||
}
|
||||
|
||||
impl ShareKey {
|
||||
pub fn new(bytes: &[u8]) -> Result<ShareKey, ShareError> {
|
||||
if bytes.len() < MIN_KEY_LEN {
|
||||
return Err(ShareError::KeyTooShort);
|
||||
}
|
||||
Ok(ShareKey(hmac::Key::new(hmac::HMAC_SHA256, bytes)))
|
||||
}
|
||||
}
|
||||
|
||||
/// What a token says. For a token checked with [`verify_link`] or [`verify_session`], all of
|
||||
/// it is proven by the MAC; from [`peek`], none of it is.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Claims {
|
||||
pub id: ShareId,
|
||||
pub epoch: u32,
|
||||
pub expires_at: u64,
|
||||
pub password: bool,
|
||||
pub prefix: String,
|
||||
}
|
||||
|
||||
/// What to mint.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LinkSpec<'a> {
|
||||
pub id: ShareId,
|
||||
pub epoch: u32,
|
||||
pub expires_at: u64,
|
||||
/// Already checked with [`check_prefix`].
|
||||
pub prefix: &'a str,
|
||||
pub password: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// Why a token was refused.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Rejection {
|
||||
/// Not a token at all (bad encoding, wrong version, too long).
|
||||
Malformed,
|
||||
/// The MAC does not match: altered, minted for another host, made with another key, or
|
||||
/// (for a password link) the wrong password.
|
||||
Invalid,
|
||||
/// The link needs a password and none was given.
|
||||
PasswordRequired,
|
||||
/// Proven genuine, but past its expiry.
|
||||
Expired { expires_at: u64 },
|
||||
/// Proven genuine, but stopped (deny list or an older epoch).
|
||||
Revoked,
|
||||
}
|
||||
|
||||
/// The revocation state edge checks against (from the deny-list file control writes).
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Revocations {
|
||||
/// Tokens minted in an older epoch are refused ("stop all").
|
||||
pub epoch: u32,
|
||||
/// Stopped links.
|
||||
pub deny: BTreeSet<ShareId>,
|
||||
}
|
||||
|
||||
impl Revocations {
|
||||
pub fn is_revoked(&self, c: &Claims) -> bool {
|
||||
c.epoch < self.epoch || self.deny.contains(&c.id)
|
||||
}
|
||||
}
|
||||
|
||||
fn payload(spec: &LinkSpec<'_>) -> Vec<u8> {
|
||||
let mut p = Vec::with_capacity(FIXED_LEN + spec.prefix.len());
|
||||
p.push(VERSION);
|
||||
p.extend_from_slice(&spec.id.0);
|
||||
p.extend_from_slice(&spec.epoch.to_be_bytes());
|
||||
p.extend_from_slice(&spec.expires_at.to_be_bytes());
|
||||
p.push(if spec.password.is_some() {
|
||||
FLAG_PASSWORD
|
||||
} else {
|
||||
0
|
||||
});
|
||||
p.extend_from_slice(spec.prefix.as_bytes());
|
||||
p
|
||||
}
|
||||
|
||||
fn password_tag(key: &ShareKey, id: &ShareId, password: &str) -> hmac::Tag {
|
||||
let mut ctx = hmac::Context::with_key(&key.0);
|
||||
ctx.update(b"ianitor share password v1\0");
|
||||
ctx.update(&id.0);
|
||||
ctx.update(password.as_bytes());
|
||||
ctx.sign()
|
||||
}
|
||||
|
||||
fn link_message(
|
||||
key: &ShareKey,
|
||||
host: &str,
|
||||
payload: &[u8],
|
||||
id: &ShareId,
|
||||
password: Option<&str>,
|
||||
) -> Vec<u8> {
|
||||
let mut m = Vec::with_capacity(64 + host.len() + payload.len());
|
||||
m.extend_from_slice(b"ianitor share link v1\0");
|
||||
m.extend_from_slice(host.as_bytes());
|
||||
m.push(0);
|
||||
m.extend_from_slice(payload);
|
||||
if let Some(pw) = password {
|
||||
m.push(0);
|
||||
m.extend_from_slice(password_tag(key, id, pw).as_ref());
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
fn session_message(host: &str, payload: &[u8]) -> Vec<u8> {
|
||||
let mut m = Vec::with_capacity(64 + host.len() + payload.len());
|
||||
m.extend_from_slice(b"ianitor share session v1\0");
|
||||
m.extend_from_slice(host.as_bytes());
|
||||
m.push(0);
|
||||
m.extend_from_slice(payload);
|
||||
m
|
||||
}
|
||||
|
||||
fn check_password(pw: &str) -> Result<(), ShareError> {
|
||||
let n = pw.chars().count();
|
||||
if (MIN_PASSWORD_CHARS..=MAX_PASSWORD_CHARS).contains(&n) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ShareError::Password)
|
||||
}
|
||||
}
|
||||
|
||||
/// Mint a link token for `host` (a validated hostname).
|
||||
pub fn mint(key: &ShareKey, host: &str, spec: &LinkSpec<'_>) -> Result<String, ShareError> {
|
||||
let prefix = check_prefix(spec.prefix).map_err(ShareError::Prefix)?;
|
||||
if prefix != spec.prefix {
|
||||
return Err(ShareError::Prefix("it is not in its normal form"));
|
||||
}
|
||||
if let Some(pw) = spec.password {
|
||||
check_password(pw)?;
|
||||
}
|
||||
let p = payload(spec);
|
||||
let tag = hmac::sign(
|
||||
&key.0,
|
||||
&link_message(key, host, &p, &spec.id, spec.password),
|
||||
);
|
||||
let mut raw = p;
|
||||
raw.extend_from_slice(tag.as_ref());
|
||||
Ok(format!("{LINK_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw)))
|
||||
}
|
||||
|
||||
/// Split and decode without checking the MAC. Only for showing a password page.
|
||||
fn decode(token: &str, prefix: &str) -> Result<(Claims, Vec<u8>, Vec<u8>), Rejection> {
|
||||
if token.len() > MAX_ENCODED_LEN {
|
||||
return Err(Rejection::Malformed);
|
||||
}
|
||||
let body = token.strip_prefix(prefix).ok_or(Rejection::Malformed)?;
|
||||
let raw = URL_SAFE_NO_PAD
|
||||
.decode(body)
|
||||
.map_err(|_| Rejection::Malformed)?;
|
||||
if raw.len() < FIXED_LEN + MAC_LEN + 1 {
|
||||
return Err(Rejection::Malformed);
|
||||
}
|
||||
let (p, mac) = raw.split_at(raw.len() - MAC_LEN);
|
||||
if p[0] != VERSION || p[FIXED_LEN - 1] & !FLAG_PASSWORD != 0 {
|
||||
return Err(Rejection::Malformed);
|
||||
}
|
||||
let mut id = [0u8; 16];
|
||||
id.copy_from_slice(&p[1..17]);
|
||||
let mut e = [0u8; 4];
|
||||
e.copy_from_slice(&p[17..21]);
|
||||
let mut x = [0u8; 8];
|
||||
x.copy_from_slice(&p[21..29]);
|
||||
let prefix = std::str::from_utf8(&p[FIXED_LEN..]).map_err(|_| Rejection::Malformed)?;
|
||||
// A token whose prefix is not in normal form was never minted.
|
||||
if check_prefix(prefix).ok().as_deref() != Some(prefix) {
|
||||
return Err(Rejection::Malformed);
|
||||
}
|
||||
Ok((
|
||||
Claims {
|
||||
id: ShareId(id),
|
||||
epoch: u32::from_be_bytes(e),
|
||||
expires_at: u64::from_be_bytes(x),
|
||||
password: p[FIXED_LEN - 1] & FLAG_PASSWORD != 0,
|
||||
prefix: prefix.to_owned(),
|
||||
},
|
||||
p.to_vec(),
|
||||
mac.to_vec(),
|
||||
))
|
||||
}
|
||||
|
||||
/// What a link token claims, unchecked (for the password page: is a password needed, and
|
||||
/// until when does it claim to work). Never grant anything on this alone.
|
||||
pub fn peek(token: &str) -> Result<Claims, Rejection> {
|
||||
decode(token, LINK_PREFIX).map(|(c, _, _)| c)
|
||||
}
|
||||
|
||||
/// Check a link token for `host`. The order of checks fixes what a visitor learns: a password
|
||||
/// is asked for before anything else is proven; expiry and revocation are reported only for
|
||||
/// tokens proven genuine.
|
||||
pub fn verify_link(
|
||||
key: &ShareKey,
|
||||
host: &str,
|
||||
token: &str,
|
||||
password: Option<&str>,
|
||||
now: u64,
|
||||
revocations: &Revocations,
|
||||
) -> Result<Claims, Rejection> {
|
||||
let (claims, p, mac) = decode(token, LINK_PREFIX)?;
|
||||
let password = match (claims.password, password) {
|
||||
(true, None) => return Err(Rejection::PasswordRequired),
|
||||
(true, Some(pw)) => Some(pw),
|
||||
(false, _) => None,
|
||||
};
|
||||
let msg = link_message(key, host, &p, &claims.id, password);
|
||||
hmac::verify(&key.0, &msg, &mac).map_err(|_| Rejection::Invalid)?;
|
||||
finish(claims, now, revocations)
|
||||
}
|
||||
|
||||
fn finish(claims: Claims, now: u64, revocations: &Revocations) -> Result<Claims, Rejection> {
|
||||
if now >= claims.expires_at {
|
||||
return Err(Rejection::Expired {
|
||||
expires_at: claims.expires_at,
|
||||
});
|
||||
}
|
||||
if revocations.is_revoked(&claims) {
|
||||
return Err(Rejection::Revoked);
|
||||
}
|
||||
Ok(claims)
|
||||
}
|
||||
|
||||
/// The session cookie value for claims proven by [`verify_link`].
|
||||
pub fn session_value(key: &ShareKey, host: &str, claims: &Claims) -> String {
|
||||
let spec = LinkSpec {
|
||||
id: claims.id,
|
||||
epoch: claims.epoch,
|
||||
expires_at: claims.expires_at,
|
||||
prefix: &claims.prefix,
|
||||
password: claims.password.then_some(""),
|
||||
};
|
||||
let p = payload(&spec);
|
||||
let tag = hmac::sign(&key.0, &session_message(host, &p));
|
||||
let mut raw = p;
|
||||
raw.extend_from_slice(tag.as_ref());
|
||||
format!("{SESSION_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw))
|
||||
}
|
||||
|
||||
/// Check a session cookie value for `host`.
|
||||
pub fn verify_session(
|
||||
key: &ShareKey,
|
||||
host: &str,
|
||||
value: &str,
|
||||
now: u64,
|
||||
revocations: &Revocations,
|
||||
) -> Result<Claims, Rejection> {
|
||||
let (claims, p, mac) = decode(value, SESSION_PREFIX)?;
|
||||
hmac::verify(&key.0, &session_message(host, &p), &mac).map_err(|_| Rejection::Invalid)?;
|
||||
finish(claims, now, revocations)
|
||||
}
|
||||
|
||||
/// Normalise and check a path prefix: starts with `/`, at most [`MAX_PREFIX_LEN`] bytes, only
|
||||
/// unreserved characters and `!$&'()*+,=:@-._~`, no `%`, `;`, backslash, empty segment or dot
|
||||
/// segment. A trailing `/` is dropped (except for `/` itself).
|
||||
pub fn check_prefix(prefix: &str) -> Result<String, &'static str> {
|
||||
if !prefix.starts_with('/') {
|
||||
return Err("it must start with /");
|
||||
}
|
||||
if prefix.len() > MAX_PREFIX_LEN {
|
||||
return Err("it is longer than 256 characters");
|
||||
}
|
||||
let ok = |c: u8| c.is_ascii_alphanumeric() || b"/!$&'()*+,=:@-._~".contains(&c);
|
||||
if !prefix.bytes().all(ok) {
|
||||
return Err("only letters, digits, / and -._~!$&'()*+,=:@ are allowed");
|
||||
}
|
||||
if prefix.contains("//") {
|
||||
return Err("it has an empty segment (//)");
|
||||
}
|
||||
let trimmed = if prefix.len() > 1 {
|
||||
prefix.strip_suffix('/').unwrap_or(prefix)
|
||||
} else {
|
||||
prefix
|
||||
};
|
||||
if trimmed == "/" {
|
||||
return Ok("/".into());
|
||||
}
|
||||
for seg in trimmed[1..].split('/') {
|
||||
if seg.is_empty() {
|
||||
return Err("it has an empty segment (//)");
|
||||
}
|
||||
if seg.bytes().all(|c| c == b'.') {
|
||||
return Err("it has a . or .. segment");
|
||||
}
|
||||
}
|
||||
Ok(trimmed.to_owned())
|
||||
}
|
||||
|
||||
/// Percent-encodings no plain path needs (lowercased before matching): `.`, `/`, `\`, `%`
|
||||
/// itself (double encoding), NUL, and IIS `%u` escapes.
|
||||
pub const REFUSED_ENCODINGS: &[&str] = &["%2e", "%2f", "%5c", "%25", "%00", "%u"];
|
||||
|
||||
/// ASCII characters a look-alike must not stand for after NFKC normalisation.
|
||||
/// ASCII characters a non-ASCII character must not turn into under NFKC.
|
||||
const STRUCTURAL: &[char] = &['/', '\\', ';', '?', '#', '%'];
|
||||
|
||||
/// Slash and backslash look-alikes NFKC leaves alone (some upstreams still treat them as
|
||||
/// separators): division slash, fraction slash, big solidus, big reverse solidus, set minus,
|
||||
/// reverse solidus operator, box-drawing diagonals.
|
||||
const SLASH_LOOKALIKES: &[char] = &[
|
||||
'\u{2215}', '\u{2044}', '\u{29F8}', '\u{29F9}', '\u{2216}', '\u{29F5}', '\u{2571}', '\u{2572}',
|
||||
];
|
||||
|
||||
/// Unicode's Default_Ignorable_Code_Point (DerivedCoreProperties.txt, Unicode 15).
|
||||
fn default_ignorable(c: char) -> bool {
|
||||
matches!(
|
||||
c as u32,
|
||||
0x00AD
|
||||
| 0x034F
|
||||
| 0x061C
|
||||
| 0x115F..=0x1160
|
||||
| 0x17B4..=0x17B5
|
||||
| 0x180B..=0x180F
|
||||
| 0x200B..=0x200F
|
||||
| 0x202A..=0x202E
|
||||
| 0x2060..=0x206F
|
||||
| 0x3164
|
||||
| 0xFE00..=0xFE0F
|
||||
| 0xFEFF
|
||||
| 0xFFA0
|
||||
| 0xFFF0..=0xFFF8
|
||||
| 0x1BCA0..=0x1BCA3
|
||||
| 0x1D173..=0x1D17A
|
||||
| 0xE0000..=0xE0FFF
|
||||
)
|
||||
}
|
||||
|
||||
/// Decode `%xx` escapes once. `None` for a broken escape.
|
||||
fn percent_decode(raw: &str) -> Option<Vec<u8>> {
|
||||
let b = raw.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
if b[i] == b'%' {
|
||||
let hex = raw.get(i + 1..i + 3)?;
|
||||
// from_str_radix would also take "+f".
|
||||
if !hex.bytes().all(|c| c.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
out.push(u8::from_str_radix(hex, 16).ok()?);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(b[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Is `raw_path` (the request path exactly as sent, still percent-encoded) under `prefix`?
|
||||
///
|
||||
/// Refused outright, whatever the prefix:
|
||||
/// - anything but visible ASCII, a backslash, an empty segment (`//`);
|
||||
/// - the encodings in [`REFUSED_ENCODINGS`] and broken `%` escapes;
|
||||
/// - escapes that do not decode to valid UTF-8 (this refuses every overlong form, such as
|
||||
/// `%c0%ae`);
|
||||
/// - any encoded character that NFKC normalisation turns into something containing `/`, `\`,
|
||||
/// `;`, `?`, `#`, `%` or a control character (fullwidth and small forms), and the slash
|
||||
/// look-alikes NFKC leaves alone ([`SLASH_LOOKALIKES`]);
|
||||
/// - a segment that NFKC turns into only dots or nothing, after dropping default-ignorable
|
||||
/// characters and combining marks and trimming whitespace (two-dot
|
||||
/// leaders, ellipses, fullwidth dots, look-alike spaces); look-alike dots and spaces inside a
|
||||
/// name with other characters (`Wait….pdf`, an ideographic space) are fine;
|
||||
/// - a segment of only dots, also with `;params` (`..;x`, `..%3b`), and any segment that is
|
||||
/// one or more dots followed by a percent-encoded byte (`..%20`, `..%3f`, `..%23`), since
|
||||
/// some servers trim or decode that into a dot segment.
|
||||
///
|
||||
/// Other paths match on whole segments, case-sensitively: prefix `/a` covers `/a` and `/a/x`,
|
||||
/// not `/ab` or `/A`.
|
||||
pub fn path_within(prefix: &str, raw_path: &str) -> bool {
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
if !raw_path.starts_with('/')
|
||||
|| !raw_path.bytes().all(|c| c.is_ascii_graphic())
|
||||
|| raw_path.contains('\\')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let lower = raw_path.to_ascii_lowercase();
|
||||
if REFUSED_ENCODINGS.iter().any(|bad| lower.contains(bad)) {
|
||||
return false;
|
||||
}
|
||||
// An empty segment anywhere but at the end (a trailing slash) is `//`.
|
||||
if raw_path.contains("//") {
|
||||
return false;
|
||||
}
|
||||
let Some(decoded) = percent_decode(raw_path) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(decoded) = String::from_utf8(decoded) else {
|
||||
return false;
|
||||
};
|
||||
let looks_structural = decoded.chars().filter(|c| !c.is_ascii()).any(|c| {
|
||||
SLASH_LOOKALIKES.contains(&c)
|
||||
|| std::iter::once(c)
|
||||
.nfkc()
|
||||
.any(|n| STRUCTURAL.contains(&n) || n.is_control())
|
||||
});
|
||||
if looks_structural {
|
||||
return false;
|
||||
}
|
||||
// Dot segments as an upstream that normalises (NFKC) and trims whitespace would see them.
|
||||
let segments: Vec<&str> = decoded[1..].split('/').collect();
|
||||
for (i, seg) in segments.iter().enumerate() {
|
||||
if seg.is_empty() && i + 1 == segments.len() {
|
||||
continue; // trailing slash
|
||||
}
|
||||
if seg.is_ascii() {
|
||||
continue; // the raw checks below cover ASCII segments
|
||||
}
|
||||
// Invisible characters (default-ignorable code points, combining marks) do not count:
|
||||
// `\u{200B}..` is `..` to a server that drops them.
|
||||
let n: String = seg.nfkc().collect();
|
||||
let visible: String = n
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.chars()
|
||||
.filter(|c| {
|
||||
!default_ignorable(*c) && !unicode_normalization::char::is_combining_mark(*c)
|
||||
})
|
||||
.collect();
|
||||
if visible.trim().chars().all(|c| c == '.') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for seg in lower[1..].split('/') {
|
||||
// `..;x` is `..` to Tomcat and friends; `..%3b` is `..;` to servers that decode
|
||||
// before splitting.
|
||||
let seg = seg.replace("%3b", ";");
|
||||
let name = seg.split(';').next().unwrap_or("");
|
||||
let after_dots = name.trim_start_matches('.');
|
||||
if name.starts_with('.') && (after_dots.is_empty() || after_dots.starts_with('%')) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if prefix == "/" {
|
||||
return true;
|
||||
}
|
||||
match raw_path.strip_prefix(prefix) {
|
||||
Some(rest) => rest.is_empty() || rest.starts_with('/'),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// 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/.
|
||||
|
||||
//! Unix seconds to calendar dates (UTC), for API timestamps and visitor pages. Pure: the
|
||||
//! caller passes the time in.
|
||||
|
||||
/// Days since 1970-01-01 → (year, month 1–12, day 1–31). Howard Hinnant's `civil_from_days`.
|
||||
fn civil_from_days(days: i64) -> (i64, u32, u32) {
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z.rem_euclid(146_097);
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let y = yoe + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
|
||||
(if m <= 2 { y + 1 } else { y }, m, d)
|
||||
}
|
||||
|
||||
/// `2026-11-14T14:20:00Z`.
|
||||
pub fn rfc3339(unix: u64) -> String {
|
||||
let secs = i64::try_from(unix).unwrap_or(i64::MAX / 2);
|
||||
let (y, m, d) = civil_from_days(secs.div_euclid(86_400));
|
||||
let s = secs.rem_euclid(86_400);
|
||||
format!(
|
||||
"{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
|
||||
s / 3600,
|
||||
(s / 60) % 60,
|
||||
s % 60
|
||||
)
|
||||
}
|
||||
|
||||
const MONTHS: [&str; 12] = [
|
||||
"January",
|
||||
"February",
|
||||
"March",
|
||||
"April",
|
||||
"May",
|
||||
"June",
|
||||
"July",
|
||||
"August",
|
||||
"September",
|
||||
"October",
|
||||
"November",
|
||||
"December",
|
||||
];
|
||||
|
||||
/// `14 November 2026` (UTC).
|
||||
pub fn long_date(unix: u64) -> String {
|
||||
let secs = i64::try_from(unix).unwrap_or(i64::MAX / 2);
|
||||
let (y, m, d) = civil_from_days(secs.div_euclid(86_400));
|
||||
let month = MONTHS
|
||||
.get(m.saturating_sub(1) as usize)
|
||||
.copied()
|
||||
.unwrap_or("?");
|
||||
format!("{d} {month} {y}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn known_dates() {
|
||||
assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z");
|
||||
assert_eq!(rfc3339(951_782_400), "2000-02-29T00:00:00Z");
|
||||
assert_eq!(rfc3339(1_794_666_000), "2026-11-14T14:20:00Z");
|
||||
assert_eq!(long_date(1_794_666_000), "14 November 2026");
|
||||
assert_eq!(long_date(4_133_980_799), "31 December 2100");
|
||||
}
|
||||
}
|
||||
+145
-53
@@ -11,7 +11,7 @@ use std::net::IpAddr;
|
||||
use serde::Deserialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::error::{ValidationError as E, ValidationErrors};
|
||||
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,
|
||||
@@ -274,11 +274,13 @@ fn check_site(file: &str, raw: RawSite, errors: &mut Vec<E>) -> Option<Site> {
|
||||
errors.push(E::InvalidHeaderName {
|
||||
file: file.to_owned(),
|
||||
name: h.clone(),
|
||||
field: "forward_auth.copy_headers".into(),
|
||||
});
|
||||
} else if is_protected(h) {
|
||||
errors.push(E::ProtectedHeader {
|
||||
file: file.to_owned(),
|
||||
header: h.clone(),
|
||||
field: "forward_auth.copy_headers".into(),
|
||||
});
|
||||
} else if !seen.insert(h.to_ascii_lowercase()) {
|
||||
errors.push(bad("copy_headers lists a header twice"));
|
||||
@@ -375,9 +377,8 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
|
||||
reason,
|
||||
}),
|
||||
Ok(()) => {
|
||||
// One TOML per host, named after it: `hosts/<hostname>.toml`.
|
||||
let base = file.rsplit(['/', '\\']).next().unwrap_or(file);
|
||||
if base != format!("{}.toml", raw.hostname) {
|
||||
// One TOML per host, named after it: exactly `hosts/<hostname>.toml`.
|
||||
if file != format!("hosts/{}.toml", raw.hostname) {
|
||||
errors.push(E::FileNameMismatch {
|
||||
file: f(),
|
||||
hostname: raw.hostname.clone(),
|
||||
@@ -397,7 +398,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
|
||||
}
|
||||
let mut upstreams: Vec<Upstream> = Vec::new();
|
||||
let mut seen_upstreams = BTreeSet::new();
|
||||
for u in raw.upstreams.iter().take(MAX_UPSTREAMS) {
|
||||
for (index, u) in raw.upstreams.iter().take(MAX_UPSTREAMS).enumerate() {
|
||||
match parse_url(u, false) {
|
||||
Ok((up, _)) => {
|
||||
if seen_upstreams.insert(up.clone()) {
|
||||
@@ -405,14 +406,16 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
|
||||
} else {
|
||||
errors.push(E::DuplicateUpstream {
|
||||
file: f(),
|
||||
url: u.clone(),
|
||||
url: shown_url(u),
|
||||
index,
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(reason) => errors.push(E::BadUpstreamUrl {
|
||||
file: f(),
|
||||
url: u.clone(),
|
||||
url: shown_url(u),
|
||||
reason,
|
||||
index: Some(index),
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -420,8 +423,14 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
|
||||
if upstreams.windows(2).any(|w| w[0].scheme != w[1].scheme) {
|
||||
errors.push(E::BadUpstreamUrl {
|
||||
file: f(),
|
||||
url: raw.upstreams.join(", "),
|
||||
reason: "all upstreams of a host must use the same scheme",
|
||||
url: raw
|
||||
.upstreams
|
||||
.iter()
|
||||
.map(|u| shown_url(u))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
reason: r::URL_MIXED,
|
||||
index: None,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -450,8 +459,22 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
|
||||
}
|
||||
AuthMode::None => Vec::new(),
|
||||
};
|
||||
let request_headers = check_rules(file, raw.request_headers, true, &identity, site, errors);
|
||||
let response_headers = check_rules(file, raw.response_headers, false, &[], site, errors);
|
||||
let request_headers = check_rules(
|
||||
file,
|
||||
"request_headers",
|
||||
raw.request_headers,
|
||||
&identity,
|
||||
site,
|
||||
errors,
|
||||
);
|
||||
let response_headers = check_rules(
|
||||
file,
|
||||
"response_headers",
|
||||
raw.response_headers,
|
||||
&[],
|
||||
site,
|
||||
errors,
|
||||
);
|
||||
|
||||
let health_check = raw.health_check.and_then(|hc| {
|
||||
let bad = |reason| E::BadHealthCheck { file: f(), reason };
|
||||
@@ -462,9 +485,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_graphic() && !b"{}#".contains(&c));
|
||||
if !ok_path {
|
||||
errors.push(bad(
|
||||
"path must start with '/' and contain only visible ASCII without '{', '}' or '#'",
|
||||
));
|
||||
errors.push(bad(r::HEALTH_PATH));
|
||||
return None;
|
||||
}
|
||||
match u32::try_from(hc.interval_secs) {
|
||||
@@ -473,7 +494,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
|
||||
interval_secs: i,
|
||||
}),
|
||||
_ => {
|
||||
errors.push(bad("interval_secs must be between 1 and 3600"));
|
||||
errors.push(bad(r::HEALTH_INTERVAL));
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -527,45 +548,65 @@ fn is_protected(name: &str) -> bool {
|
||||
|
||||
fn check_rules(
|
||||
file: &str,
|
||||
list: &str,
|
||||
raw: Vec<RawRule>,
|
||||
request: bool,
|
||||
identity: &[String],
|
||||
site: Option<&Site>,
|
||||
errors: &mut Vec<E>,
|
||||
) -> Vec<HeaderRule> {
|
||||
let request = list == "request_headers";
|
||||
let f = || file.to_owned();
|
||||
let mut out = Vec::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
for r in raw {
|
||||
for (i, r) in raw.into_iter().enumerate() {
|
||||
let at = |part: &str| {
|
||||
if part.is_empty() {
|
||||
format!("{list}[{i}]")
|
||||
} else {
|
||||
format!("{list}[{i}].{part}")
|
||||
}
|
||||
};
|
||||
let header = r.name.clone();
|
||||
if !valid_header_name(&r.name) {
|
||||
errors.push(E::InvalidHeaderName {
|
||||
file: f(),
|
||||
name: r.name,
|
||||
field: at("name"),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let lower = r.name.to_ascii_lowercase();
|
||||
if is_protected(&r.name) || identity.contains(&lower) {
|
||||
errors.push(E::ProtectedHeader { file: f(), header });
|
||||
errors.push(E::ProtectedHeader {
|
||||
file: f(),
|
||||
header,
|
||||
field: at("name"),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if !seen.insert(lower) {
|
||||
errors.push(E::DuplicateHeaderRule { file: f(), header });
|
||||
errors.push(E::DuplicateHeaderRule {
|
||||
file: f(),
|
||||
header,
|
||||
field: at("name"),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let bad = |reason| E::BadHeaderRule {
|
||||
file: f(),
|
||||
header: header.clone(),
|
||||
reason,
|
||||
field: at(if reason == r::RULE_NEITHER {
|
||||
"value"
|
||||
} else {
|
||||
""
|
||||
}),
|
||||
};
|
||||
match (r.action, r.value, r.secret) {
|
||||
(RawAction::Remove, None, None) => out.push(HeaderRule::Remove { name: r.name }),
|
||||
(RawAction::Remove, _, _) => errors.push(bad("remove takes no value or secret")),
|
||||
(RawAction::Set, Some(_), Some(_)) => {
|
||||
errors.push(bad("give either value or secret, not both"))
|
||||
}
|
||||
(RawAction::Set, None, None) => errors.push(bad("set needs a value or a secret")),
|
||||
(RawAction::Remove, _, _) => errors.push(bad(r::RULE_REMOVE_VALUE)),
|
||||
(RawAction::Set, Some(_), Some(_)) => errors.push(bad(r::RULE_BOTH)),
|
||||
(RawAction::Set, None, None) => errors.push(bad(r::RULE_NEITHER)),
|
||||
(RawAction::Set, Some(v), None) => match check_header_value(&v) {
|
||||
Ok(()) => out.push(HeaderRule::Set {
|
||||
name: r.name,
|
||||
@@ -575,15 +616,21 @@ fn check_rules(
|
||||
file: f(),
|
||||
header,
|
||||
reason,
|
||||
field: at("value"),
|
||||
}),
|
||||
},
|
||||
(RawAction::Set, None, Some(s)) => {
|
||||
if !request {
|
||||
errors.push(E::SecretInResponseHeader { file: f(), header });
|
||||
errors.push(E::SecretInResponseHeader {
|
||||
file: f(),
|
||||
header,
|
||||
field: at(""),
|
||||
});
|
||||
} else if site.is_some_and(|site| !site.secrets.contains(&SecretName(s.clone()))) {
|
||||
errors.push(E::UndefinedSecret {
|
||||
file: f(),
|
||||
secret: s,
|
||||
field: at("secret"),
|
||||
});
|
||||
} else {
|
||||
out.push(HeaderRule::Set {
|
||||
@@ -608,19 +655,19 @@ fn valid_header_name(n: &str) -> bool {
|
||||
|
||||
fn check_header_value(v: &str) -> Result<(), &'static str> {
|
||||
if v.is_empty() {
|
||||
return Err("an empty value is not allowed; use action = \"remove\"");
|
||||
return Err(r::VALUE_EMPTY);
|
||||
}
|
||||
if v.len() > 4096 {
|
||||
return Err("it is longer than 4096 characters");
|
||||
return Err(r::VALUE_LONG);
|
||||
}
|
||||
if !v.bytes().all(|c| (0x20..0x7f).contains(&c)) {
|
||||
return Err("only visible ASCII characters and spaces are allowed");
|
||||
return Err(r::VALUE_ASCII);
|
||||
}
|
||||
if v.contains(['{', '}']) {
|
||||
return Err("'{' and '}' are not allowed (they are placeholders in Caddy)");
|
||||
return Err(r::VALUE_BRACES);
|
||||
}
|
||||
if v.starts_with(' ') || v.ends_with(' ') {
|
||||
return Err("it must not start or end with a space");
|
||||
return Err(r::VALUE_EDGE_SPACE);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -629,44 +676,47 @@ fn check_header_value(v: &str) -> Result<(), &'static str> {
|
||||
|
||||
pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> {
|
||||
if h.is_empty() {
|
||||
return Err("it is empty");
|
||||
return Err(r::HOST_EMPTY);
|
||||
}
|
||||
if h.len() > 253 {
|
||||
return Err("it is longer than 253 characters");
|
||||
return Err(r::HOST_TOO_LONG);
|
||||
}
|
||||
if h.parse::<IpAddr>().is_ok() || h.starts_with('[') {
|
||||
return Err("IP addresses are not hostnames");
|
||||
return Err(r::HOST_IP);
|
||||
}
|
||||
if h.contains('*') {
|
||||
return Err("wildcards are not supported");
|
||||
return Err(r::HOST_WILDCARD);
|
||||
}
|
||||
if h.contains(char::is_whitespace) {
|
||||
return Err(r::HOST_SPACES);
|
||||
}
|
||||
if h.ends_with('.') {
|
||||
return Err("it must not end with a dot");
|
||||
return Err(r::HOST_TRAILING_DOT);
|
||||
}
|
||||
if h.bytes().any(|c| c.is_ascii_uppercase()) {
|
||||
return Err("it must be lowercase");
|
||||
return Err(r::HOST_UPPERCASE);
|
||||
}
|
||||
let mut last = "";
|
||||
for label in h.split('.') {
|
||||
if label.is_empty() {
|
||||
return Err("it has an empty label");
|
||||
return Err(r::HOST_EMPTY_LABEL);
|
||||
}
|
||||
if label.len() > 63 {
|
||||
return Err("a label is longer than 63 characters");
|
||||
return Err(r::HOST_LABEL_LONG);
|
||||
}
|
||||
if !label
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
|
||||
{
|
||||
return Err("only a-z, 0-9, '-' and '.' are allowed");
|
||||
return Err(r::HOST_CHARACTERS);
|
||||
}
|
||||
if label.starts_with('-') || label.ends_with('-') {
|
||||
return Err("a label must not start or end with '-'");
|
||||
return Err(r::HOST_LABEL_DASH);
|
||||
}
|
||||
last = label;
|
||||
}
|
||||
if last.bytes().all(|c| c.is_ascii_digit()) {
|
||||
return Err("the last label must not be numeric");
|
||||
return Err(r::HOST_NUMERIC);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -675,42 +725,42 @@ pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> {
|
||||
/// (for the forward-auth endpoint); otherwise any path other than `/` is rejected.
|
||||
fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static str> {
|
||||
if !raw.bytes().all(|c| c.is_ascii_graphic()) {
|
||||
return Err("it must be plain ASCII without spaces");
|
||||
return Err(r::URL_ASCII);
|
||||
}
|
||||
let u = url::Url::parse(raw).map_err(|_| "it is not a URL like http://127.0.0.1:8080")?;
|
||||
let u = url::Url::parse(raw).map_err(|_| r::URL_NOT_URL)?;
|
||||
let scheme = match u.scheme() {
|
||||
"http" => Scheme::Http,
|
||||
"https" => Scheme::Https,
|
||||
_ => return Err("only http:// and https:// are supported"),
|
||||
_ => return Err(r::URL_SCHEME),
|
||||
};
|
||||
if !u.username().is_empty() || u.password().is_some() {
|
||||
return Err("credentials in the URL are not allowed");
|
||||
return Err(r::URL_CREDENTIALS);
|
||||
}
|
||||
if u.fragment().is_some() {
|
||||
return Err("a #fragment is not allowed");
|
||||
return Err(r::URL_FRAGMENT);
|
||||
}
|
||||
let host = match u.host() {
|
||||
None => return Err("it has no host"),
|
||||
None => return Err(r::URL_NO_HOST),
|
||||
Some(url::Host::Ipv4(ip)) => UpstreamHost::Ip(IpAddr::V4(ip)),
|
||||
Some(url::Host::Ipv6(ip)) => UpstreamHost::Ip(IpAddr::V6(ip)),
|
||||
Some(url::Host::Domain(d)) => {
|
||||
if check_hostname(d).is_err() {
|
||||
return Err("the host name is not valid");
|
||||
return Err(r::URL_HOST_NAME);
|
||||
}
|
||||
UpstreamHost::Name(d.to_owned())
|
||||
}
|
||||
};
|
||||
let port = u.port_or_known_default().ok_or("it has no port")?;
|
||||
let port = u.port_or_known_default().ok_or(r::URL_NO_PORT)?;
|
||||
if port == 0 {
|
||||
return Err("port 0 is not usable");
|
||||
return Err(r::URL_PORT_ZERO);
|
||||
}
|
||||
let mut path = u.path().to_owned();
|
||||
if !allow_path {
|
||||
if path != "/" && !path.is_empty() {
|
||||
return Err("a path is not allowed; requests keep their own path");
|
||||
return Err(r::URL_PATH);
|
||||
}
|
||||
if u.query().is_some() {
|
||||
return Err("a ?query is not allowed");
|
||||
return Err(r::URL_QUERY);
|
||||
}
|
||||
} else {
|
||||
if let Some(q) = u.query() {
|
||||
@@ -718,8 +768,50 @@ fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static
|
||||
path.push_str(q);
|
||||
}
|
||||
if path.contains(['{', '}']) {
|
||||
return Err("'{' and '}' are not allowed");
|
||||
return Err(r::URL_BRACES);
|
||||
}
|
||||
}
|
||||
Ok((Upstream { scheme, host, port }, path))
|
||||
}
|
||||
|
||||
/// A URL as an error may show it: everything before the last `@` (after the scheme) is
|
||||
/// replaced by `…`, so a user name or password, even one containing `/`, `?` or `#`, never
|
||||
/// reaches a message, a log or the API. A URL with no `@` is shown as it is.
|
||||
pub(crate) fn shown_url(raw: &str) -> String {
|
||||
let (scheme, rest) = match raw.find("://") {
|
||||
Some(i) => (&raw[..i + 3], &raw[i + 3..]),
|
||||
None => ("", raw),
|
||||
};
|
||||
match rest.rfind('@') {
|
||||
Some(at) => format!("{scheme}\u{2026}@{}", &rest[at + 1..]),
|
||||
None => raw.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shown_tests {
|
||||
use super::shown_url;
|
||||
|
||||
#[test]
|
||||
fn userinfo_is_hidden() {
|
||||
assert_eq!(
|
||||
shown_url("http://user:hunter2@10.0.0.1:80/x"),
|
||||
"http://\u{2026}@10.0.0.1:80/x"
|
||||
);
|
||||
assert_eq!(shown_url("user:hunter2@host:80"), "\u{2026}@host:80");
|
||||
assert_eq!(shown_url("http://10.0.0.1:80"), "http://10.0.0.1:80");
|
||||
assert_eq!(shown_url("http://h/a@b"), "http://\u{2026}@b");
|
||||
assert_eq!(
|
||||
shown_url("http://admin:hunter/2@10.0.0.1:80"),
|
||||
"http://\u{2026}@10.0.0.1:80"
|
||||
);
|
||||
assert_eq!(
|
||||
shown_url("http://admin:hunter?2@10.0.0.1:80"),
|
||||
"http://\u{2026}@10.0.0.1:80"
|
||||
);
|
||||
assert_eq!(
|
||||
shown_url("http://admin:hunter#2@10.0.0.1:80"),
|
||||
"http://\u{2026}@10.0.0.1:80"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": 1,
|
||||
"version": 2,
|
||||
"http_listen": "0.0.0.0:80",
|
||||
"https_listen": "0.0.0.0:443",
|
||||
"https_port": 443,
|
||||
@@ -82,7 +82,8 @@
|
||||
"path": "/api/v1/status",
|
||||
"interval_secs": 15
|
||||
},
|
||||
"access_log": true
|
||||
"access_log": true,
|
||||
"share_links": false
|
||||
},
|
||||
{
|
||||
"hostname": "status.example.org",
|
||||
@@ -101,7 +102,8 @@
|
||||
"request_headers": [],
|
||||
"response_headers": [],
|
||||
"health_check": null,
|
||||
"access_log": false
|
||||
"access_log": false,
|
||||
"share_links": false
|
||||
},
|
||||
{
|
||||
"hostname": "wiki.home.test",
|
||||
@@ -131,7 +133,8 @@
|
||||
],
|
||||
"response_headers": [],
|
||||
"health_check": null,
|
||||
"access_log": false
|
||||
"access_log": false,
|
||||
"share_links": false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
// 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 routes repository holds exactly `ianitor.toml` and `hosts/<hostname>.toml`, and the
|
||||
//! loader requires the exact path (ROADMAP §10: the check used to look at the base name only).
|
||||
//! Validation errors carry a stable code, a field path and params for the UI (docs/ui-api.md §3.1).
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use ianitor_core::routes::{EntryKind, RoutePath, check_path, check_tree};
|
||||
use ianitor_core::{SourceFile, ValidationError, load};
|
||||
|
||||
#[test]
|
||||
fn only_the_site_file_and_host_files_are_allowed() {
|
||||
assert_eq!(
|
||||
check_path("ianitor.toml", EntryKind::File).unwrap(),
|
||||
RoutePath::Site
|
||||
);
|
||||
assert_eq!(
|
||||
check_path("hosts/wiki.home.test.toml", EntryKind::File).unwrap(),
|
||||
RoutePath::Host {
|
||||
hostname: "wiki.home.test".into()
|
||||
}
|
||||
);
|
||||
for bad in [
|
||||
"README.md",
|
||||
".gitattributes",
|
||||
"hosts.toml",
|
||||
"other/wiki.home.test.toml",
|
||||
"hosts/sub/wiki.home.test.toml",
|
||||
"hosts/wiki.home.test.toml/x",
|
||||
"hosts/Wiki.home.test.toml",
|
||||
"hosts/wiki.home.test.TOML",
|
||||
"hosts/wiki.home.test",
|
||||
"hosts/.toml",
|
||||
"hosts/*.home.test.toml",
|
||||
"hosts/wiki..test.toml",
|
||||
"hosts/10.0.0.1.toml",
|
||||
"hosts/wiki home.toml",
|
||||
"hosts\\wiki.home.test.toml",
|
||||
"hosts/wiki\\x.toml",
|
||||
"IANITOR.toml",
|
||||
"./ianitor.toml",
|
||||
] {
|
||||
let e = check_path(bad, EntryKind::File).unwrap_err();
|
||||
assert!(
|
||||
matches!(e, ValidationError::UnexpectedFile { ref file, .. } if file == bad),
|
||||
"{bad}: {e:?}"
|
||||
);
|
||||
assert_eq!(e.code(), "repo.unexpected_file");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_executables_and_submodules_are_refused() {
|
||||
for kind in [
|
||||
EntryKind::Symlink,
|
||||
EntryKind::Submodule,
|
||||
EntryKind::Executable,
|
||||
] {
|
||||
assert!(check_path("hosts/a.test.toml", kind).is_err(), "{kind:?}");
|
||||
assert!(check_path("ianitor.toml", kind).is_err(), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tree_needs_the_site_file_and_reports_every_stray_file() {
|
||||
let ok = [
|
||||
("ianitor.toml", EntryKind::File),
|
||||
("hosts/a.test.toml", EntryKind::File),
|
||||
];
|
||||
assert!(check_tree(ok).is_ok());
|
||||
let errs = check_tree([
|
||||
("hosts/a.test.toml", EntryKind::File),
|
||||
("notes.txt", EntryKind::File),
|
||||
("hosts/b/c.toml", EntryKind::File),
|
||||
])
|
||||
.unwrap_err();
|
||||
assert_eq!(errs.len(), 3, "{errs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_loader_requires_the_exact_path() {
|
||||
let site = SourceFile {
|
||||
name: "ianitor.toml",
|
||||
contents: "",
|
||||
};
|
||||
let body = "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n";
|
||||
for name in [
|
||||
"app.test.toml",
|
||||
"other/app.test.toml",
|
||||
"hosts/x/app.test.toml",
|
||||
"hosts\\app.test.toml",
|
||||
"./hosts/app.test.toml",
|
||||
] {
|
||||
let errs = load(
|
||||
&site,
|
||||
&[SourceFile {
|
||||
name,
|
||||
contents: body,
|
||||
}],
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
errs.errors()
|
||||
.iter()
|
||||
.any(|e| matches!(e, ValidationError::FileNameMismatch { .. })),
|
||||
"{name}: {errs:?}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
load(
|
||||
&site,
|
||||
&[SourceFile {
|
||||
name: "hosts/app.test.toml",
|
||||
contents: body
|
||||
}]
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
fn errors_for(body: &str) -> Vec<ValidationError> {
|
||||
let site = SourceFile {
|
||||
name: "ianitor.toml",
|
||||
contents: "secrets = [\"api_key\"]\n",
|
||||
};
|
||||
load(
|
||||
&site,
|
||||
&[SourceFile {
|
||||
name: "hosts/app.test.toml",
|
||||
contents: body,
|
||||
}],
|
||||
)
|
||||
.unwrap_err()
|
||||
.into_errors()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_have_codes_fields_and_params_for_the_ui() {
|
||||
let cases: &[(&str, &str, Option<&str>)] = &[
|
||||
(
|
||||
"upstreams = [\"http://127.0.0.1:1\"]\n",
|
||||
"host.hostname.missing",
|
||||
Some("hostname"),
|
||||
),
|
||||
(
|
||||
"hostname = \"app.test\"\n",
|
||||
"host.upstreams.missing",
|
||||
Some("upstreams"),
|
||||
),
|
||||
(
|
||||
"hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||
"host.hostname.uppercase",
|
||||
Some("hostname"),
|
||||
),
|
||||
(
|
||||
"hostname = \"app test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||
"host.hostname.spaces",
|
||||
Some("hostname"),
|
||||
),
|
||||
(
|
||||
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"ftp://x\"]\n",
|
||||
"host.upstream.scheme",
|
||||
Some("upstreams[1]"),
|
||||
),
|
||||
(
|
||||
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1/x\"]\n",
|
||||
"host.upstream.path",
|
||||
Some("upstreams[0]"),
|
||||
),
|
||||
(
|
||||
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"http://127.0.0.1:1\"]\n",
|
||||
"host.upstream.duplicate",
|
||||
Some("upstreams[1]"),
|
||||
),
|
||||
(
|
||||
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"https://127.0.0.1:2\"]\n",
|
||||
"host.upstream.mixed_schemes",
|
||||
Some("upstreams"),
|
||||
),
|
||||
(
|
||||
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\ncolour = 1\n",
|
||||
"host.field.unknown",
|
||||
Some("colour"),
|
||||
),
|
||||
(
|
||||
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\n[[request_headers]]\naction = \"set\"\nname = \"Host\"\nvalue = \"x\"\n",
|
||||
"host.header.protected",
|
||||
Some("request_headers[1].name"),
|
||||
),
|
||||
(
|
||||
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[response_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"api_key\"\n",
|
||||
"host.header.secret_response",
|
||||
Some("response_headers[0]"),
|
||||
),
|
||||
(
|
||||
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"nope\"\n",
|
||||
"host.header.secret_unknown",
|
||||
Some("request_headers[0].secret"),
|
||||
),
|
||||
(
|
||||
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[health_check]\npath = \"/x\"\ninterval_secs = 0\n",
|
||||
"host.health.interval",
|
||||
Some("health_check.interval_secs"),
|
||||
),
|
||||
(
|
||||
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\nauth = \"forward-auth\"\n",
|
||||
"host.auth.not_configured",
|
||||
Some("auth"),
|
||||
),
|
||||
];
|
||||
for (body, code, field) in cases {
|
||||
let errs = errors_for(body);
|
||||
let e = errs
|
||||
.iter()
|
||||
.find(|e| e.code() == *code)
|
||||
.unwrap_or_else(|| panic!("no {code} for {body:?}: {errs:?}"));
|
||||
assert_eq!(e.field().as_deref(), *field, "{code}");
|
||||
assert_eq!(e.params()["file"], "hosts/app.test.toml");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_carry_suggestions() {
|
||||
let errs = errors_for("hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n");
|
||||
let e = errs
|
||||
.iter()
|
||||
.find(|e| e.code() == "host.hostname.uppercase")
|
||||
.unwrap();
|
||||
assert_eq!(e.params()["suggestion"], "app.test");
|
||||
let errs = errors_for("hostname = \"app.test\"\nupstreams = [\"http://10.0.0.2:3000/app\"]\n");
|
||||
let e = errs
|
||||
.iter()
|
||||
.find(|e| e.code() == "host.upstream.path")
|
||||
.unwrap();
|
||||
assert_eq!(e.params()["suggestion"], "http://10.0.0.2:3000");
|
||||
assert_eq!(e.params()["url"], "http://10.0.0.2:3000/app");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_password_in_an_upstream_url_is_never_repeated() {
|
||||
let errs = errors_for(
|
||||
"hostname = \"app.test\"\nupstreams = [\"http://admin:hunter2@10.0.0.2:3000\", \"ftp://u:hunter2@x\", \"http://admin:hunter2@10.0.0.2:3000\"]\n",
|
||||
);
|
||||
assert!(!errs.is_empty());
|
||||
for e in &errs {
|
||||
let all = format!("{e} {:?} {:?}", e.params(), e.field());
|
||||
assert!(!all.contains("hunter2"), "{all}");
|
||||
}
|
||||
let e = errs
|
||||
.iter()
|
||||
.find(|e| e.code() == "host.upstream.credentials")
|
||||
.unwrap();
|
||||
assert_eq!(e.params()["url"], "http://\u{2026}@10.0.0.2:3000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credentials_with_slash_query_or_hash_are_never_repeated() {
|
||||
for url in [
|
||||
"http://admin:hunter/2@10.0.0.1:80",
|
||||
"http://admin:hunter?2@10.0.0.1:80",
|
||||
"http://admin:hunter#2@10.0.0.1:80",
|
||||
"ftp://admin:hunter2@10.0.0.1",
|
||||
] {
|
||||
let errs = errors_for(&format!(
|
||||
"hostname = \"app.test\"\nupstreams = [\"{url}\"]\n"
|
||||
));
|
||||
assert!(!errs.is_empty(), "{url} accepted");
|
||||
for e in &errs {
|
||||
let all = format!("{e} {:?}", e.params());
|
||||
assert!(!all.contains("hunter"), "{url}: {all}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
-53
@@ -148,11 +148,11 @@ value = "max-age=31536000"
|
||||
#[test]
|
||||
fn hosts_are_sorted_by_hostname_whatever_the_file_order() {
|
||||
let a = SourceFile {
|
||||
name: "b.test.toml",
|
||||
name: "hosts/b.test.toml",
|
||||
contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||
};
|
||||
let b = SourceFile {
|
||||
name: "a.test.toml",
|
||||
name: "hosts/a.test.toml",
|
||||
contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||
};
|
||||
let m1 = load(&site(), &[a, b]).unwrap();
|
||||
@@ -175,7 +175,7 @@ fn empty_site_file_is_allowed() {
|
||||
contents: "",
|
||||
},
|
||||
&[SourceFile {
|
||||
name: "app.test.toml",
|
||||
name: "hosts/app.test.toml",
|
||||
contents: MINIMAL,
|
||||
}],
|
||||
);
|
||||
@@ -236,7 +236,7 @@ fn rejects_unknown_field_in_site_file() {
|
||||
contents: "secrets = []\nsecret_values = { a = \"b\" }\n",
|
||||
},
|
||||
&[SourceFile {
|
||||
name: "app.test.toml",
|
||||
name: "hosts/app.test.toml",
|
||||
contents: MINIMAL,
|
||||
}],
|
||||
);
|
||||
@@ -348,10 +348,11 @@ fn accepts_good_hostnames() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicate_hostnames_across_files() {
|
||||
let r = load(
|
||||
&site(),
|
||||
&[
|
||||
fn a_second_file_for_the_same_host_is_refused_by_its_path() {
|
||||
// With the exact `hosts/<hostname>.toml` rule, two files can never hold one hostname:
|
||||
// the second one is in the wrong place, whatever the file order.
|
||||
for order in [false, true] {
|
||||
let mut files = vec![
|
||||
SourceFile {
|
||||
name: "hosts/app.test.toml",
|
||||
contents: MINIMAL,
|
||||
@@ -360,38 +361,19 @@ fn rejects_duplicate_hostnames_across_files() {
|
||||
name: "other/app.test.toml",
|
||||
contents: MINIMAL,
|
||||
},
|
||||
],
|
||||
);
|
||||
let errs = r.unwrap_err();
|
||||
assert_eq!(
|
||||
errs.errors(),
|
||||
[ValidationError::DuplicateHostname {
|
||||
hostname: "app.test".into(),
|
||||
first: "hosts/app.test.toml".into(),
|
||||
second: "other/app.test.toml".into()
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_detection_is_independent_of_file_order() {
|
||||
let r = load(
|
||||
&site(),
|
||||
&[
|
||||
SourceFile {
|
||||
name: "other/app.test.toml",
|
||||
contents: MINIMAL,
|
||||
},
|
||||
SourceFile {
|
||||
name: "hosts/app.test.toml",
|
||||
contents: MINIMAL,
|
||||
},
|
||||
],
|
||||
);
|
||||
let errs = r.unwrap_err();
|
||||
assert!(
|
||||
matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/app.test.toml" && second == "other/app.test.toml")
|
||||
);
|
||||
];
|
||||
if order {
|
||||
files.reverse();
|
||||
}
|
||||
let errs = load(&site(), &files).unwrap_err();
|
||||
assert_eq!(
|
||||
errs.errors(),
|
||||
[ValidationError::FileNameMismatch {
|
||||
file: "other/app.test.toml".into(),
|
||||
hostname: "app.test".into()
|
||||
}]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -400,11 +382,11 @@ fn rejects_duplicate_source_file_names() {
|
||||
&site(),
|
||||
&[
|
||||
SourceFile {
|
||||
name: "app.test.toml",
|
||||
name: "hosts/app.test.toml",
|
||||
contents: MINIMAL,
|
||||
},
|
||||
SourceFile {
|
||||
name: "app.test.toml",
|
||||
name: "hosts/app.test.toml",
|
||||
contents: MINIMAL,
|
||||
},
|
||||
],
|
||||
@@ -440,7 +422,9 @@ fn rejects_bad_upstream_urls() {
|
||||
] {
|
||||
let e = single_error(&format!("hostname = \"app.test\"\nupstreams = [{bad:?}]\n"));
|
||||
assert!(
|
||||
matches!(e, ValidationError::BadUpstreamUrl { ref url, .. } if url == bad),
|
||||
// Credentials are never repeated in an error.
|
||||
matches!(e, ValidationError::BadUpstreamUrl { ref url, .. }
|
||||
if url == bad || (bad.contains('@') && url == "http://\u{2026}@127.0.0.1:8080")),
|
||||
"upstream {bad:?} gave {e:?}"
|
||||
);
|
||||
}
|
||||
@@ -485,7 +469,8 @@ fn rejects_undefined_secret_reference() {
|
||||
e,
|
||||
ValidationError::UndefinedSecret {
|
||||
file: "hosts/app.test.toml".into(),
|
||||
secret: "nope".into()
|
||||
secret: "nope".into(),
|
||||
field: "request_headers[0].secret".into()
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -498,7 +483,7 @@ fn undefined_secret_is_reported_when_site_declares_none() {
|
||||
contents: "",
|
||||
},
|
||||
&[SourceFile {
|
||||
name: "app.test.toml",
|
||||
name: "hosts/app.test.toml",
|
||||
contents: &format!(
|
||||
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-K\"\nsecret = \"api_key\"\n"
|
||||
),
|
||||
@@ -532,7 +517,7 @@ fn rejects_bad_secret_names_in_site_file() {
|
||||
contents: &format!("secrets = [{bad:?}]\n"),
|
||||
},
|
||||
&[SourceFile {
|
||||
name: "app.test.toml",
|
||||
name: "hosts/app.test.toml",
|
||||
contents: MINIMAL,
|
||||
}],
|
||||
);
|
||||
@@ -678,7 +663,7 @@ fn forward_auth_requires_site_configuration() {
|
||||
contents: "",
|
||||
},
|
||||
&[SourceFile {
|
||||
name: "app.test.toml",
|
||||
name: "hosts/app.test.toml",
|
||||
contents: &format!("{MINIMAL}auth = \"forward-auth\"\n"),
|
||||
}],
|
||||
);
|
||||
@@ -704,7 +689,7 @@ fn rejects_bad_forward_auth_site_config() {
|
||||
contents: &format!("[forward_auth]\nurl = {bad:?}\n"),
|
||||
},
|
||||
&[SourceFile {
|
||||
name: "app.test.toml",
|
||||
name: "hosts/app.test.toml",
|
||||
contents: MINIMAL,
|
||||
}],
|
||||
);
|
||||
@@ -743,15 +728,15 @@ fn collects_errors_from_every_file() {
|
||||
&site(),
|
||||
&[
|
||||
SourceFile {
|
||||
name: "a.test.toml",
|
||||
name: "hosts/a.test.toml",
|
||||
contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n",
|
||||
},
|
||||
SourceFile {
|
||||
name: "B.test.toml",
|
||||
name: "hosts/B.test.toml",
|
||||
contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||
},
|
||||
SourceFile {
|
||||
name: "app.test.toml",
|
||||
name: "hosts/app.test.toml",
|
||||
contents: MINIMAL,
|
||||
},
|
||||
],
|
||||
@@ -830,7 +815,7 @@ fn rejects_wildcards_in_copy_headers() {
|
||||
contents: "[forward_auth]\nurl = \"http://127.0.0.1:9091/x\"\ncopy_headers = [\"Remote-*\"]\n",
|
||||
},
|
||||
&[SourceFile {
|
||||
name: "app.test.toml",
|
||||
name: "hosts/app.test.toml",
|
||||
contents: MINIMAL,
|
||||
}],
|
||||
);
|
||||
@@ -861,7 +846,7 @@ fn rejects_oversized_route_files() {
|
||||
contents: &big,
|
||||
},
|
||||
&[SourceFile {
|
||||
name: "app.test.toml",
|
||||
name: "hosts/app.test.toml",
|
||||
contents: MINIMAL,
|
||||
}],
|
||||
);
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
// 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/.
|
||||
|
||||
//! Share-link tokens (ROADMAP §6 phase 2, tests first): a token is refused when expired, for
|
||||
//! the wrong path, for the wrong host, tampered, without its password or with a wrong one,
|
||||
//! and no path trick lets it escape its prefix.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use ianitor_core::share::{
|
||||
Claims, LinkSpec, Rejection, Revocations, ShareId, ShareKey, check_prefix, mint, path_within,
|
||||
peek, session_value, verify_link, verify_session,
|
||||
};
|
||||
|
||||
const NOW: u64 = 1_800_000_000;
|
||||
const HOST: &str = "photos.home.test";
|
||||
|
||||
fn key() -> ShareKey {
|
||||
ShareKey::new(b"0123456789abcdef0123456789abcdef-test-key").unwrap()
|
||||
}
|
||||
|
||||
fn other_key() -> ShareKey {
|
||||
ShareKey::new(b"fedcba9876543210fedcba9876543210-test-key").unwrap()
|
||||
}
|
||||
|
||||
fn id(n: u8) -> ShareId {
|
||||
ShareId([n; 16])
|
||||
}
|
||||
|
||||
fn spec<'a>(prefix: &'a str, password: Option<&'a str>) -> LinkSpec<'a> {
|
||||
LinkSpec {
|
||||
id: id(7),
|
||||
epoch: 3,
|
||||
expires_at: NOW + 3600,
|
||||
prefix,
|
||||
password,
|
||||
}
|
||||
}
|
||||
|
||||
fn none() -> Revocations {
|
||||
Revocations {
|
||||
epoch: 3,
|
||||
deny: BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn token(prefix: &str, password: Option<&str>) -> String {
|
||||
mint(&key(), HOST, &spec(prefix, password)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fresh_token_is_accepted_and_says_what_it_covers() {
|
||||
let t = token("/albums/summer", None);
|
||||
assert!(t.starts_with("ish1."), "{t}");
|
||||
let c = verify_link(&key(), HOST, &t, None, NOW, &none()).unwrap();
|
||||
assert_eq!(
|
||||
c,
|
||||
Claims {
|
||||
id: id(7),
|
||||
epoch: 3,
|
||||
expires_at: NOW + 3600,
|
||||
password: false,
|
||||
prefix: "/albums/summer".into()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_expired_token_is_refused_as_expired() {
|
||||
let t = token("/", None);
|
||||
assert_eq!(
|
||||
verify_link(&key(), HOST, &t, None, NOW + 3600, &none()),
|
||||
Err(Rejection::Expired {
|
||||
expires_at: NOW + 3600
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
verify_link(&key(), HOST, &t, None, NOW + 99_999, &none()),
|
||||
Err(Rejection::Expired {
|
||||
expires_at: NOW + 3600
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_token_for_another_host_is_refused() {
|
||||
let t = token("/", None);
|
||||
for host in [
|
||||
"other.home.test",
|
||||
"PHOTOS.home.test",
|
||||
"photos.home.test.",
|
||||
"photos.home",
|
||||
] {
|
||||
assert_eq!(
|
||||
verify_link(&key(), host, &t, None, NOW, &none()),
|
||||
Err(Rejection::Invalid),
|
||||
"{host}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_token_made_with_another_key_is_refused() {
|
||||
let t = mint(&other_key(), HOST, &spec("/", None)).unwrap();
|
||||
assert_eq!(
|
||||
verify_link(&key(), HOST, &t, None, NOW, &none()),
|
||||
Err(Rejection::Invalid)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_single_bit_flip_is_refused() {
|
||||
let t = token("/albums", None);
|
||||
let raw = URL_SAFE_NO_PAD
|
||||
.decode(t.strip_prefix("ish1.").unwrap())
|
||||
.unwrap();
|
||||
for i in 0..raw.len() {
|
||||
for bit in 0..8 {
|
||||
let mut r = raw.clone();
|
||||
r[i] ^= 1 << bit;
|
||||
let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&r));
|
||||
let got = verify_link(&key(), HOST, &forged, None, NOW, &none());
|
||||
assert!(
|
||||
matches!(
|
||||
got,
|
||||
Err(Rejection::Invalid | Rejection::Malformed | Rejection::PasswordRequired)
|
||||
),
|
||||
"byte {i} bit {bit}: {got:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_longer_expiry_or_wider_prefix_cannot_be_spliced_in() {
|
||||
let t = token("/albums/summer", None);
|
||||
let raw = URL_SAFE_NO_PAD
|
||||
.decode(t.strip_prefix("ish1.").unwrap())
|
||||
.unwrap();
|
||||
let (payload, mac) = raw.split_at(raw.len() - 32);
|
||||
// Same MAC, prefix cut down to "/albums".
|
||||
let mut p = payload[..30].to_vec();
|
||||
p.extend_from_slice(b"/albums");
|
||||
p.extend_from_slice(mac);
|
||||
let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&p));
|
||||
assert_eq!(
|
||||
verify_link(&key(), HOST, &forged, None, NOW, &none()),
|
||||
Err(Rejection::Invalid)
|
||||
);
|
||||
// Same MAC, expiry pushed out.
|
||||
let mut p = payload.to_vec();
|
||||
p[21..29].copy_from_slice(&(NOW + 10 * 3600).to_be_bytes());
|
||||
p.extend_from_slice(mac);
|
||||
let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&p));
|
||||
assert_eq!(
|
||||
verify_link(&key(), HOST, &forged, None, NOW, &none()),
|
||||
Err(Rejection::Invalid)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_is_malformed_never_a_panic() {
|
||||
for bad in [
|
||||
"",
|
||||
"ish1.",
|
||||
"ish1.!!!!",
|
||||
"ish2.AAAA",
|
||||
"iss1.AAAA",
|
||||
"ish1.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
|
||||
&"ish1.".repeat(400),
|
||||
"ish1.\u{0}",
|
||||
] {
|
||||
assert_eq!(
|
||||
verify_link(&key(), HOST, bad, None, NOW, &none()),
|
||||
Err(Rejection::Malformed),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_password_link_needs_its_password() {
|
||||
let t = token("/", Some("correct horse"));
|
||||
assert!(peek(&t).unwrap().password);
|
||||
assert_eq!(
|
||||
verify_link(&key(), HOST, &t, None, NOW, &none()),
|
||||
Err(Rejection::PasswordRequired)
|
||||
);
|
||||
for wrong in ["", "correct hors", "correct horse ", "Correct horse", "x"] {
|
||||
assert_eq!(
|
||||
verify_link(&key(), HOST, &t, Some(wrong), NOW, &none()),
|
||||
Err(Rejection::Invalid),
|
||||
"{wrong:?}"
|
||||
);
|
||||
}
|
||||
let c = verify_link(&key(), HOST, &t, Some("correct horse"), NOW, &none()).unwrap();
|
||||
assert!(c.password);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_token_carries_no_password_hash() {
|
||||
// Two links that differ only in the password have the same payload; only the MAC differs.
|
||||
let a = token("/", Some("password-one"));
|
||||
let b = token("/", Some("password-two"));
|
||||
let ra = URL_SAFE_NO_PAD
|
||||
.decode(a.strip_prefix("ish1.").unwrap())
|
||||
.unwrap();
|
||||
let rb = URL_SAFE_NO_PAD
|
||||
.decode(b.strip_prefix("ish1.").unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(ra.len(), rb.len());
|
||||
assert_eq!(ra[..ra.len() - 32], rb[..rb.len() - 32]);
|
||||
assert_ne!(ra[ra.len() - 32..], rb[rb.len() - 32..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_password_flag_does_not_open_the_link() {
|
||||
let t = token("/", Some("correct horse"));
|
||||
let mut raw = URL_SAFE_NO_PAD
|
||||
.decode(t.strip_prefix("ish1.").unwrap())
|
||||
.unwrap();
|
||||
raw[29] = 0;
|
||||
let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&raw));
|
||||
assert_eq!(
|
||||
verify_link(&key(), HOST, &forged, None, NOW, &none()),
|
||||
Err(Rejection::Invalid)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passwords_are_8_to_128_characters() {
|
||||
assert!(mint(&key(), HOST, &spec("/", Some("short"))).is_err());
|
||||
assert!(mint(&key(), HOST, &spec("/", Some(&"x".repeat(129)))).is_err());
|
||||
assert!(mint(&key(), HOST, &spec("/", Some("12345678"))).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopped_links_and_older_epochs_are_revoked() {
|
||||
let t = token("/", None);
|
||||
let mut r = none();
|
||||
r.deny.insert(id(7));
|
||||
assert_eq!(
|
||||
verify_link(&key(), HOST, &t, None, NOW, &r),
|
||||
Err(Rejection::Revoked)
|
||||
);
|
||||
let r = Revocations {
|
||||
epoch: 4,
|
||||
deny: BTreeSet::new(),
|
||||
};
|
||||
assert_eq!(
|
||||
verify_link(&key(), HOST, &t, None, NOW, &r),
|
||||
Err(Rejection::Revoked)
|
||||
);
|
||||
// Another link on the deny list does not matter.
|
||||
let mut r = none();
|
||||
r.deny.insert(id(8));
|
||||
assert!(verify_link(&key(), HOST, &t, None, NOW, &r).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_cookies_and_link_tokens_are_not_interchangeable() {
|
||||
let t = token("/albums", Some("correct horse"));
|
||||
let c = verify_link(&key(), HOST, &t, Some("correct horse"), NOW, &none()).unwrap();
|
||||
let s = session_value(&key(), HOST, &c);
|
||||
assert!(s.starts_with("iss1."));
|
||||
assert_eq!(verify_session(&key(), HOST, &s, NOW, &none()).unwrap(), c);
|
||||
// A cookie is not a link, a link is not a cookie, even with the prefix swapped.
|
||||
assert!(verify_link(&key(), HOST, &s, None, NOW, &none()).is_err());
|
||||
assert!(verify_session(&key(), HOST, &t, NOW, &none()).is_err());
|
||||
let swapped = s.replacen("iss1.", "ish1.", 1);
|
||||
assert!(verify_link(&key(), HOST, &swapped, Some("correct horse"), NOW, &none()).is_err());
|
||||
let swapped = t.replacen("ish1.", "iss1.", 1);
|
||||
assert!(verify_session(&key(), HOST, &swapped, NOW, &none()).is_err());
|
||||
// Cookies are host-bound, expire and are revoked like links.
|
||||
assert_eq!(
|
||||
verify_session(&key(), "other.home.test", &s, NOW, &none()),
|
||||
Err(Rejection::Invalid)
|
||||
);
|
||||
assert!(matches!(
|
||||
verify_session(&key(), HOST, &s, NOW + 3600, &none()),
|
||||
Err(Rejection::Expired { .. })
|
||||
));
|
||||
let mut r = none();
|
||||
r.deny.insert(id(7));
|
||||
assert_eq!(
|
||||
verify_session(&key(), HOST, &s, NOW, &r),
|
||||
Err(Rejection::Revoked)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_keys_are_refused() {
|
||||
assert!(ShareKey::new(b"short").is_err());
|
||||
assert!(ShareKey::new(&[0u8; 31]).is_err());
|
||||
assert!(ShareKey::new(&[0u8; 32]).is_ok());
|
||||
assert!(!format!("{:?}", key()).contains("0123"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefixes_are_normalised_or_refused() {
|
||||
assert_eq!(check_prefix("/").unwrap(), "/");
|
||||
assert_eq!(check_prefix("/a/").unwrap(), "/a");
|
||||
assert_eq!(
|
||||
check_prefix("/albums/summer-2026").unwrap(),
|
||||
"/albums/summer-2026"
|
||||
);
|
||||
for bad in [
|
||||
"", "a", "//", "/a//b", "/a/../b", "/..", "/.", "/a/./b", "/a%2fb", "/a\\b", "/a b",
|
||||
"/a;b", "/ä", "/a?b", "/a#b",
|
||||
] {
|
||||
assert!(check_prefix(bad).is_err(), "{bad:?} accepted");
|
||||
}
|
||||
assert!(check_prefix(&format!("/{}", "a".repeat(256))).is_err());
|
||||
// A prefix that is not in normal form is not minted.
|
||||
assert!(mint(&key(), HOST, &spec("/a/", None)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_round_trip_as_hex() {
|
||||
let i = ShareId([0xab; 16]);
|
||||
assert_eq!(i.to_hex(), "ab".repeat(16));
|
||||
assert_eq!(ShareId::from_hex(&i.to_hex()), Some(i));
|
||||
for bad in [
|
||||
"",
|
||||
"ab",
|
||||
&"AB".repeat(16),
|
||||
&"zz".repeat(16),
|
||||
&"a".repeat(33),
|
||||
] {
|
||||
assert_eq!(ShareId::from_hex(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ prefix escapes
|
||||
|
||||
#[test]
|
||||
fn paths_under_the_prefix_are_within() {
|
||||
for (prefix, path) in [
|
||||
("/a", "/a"),
|
||||
("/a", "/a/"),
|
||||
("/a", "/a/b"),
|
||||
("/a", "/a/b/c.jpg"),
|
||||
("/a", "/a/b%20c"),
|
||||
("/a", "/a/%E2%9C%93"),
|
||||
("/", "/"),
|
||||
("/", "/anything/at/all"),
|
||||
("/a/b", "/a/b/c"),
|
||||
("/a", "/a/b;v=1"),
|
||||
("/a", "/a/.well"),
|
||||
("/a", "/a/%C3%A9t%C3%A9.jpg"),
|
||||
("/a", "/a/%e2%9c%93"),
|
||||
("/a", "/a/a%20b"),
|
||||
// QC fix round 3: ordinary names with look-alike dots or spaces inside.
|
||||
("/a", "/a/Wait%E2%80%A6.pdf"),
|
||||
("/a", "/a/%E3%80%80photo"),
|
||||
("/a", "/a/my%C2%A0file.pdf"),
|
||||
("/a", "/a/dokumenty/p%C5%99ehled"),
|
||||
("/a", "/a/my%20file.pdf"),
|
||||
("/a", "/a/a+b"),
|
||||
("/a", "/a/caf%C3%A9"),
|
||||
("/a", "/a/cafe%CC%81"),
|
||||
("/a", "/a/%E3%80%80photo%E3%80%80album"),
|
||||
("/a", "/a/e%CC%81"),
|
||||
("/a", "/a/%E2%80%93"),
|
||||
("/a", "/a/%E6%97%85%E8%A1%8C"),
|
||||
("/a", "/a/.well-known/x"),
|
||||
("/a", "/a/%C2%BD.txt"),
|
||||
("/a", "/a/x%3Fy"),
|
||||
] {
|
||||
assert!(path_within(prefix, path), "{prefix} should cover {path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_path_trick_escapes_the_prefix() {
|
||||
let cases = [
|
||||
("/a", "/ab"),
|
||||
("/a", "/abc/d"),
|
||||
("/a", "/A"),
|
||||
("/a", "/A/b"),
|
||||
("/a/b", "/a"),
|
||||
("/a/b", "/a/bc"),
|
||||
("/a", "/b"),
|
||||
("/a", "/a/../b"),
|
||||
("/a", "/a/.."),
|
||||
("/a", "/a/./../b"),
|
||||
("/a", "/a/%2e%2e/b"),
|
||||
("/a", "/a/%2E%2E/b"),
|
||||
("/a", "/a/.%2e/b"),
|
||||
("/a", "/a/%2e./b"),
|
||||
("/a", "/a/%252e%252e/b"),
|
||||
("/a", "/a/%25252e/b"),
|
||||
("/a", "/a%2f..%2fb"),
|
||||
("/a", "/a%2F..%2Fb"),
|
||||
("/a", "/a/..%2fb"),
|
||||
("/a", "/a//b"),
|
||||
("/a", "//a/b"),
|
||||
("/a", "/a\\..\\b"),
|
||||
("/a", "/a/..\\b"),
|
||||
("/a", "/a%5c..%5cb"),
|
||||
("/a", "/a/..;/b"),
|
||||
("/a", "/a/.;/b"),
|
||||
("/a", "/a/%00/b"),
|
||||
("/a", "/a/b c"),
|
||||
("/a", "/a/\tb"),
|
||||
("/a", "a/b"),
|
||||
("/a", ""),
|
||||
("/a", "/a/ä"),
|
||||
("/", "/../etc/passwd"),
|
||||
("/", "//evil"),
|
||||
("/", "/%2e%2e/x"),
|
||||
// QC fix round 1: overlong UTF-8, IIS %u, fullwidth dots, Windows-trimmed and
|
||||
// encoded-semicolon dot segments.
|
||||
("/a", "/a/%c0%ae%c0%ae/b"),
|
||||
("/a", "/a/%C0%AE%C0%AE/secret"),
|
||||
("/a", "/a/..%c0%afb"),
|
||||
("/a", "/a/%e0%80%ae%e0%80%ae/b"),
|
||||
("/a", "/a/%f0%80%80%ae/b"),
|
||||
("/a", "/a/%u002e%u002e/b"),
|
||||
("/a", "/a/%u002E%u002E/b"),
|
||||
("/a", "/a/..%u2215b"),
|
||||
("/a", "/a/%ef%bc%8e%ef%bc%8e/b"),
|
||||
("/a", "/a/..%ef%bc%8fb"),
|
||||
("/a", "/a/..%e2%88%95b"),
|
||||
("/a", "/a/..%20/b"),
|
||||
("/a", "/a/.%20/b"),
|
||||
("/a", "/a/..%09/b"),
|
||||
("/a", "/a/..%3b/b"),
|
||||
("/a", "/a/..%3B/b"),
|
||||
("/a", "/a/..%3bx/b"),
|
||||
("/a", "/a/.;x/b"),
|
||||
("/a", "/a;/../b"),
|
||||
("/a", "/a/%2E./b"),
|
||||
// QC fix round 2: NFKC look-alikes and dots before an encoded byte.
|
||||
("/a", "/a/%e2%80%a5/b"),
|
||||
("/a", "/a/%E2%80%A5/b"),
|
||||
("/a", "/a/%ef%b8%b0/b"),
|
||||
("/a", "/a/..%ef%b9%a8secret"),
|
||||
("/a", "/a/..%3f/b"),
|
||||
("/a", "/a/..%3F"),
|
||||
("/a", "/a/..%23/b"),
|
||||
("/a", "/a/%e3%80%80/b"),
|
||||
("/a", "/a/%zz/b"),
|
||||
("/a", "/a/%e2%9c"),
|
||||
// QC fix round 3: a segment that is only an ellipsis or a look-alike space, slash
|
||||
// look-alikes, and a broken escape that from_str_radix would take.
|
||||
("/a", "/a/%E2%80%A6/b"),
|
||||
("/a", "/a/%E2%80%A6"),
|
||||
("/a", "/a/%E3%80%80/b"),
|
||||
("/a", "/a/%C2%A0%C2%A0/b"),
|
||||
("/a", "/a/..%e2%88%95b"),
|
||||
("/a", "/a/..%e2%81%84b"),
|
||||
("/a", "/a/..%e2%a7%b8b"),
|
||||
("/a", "/a/x%e2%88%95y"),
|
||||
("/a", "/a/x%e2%81%84y"),
|
||||
("/a", "/a/%+f/b"),
|
||||
("/a", "/a/%-1/b"),
|
||||
// QC fix round 4: dot-only segments hidden by invisible characters.
|
||||
("/a", "/a/%e2%80%8b../b"),
|
||||
("/a", "/a/%ef%bb%bf../b"),
|
||||
("/a", "/a/%c2%ad../b"),
|
||||
("/a", "/a/%cc%81../b"),
|
||||
("/a", "/a/%e2%80%a4.%e2%80%8b/b"),
|
||||
("/a", "/a/%e2%81%a0%e2%80%a5/b"),
|
||||
("/a", "/a/..%cc%81/b"),
|
||||
("/a", "/a/%e3%80%80../b"),
|
||||
("/a", "/a/%ef%bc%8e%ef%bc%8e/b"),
|
||||
("/a", "/a/%e2%80%a5%3bx/b"),
|
||||
("/a", "/a/%ef%bc%85/b"),
|
||||
("/a", "/a/x%ef%bc%8fy"),
|
||||
("/a", "/a/%e2%80%a4%09/b"),
|
||||
("/a", "/a/%ef%b9%a8"),
|
||||
("/a", "/a/%e2%88%96"),
|
||||
("/a", "/a/%e2%80%8b/b"),
|
||||
];
|
||||
for (prefix, path) in cases {
|
||||
assert!(
|
||||
!path_within(prefix, path),
|
||||
"{prefix} must not cover {path:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -27,9 +27,15 @@ arc-swap = "1.7"
|
||||
instant-acme = { version = "0.8.5", default-features = false, features = ["ring", "hyper-rustls", "rcgen"] }
|
||||
x509-parser = "0.18"
|
||||
thiserror.workspace = true
|
||||
ring.workspace = true
|
||||
hyper.workspace = true
|
||||
hyper-util.workspace = true
|
||||
http-body-util.workspace = true
|
||||
form_urlencoded = "1.2"
|
||||
|
||||
[dev-dependencies]
|
||||
ianitor-testkit.workspace = true
|
||||
ring.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
+89
-31
@@ -21,13 +21,14 @@ use pingora::server::ShutdownWatch;
|
||||
use pingora::services::background::BackgroundService;
|
||||
|
||||
use crate::logging::now_secs;
|
||||
use crate::runtime::Runtime;
|
||||
use crate::tls::{CertStore, certified_key, not_after};
|
||||
use crate::shared::{CertState, Shared};
|
||||
use crate::tls::{certified_key, not_after};
|
||||
|
||||
const RENEW_BEFORE_SECS: f64 = 30.0 * 86_400.0;
|
||||
const CHECK_EVERY: Duration = Duration::from_secs(12 * 3600);
|
||||
const FIRST_RETRY: Duration = Duration::from_secs(30);
|
||||
const MAX_RETRY: Duration = Duration::from_secs(3600);
|
||||
const MIN_GAP: Duration = Duration::from_secs(5);
|
||||
|
||||
/// HTTP-01 tokens → key authorizations, shared with the HTTP listener.
|
||||
#[derive(Default)]
|
||||
@@ -52,8 +53,7 @@ impl Challenges {
|
||||
}
|
||||
|
||||
pub struct AcmeService {
|
||||
pub rt: Arc<Runtime>,
|
||||
pub certs: Arc<CertStore>,
|
||||
pub shared: Arc<Shared>,
|
||||
pub challenges: Arc<Challenges>,
|
||||
/// Extra trust root for the ACME directory (tests against Pebble only).
|
||||
pub ca_root: Option<PathBuf>,
|
||||
@@ -84,7 +84,7 @@ fn fnv(data: &[u8]) -> String {
|
||||
|
||||
impl AcmeService {
|
||||
fn dir(&self) -> PathBuf {
|
||||
self.rt.acme_dir()
|
||||
self.shared.current().acme_dir()
|
||||
}
|
||||
|
||||
fn paths(&self, host: &str) -> (PathBuf, PathBuf) {
|
||||
@@ -102,7 +102,8 @@ impl AcmeService {
|
||||
let expiry = not_after(&cert_pem)?;
|
||||
match certified_key(&cert_pem, &key_pem) {
|
||||
Ok(ck) => {
|
||||
self.certs.insert(host, ck);
|
||||
self.shared.certs.insert(host, ck);
|
||||
self.ok(host, expiry);
|
||||
Some(expiry)
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -207,18 +208,30 @@ impl AcmeService {
|
||||
let (crt, key) = self.paths(host);
|
||||
write_private(&key, key_pem.as_bytes())?;
|
||||
write_private(&crt, chain_pem.as_bytes())?;
|
||||
self.certs.insert(host, ck);
|
||||
self.shared.certs.insert(host, ck);
|
||||
self.ok(host, expiry);
|
||||
log::info!(target: "ianitor::acme", "{host}: certificate issued, valid until {expiry}");
|
||||
Ok(expiry)
|
||||
}
|
||||
|
||||
/// One pass over every ACME host. Returns false if any host failed.
|
||||
fn ok(&self, host: &str, expiry: i64) {
|
||||
self.shared.set_cert_state(
|
||||
host,
|
||||
CertState {
|
||||
state: "ok",
|
||||
not_after: Some(expiry),
|
||||
error: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async fn round(&self, expiries: &mut HashMap<String, i64>) -> bool {
|
||||
let Some(acme) = &self.rt.cfg.acme else {
|
||||
let rt = self.shared.current();
|
||||
let Some(acme) = &rt.cfg.acme else {
|
||||
return true;
|
||||
};
|
||||
let due: Vec<String> = self
|
||||
.rt
|
||||
let due: Vec<String> = rt
|
||||
.acme_hosts()
|
||||
.into_iter()
|
||||
.filter(|h| {
|
||||
@@ -230,10 +243,25 @@ impl AcmeService {
|
||||
if due.is_empty() {
|
||||
return true;
|
||||
}
|
||||
for h in &due {
|
||||
if !expiries.contains_key(h) {
|
||||
self.shared.set_cert_state(
|
||||
h,
|
||||
CertState {
|
||||
state: "pending",
|
||||
not_after: None,
|
||||
error: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
let account = match self.account(&acme.directory, acme.email.as_deref()).await {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
log::error!(target: "ianitor::acme", "{e}");
|
||||
for h in &due {
|
||||
self.failed(h, expiries.get(h).copied(), &e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -245,43 +273,73 @@ impl AcmeService {
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!(target: "ianitor::acme", "{host}: could not obtain a certificate: {e}");
|
||||
self.failed(&host, expiries.get(&host).copied(), &e);
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
/// A host that still has a valid certificate stays `ok` while renewal retries.
|
||||
fn failed(&self, host: &str, expiry: Option<i64>, error: &str) {
|
||||
let still_valid = expiry.is_some_and(|e| (e as f64) > now_secs());
|
||||
self.shared.set_cert_state(
|
||||
host,
|
||||
CertState {
|
||||
state: if still_valid { "ok" } else { "failed" },
|
||||
not_after: expiry,
|
||||
error: Some(error.chars().take(300).collect()),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BackgroundService for AcmeService {
|
||||
async fn start(&self, mut shutdown: ShutdownWatch) {
|
||||
if self.rt.acme_hosts().is_empty() {
|
||||
return;
|
||||
}
|
||||
let dir = self.dir();
|
||||
if let Err(e) = std::fs::create_dir_all(&dir) {
|
||||
log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display());
|
||||
return;
|
||||
}
|
||||
let mut expiries = HashMap::new();
|
||||
for h in self.rt.acme_hosts() {
|
||||
if let Some(e) = self.load_stored(&h) {
|
||||
expiries.insert(h, e);
|
||||
}
|
||||
}
|
||||
let mut retry = FIRST_RETRY;
|
||||
let mut last: Option<std::time::Instant> = None;
|
||||
loop {
|
||||
let wait = if self.round(&mut expiries).await {
|
||||
retry = FIRST_RETRY;
|
||||
CHECK_EVERY
|
||||
} else {
|
||||
let w = retry;
|
||||
retry = (retry * 2).min(MAX_RETRY);
|
||||
w
|
||||
};
|
||||
// Reloads can come many times a second; ACME rounds at most every 5 s.
|
||||
if let Some(l) = last
|
||||
&& l.elapsed() < MIN_GAP
|
||||
{
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(MIN_GAP - l.elapsed()) => {}
|
||||
_ = shutdown.changed() => return,
|
||||
}
|
||||
}
|
||||
last = Some(std::time::Instant::now());
|
||||
let hosts = self.shared.current().acme_hosts();
|
||||
let mut wait = CHECK_EVERY;
|
||||
if !hosts.is_empty() {
|
||||
let dir = self.dir();
|
||||
if let Err(e) = std::fs::create_dir_all(&dir) {
|
||||
log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display());
|
||||
} else {
|
||||
for h in hosts {
|
||||
if !expiries.contains_key(&h)
|
||||
&& let Some(e) = self.load_stored(&h)
|
||||
{
|
||||
expiries.insert(h, e);
|
||||
}
|
||||
}
|
||||
wait = if self.round(&mut expiries).await {
|
||||
retry = FIRST_RETRY;
|
||||
CHECK_EVERY
|
||||
} else {
|
||||
let w = retry;
|
||||
retry = (retry * 2).min(MAX_RETRY);
|
||||
w
|
||||
};
|
||||
}
|
||||
}
|
||||
// Woken early by a reload (new hosts) or a "try again" from control.
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(wait) => {}
|
||||
_ = self.shared.acme_wake.notified() => {}
|
||||
_ = shutdown.changed() => return,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
// 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 admin socket: a Unix socket (mode 0660, so only edge's user and group, i.e. control,
|
||||
//! can connect; never a TCP port) speaking small JSON over HTTP/1.1.
|
||||
//!
|
||||
//! | Request | Does |
|
||||
//! |:--|:--|
|
||||
//! | `GET /v1/status` | config hash, trial, revocations, health per host and upstream, certificates |
|
||||
//! | `POST /v1/reload` | reload the config file (refused while a trial runs) |
|
||||
//! | `POST /v1/trial {confirm_within_secs, watch_hosts?, watch_every_secs?}` | serve the trial file until confirmed |
|
||||
//! | `POST /v1/confirm {config_sha256}` | keep the running trial |
|
||||
//! | `POST /v1/abort` | back to the config before the trial (idempotent) |
|
||||
//! | `POST /v1/share-revocations/reload` | re-read the share-link revocation file |
|
||||
//! | `POST /v1/acme/retry` | try Let's Encrypt again now |
|
||||
//!
|
||||
//! Bodies are at most 4 KiB with no unknown fields. Answers never carry a secret.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use bytes::Bytes;
|
||||
use http_body_util::{BodyExt, Full, Limited};
|
||||
use hyper::body::Incoming;
|
||||
use hyper::server::conn::http1;
|
||||
use hyper::service::service_fn;
|
||||
use hyper::{Request, Response, StatusCode};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use pingora::server::ShutdownWatch;
|
||||
use pingora::services::background::BackgroundService;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::shared::{AdminError, Shared, WatchSpec};
|
||||
|
||||
const MAX_BODY: usize = 4096;
|
||||
/// Longest trial the admin socket accepts.
|
||||
const MAX_TRIAL_SECS: u64 = 3600;
|
||||
|
||||
pub struct AdminSocket {
|
||||
pub shared: Arc<Shared>,
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct TrialBody {
|
||||
confirm_within_secs: u64,
|
||||
#[serde(default)]
|
||||
watch_hosts: Vec<String>,
|
||||
watch_every_secs: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ConfirmBody {
|
||||
config_sha256: String,
|
||||
}
|
||||
|
||||
type Resp = Response<Full<Bytes>>;
|
||||
|
||||
fn reply(status: StatusCode, v: Value) -> Resp {
|
||||
let mut r = Response::new(Full::new(Bytes::from(v.to_string())));
|
||||
*r.status_mut() = status;
|
||||
r.headers_mut().insert(
|
||||
http::header::CONTENT_TYPE,
|
||||
http::HeaderValue::from_static("application/json"),
|
||||
);
|
||||
r
|
||||
}
|
||||
|
||||
fn error(status: StatusCode, message: impl std::fmt::Display) -> Resp {
|
||||
reply(status, json!({ "error": message.to_string() }))
|
||||
}
|
||||
|
||||
fn admin_error(e: AdminError) -> Resp {
|
||||
match e {
|
||||
AdminError::Refused(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
|
||||
AdminError::Conflict(m) => error(StatusCode::CONFLICT, m),
|
||||
}
|
||||
}
|
||||
|
||||
/// The status document.
|
||||
pub fn status(shared: &Shared) -> Value {
|
||||
let rt = shared.current();
|
||||
let mut hosts: Vec<&String> = rt.hosts.keys().collect();
|
||||
hosts.sort();
|
||||
let hosts: Vec<Value> = hosts
|
||||
.into_iter()
|
||||
.filter_map(|name| rt.hosts.get(name))
|
||||
.map(|h| {
|
||||
let name = &h.cfg.hostname;
|
||||
let cert = match &h.cfg.tls {
|
||||
ianitor_core::edge_config::EdgeTls::Files { .. } => json!({
|
||||
"state": "ok",
|
||||
"not_after": rt.file_cert_expiry.get(name),
|
||||
"error": null,
|
||||
}),
|
||||
ianitor_core::edge_config::EdgeTls::Acme => match shared.cert_state(name) {
|
||||
Some(c) => {
|
||||
json!({ "state": c.state, "not_after": c.not_after, "error": c.error })
|
||||
}
|
||||
None => json!({ "state": "pending", "not_after": null, "error": null }),
|
||||
},
|
||||
};
|
||||
json!({
|
||||
"hostname": name,
|
||||
"health_check": h.cfg.health_check.is_some(),
|
||||
"upstreams": h.upstreams.iter().map(|u| json!({
|
||||
"address": u.authority,
|
||||
"healthy": u.healthy.load(std::sync::atomic::Ordering::Relaxed),
|
||||
"checks": u.health.checks(),
|
||||
})).collect::<Vec<_>>(),
|
||||
"certificate": cert,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let rev = shared.revocations();
|
||||
json!({
|
||||
"generation": shared.generation(),
|
||||
"config_sha256": rt.sha256,
|
||||
"started_at": shared.started_at,
|
||||
"trial": shared.trial_info().map(|(sha, left, prev)| json!({
|
||||
"config_sha256": sha,
|
||||
"seconds_left": left,
|
||||
"previous_sha256": prev,
|
||||
})),
|
||||
"share_revocations": {
|
||||
"loaded": rev.loaded,
|
||||
"epoch": rev.revocations.epoch,
|
||||
"stopped": rev.revocations.deny.len(),
|
||||
"error": rev.error,
|
||||
},
|
||||
"hosts": hosts,
|
||||
})
|
||||
}
|
||||
|
||||
async fn body<T: for<'de> Deserialize<'de>>(
|
||||
req: Request<Incoming>,
|
||||
) -> Result<Option<T>, Box<Resp>> {
|
||||
let bytes = Limited::new(req.into_body(), MAX_BODY)
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|_| {
|
||||
error(
|
||||
StatusCode::PAYLOAD_TOO_LARGE,
|
||||
"the body is larger than 4 KiB",
|
||||
)
|
||||
})?
|
||||
.to_bytes();
|
||||
if bytes.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
serde_json::from_slice(&bytes)
|
||||
.map(Some)
|
||||
.map_err(|e| Box::new(error(StatusCode::BAD_REQUEST, format!("bad body: {e}"))))
|
||||
}
|
||||
|
||||
async fn handle(shared: Arc<Shared>, req: Request<Incoming>) -> Resp {
|
||||
let method = req.method().clone();
|
||||
let path = req.uri().path().to_owned();
|
||||
match (method.as_str(), path.as_str()) {
|
||||
("GET", "/v1/status") => reply(StatusCode::OK, status(&shared)),
|
||||
("POST", "/v1/reload") => {
|
||||
let r = tokio::task::spawn_blocking({
|
||||
let s = shared.clone();
|
||||
move || s.reload()
|
||||
})
|
||||
.await;
|
||||
match r {
|
||||
Ok(Ok(rt)) => reply(
|
||||
StatusCode::OK,
|
||||
json!({ "config_sha256": rt.sha256, "generation": shared.generation() }),
|
||||
),
|
||||
Ok(Err(e)) => admin_error(e),
|
||||
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
|
||||
}
|
||||
}
|
||||
("POST", "/v1/trial") => {
|
||||
let b: TrialBody = match body(req).await {
|
||||
Ok(Some(b)) => b,
|
||||
Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"),
|
||||
Err(r) => return *r,
|
||||
};
|
||||
if !(1..=MAX_TRIAL_SECS).contains(&b.confirm_within_secs) {
|
||||
return error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"confirm_within_secs must be between 1 and 3600",
|
||||
);
|
||||
}
|
||||
let every = b.watch_every_secs.unwrap_or(5);
|
||||
if !(1..=60).contains(&every) || b.watch_hosts.len() > 1000 {
|
||||
return error(StatusCode::BAD_REQUEST, "watch_every_secs must be 1 to 60");
|
||||
}
|
||||
let watch = (!b.watch_hosts.is_empty()).then(|| WatchSpec {
|
||||
hosts: b.watch_hosts,
|
||||
every: Duration::from_secs(every),
|
||||
});
|
||||
let within = Duration::from_secs(b.confirm_within_secs);
|
||||
let r = tokio::task::spawn_blocking({
|
||||
let s = shared.clone();
|
||||
move || s.start_trial(within, watch)
|
||||
})
|
||||
.await;
|
||||
match r {
|
||||
Ok(Ok((id, rt))) => {
|
||||
let s = shared.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Some(deadline) = s.trial_deadline(id) {
|
||||
tokio::time::sleep_until(deadline.into()).await;
|
||||
s.expire_trial(id);
|
||||
}
|
||||
});
|
||||
reply(
|
||||
StatusCode::OK,
|
||||
json!({ "config_sha256": rt.sha256, "generation": shared.generation() }),
|
||||
)
|
||||
}
|
||||
Ok(Err(e)) => admin_error(e),
|
||||
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
|
||||
}
|
||||
}
|
||||
("POST", "/v1/confirm") => {
|
||||
let b: ConfirmBody = match body(req).await {
|
||||
Ok(Some(b)) => b,
|
||||
Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"),
|
||||
Err(r) => return *r,
|
||||
};
|
||||
match shared.confirm(&b.config_sha256) {
|
||||
Ok(()) => reply(StatusCode::OK, json!({ "confirmed": true })),
|
||||
Err(e) => admin_error(e),
|
||||
}
|
||||
}
|
||||
("POST", "/v1/abort") => reply(StatusCode::OK, json!({ "reverted": shared.abort() })),
|
||||
("POST", "/v1/share-revocations/reload") => match shared.reload_revocations() {
|
||||
Ok(()) => {
|
||||
let r = shared.revocations();
|
||||
reply(
|
||||
StatusCode::OK,
|
||||
json!({ "epoch": r.revocations.epoch, "stopped": r.revocations.deny.len() }),
|
||||
)
|
||||
}
|
||||
Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
|
||||
},
|
||||
("POST", "/v1/acme/retry") => {
|
||||
shared.acme_wake.notify_one();
|
||||
reply(StatusCode::OK, json!({ "retrying": true }))
|
||||
}
|
||||
(_, "/v1/status" | "/v1/reload" | "/v1/trial" | "/v1/confirm" | "/v1/abort") => {
|
||||
error(StatusCode::METHOD_NOT_ALLOWED, "method not allowed")
|
||||
}
|
||||
_ => error(StatusCode::NOT_FOUND, "no such admin request"),
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(path: &Path) -> std::io::Result<tokio::net::UnixListener> {
|
||||
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
|
||||
// A socket left over from a previous run is removed; anything else at the path is not.
|
||||
if let Ok(meta) = std::fs::symlink_metadata(path) {
|
||||
if meta.file_type().is_socket() {
|
||||
std::fs::remove_file(path)?;
|
||||
} else {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::AlreadyExists,
|
||||
format!("{} exists and is not a socket", path.display()),
|
||||
));
|
||||
}
|
||||
}
|
||||
// Bind inside a fresh 0700 directory, set the mode, then move the socket into place, so
|
||||
// there is no moment in which the socket exists with the process umask's permissions.
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
let parent = path.parent().unwrap_or(Path::new("."));
|
||||
let private = parent.join(format!(".ianitor-admin-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&private);
|
||||
std::fs::DirBuilder::new().mode(0o700).create(&private)?;
|
||||
let staged = private.join("admin.sock");
|
||||
let bound = tokio::net::UnixListener::bind(&staged).and_then(|l| {
|
||||
std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o660))?;
|
||||
std::fs::rename(&staged, path)?;
|
||||
Ok(l)
|
||||
});
|
||||
let _ = std::fs::remove_dir_all(&private);
|
||||
bound
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BackgroundService for AdminSocket {
|
||||
async fn start(&self, mut shutdown: ShutdownWatch) {
|
||||
let listener = match bind(&self.path) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
log::error!(target: "ianitor::admin", "cannot listen on {}: {e}; control cannot reach edge", self.path.display());
|
||||
return;
|
||||
}
|
||||
};
|
||||
log::info!(target: "ianitor::admin", "admin socket at {}", self.path.display());
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.changed() => break,
|
||||
a = listener.accept() => {
|
||||
let Ok((stream, _)) = a else { continue };
|
||||
let shared = self.shared.clone();
|
||||
tokio::spawn(async move {
|
||||
let svc = service_fn(move |req| {
|
||||
let shared = shared.clone();
|
||||
async move { Ok::<_, std::convert::Infallible>(handle(shared, req).await) }
|
||||
});
|
||||
let _ = http1::Builder::new()
|
||||
.serve_connection(TokioIo::new(stream), svc)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-reads the share-link revocation file when it changes (every 5 s), so a stopped link
|
||||
/// stops even if control's reload request was lost.
|
||||
pub struct RevocationPoller {
|
||||
pub shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BackgroundService for RevocationPoller {
|
||||
async fn start(&self, mut shutdown: ShutdownWatch) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.changed() => return,
|
||||
_ = tokio::time::sleep(Duration::from_secs(5)) => self.shared.poll_revocations(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+188
-49
@@ -4,57 +4,153 @@
|
||||
|
||||
//! Active health checks, like Caddy's `health_checks.active`: `GET <path>` with the upstream
|
||||
//! address as Host, healthy on 2xx, 5 s timeout, one result flips the state. The first round
|
||||
//! runs at startup; upstreams start healthy.
|
||||
//! runs when a config is loaded; upstreams start healthy.
|
||||
//!
|
||||
//! Every result is also recorded (time, latency, why it failed) for the admin socket.
|
||||
//! During a trial, the watched hosts are probed at least every `every` seconds; a watched
|
||||
//! host without a health check gets `GET /` with its own hostname as Host, and any answer
|
||||
//! below 500 counts as alive (docs/ui-api.md G3). Those watch probes never change routing.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use pingora::connectors::http::Connector;
|
||||
use pingora::http::RequestHeader;
|
||||
use pingora::server::ShutdownWatch;
|
||||
use pingora::services::background::BackgroundService;
|
||||
use pingora::{Error, ErrorType};
|
||||
|
||||
use crate::fetch::fetch;
|
||||
use crate::runtime::{HostRt, Runtime, UpstreamRt};
|
||||
use crate::logging::now_secs;
|
||||
use crate::runtime::{Check, HostRt, UpstreamRt};
|
||||
use crate::shared::Shared;
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
pub struct HealthChecks {
|
||||
pub rt: Arc<Runtime>,
|
||||
pub shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
async fn probe(connector: &Connector, u: &UpstreamRt, path: &str) -> bool {
|
||||
let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else {
|
||||
return false;
|
||||
/// Why a probe failed, in the words of docs/ui-api.md §3.3.
|
||||
pub fn failure_kind(e: &Error) -> &'static str {
|
||||
match e.etype() {
|
||||
ErrorType::ConnectRefused | ErrorType::ConnectError | ErrorType::ConnectionClosed => {
|
||||
"refused"
|
||||
}
|
||||
ErrorType::ConnectTimedout
|
||||
| ErrorType::ReadTimedout
|
||||
| ErrorType::WriteTimedout
|
||||
| ErrorType::TLSHandshakeTimedout => "timeout",
|
||||
ErrorType::ConnectNoRoute => "name",
|
||||
ErrorType::TLSHandshakeFailure | ErrorType::InvalidCert | ErrorType::HandshakeError => {
|
||||
"tls"
|
||||
}
|
||||
_ => "bad_answer",
|
||||
}
|
||||
}
|
||||
|
||||
fn status_kind(status: u16) -> &'static str {
|
||||
match status {
|
||||
300..=399 => "redirect",
|
||||
401 | 403 => "sign_in",
|
||||
404 => "not_found",
|
||||
500..=599 => "server_error",
|
||||
_ => "bad_answer",
|
||||
}
|
||||
}
|
||||
|
||||
/// One probe. `watch` probes count any answer below 500 as alive.
|
||||
async fn probe(
|
||||
connector: &Connector,
|
||||
u: &UpstreamRt,
|
||||
path: &str,
|
||||
host: &str,
|
||||
watch: bool,
|
||||
) -> Check {
|
||||
let started = Instant::now();
|
||||
let at = now_secs() as u64;
|
||||
let source = if watch { "watch" } else { "health_check" };
|
||||
let fail = |kind: &'static str, status: Option<u16>, latency: Option<u64>| Check {
|
||||
seq: 0,
|
||||
at,
|
||||
ok: false,
|
||||
source,
|
||||
kind: Some(kind),
|
||||
status,
|
||||
latency_ms: latency,
|
||||
};
|
||||
if req
|
||||
.insert_header(http::header::HOST, u.authority.as_str())
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else {
|
||||
return fail("bad_answer", None, None);
|
||||
};
|
||||
if req.insert_header(http::header::HOST, host).is_err() {
|
||||
return fail("bad_answer", None, None);
|
||||
}
|
||||
match fetch(connector, u, req, 64 * 1024, TIMEOUT).await {
|
||||
Ok(f) => f.header.status.is_success(),
|
||||
Err(_) => false,
|
||||
Ok(f) => {
|
||||
let status = f.header.status.as_u16();
|
||||
let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
|
||||
let ok = if watch {
|
||||
(100..500).contains(&status)
|
||||
} else {
|
||||
f.header.status.is_success()
|
||||
};
|
||||
if ok {
|
||||
Check {
|
||||
seq: 0,
|
||||
at,
|
||||
ok: true,
|
||||
source,
|
||||
kind: None,
|
||||
status: Some(status),
|
||||
latency_ms: Some(latency),
|
||||
}
|
||||
} else {
|
||||
fail(status_kind(status), Some(status), Some(latency))
|
||||
}
|
||||
}
|
||||
Err(e) => fail(failure_kind(&e), None, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// One round over a host's upstreams. Each probe runs in its own task, so a panic inside a
|
||||
/// probe (e.g. a library bug on an odd answer) marks that upstream unhealthy instead of
|
||||
/// ending health checks.
|
||||
async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>) {
|
||||
async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>, watch: bool) {
|
||||
for i in 0..host.upstreams.len() {
|
||||
let (h, p, c) = (host.clone(), path.to_owned(), connector.clone());
|
||||
let ok = match tokio::spawn(async move { probe(&c, &h.upstreams[i], &p).await }).await {
|
||||
Ok(ok) => ok,
|
||||
let probe_host = if watch {
|
||||
host.cfg.hostname.clone()
|
||||
} else {
|
||||
host.upstreams[i].authority.clone()
|
||||
};
|
||||
let check = match tokio::spawn(async move {
|
||||
probe(&c, &h.upstreams[i], &p, &probe_host, watch).await
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::error!(target: "ianitor::health", "{}: health check of {} crashed ({e}); counting it as failed", host.cfg.hostname, host.upstreams[i].authority);
|
||||
false
|
||||
Check {
|
||||
seq: 0,
|
||||
at: now_secs() as u64,
|
||||
ok: false,
|
||||
source: if watch { "watch" } else { "health_check" },
|
||||
kind: Some("bad_answer"),
|
||||
status: None,
|
||||
latency_ms: None,
|
||||
}
|
||||
}
|
||||
};
|
||||
let u = &host.upstreams[i];
|
||||
let ok = check.ok;
|
||||
u.health.record(check);
|
||||
if watch {
|
||||
// Watch probes only report; routing follows the host's own health check.
|
||||
continue;
|
||||
}
|
||||
if u.healthy.swap(ok, Ordering::Relaxed) != ok {
|
||||
if ok {
|
||||
log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority);
|
||||
@@ -65,50 +161,93 @@ async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>) {
|
||||
}
|
||||
}
|
||||
|
||||
async fn watch(host: Arc<HostRt>, path: String, every: Duration) {
|
||||
async fn watcher(host: Arc<HostRt>, path: String, every: Duration, watch: bool) {
|
||||
let connector = Arc::new(Connector::new(None));
|
||||
loop {
|
||||
round(&host, &path, &connector).await;
|
||||
round(&host, &path, &connector, watch).await;
|
||||
tokio::time::sleep(every).await;
|
||||
}
|
||||
}
|
||||
|
||||
struct Job {
|
||||
host: Arc<HostRt>,
|
||||
path: String,
|
||||
every: Duration,
|
||||
watch: bool,
|
||||
}
|
||||
|
||||
fn jobs(shared: &Shared) -> Vec<Job> {
|
||||
let rt = shared.current();
|
||||
let spec = shared.watch_spec();
|
||||
let watched = |h: &str| {
|
||||
spec.as_ref()
|
||||
.is_some_and(|s| s.hosts.iter().any(|w| w == h))
|
||||
};
|
||||
let every = spec.as_ref().map(|s| s.every);
|
||||
let mut out = Vec::new();
|
||||
for h in rt.hosts.values() {
|
||||
let name = &h.cfg.hostname;
|
||||
match &h.cfg.health_check {
|
||||
Some(hc) => {
|
||||
let mut interval = Duration::from_secs(u64::from(hc.interval_secs.max(1)));
|
||||
if watched(name)
|
||||
&& let Some(e) = every
|
||||
{
|
||||
interval = interval.min(e);
|
||||
}
|
||||
out.push(Job {
|
||||
host: h.clone(),
|
||||
path: hc.path.clone(),
|
||||
every: interval,
|
||||
watch: false,
|
||||
});
|
||||
}
|
||||
None if watched(name) => out.push(Job {
|
||||
host: h.clone(),
|
||||
path: "/".into(),
|
||||
every: every.unwrap_or(Duration::from_secs(5)),
|
||||
watch: true,
|
||||
}),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BackgroundService for HealthChecks {
|
||||
async fn start(&self, mut shutdown: ShutdownWatch) {
|
||||
let checked: Vec<(Arc<HostRt>, String, Duration)> = self
|
||||
.rt
|
||||
.hosts
|
||||
.values()
|
||||
.filter_map(|h| {
|
||||
h.cfg.health_check.as_ref().map(|hc| {
|
||||
(
|
||||
h.clone(),
|
||||
hc.path.clone(),
|
||||
Duration::from_secs(u64::from(hc.interval_secs.max(1))),
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut tasks = tokio::task::JoinSet::new();
|
||||
let mut which = std::collections::HashMap::new();
|
||||
for (i, (h, p, every)) in checked.iter().enumerate() {
|
||||
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i);
|
||||
}
|
||||
// A watcher never returns; if one ends anyway, say so and start it again.
|
||||
let mut changes = self.shared.subscribe();
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.changed() => break,
|
||||
Some(done) = tasks.join_next_with_id() => {
|
||||
let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() };
|
||||
if let Some(i) = which.remove(&id) {
|
||||
let (h, p, every) = &checked[i];
|
||||
log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", h.cfg.hostname);
|
||||
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i);
|
||||
let jobs = jobs(&self.shared);
|
||||
let mut tasks = tokio::task::JoinSet::new();
|
||||
let mut which = std::collections::HashMap::new();
|
||||
for (i, j) in jobs.iter().enumerate() {
|
||||
let id = tasks
|
||||
.spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch))
|
||||
.id();
|
||||
which.insert(id, i);
|
||||
}
|
||||
// Run until the config or the watch changes; a watcher never returns, and if one
|
||||
// ends anyway, say so and start it again.
|
||||
let stop = loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.changed() => break true,
|
||||
r = changes.changed() => break r.is_err(),
|
||||
Some(done) = tasks.join_next_with_id() => {
|
||||
let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() };
|
||||
if let Some(i) = which.remove(&id) {
|
||||
let j = &jobs[i];
|
||||
log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", j.host.cfg.hostname);
|
||||
which.insert(tasks.spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch)).id(), i);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
tasks.abort_all();
|
||||
if stop {
|
||||
return;
|
||||
}
|
||||
}
|
||||
tasks.abort_all();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,10 +19,10 @@ use pingora::server::ShutdownWatch;
|
||||
use crate::acme::Challenges;
|
||||
use crate::logging::{AccessRecord, now_secs, truncate_ip};
|
||||
use crate::proxy::{host_header, hostname};
|
||||
use crate::runtime::Runtime;
|
||||
use crate::shared::Shared;
|
||||
|
||||
pub struct HttpApp {
|
||||
pub rt: Arc<Runtime>,
|
||||
pub shared: Arc<Shared>,
|
||||
pub challenges: Arc<Challenges>,
|
||||
}
|
||||
|
||||
@@ -75,6 +75,7 @@ impl HttpServerApp for HttpApp {
|
||||
impl HttpApp {
|
||||
async fn response(&self, session: &mut ServerSession) -> Response<Vec<u8>> {
|
||||
let start = Instant::now();
|
||||
let rt = self.shared.current();
|
||||
let req = session.req_header();
|
||||
let hh = host_header(req);
|
||||
let name = hostname(&hh);
|
||||
@@ -92,11 +93,11 @@ impl HttpApp {
|
||||
return r;
|
||||
}
|
||||
|
||||
let Some(host) = self.rt.host(&name) else {
|
||||
let Some(host) = rt.host(&name) else {
|
||||
return empty(StatusCode::NOT_FOUND);
|
||||
};
|
||||
let uri = req.uri.path_and_query().map_or("/", |p| p.as_str());
|
||||
let port = self.rt.cfg.https_port;
|
||||
let port = rt.cfg.https_port;
|
||||
let location = if port == 443 {
|
||||
format!("https://{name}{uri}")
|
||||
} else {
|
||||
@@ -110,7 +111,7 @@ impl HttpApp {
|
||||
Err(_) => return empty(StatusCode::BAD_REQUEST),
|
||||
}
|
||||
if host.cfg.access_log
|
||||
&& let Some(log) = &self.rt.access_log
|
||||
&& let Some(log) = &rt.access_log
|
||||
{
|
||||
log.write(&AccessRecord {
|
||||
ts: now_secs(),
|
||||
|
||||
+84
-15
@@ -5,23 +5,29 @@
|
||||
//! Ianitor edge: the Pingora data plane. It reads the config compiled by `ianitor-core`
|
||||
//! and serves it; it never decides policy.
|
||||
//!
|
||||
//! Services: HTTPS reverse proxy (SNI certificates, forward-auth, websockets, header rules,
|
||||
//! round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and redirects),
|
||||
//! health checks, ACME issuance and renewal.
|
||||
//! Services: HTTPS reverse proxy (SNI certificates, forward-auth, share links, websockets,
|
||||
//! header rules, round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and
|
||||
//! redirects), health checks, ACME issuance and renewal, and the admin socket through which
|
||||
//! control reloads the config in process (see `shared`).
|
||||
|
||||
pub mod acme;
|
||||
#[cfg(unix)]
|
||||
pub mod admin;
|
||||
pub mod error;
|
||||
pub mod fetch;
|
||||
pub mod forward_auth;
|
||||
pub mod health;
|
||||
pub mod http_app;
|
||||
pub mod logging;
|
||||
pub mod pages;
|
||||
pub mod proxy;
|
||||
pub mod runtime;
|
||||
pub mod secrets;
|
||||
pub mod share;
|
||||
pub mod shared;
|
||||
pub mod tls;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use pingora::connectors::http::Connector;
|
||||
@@ -34,24 +40,67 @@ use pingora::services::listening::Service;
|
||||
|
||||
pub use error::EdgeError;
|
||||
pub use runtime::Runtime;
|
||||
pub use shared::Shared;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Options {
|
||||
/// The compiled edge config (`ianitor-core` edge compiler output).
|
||||
pub config: PathBuf,
|
||||
/// The trial config control writes before an apply; default `<config>.trial`.
|
||||
pub trial_config: Option<PathBuf>,
|
||||
/// Admin socket for control (Unix only); none when `None`.
|
||||
pub admin_socket: Option<PathBuf>,
|
||||
/// The share-link revocation file control writes; without it, share links are refused.
|
||||
pub share_revocations: Option<PathBuf>,
|
||||
/// Extra trust root for the ACME directory's TLS (Pebble in tests).
|
||||
pub acme_root: Option<PathBuf>,
|
||||
/// Overrides `$CREDENTIALS_DIRECTORY` (tests running several edges in one process).
|
||||
pub credentials_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
pub fn trial_path(&self) -> PathBuf {
|
||||
self.trial_config
|
||||
.clone()
|
||||
.unwrap_or_else(|| default_trial_path(&self.config))
|
||||
}
|
||||
}
|
||||
|
||||
/// `<config>.trial`, next to the config.
|
||||
pub fn default_trial_path(config: &Path) -> PathBuf {
|
||||
let mut name = config.file_name().unwrap_or_default().to_os_string();
|
||||
name.push(".trial");
|
||||
config.with_file_name(name)
|
||||
}
|
||||
|
||||
fn credentials_dir(opts: &Options) -> Option<PathBuf> {
|
||||
opts.credentials_dir
|
||||
.clone()
|
||||
.or_else(|| std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from))
|
||||
}
|
||||
|
||||
/// Read the config, load secrets from `$CREDENTIALS_DIRECTORY`, load certificates.
|
||||
pub fn prepare(opts: &Options) -> Result<Arc<Runtime>, EdgeError> {
|
||||
let cfg = runtime::read_config(&opts.config)?;
|
||||
let creds = std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from);
|
||||
runtime::build(cfg, creds.as_deref()).map(Arc::new)
|
||||
pub fn prepare(opts: &Options) -> Result<Arc<Shared>, EdgeError> {
|
||||
let creds = credentials_dir(opts);
|
||||
let rt = runtime::build_file(&opts.config, creds.as_deref())?;
|
||||
Ok(shared_for(rt, opts))
|
||||
}
|
||||
|
||||
/// Wrap an already built runtime (tests run edge in process this way).
|
||||
pub fn shared_for(rt: Runtime, opts: &Options) -> Arc<Shared> {
|
||||
Shared::new(
|
||||
rt,
|
||||
shared::Paths {
|
||||
config: opts.config.clone(),
|
||||
trial: opts.trial_path(),
|
||||
revocations: opts.share_revocations.clone(),
|
||||
},
|
||||
credentials_dir(opts),
|
||||
)
|
||||
}
|
||||
|
||||
/// Assemble the Pingora server with all services. Listeners bind when it runs.
|
||||
pub fn server(rt: Arc<Runtime>, opts: &Options) -> Result<Server, EdgeError> {
|
||||
pub fn server(shared: Arc<Shared>, opts: &Options) -> Result<Server, EdgeError> {
|
||||
pingora::tls::install_default_crypto_provider();
|
||||
let conf = ServerConf {
|
||||
threads: 2,
|
||||
@@ -63,11 +112,12 @@ pub fn server(rt: Arc<Runtime>, opts: &Options) -> Result<Server, EdgeError> {
|
||||
server.bootstrap();
|
||||
|
||||
let challenges = Arc::new(acme::Challenges::default());
|
||||
let rt = shared.current();
|
||||
|
||||
let mut https = http_proxy_service(
|
||||
&server.configuration,
|
||||
proxy::EdgeProxy {
|
||||
rt: rt.clone(),
|
||||
shared: shared.clone(),
|
||||
connector: Connector::new(None),
|
||||
},
|
||||
);
|
||||
@@ -75,14 +125,14 @@ pub fn server(rt: Arc<Runtime>, opts: &Options) -> Result<Server, EdgeError> {
|
||||
address: rt.cfg.https_listen.clone(),
|
||||
reason: e.to_string(),
|
||||
})?;
|
||||
tls.set_cert_resolver(rt.certs.clone());
|
||||
tls.set_cert_resolver(shared.certs.clone());
|
||||
tls.enable_h2();
|
||||
https.add_tls_with_settings(&rt.cfg.https_listen, None, tls);
|
||||
|
||||
let mut http = Service::new(
|
||||
"ianitor http".to_owned(),
|
||||
http_app::HttpApp {
|
||||
rt: rt.clone(),
|
||||
shared: shared.clone(),
|
||||
challenges: challenges.clone(),
|
||||
},
|
||||
);
|
||||
@@ -92,17 +142,36 @@ pub fn server(rt: Arc<Runtime>, opts: &Options) -> Result<Server, EdgeError> {
|
||||
server.add_service(http);
|
||||
server.add_service(background_service(
|
||||
"ianitor health checks",
|
||||
health::HealthChecks { rt: rt.clone() },
|
||||
health::HealthChecks {
|
||||
shared: shared.clone(),
|
||||
},
|
||||
));
|
||||
server.add_service(background_service(
|
||||
"ianitor acme",
|
||||
acme::AcmeService {
|
||||
rt: rt.clone(),
|
||||
certs: rt.certs.clone(),
|
||||
shared: shared.clone(),
|
||||
challenges,
|
||||
ca_root: opts.acme_root.clone(),
|
||||
},
|
||||
));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
server.add_service(background_service(
|
||||
"ianitor share revocations",
|
||||
admin::RevocationPoller {
|
||||
shared: shared.clone(),
|
||||
},
|
||||
));
|
||||
if let Some(path) = &opts.admin_socket {
|
||||
server.add_service(background_service(
|
||||
"ianitor admin socket",
|
||||
admin::AdminSocket {
|
||||
shared: shared.clone(),
|
||||
path: path.clone(),
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(server)
|
||||
}
|
||||
|
||||
|
||||
+10
-5
@@ -2,7 +2,8 @@
|
||||
// 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/.
|
||||
|
||||
//! `ianitor-edge --config <edge.json> [--check] [--acme-root <ca.pem>]`
|
||||
//! `ianitor-edge --config <edge.json> [--check] [--admin-socket <path>] [--trial-config <path>]
|
||||
//! [--share-revocations <path>] [--acme-root <ca.pem>]`
|
||||
//!
|
||||
//! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG`
|
||||
//! (error, warn, info, debug, trace; libraries are capped at info).
|
||||
@@ -21,10 +22,14 @@ fn parse_args() -> Result<(Options, bool), EdgeError> {
|
||||
match a.to_str() {
|
||||
Some("--config") => config = args.next().map(PathBuf::from),
|
||||
Some("--acme-root") => opts.acme_root = args.next().map(PathBuf::from),
|
||||
Some("--admin-socket") => opts.admin_socket = args.next().map(PathBuf::from),
|
||||
Some("--trial-config") => opts.trial_config = args.next().map(PathBuf::from),
|
||||
Some("--share-revocations") => opts.share_revocations = args.next().map(PathBuf::from),
|
||||
Some("--check") => check = true,
|
||||
Some("--help" | "-h") => {
|
||||
println!(
|
||||
"usage: ianitor-edge --config <edge.json> [--check] [--acme-root <ca.pem>]"
|
||||
"usage: ianitor-edge --config <edge.json> [--check] [--admin-socket <path>] \
|
||||
[--trial-config <path>] [--share-revocations <path>] [--acme-root <ca.pem>]"
|
||||
);
|
||||
std::process::exit(0);
|
||||
}
|
||||
@@ -44,12 +49,12 @@ fn parse_args() -> Result<(Options, bool), EdgeError> {
|
||||
fn main() -> ExitCode {
|
||||
ianitor_edge::logging::init(std::env::var("IANITOR_LOG").ok().as_deref());
|
||||
let started = parse_args().and_then(|(opts, check)| {
|
||||
let rt = ianitor_edge::prepare(&opts)?;
|
||||
log::info!(target: "ianitor::edge", "config {} loaded: {} hosts", opts.config.display(), rt.hosts.len());
|
||||
let shared = ianitor_edge::prepare(&opts)?;
|
||||
log::info!(target: "ianitor::edge", "config {} loaded: {} hosts", opts.config.display(), shared.current().hosts.len());
|
||||
if check {
|
||||
return Ok(None);
|
||||
}
|
||||
ianitor_edge::server(rt, &opts).map(Some)
|
||||
ianitor_edge::server(shared, &opts).map(Some)
|
||||
});
|
||||
match started {
|
||||
Ok(None) => ExitCode::SUCCESS,
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
// 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 share-link visitor pages (docs/ui-api.md §4): one self-contained HTML page each, inline
|
||||
//! CSS, no JavaScript, no external requests, under 8 KB. Only the hostname and a date come
|
||||
//! from the request side, both escaped; the token is echoed only into the password form's
|
||||
//! hidden field (it is already in the visitor's address bar at that point), escaped too.
|
||||
|
||||
use ianitor_core::share::PASSWORD_PATH;
|
||||
use ianitor_core::time::long_date;
|
||||
|
||||
pub enum Problem {
|
||||
WrongPassword,
|
||||
TooMany,
|
||||
}
|
||||
|
||||
pub enum Page<'a> {
|
||||
Password {
|
||||
host: &'a str,
|
||||
token: &'a str,
|
||||
until: u64,
|
||||
problem: Option<Problem>,
|
||||
},
|
||||
Expired {
|
||||
host: &'a str,
|
||||
until: u64,
|
||||
},
|
||||
Invalid {
|
||||
host: &'a str,
|
||||
},
|
||||
}
|
||||
|
||||
impl Page<'_> {
|
||||
pub fn status(&self) -> u16 {
|
||||
match self {
|
||||
Page::Password {
|
||||
problem: Some(Problem::TooMany),
|
||||
..
|
||||
} => 429,
|
||||
Page::Password { .. } => 401,
|
||||
Page::Expired { .. } => 410,
|
||||
Page::Invalid { .. } => 403,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn escape(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
c if c.is_control() => {}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
const STYLE: &str = "\
|
||||
*{box-sizing:border-box}\
|
||||
body{margin:0;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;\
|
||||
background:#0c0b0f;color:#f1edf3;font-family:system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif;padding:16px}\
|
||||
.card{width:100%;max-width:420px;padding:32px;background:#18151d;border:1px solid #3c3445;border-radius:18px}\
|
||||
@media (max-width:480px){.card{padding:24px}}\
|
||||
.host{color:#cfc6d4;font-size:.95rem;font-weight:600;margin:0 0 16px;overflow-wrap:anywhere}\
|
||||
svg{display:block;margin:0 0 12px}\
|
||||
h1{font-size:1.5rem;font-weight:700;color:#f1edf3;margin:0 0 8px}\
|
||||
p{font-size:1rem;line-height:1.5;color:#cfc6d4;margin:0 0 16px}\
|
||||
label{display:block;color:#cfc6d4;font-size:.9rem;margin:0 0 6px}\
|
||||
input[type=password]{width:100%;height:48px;background:#0c0b0f;border:1px solid #7d7189;border-radius:10px;\
|
||||
color:#f1edf3;font-size:1rem;padding:0 12px}\
|
||||
input[type=password]:focus{outline:none;border-color:#e0a3dc;box-shadow:0 0 0 4px rgba(224,163,220,.16)}\
|
||||
.err{color:#e2683a;font-size:.92rem;margin:8px 0 0;display:flex;gap:6px;align-items:center}\
|
||||
button{margin-top:16px;width:100%;height:48px;border-radius:12px;border:1px solid #c77cc1;color:#fff;font-weight:700;\
|
||||
font-size:1rem;background:linear-gradient(#8d3b89,#76306f 55%,#5c2257)}\
|
||||
button:focus{outline:2px solid #f2c9ee;outline-offset:2px}\
|
||||
button:disabled{opacity:.5}\
|
||||
.small{font-size:.92rem;margin:16px 0 0}\
|
||||
a{color:#e0a3dc;display:inline-flex;align-items:center;min-height:44px}\
|
||||
footer{color:#a99eb1;font-size:.72rem;letter-spacing:.2em;text-transform:uppercase;margin-top:16px}";
|
||||
|
||||
fn icon(kind: &str) -> String {
|
||||
let (colour, body) = match kind {
|
||||
// lock
|
||||
"lock" => (
|
||||
"#e0a3dc",
|
||||
"<rect x=\"8\" y=\"18\" width=\"24\" height=\"16\" rx=\"3\"/><path d=\"M13 18v-5a7 7 0 0 1 14 0v5\"/>",
|
||||
),
|
||||
// clock
|
||||
"clock" => (
|
||||
"#d99a35",
|
||||
"<circle cx=\"20\" cy=\"20\" r=\"14\"/><path d=\"M20 12v8l5 4\"/>",
|
||||
),
|
||||
// broken link
|
||||
_ => (
|
||||
"#d99a35",
|
||||
"<path d=\"M17 23l-3 3a5 5 0 0 1-7-7l3-3\"/><path d=\"M23 17l3-3a5 5 0 0 0-7-7l-3 3\"/><path d=\"M8 8l3 3M29 29l3 3M28 12h4M8 28H12\"/>",
|
||||
),
|
||||
};
|
||||
format!(
|
||||
"<svg width=\"40\" height=\"40\" viewBox=\"0 0 40 40\" fill=\"none\" stroke=\"{colour}\" stroke-width=\"2.2\" \
|
||||
stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">{body}</svg>"
|
||||
)
|
||||
}
|
||||
|
||||
const RING: &str = "<svg width=\"14\" height=\"14\" viewBox=\"0 0 14 14\" fill=\"none\" stroke=\"#e2683a\" stroke-width=\"2\" aria-hidden=\"true\"><circle cx=\"7\" cy=\"7\" r=\"5\"/></svg>";
|
||||
|
||||
fn shell(host: &str, inner: &str, title: &str) -> String {
|
||||
format!(
|
||||
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
|
||||
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
|
||||
<meta name=\"referrer\" content=\"no-referrer\"><meta name=\"robots\" content=\"noindex\">\
|
||||
<title>{title}</title><style>{STYLE}</style></head><body><main class=\"card\">\
|
||||
<p class=\"host\">{}</p>{inner}</main><footer>Ianitor Domi</footer></body></html>",
|
||||
escape(host)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn render(p: &Page<'_>) -> String {
|
||||
match p {
|
||||
Page::Password {
|
||||
host,
|
||||
token,
|
||||
until,
|
||||
problem,
|
||||
} => {
|
||||
let h = escape(host);
|
||||
let (msg, disabled) = match problem {
|
||||
Some(Problem::WrongPassword) => (
|
||||
format!(
|
||||
"<p class=\"err\" role=\"alert\">{RING}That password is not right. Check it with the person who sent the link.</p>"
|
||||
),
|
||||
"",
|
||||
),
|
||||
Some(Problem::TooMany) => (
|
||||
format!(
|
||||
"<p class=\"err\" role=\"alert\">{RING}Too many tries. Wait a minute, then try again.</p>"
|
||||
),
|
||||
" disabled",
|
||||
),
|
||||
None => (String::new(), ""),
|
||||
};
|
||||
let inner = format!(
|
||||
"{}<h1>This link is protected</h1>\
|
||||
<p>Someone shared {h} with you. Enter the password they gave you.</p>\
|
||||
<form method=\"post\" action=\"{PASSWORD_PATH}\">\
|
||||
<input type=\"hidden\" name=\"t\" value=\"{}\">\
|
||||
<label for=\"pw\">Password</label>\
|
||||
<input id=\"pw\" type=\"password\" name=\"password\" autocomplete=\"current-password\" autofocus required>\
|
||||
{msg}<button type=\"submit\"{disabled}>Open</button></form>\
|
||||
<p class=\"small\">The link works until {}.</p>",
|
||||
icon("lock"),
|
||||
escape(token),
|
||||
long_date(*until)
|
||||
);
|
||||
shell(host, &inner, "This link is protected")
|
||||
}
|
||||
Page::Expired { host, until } => {
|
||||
let inner = format!(
|
||||
"{}<h1>This link has expired</h1>\
|
||||
<p>It worked until {}. Ask the person who sent it for a new one.</p>\
|
||||
<a href=\"/\">Have an account? Sign in</a>",
|
||||
icon("clock"),
|
||||
long_date(*until)
|
||||
);
|
||||
shell(host, &inner, "This link has expired")
|
||||
}
|
||||
Page::Invalid { host } => {
|
||||
let inner = format!(
|
||||
"{}<h1>This link no longer works</h1>\
|
||||
<p>It may have been stopped, or not copied in full. Ask the person who sent it for a new one.</p>\
|
||||
<a href=\"/\">Have an account? Sign in</a>",
|
||||
icon("broken")
|
||||
);
|
||||
shell(host, &inner, "This link no longer works")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pages_are_small_and_escaped() {
|
||||
for p in [
|
||||
Page::Password {
|
||||
host: "<b>x</b>",
|
||||
token: "\"><script>",
|
||||
until: 1_794_666_000,
|
||||
problem: Some(Problem::WrongPassword),
|
||||
},
|
||||
Page::Expired {
|
||||
host: "a.test",
|
||||
until: 0,
|
||||
},
|
||||
Page::Invalid { host: "a.test" },
|
||||
] {
|
||||
let html = render(&p);
|
||||
assert!(html.len() < 8 * 1024, "{}", html.len());
|
||||
assert!(!html.contains("<script"));
|
||||
assert!(!html.contains("<b>x"));
|
||||
assert!(!html.contains("http://") && !html.contains("https://"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,13 +22,17 @@ use crate::fetch;
|
||||
use crate::forward_auth::{self, Outcome};
|
||||
use crate::logging::{AccessRecord, now_secs, truncate_ip};
|
||||
use crate::runtime::{HostRt, Op, Runtime};
|
||||
use crate::share::{self, Decision};
|
||||
use crate::shared::Shared;
|
||||
|
||||
pub struct EdgeProxy {
|
||||
pub rt: Arc<Runtime>,
|
||||
pub shared: Arc<Shared>,
|
||||
pub connector: Connector,
|
||||
}
|
||||
|
||||
pub struct Ctx {
|
||||
/// The runtime current when the request started; used for the whole request.
|
||||
rt: Option<Arc<Runtime>>,
|
||||
host: Option<Arc<HostRt>>,
|
||||
/// Chosen upstream and its resolved addresses; connect failures move to the next address.
|
||||
upstream: Option<usize>,
|
||||
@@ -113,6 +117,7 @@ impl ProxyHttp for EdgeProxy {
|
||||
|
||||
fn new_ctx(&self) -> Ctx {
|
||||
Ctx {
|
||||
rt: None,
|
||||
host: None,
|
||||
upstream: None,
|
||||
addrs: Vec::new(),
|
||||
@@ -123,15 +128,39 @@ impl ProxyHttp for EdgeProxy {
|
||||
}
|
||||
|
||||
async fn request_filter(&self, session: &mut Session, ctx: &mut Ctx) -> Result<bool> {
|
||||
let rt = self.shared.current();
|
||||
ctx.rt = Some(rt.clone());
|
||||
ctx.host_header = host_header(session.req_header());
|
||||
let Some(host) = self.rt.host(&hostname(&ctx.host_header)).cloned() else {
|
||||
let Some(host) = rt.host(&hostname(&ctx.host_header)).cloned() else {
|
||||
respond_empty(session, 404).await?;
|
||||
return Ok(true);
|
||||
};
|
||||
ctx.host = Some(host.clone());
|
||||
|
||||
let mut shared_access = false;
|
||||
if !host.cfg.share_links {
|
||||
share::strip_any_token(session)?;
|
||||
} else {
|
||||
let ip = client_ip(session);
|
||||
let revs = self.shared.revocations();
|
||||
match share::handle(
|
||||
session,
|
||||
&host.cfg.hostname,
|
||||
rt.share_key.as_deref(),
|
||||
&revs,
|
||||
&self.shared.throttle,
|
||||
ip,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Decision::Answered => return Ok(true),
|
||||
Decision::Allowed => shared_access = true,
|
||||
Decision::Continue => {}
|
||||
}
|
||||
}
|
||||
|
||||
if host.cfg.forward_auth {
|
||||
let fa = self.rt.forward_auth.as_ref().ok_or_else(|| {
|
||||
let fa = rt.forward_auth.as_ref().ok_or_else(|| {
|
||||
Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured")
|
||||
})?;
|
||||
// Client-sent identity headers never survive, whatever copy_headers says.
|
||||
@@ -139,6 +168,10 @@ impl ProxyHttp for EdgeProxy {
|
||||
for name in &fa.strip_headers {
|
||||
req.remove_header(name);
|
||||
}
|
||||
if shared_access {
|
||||
// A valid share link stands in for the sign-in on its prefix.
|
||||
return self.after_auth(session, &host).await;
|
||||
}
|
||||
let ip = client_ip(session).map(|i| i.to_string());
|
||||
let outcome = match forward_auth::check(
|
||||
&self.connector,
|
||||
@@ -180,11 +213,7 @@ impl ProxyHttp for EdgeProxy {
|
||||
}
|
||||
}
|
||||
|
||||
if !host.cfg.websockets && is_websocket_upgrade(session.req_header()) {
|
||||
respond_empty(session, 403).await?;
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
self.after_auth(session, &host).await
|
||||
}
|
||||
|
||||
async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result<Box<HttpPeer>> {
|
||||
@@ -350,7 +379,7 @@ impl ProxyHttp for EdgeProxy {
|
||||
if !host.cfg.access_log {
|
||||
return;
|
||||
}
|
||||
let Some(log) = &self.rt.access_log else {
|
||||
let Some(log) = ctx.rt.as_ref().and_then(|rt| rt.access_log.as_ref()) else {
|
||||
return;
|
||||
};
|
||||
let req = session.req_header();
|
||||
@@ -372,6 +401,17 @@ impl ProxyHttp for EdgeProxy {
|
||||
}
|
||||
}
|
||||
|
||||
impl EdgeProxy {
|
||||
/// The steps after the sign-in check: websocket refusal.
|
||||
async fn after_auth(&self, session: &mut Session, host: &HostRt) -> Result<bool> {
|
||||
if !host.cfg.websockets && is_websocket_upgrade(session.req_header()) {
|
||||
respond_empty(session, 403).await?;
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
|
||||
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
+161
-20
@@ -2,31 +2,81 @@
|
||||
// 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 edge config turned into ready-to-serve state: resolved upstream addresses,
|
||||
//! parsed header names, secrets loaded, certificates loaded. Built once at startup.
|
||||
//! The compiled edge config turned into ready-to-serve state: parsed upstreams and header
|
||||
//! names, secrets loaded, certificates loaded, the share-link key loaded. Built at startup
|
||||
//! and again on every reload; a reload swaps the whole [`Runtime`] at once (see `shared`).
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::collections::{BTreeSet, HashMap, VecDeque};
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use http::{HeaderName, HeaderValue};
|
||||
use ianitor_core::edge_config::{
|
||||
EDGE_CONFIG_VERSION, EdgeConfig, EdgeHeaderOp, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
|
||||
};
|
||||
use ianitor_core::share::{KEY_CREDENTIAL, ShareKey};
|
||||
use rustls::sign::CertifiedKey;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::error::EdgeError;
|
||||
use crate::logging::AccessLog;
|
||||
use crate::secrets::Secrets;
|
||||
use crate::tls::{CertStore, certified_key};
|
||||
use crate::tls::{certified_key, not_after};
|
||||
|
||||
pub enum Op {
|
||||
Set(HeaderName, HeaderValue),
|
||||
Remove(HeaderName),
|
||||
}
|
||||
|
||||
/// One health probe result, as reported on the admin socket.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Check {
|
||||
/// Increases by one per probe of this upstream.
|
||||
pub seq: u64,
|
||||
/// Unix seconds.
|
||||
pub at: u64,
|
||||
pub ok: bool,
|
||||
/// `health_check` (the host's own check) or `watch` (`GET /` during a trial).
|
||||
pub source: &'static str,
|
||||
/// `refused`, `timeout`, `name`, `tls`, `server_error`, `not_found`, `redirect`,
|
||||
/// `sign_in` or `bad_answer`; `None` when `ok`.
|
||||
pub kind: Option<&'static str>,
|
||||
pub status: Option<u16>,
|
||||
pub latency_ms: Option<u64>,
|
||||
}
|
||||
|
||||
/// The last few probe results of one upstream.
|
||||
#[derive(Default)]
|
||||
pub struct HealthRecord {
|
||||
inner: Mutex<(u64, VecDeque<Check>)>,
|
||||
}
|
||||
|
||||
/// How many results are kept per upstream.
|
||||
pub const KEPT_CHECKS: usize = 5;
|
||||
|
||||
impl HealthRecord {
|
||||
pub fn record(&self, mut c: Check) {
|
||||
if let Ok(mut g) = self.inner.lock() {
|
||||
g.0 += 1;
|
||||
c.seq = g.0;
|
||||
g.1.push_back(c);
|
||||
while g.1.len() > KEPT_CHECKS {
|
||||
g.1.pop_front();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn checks(&self) -> Vec<Check> {
|
||||
self.inner
|
||||
.lock()
|
||||
.map(|g| g.1.iter().cloned().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UpstreamRt {
|
||||
/// Host name or IP literal (IPv6 without brackets).
|
||||
pub host: String,
|
||||
@@ -36,6 +86,7 @@ pub struct UpstreamRt {
|
||||
pub tls: bool,
|
||||
pub sni: String,
|
||||
pub healthy: AtomicBool,
|
||||
pub health: HealthRecord,
|
||||
}
|
||||
|
||||
pub struct HostRt {
|
||||
@@ -61,7 +112,15 @@ pub struct Runtime {
|
||||
pub hosts: HashMap<String, Arc<HostRt>>,
|
||||
pub forward_auth: Option<ForwardAuthRt>,
|
||||
pub access_log: Option<AccessLog>,
|
||||
pub certs: Arc<CertStore>,
|
||||
/// Domi certificates (`tls = "domi"`), by hostname.
|
||||
pub file_certs: HashMap<String, Arc<CertifiedKey>>,
|
||||
/// `notAfter` (Unix seconds) of each Domi certificate.
|
||||
pub file_cert_expiry: HashMap<String, i64>,
|
||||
/// Loaded when any host has share links.
|
||||
pub share_key: Option<Arc<ShareKey>>,
|
||||
/// SHA-256 (hex) of the config file bytes this runtime was built from; empty when it was
|
||||
/// built from a parsed config.
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
@@ -83,12 +142,45 @@ impl Runtime {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_config(path: &Path) -> Result<EdgeConfig, EdgeError> {
|
||||
let text = std::fs::read_to_string(path).map_err(|source| EdgeError::Read {
|
||||
pub fn sha256_hex(data: &[u8]) -> String {
|
||||
ring::digest::digest(&ring::digest::SHA256, data)
|
||||
.as_ref()
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Largest config file read.
|
||||
const MAX_CONFIG_BYTES: u64 = 16 << 20;
|
||||
|
||||
/// Read and parse a config file; returns the parsed config and the SHA-256 of its bytes.
|
||||
pub fn read_config_file(path: &Path) -> Result<(EdgeConfig, String), EdgeError> {
|
||||
let read_err = |source| EdgeError::Read {
|
||||
path: path.to_owned(),
|
||||
source,
|
||||
};
|
||||
let meta = std::fs::metadata(path).map_err(read_err)?;
|
||||
if meta.len() > MAX_CONFIG_BYTES {
|
||||
return Err(EdgeError::Config {
|
||||
path: path.to_owned(),
|
||||
message: "the file is larger than 16 MiB".into(),
|
||||
});
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(read_err)?;
|
||||
let text = std::str::from_utf8(&bytes).map_err(|_| EdgeError::Config {
|
||||
path: path.to_owned(),
|
||||
message: "the file is not UTF-8".into(),
|
||||
})?;
|
||||
let cfg: EdgeConfig = serde_json::from_str(&text).map_err(|e| EdgeError::Config {
|
||||
let cfg = parse_config(path, text)?;
|
||||
Ok((cfg, sha256_hex(&bytes)))
|
||||
}
|
||||
|
||||
pub fn read_config(path: &Path) -> Result<EdgeConfig, EdgeError> {
|
||||
read_config_file(path).map(|(c, _)| c)
|
||||
}
|
||||
|
||||
fn parse_config(path: &Path, text: &str) -> Result<EdgeConfig, EdgeError> {
|
||||
let cfg: EdgeConfig = serde_json::from_str(text).map_err(|e| EdgeError::Config {
|
||||
path: path.to_owned(),
|
||||
message: e.to_string(),
|
||||
})?;
|
||||
@@ -125,6 +217,7 @@ fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
|
||||
tls: u.tls,
|
||||
sni: u.sni.clone(),
|
||||
healthy: AtomicBool::new(true),
|
||||
health: HealthRecord::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -221,10 +314,18 @@ fn ops(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Load secrets and certificates and resolve upstreams. Fails on the first problem; edge never
|
||||
/// starts half-configured.
|
||||
/// Read, parse and build a config file. Fails on the first problem; edge never serves a
|
||||
/// half-built config.
|
||||
pub fn build_file(path: &Path, credentials_dir: Option<&Path>) -> Result<Runtime, EdgeError> {
|
||||
let (cfg, sha) = read_config_file(path)?;
|
||||
let mut rt = build(cfg, credentials_dir)?;
|
||||
rt.sha256 = sha;
|
||||
Ok(rt)
|
||||
}
|
||||
|
||||
/// Load secrets, certificates and the share-link key. Fails on the first problem.
|
||||
pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime, EdgeError> {
|
||||
let names: BTreeSet<String> = cfg
|
||||
let mut names: BTreeSet<String> = cfg
|
||||
.hosts
|
||||
.iter()
|
||||
.flat_map(|h| h.request_headers.iter().chain(&h.response_headers))
|
||||
@@ -236,9 +337,23 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let wants_share = cfg.hosts.iter().any(|h| h.share_links);
|
||||
if wants_share {
|
||||
names.insert(KEY_CREDENTIAL.to_owned());
|
||||
}
|
||||
let secrets = Secrets::load(&names, credentials_dir)?;
|
||||
let share_key = match secrets.get(KEY_CREDENTIAL) {
|
||||
Some(s) if wants_share => Some(Arc::new(ShareKey::new(s.as_bytes()).map_err(|_| {
|
||||
EdgeError::Secret {
|
||||
name: KEY_CREDENTIAL.into(),
|
||||
reason: "the share-link key must be at least 32 characters",
|
||||
}
|
||||
})?)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let certs = Arc::new(CertStore::default());
|
||||
let mut file_certs = HashMap::new();
|
||||
let mut file_cert_expiry = HashMap::new();
|
||||
let mut hosts = HashMap::new();
|
||||
for h in &cfg.hosts {
|
||||
if let EdgeTls::Files { cert, key } = &h.tls {
|
||||
@@ -248,12 +363,15 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
|
||||
source,
|
||||
})
|
||||
};
|
||||
let pair =
|
||||
certified_key(&read(cert)?, &read(key)?).map_err(|reason| EdgeError::Cert {
|
||||
host: h.hostname.clone(),
|
||||
reason,
|
||||
})?;
|
||||
certs.insert(&h.hostname, pair);
|
||||
let cert_pem = read(cert)?;
|
||||
let pair = certified_key(&cert_pem, &read(key)?).map_err(|reason| EdgeError::Cert {
|
||||
host: h.hostname.clone(),
|
||||
reason,
|
||||
})?;
|
||||
if let Some(exp) = not_after(&cert_pem) {
|
||||
file_cert_expiry.insert(h.hostname.clone(), exp);
|
||||
}
|
||||
file_certs.insert(h.hostname.clone(), Arc::new(pair));
|
||||
}
|
||||
let mut secret_values = Vec::new();
|
||||
let request_ops = ops(&h.request_headers, &secrets, &mut secret_values)?;
|
||||
@@ -317,7 +435,10 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
|
||||
hosts,
|
||||
forward_auth,
|
||||
access_log,
|
||||
certs,
|
||||
file_certs,
|
||||
file_cert_expiry,
|
||||
share_key,
|
||||
sha256: String::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -361,4 +482,24 @@ mod resolve_tests {
|
||||
.await;
|
||||
assert_eq!(got.unwrap_err().kind(), std::io::ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn health_records_keep_the_last_five() {
|
||||
let r = HealthRecord::default();
|
||||
for i in 0..8 {
|
||||
r.record(Check {
|
||||
seq: 0,
|
||||
at: i,
|
||||
ok: i % 2 == 0,
|
||||
source: "health_check",
|
||||
kind: None,
|
||||
status: None,
|
||||
latency_ms: None,
|
||||
});
|
||||
}
|
||||
let c = r.checks();
|
||||
assert_eq!(c.len(), KEPT_CHECKS);
|
||||
assert_eq!(c.first().unwrap().seq, 4);
|
||||
assert_eq!(c.last().unwrap().seq, 8);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,481 @@
|
||||
// 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/.
|
||||
|
||||
//! Share links on hosts with `share_links = true` (tokens: `ianitor_core::share`).
|
||||
//!
|
||||
//! 1. `GET <path>?share=ish1.…` within the link's prefix: edge checks the token and answers
|
||||
//! `303` to the same URL without `share=`, setting the session cookie (`__Secure-`, Path =
|
||||
//! prefix, HttpOnly, Secure, SameSite=Lax, Max-Age = time left). The token is in a URL once.
|
||||
//! A password link instead gets the password page; its form posts the token and the
|
||||
//! password to [`PASSWORD_PATH`], and on success edge sets the cookie and redirects to
|
||||
//! the prefix.
|
||||
//! 2. A request carrying a valid session cookie for a path within its prefix skips
|
||||
//! forward-auth. The cookie (and any `share=` token) is removed before the request goes on,
|
||||
//! so neither the upstream nor the auth server ever sees it.
|
||||
//! 3. A token outside its prefix, or one for a host without share links, is ignored: the
|
||||
//! request takes the normal sign-in, without the `share=` parameter.
|
||||
//!
|
||||
//! SameSite=Lax, not Strict: a visitor arrives by clicking a link in another site or app, and
|
||||
//! browsers do not send Strict cookies on the redirect that follows such a navigation.
|
||||
//! Wrong passwords are limited to 5 a minute per link and visitor /24 (and /48).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use http::header;
|
||||
use ianitor_core::share::{
|
||||
COOKIE_NAME, Claims, LINK_PREFIX, PASSWORD_PATH, QUERY_PARAM, Rejection, ShareId, ShareKey,
|
||||
path_within, peek, session_value, verify_link, verify_session,
|
||||
};
|
||||
use pingora::http::ResponseHeader;
|
||||
use pingora::proxy::Session;
|
||||
use pingora::{Error, ErrorType, Result};
|
||||
|
||||
use crate::logging::{now_secs, truncate_ip};
|
||||
use crate::pages::{self, Page};
|
||||
use crate::shared::RevocationState;
|
||||
|
||||
const WINDOW: Duration = Duration::from_secs(60);
|
||||
/// Wrong passwords a minute for one link from one network.
|
||||
const MAX_FAILURES: u32 = 5;
|
||||
/// Wrong passwords a minute from one network, whatever the link: the link id a guess names
|
||||
/// is unproven, so per-link counting alone could be dodged with made-up ids.
|
||||
const MAX_NETWORK_FAILURES: u32 = 20;
|
||||
const MAX_ENTRIES: usize = 10_000;
|
||||
const MAX_FORM: usize = 8 * 1024;
|
||||
|
||||
type Window = (Instant, u32);
|
||||
|
||||
/// Wrong-password counters per (link, visitor network) and per visitor network. Entries live
|
||||
/// one minute. A full table refuses newcomers rather than forgetting anyone, so flooding it
|
||||
/// can lock visitors out for a minute but never reset a counter.
|
||||
#[derive(Default)]
|
||||
pub struct Throttle {
|
||||
inner: Mutex<Counters>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Counters {
|
||||
links: HashMap<(ShareId, IpAddr), Window>,
|
||||
networks: HashMap<IpAddr, Window>,
|
||||
}
|
||||
|
||||
fn live(w: &Window) -> bool {
|
||||
w.0.elapsed() < WINDOW
|
||||
}
|
||||
|
||||
fn count<K: std::hash::Hash + Eq>(m: &mut HashMap<K, Window>, k: K) {
|
||||
if m.len() >= MAX_ENTRIES && !m.contains_key(&k) {
|
||||
m.retain(|_, w| live(w));
|
||||
if m.len() >= MAX_ENTRIES {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let e = m.entry(k).or_insert((Instant::now(), 0));
|
||||
if !live(e) {
|
||||
*e = (Instant::now(), 0);
|
||||
}
|
||||
e.1 = e.1.saturating_add(1);
|
||||
}
|
||||
|
||||
impl Throttle {
|
||||
fn net(ip: Option<IpAddr>) -> IpAddr {
|
||||
ip.map_or(IpAddr::from([0, 0, 0, 0]), truncate_ip)
|
||||
}
|
||||
|
||||
/// True when this visitor may try a password for this link now.
|
||||
pub fn allowed(&self, id: ShareId, ip: Option<IpAddr>) -> bool {
|
||||
let Ok(mut c) = self.inner.lock() else {
|
||||
return false;
|
||||
};
|
||||
let net = Self::net(ip);
|
||||
let under = |w: Option<&Window>, max: u32| w.is_none_or(|w| !live(w) || w.1 < max);
|
||||
if !under(c.networks.get(&net), MAX_NETWORK_FAILURES)
|
||||
|| !under(c.links.get(&(id, net)), MAX_FAILURES)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// A full table that has no room for this visitor: refuse.
|
||||
for full in [
|
||||
c.links.len() >= MAX_ENTRIES,
|
||||
c.networks.len() >= MAX_ENTRIES,
|
||||
] {
|
||||
if full {
|
||||
c.links.retain(|_, w| live(w));
|
||||
c.networks.retain(|_, w| live(w));
|
||||
}
|
||||
}
|
||||
let room_links = c.links.len() < MAX_ENTRIES || c.links.contains_key(&(id, net));
|
||||
let room_nets = c.networks.len() < MAX_ENTRIES || c.networks.contains_key(&net);
|
||||
room_links && room_nets
|
||||
}
|
||||
|
||||
pub fn failed(&self, id: ShareId, ip: Option<IpAddr>) {
|
||||
let Ok(mut c) = self.inner.lock() else { return };
|
||||
let net = Self::net(ip);
|
||||
count(&mut c.links, (id, net));
|
||||
count(&mut c.networks, net);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the share layer decided for a request.
|
||||
pub enum Decision {
|
||||
/// Answered here (redirect or visitor page); stop.
|
||||
Answered,
|
||||
/// A valid session cookie covers this path: skip forward-auth.
|
||||
Allowed,
|
||||
/// Nothing to do with share links: continue as usual.
|
||||
Continue,
|
||||
}
|
||||
|
||||
fn now() -> u64 {
|
||||
now_secs() as u64
|
||||
}
|
||||
|
||||
/// Remove every share cookie from the request; return their values.
|
||||
fn take_cookies(session: &mut Session) -> Result<Vec<String>> {
|
||||
let req = session.req_header_mut();
|
||||
let all: Vec<String> = req
|
||||
.headers
|
||||
.get_all(header::COOKIE)
|
||||
.iter()
|
||||
.map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned())
|
||||
.collect();
|
||||
if all.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut ours = Vec::new();
|
||||
let mut rest = Vec::new();
|
||||
for line in &all {
|
||||
for part in line.split(';') {
|
||||
let p = part.trim();
|
||||
if p.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match p.split_once('=') {
|
||||
Some((n, v)) if n.trim() == COOKIE_NAME => ours.push(v.trim().to_owned()),
|
||||
_ => rest.push(p.to_owned()),
|
||||
}
|
||||
}
|
||||
}
|
||||
if ours.is_empty() {
|
||||
return Ok(ours);
|
||||
}
|
||||
req.remove_header(&header::COOKIE);
|
||||
if !rest.is_empty() {
|
||||
req.insert_header(header::COOKIE, rest.join("; "))?;
|
||||
}
|
||||
Ok(ours)
|
||||
}
|
||||
|
||||
/// Split the query into our token (the first `share=ish1.…`) and everything else, kept in
|
||||
/// its original encoding.
|
||||
fn split_query(query: &str) -> (Option<String>, String) {
|
||||
let mut token = None;
|
||||
let mut rest = Vec::new();
|
||||
for pair in query.split('&') {
|
||||
// Every `share=ish1.…`, also with the name or value encoded, comes out; the first
|
||||
// one is the token.
|
||||
if let Some((k, v)) = form_urlencoded::parse(pair.as_bytes()).next()
|
||||
&& k == QUERY_PARAM
|
||||
&& v.starts_with(LINK_PREFIX)
|
||||
{
|
||||
if token.is_none() {
|
||||
token = Some(v.into_owned());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !pair.is_empty() {
|
||||
rest.push(pair);
|
||||
}
|
||||
}
|
||||
(token, rest.join("&"))
|
||||
}
|
||||
|
||||
fn with_query(path: &str, query: &str) -> String {
|
||||
if query.is_empty() {
|
||||
path.to_owned()
|
||||
} else {
|
||||
format!("{path}?{query}")
|
||||
}
|
||||
}
|
||||
|
||||
/// On a host without share links: drop any `share=ish1.…` token from the request target, so
|
||||
/// neither the auth server (X-Forwarded-Uri) nor the upstream ever sees one.
|
||||
pub fn strip_any_token(session: &mut Session) -> Result<()> {
|
||||
let Some(query) = session.req_header().uri.query().map(str::to_owned) else {
|
||||
return Ok(());
|
||||
};
|
||||
let (token, rest) = split_query(&query);
|
||||
if token.is_some() {
|
||||
let path = session.req_header().uri.path().to_owned();
|
||||
strip_token(session, &path, &rest)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drop the `share=` token from the request target, so the upstream never sees it.
|
||||
fn strip_token(session: &mut Session, path: &str, rest: &str) -> Result<()> {
|
||||
let uri = with_query(path, rest)
|
||||
.parse::<http::Uri>()
|
||||
.map_err(|_| Error::explain(ErrorType::HTTPStatus(400), "bad request target"))?;
|
||||
session.req_header_mut().set_uri(uri);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cookie(value: &str, claims: &Claims) -> String {
|
||||
let left = claims.expires_at.saturating_sub(now());
|
||||
format!(
|
||||
"{COOKIE_NAME}={value}; Path={}; Max-Age={left}; HttpOnly; Secure; SameSite=Lax",
|
||||
claims.prefix
|
||||
)
|
||||
}
|
||||
|
||||
async fn redirect(session: &mut Session, location: &str, set_cookie: Option<String>) -> Result<()> {
|
||||
let mut resp = ResponseHeader::build(303, Some(5))?;
|
||||
resp.insert_header(header::LOCATION, location)?;
|
||||
resp.insert_header(header::CACHE_CONTROL, "no-store")?;
|
||||
resp.insert_header("Referrer-Policy", "no-referrer")?;
|
||||
resp.insert_header(header::CONTENT_LENGTH, "0")?;
|
||||
if let Some(c) = set_cookie {
|
||||
resp.insert_header(header::SET_COOKIE, c)?;
|
||||
}
|
||||
session.write_response_header(Box::new(resp), true).await
|
||||
}
|
||||
|
||||
async fn page(session: &mut Session, p: Page<'_>) -> Result<()> {
|
||||
let html = pages::render(&p);
|
||||
let mut resp = ResponseHeader::build(p.status(), Some(8))?;
|
||||
resp.insert_header(header::CONTENT_TYPE, "text/html; charset=utf-8")?;
|
||||
resp.insert_header(header::CACHE_CONTROL, "no-store")?;
|
||||
resp.insert_header("Referrer-Policy", "no-referrer")?;
|
||||
resp.insert_header("X-Robots-Tag", "noindex")?;
|
||||
resp.insert_header(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'",
|
||||
)?;
|
||||
resp.insert_header(header::CONTENT_LENGTH, html.len().to_string())?;
|
||||
let head = session.req_header().method == http::Method::HEAD;
|
||||
session.write_response_header(Box::new(resp), head).await?;
|
||||
if !head {
|
||||
session
|
||||
.write_response_body(Some(Bytes::from(html)), true)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rejected_page(r: Rejection, host: &str) -> Page<'_> {
|
||||
match r {
|
||||
Rejection::Expired { expires_at } => Page::Expired {
|
||||
host,
|
||||
until: expires_at,
|
||||
},
|
||||
_ => Page::Invalid { host },
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_form(session: &mut Session) -> Result<Option<Vec<u8>>> {
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = session.read_request_body().await? {
|
||||
if body.len() + chunk.len() > MAX_FORM {
|
||||
return Ok(None);
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok(Some(body))
|
||||
}
|
||||
|
||||
/// The share layer for one request on a host with share links.
|
||||
pub async fn handle(
|
||||
session: &mut Session,
|
||||
host: &str,
|
||||
key: Option<&ShareKey>,
|
||||
revocations: &RevocationState,
|
||||
throttle: &Throttle,
|
||||
client_ip: Option<IpAddr>,
|
||||
) -> Result<Decision> {
|
||||
let cookies = take_cookies(session)?;
|
||||
let path = session.req_header().uri.path().to_owned();
|
||||
let query = session.req_header().uri.query().unwrap_or("").to_owned();
|
||||
// Without the key or a readable revocation file, no share link is honoured.
|
||||
let usable = key.filter(|_| revocations.loaded);
|
||||
let revs = &revocations.revocations;
|
||||
|
||||
if path == PASSWORD_PATH {
|
||||
let Some(key) = usable else {
|
||||
page(session, Page::Invalid { host }).await?;
|
||||
return Ok(Decision::Answered);
|
||||
};
|
||||
if session.req_header().method != http::Method::POST {
|
||||
page(session, Page::Invalid { host }).await?;
|
||||
return Ok(Decision::Answered);
|
||||
}
|
||||
let Some(body) = read_form(session).await? else {
|
||||
page(session, Page::Invalid { host }).await?;
|
||||
return Ok(Decision::Answered);
|
||||
};
|
||||
let mut token = String::new();
|
||||
let mut password = String::new();
|
||||
for (k, v) in form_urlencoded::parse(&body) {
|
||||
match k.as_ref() {
|
||||
"t" => token = v.into_owned(),
|
||||
"password" => password = v.into_owned(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let Ok(claimed) = peek(&token) else {
|
||||
page(session, Page::Invalid { host }).await?;
|
||||
return Ok(Decision::Answered);
|
||||
};
|
||||
if !throttle.allowed(claimed.id, client_ip) {
|
||||
page(
|
||||
session,
|
||||
Page::Password {
|
||||
host,
|
||||
token: &token,
|
||||
until: claimed.expires_at,
|
||||
problem: Some(pages::Problem::TooMany),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
return Ok(Decision::Answered);
|
||||
}
|
||||
match verify_link(key, host, &token, Some(&password), now(), revs) {
|
||||
Ok(c) => {
|
||||
let v = session_value(key, host, &c);
|
||||
redirect(session, &c.prefix, Some(cookie(&v, &c))).await?;
|
||||
}
|
||||
Err(Rejection::Invalid) => {
|
||||
throttle.failed(claimed.id, client_ip);
|
||||
page(
|
||||
session,
|
||||
Page::Password {
|
||||
host,
|
||||
token: &token,
|
||||
until: claimed.expires_at,
|
||||
problem: Some(pages::Problem::WrongPassword),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Err(r) => page(session, rejected_page(r, host)).await?,
|
||||
}
|
||||
return Ok(Decision::Answered);
|
||||
}
|
||||
|
||||
let (token, rest) = split_query(&query);
|
||||
if let Some(token) = token {
|
||||
let claimed = peek(&token);
|
||||
let within = claimed
|
||||
.as_ref()
|
||||
.is_ok_and(|c| path_within(&c.prefix, &path));
|
||||
if claimed.is_ok() && !within {
|
||||
// Outside its prefix: as if there were no link, minus the token.
|
||||
strip_token(session, &path, &rest)?;
|
||||
return Ok(Decision::Continue);
|
||||
}
|
||||
let Some(key) = usable else {
|
||||
page(session, Page::Invalid { host }).await?;
|
||||
return Ok(Decision::Answered);
|
||||
};
|
||||
let claimed = match claimed {
|
||||
Ok(c) => c,
|
||||
Err(_) => {
|
||||
page(session, Page::Invalid { host }).await?;
|
||||
return Ok(Decision::Answered);
|
||||
}
|
||||
};
|
||||
if claimed.password {
|
||||
if now() >= claimed.expires_at {
|
||||
page(
|
||||
session,
|
||||
Page::Expired {
|
||||
host,
|
||||
until: claimed.expires_at,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
} else {
|
||||
let problem =
|
||||
(!throttle.allowed(claimed.id, client_ip)).then_some(pages::Problem::TooMany);
|
||||
page(
|
||||
session,
|
||||
Page::Password {
|
||||
host,
|
||||
token: &token,
|
||||
until: claimed.expires_at,
|
||||
problem,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
return Ok(Decision::Answered);
|
||||
}
|
||||
match verify_link(key, host, &token, None, now(), revs) {
|
||||
Ok(c) => {
|
||||
let v = session_value(key, host, &c);
|
||||
redirect(session, &with_query(&path, &rest), Some(cookie(&v, &c))).await?;
|
||||
}
|
||||
Err(r) => page(session, rejected_page(r, host)).await?,
|
||||
}
|
||||
return Ok(Decision::Answered);
|
||||
}
|
||||
|
||||
if let Some(key) = usable {
|
||||
let t = now();
|
||||
for v in &cookies {
|
||||
if let Ok(c) = verify_session(key, host, v, t, revs)
|
||||
&& path_within(&c.prefix, &path)
|
||||
{
|
||||
return Ok(Decision::Allowed);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Decision::Continue)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_token_is_split_from_the_query() {
|
||||
assert_eq!(
|
||||
split_query("a=1&share=ish1.abc&b=2"),
|
||||
(Some("ish1.abc".into()), "a=1&b=2".into())
|
||||
);
|
||||
assert_eq!(split_query("share=holiday"), (None, "share=holiday".into()));
|
||||
assert_eq!(
|
||||
split_query("x=%20&share=ish1.a%2Db"),
|
||||
(Some("ish1.a-b".into()), "x=%20".into())
|
||||
);
|
||||
assert_eq!(split_query(""), (None, String::new()));
|
||||
assert_eq!(
|
||||
split_query("share=ish1.a&b=1&share=ish1.b&sh%61re=ish1.c"),
|
||||
(Some("ish1.a".into()), "b=1".into())
|
||||
);
|
||||
assert_eq!(split_query("sharex=ish1.a"), (None, "sharex=ish1.a".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_throttle_allows_five_failures_a_minute_per_link_and_network() {
|
||||
let t = Throttle::default();
|
||||
let id = ShareId([1; 16]);
|
||||
let ip: IpAddr = "192.0.2.10".parse().unwrap_or(IpAddr::from([0, 0, 0, 0]));
|
||||
let same_net: IpAddr = "192.0.2.99".parse().unwrap_or(IpAddr::from([0, 0, 0, 0]));
|
||||
let other_net: IpAddr = "198.51.100.1".parse().unwrap_or(IpAddr::from([0, 0, 0, 0]));
|
||||
for _ in 0..5 {
|
||||
assert!(t.allowed(id, Some(ip)));
|
||||
t.failed(id, Some(ip));
|
||||
}
|
||||
assert!(!t.allowed(id, Some(ip)));
|
||||
assert!(!t.allowed(id, Some(same_net)));
|
||||
assert!(t.allowed(id, Some(other_net)));
|
||||
assert!(t.allowed(ShareId([2; 16]), Some(ip)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
// 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/.
|
||||
|
||||
//! State that lives as long as the process, across config reloads (ROADMAP §8.4).
|
||||
//!
|
||||
//! A reload builds a complete new [`Runtime`] from the config file and swaps it in with one
|
||||
//! atomic pointer store. Listeners, TLS sessions and keep-alive connections are untouched:
|
||||
//! each request takes the runtime that is current when it starts and keeps it until it ends,
|
||||
//! so nothing in flight sees a half-applied config, and the next request on the same
|
||||
//! connection already uses the new one. A config that fails to build is refused and the old
|
||||
//! one keeps serving.
|
||||
//!
|
||||
//! A **trial** is a reload control has not confirmed yet: edge keeps the previous runtime and
|
||||
//! swaps it back by itself when the deadline passes without a confirmation. So if control
|
||||
//! dies in the middle of an apply, edge returns to the last good config on its own, and
|
||||
//! because the trial is read from a separate file, a restarted edge reads the last good
|
||||
//! config too.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use arc_swap::ArcSwap;
|
||||
use ianitor_core::share::{Revocations, ShareId};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::error::EdgeError;
|
||||
use crate::logging::now_secs;
|
||||
use crate::runtime::{self, Runtime};
|
||||
use crate::tls::CertStore;
|
||||
|
||||
/// Health probes of watched hosts during a trial.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct WatchSpec {
|
||||
pub hosts: Vec<String>,
|
||||
pub every: Duration,
|
||||
}
|
||||
|
||||
struct Trial {
|
||||
id: u64,
|
||||
sha256: String,
|
||||
previous: Arc<Runtime>,
|
||||
deadline: Instant,
|
||||
}
|
||||
|
||||
/// The share-link revocation file as edge last read it.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct RevocationState {
|
||||
pub revocations: Revocations,
|
||||
/// False when the file is missing or never read: share links are then refused.
|
||||
pub loaded: bool,
|
||||
pub error: Option<String>,
|
||||
/// SHA-256 of the file as last read; the poller re-reads when it changes.
|
||||
stamp: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RevocationFile {
|
||||
epoch: u32,
|
||||
deny: Vec<String>,
|
||||
}
|
||||
|
||||
/// Most ids on the deny list.
|
||||
pub const MAX_DENY: usize = 10_000;
|
||||
|
||||
/// Certificate state per host, for control (docs/ui-api.md G5).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CertState {
|
||||
/// `ok`, `pending` or `failed`.
|
||||
pub state: &'static str,
|
||||
pub not_after: Option<i64>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
pub struct Paths {
|
||||
pub config: PathBuf,
|
||||
pub trial: PathBuf,
|
||||
pub revocations: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// Why an admin request was refused.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AdminError {
|
||||
#[error("{0}")]
|
||||
Refused(#[from] EdgeError),
|
||||
#[error("{0}")]
|
||||
Conflict(String),
|
||||
}
|
||||
|
||||
pub struct Shared {
|
||||
current: ArcSwap<Runtime>,
|
||||
pub certs: Arc<CertStore>,
|
||||
generation: AtomicU64,
|
||||
changed: tokio::sync::watch::Sender<u64>,
|
||||
trial: Mutex<Option<Trial>>,
|
||||
trial_ids: AtomicU64,
|
||||
watch: Mutex<Option<WatchSpec>>,
|
||||
pub paths: Paths,
|
||||
credentials_dir: Option<PathBuf>,
|
||||
revocations: ArcSwap<RevocationState>,
|
||||
/// The highest revocation epoch seen since start; a file with a lower one is refused.
|
||||
epoch_seen: std::sync::atomic::AtomicU32,
|
||||
/// Set when the saved epoch floor could not be read: share links stay refused.
|
||||
floor_error: Option<String>,
|
||||
pub throttle: crate::share::Throttle,
|
||||
cert_states: Mutex<HashMap<String, CertState>>,
|
||||
pub acme_wake: tokio::sync::Notify,
|
||||
pub started_at: u64,
|
||||
}
|
||||
|
||||
fn same_listeners(a: &Runtime, b: &Runtime) -> Result<(), EdgeError> {
|
||||
if a.cfg.http_listen != b.cfg.http_listen || a.cfg.https_listen != b.cfg.https_listen {
|
||||
return Err(EdgeError::Config {
|
||||
path: PathBuf::from("<new config>"),
|
||||
message: "the listen addresses can only change with a restart".into(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
pub fn new(rt: Runtime, paths: Paths, credentials_dir: Option<PathBuf>) -> Arc<Shared> {
|
||||
let (floor, floor_error) = match read_epoch_floor(&rt) {
|
||||
Ok(f) => (f, None),
|
||||
Err(e) => {
|
||||
log::error!(target: "ianitor::share", "{e}");
|
||||
(u32::MAX, Some(e))
|
||||
}
|
||||
};
|
||||
let certs = Arc::new(CertStore::default());
|
||||
certs.replace_files(rt.file_certs.clone());
|
||||
let (changed, _) = tokio::sync::watch::channel(1);
|
||||
let s = Arc::new(Shared {
|
||||
current: ArcSwap::from_pointee(rt),
|
||||
certs,
|
||||
generation: AtomicU64::new(1),
|
||||
changed,
|
||||
trial: Mutex::new(None),
|
||||
trial_ids: AtomicU64::new(0),
|
||||
watch: Mutex::new(None),
|
||||
paths,
|
||||
credentials_dir,
|
||||
revocations: ArcSwap::from_pointee(RevocationState::default()),
|
||||
epoch_seen: std::sync::atomic::AtomicU32::new(floor),
|
||||
floor_error,
|
||||
throttle: crate::share::Throttle::default(),
|
||||
cert_states: Mutex::new(HashMap::new()),
|
||||
acme_wake: tokio::sync::Notify::new(),
|
||||
started_at: now_secs() as u64,
|
||||
});
|
||||
if let Err(e) = s.reload_revocations() {
|
||||
log::error!(target: "ianitor::share", "{e}; share links are refused until it is fixed");
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The runtime serving new requests now.
|
||||
pub fn current(&self) -> Arc<Runtime> {
|
||||
self.current.load_full()
|
||||
}
|
||||
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Changes whenever the runtime or the trial watch changes.
|
||||
pub fn subscribe(&self) -> tokio::sync::watch::Receiver<u64> {
|
||||
self.changed.subscribe()
|
||||
}
|
||||
|
||||
pub fn watch_spec(&self) -> Option<WatchSpec> {
|
||||
self.watch.lock().ok().and_then(|w| w.clone())
|
||||
}
|
||||
|
||||
fn notify(&self) {
|
||||
self.changed.send_replace(self.generation());
|
||||
}
|
||||
|
||||
fn install(&self, rt: Arc<Runtime>) {
|
||||
self.certs.replace_files(rt.file_certs.clone());
|
||||
self.current.store(rt);
|
||||
self.generation.fetch_add(1, Ordering::SeqCst);
|
||||
self.notify();
|
||||
self.acme_wake.notify_one();
|
||||
}
|
||||
|
||||
fn build(&self, path: &Path) -> Result<Runtime, EdgeError> {
|
||||
let rt = runtime::build_file(path, self.credentials_dir.as_deref())?;
|
||||
same_listeners(&self.current(), &rt)?;
|
||||
Ok(rt)
|
||||
}
|
||||
|
||||
/// Reload from the config file. Refused while a trial runs.
|
||||
pub fn reload(&self) -> Result<Arc<Runtime>, AdminError> {
|
||||
let guard = self.trial.lock().map_err(|_| poisoned())?;
|
||||
if guard.is_some() {
|
||||
return Err(AdminError::Conflict(
|
||||
"a trial config is running; confirm or abort it first".into(),
|
||||
));
|
||||
}
|
||||
let rt = Arc::new(self.build(&self.paths.config)?);
|
||||
self.install(rt.clone());
|
||||
drop(guard);
|
||||
log::info!(target: "ianitor::reload", "config reloaded ({} hosts, sha256 {})", rt.hosts.len(), short(&rt.sha256));
|
||||
Ok(rt)
|
||||
}
|
||||
|
||||
/// Serve the trial config until [`Shared::confirm`] or the deadline. Returns the trial id
|
||||
/// (for [`Shared::expire_trial`]) and the runtime.
|
||||
pub fn start_trial(
|
||||
&self,
|
||||
confirm_within: Duration,
|
||||
watch: Option<WatchSpec>,
|
||||
) -> Result<(u64, Arc<Runtime>), AdminError> {
|
||||
let mut guard = self.trial.lock().map_err(|_| poisoned())?;
|
||||
if guard.is_some() {
|
||||
return Err(AdminError::Conflict(
|
||||
"a trial config is already running".into(),
|
||||
));
|
||||
}
|
||||
let rt = Arc::new(self.build(&self.paths.trial)?);
|
||||
let id = self.trial_ids.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
*guard = Some(Trial {
|
||||
id,
|
||||
sha256: rt.sha256.clone(),
|
||||
previous: self.current(),
|
||||
deadline: Instant::now() + confirm_within,
|
||||
});
|
||||
if let Ok(mut w) = self.watch.lock() {
|
||||
*w = watch;
|
||||
}
|
||||
self.install(rt.clone());
|
||||
log::info!(target: "ianitor::reload", "trial config {} running; reverts in {confirm_within:?} unless confirmed", short(&rt.sha256));
|
||||
Ok((id, rt))
|
||||
}
|
||||
|
||||
/// Keep the trial config. Fails unless a trial with this hash is running.
|
||||
pub fn confirm(&self, sha256: &str) -> Result<(), AdminError> {
|
||||
let mut guard = self.trial.lock().map_err(|_| poisoned())?;
|
||||
match guard.as_ref() {
|
||||
Some(t) if t.sha256 == sha256 => {}
|
||||
Some(_) => {
|
||||
return Err(AdminError::Conflict(
|
||||
"the running trial has another config".into(),
|
||||
));
|
||||
}
|
||||
None => return Err(AdminError::Conflict("no trial config is running".into())),
|
||||
}
|
||||
*guard = None;
|
||||
self.end_watch();
|
||||
log::info!(target: "ianitor::reload", "trial config {} confirmed", short(sha256));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end_watch(&self) {
|
||||
if let Ok(mut w) = self.watch.lock() {
|
||||
*w = None;
|
||||
}
|
||||
self.notify();
|
||||
}
|
||||
|
||||
/// Go back to the config before the trial. Returns whether there was a trial.
|
||||
pub fn abort(&self) -> bool {
|
||||
self.revert_trial(None, "aborted")
|
||||
}
|
||||
|
||||
/// Called when a trial's deadline passes.
|
||||
pub fn expire_trial(&self, id: u64) {
|
||||
self.revert_trial(Some(id), "not confirmed in time");
|
||||
}
|
||||
|
||||
fn revert_trial(&self, id: Option<u64>, why: &str) -> bool {
|
||||
let Ok(mut guard) = self.trial.lock() else {
|
||||
return false;
|
||||
};
|
||||
let matches = guard.as_ref().is_some_and(|t| id.is_none_or(|i| i == t.id));
|
||||
if !matches {
|
||||
return false;
|
||||
}
|
||||
let Some(t) = guard.take() else { return false };
|
||||
self.install(t.previous.clone());
|
||||
self.end_watch();
|
||||
log::warn!(target: "ianitor::reload", "trial config {} {why}; back to {}", short(&t.sha256), short(&t.previous.sha256));
|
||||
true
|
||||
}
|
||||
|
||||
/// (sha256, seconds left, previous sha256) of the running trial.
|
||||
pub fn trial_info(&self) -> Option<(String, u64, String)> {
|
||||
let g = self.trial.lock().ok()?;
|
||||
g.as_ref().map(|t| {
|
||||
(
|
||||
t.sha256.clone(),
|
||||
t.deadline
|
||||
.saturating_duration_since(Instant::now())
|
||||
.as_secs(),
|
||||
t.previous.sha256.clone(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn trial_deadline(&self, id: u64) -> Option<Instant> {
|
||||
let g = self.trial.lock().ok()?;
|
||||
g.as_ref().filter(|t| t.id == id).map(|t| t.deadline)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ share-link revocations
|
||||
|
||||
pub fn revocations(&self) -> Arc<RevocationState> {
|
||||
self.revocations.load_full()
|
||||
}
|
||||
|
||||
/// Re-read the revocation file. A missing file means "refuse every share link"; a broken
|
||||
/// one keeps the last good state.
|
||||
pub fn reload_revocations(&self) -> Result<(), EdgeError> {
|
||||
let Some(path) = &self.paths.revocations else {
|
||||
self.revocations.store(Arc::new(RevocationState {
|
||||
error: Some("no revocation file is configured".into()),
|
||||
..RevocationState::default()
|
||||
}));
|
||||
return Ok(());
|
||||
};
|
||||
let meta = match std::fs::metadata(path) {
|
||||
Ok(m) => m,
|
||||
Err(source) => {
|
||||
self.revocations.store(Arc::new(RevocationState {
|
||||
error: Some(format!("cannot read {}: {source}", path.display())),
|
||||
..RevocationState::default()
|
||||
}));
|
||||
return Err(EdgeError::Read {
|
||||
path: path.clone(),
|
||||
source,
|
||||
});
|
||||
}
|
||||
};
|
||||
let text = std::fs::read(path).ok();
|
||||
let sha = text.as_deref().map(runtime::sha256_hex);
|
||||
let fail = |message: String| {
|
||||
let mut old = RevocationState::clone(&self.revocations());
|
||||
old.error = Some(message.clone());
|
||||
// Remember this content, so the poller reports it once, not every 5 s.
|
||||
if old.loaded {
|
||||
old.stamp = sha.clone();
|
||||
}
|
||||
self.revocations.store(Arc::new(old));
|
||||
EdgeError::Config {
|
||||
path: path.clone(),
|
||||
message,
|
||||
}
|
||||
};
|
||||
if meta.len() > 1 << 20 {
|
||||
return Err(fail("the revocation file is larger than 1 MiB".into()));
|
||||
}
|
||||
let text = text
|
||||
.and_then(|b| String::from_utf8(b).ok())
|
||||
.ok_or_else(|| fail("cannot read the revocation file as text".into()))?;
|
||||
let file: RevocationFile =
|
||||
serde_json::from_str(&text).map_err(|e| fail(format!("not a revocation file: {e}")))?;
|
||||
if file.deny.len() > MAX_DENY {
|
||||
return Err(fail(format!("more than {MAX_DENY} stopped links")));
|
||||
}
|
||||
let mut deny = std::collections::BTreeSet::new();
|
||||
for id in &file.deny {
|
||||
deny.insert(
|
||||
ShareId::from_hex(id)
|
||||
.ok_or_else(|| fail("a link id is not 32 hex digits".into()))?,
|
||||
);
|
||||
}
|
||||
if let Some(e) = &self.floor_error {
|
||||
return Err(fail(e.clone()));
|
||||
}
|
||||
// The epoch only goes up: a lower one would bring stopped links back.
|
||||
let seen = self.epoch_seen.load(Ordering::SeqCst);
|
||||
if file.epoch < seen {
|
||||
return Err(fail(format!(
|
||||
"the revocation epoch went down from {seen} to {}; keeping the old state",
|
||||
file.epoch
|
||||
)));
|
||||
}
|
||||
if file.epoch > seen {
|
||||
self.epoch_seen.store(file.epoch, Ordering::SeqCst);
|
||||
if let Err(e) = write_epoch_floor(&self.current(), file.epoch) {
|
||||
// Still refused within this process; only a restart could forget it.
|
||||
log::error!(target: "ianitor::share", "cannot save the revocation epoch floor: {e}");
|
||||
}
|
||||
}
|
||||
let stamp = Some(runtime::sha256_hex(text.as_bytes()));
|
||||
self.revocations.store(Arc::new(RevocationState {
|
||||
revocations: Revocations {
|
||||
epoch: file.epoch,
|
||||
deny,
|
||||
},
|
||||
loaded: true,
|
||||
error: None,
|
||||
stamp,
|
||||
}));
|
||||
log::info!(target: "ianitor::share", "share-link revocations loaded: epoch {}, {} stopped", file.epoch, file.deny.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Re-read the revocation file if it changed (or vanished) since the last read.
|
||||
pub fn poll_revocations(&self) {
|
||||
let Some(path) = &self.paths.revocations else {
|
||||
return;
|
||||
};
|
||||
// Content, not mtime: two writes within one timer tick have the same mtime.
|
||||
let now = std::fs::metadata(path)
|
||||
.ok()
|
||||
.filter(|m| m.len() <= 1 << 20)
|
||||
.and_then(|_| std::fs::read(path).ok())
|
||||
.map(|b| runtime::sha256_hex(&b));
|
||||
let state = self.revocations();
|
||||
if (now != state.stamp || (now.is_none() && state.loaded))
|
||||
&& let Err(e) = self.reload_revocations()
|
||||
{
|
||||
log::error!(target: "ianitor::share", "{e}");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ certificates
|
||||
|
||||
pub fn set_cert_state(&self, host: &str, state: CertState) {
|
||||
if let Ok(mut m) = self.cert_states.lock() {
|
||||
m.insert(host.to_owned(), state);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cert_state(&self, host: &str) -> Option<CertState> {
|
||||
self.cert_states.lock().ok()?.get(host).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Edge's own record of the highest revocation epoch it has accepted, in its state
|
||||
/// directory: a restart (even after control's files were rolled back) still refuses lower.
|
||||
fn epoch_floor_path(rt: &Runtime) -> PathBuf {
|
||||
Path::new(&rt.cfg.state_dir).join("share-epoch-floor")
|
||||
}
|
||||
|
||||
/// Missing: 0. Unreadable or not a number: an error, and share links stay refused (failing
|
||||
/// open would forget which links were stopped).
|
||||
fn read_epoch_floor(rt: &Runtime) -> Result<u32, String> {
|
||||
let path = epoch_floor_path(rt);
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(s) => s.trim().parse().map_err(|_| {
|
||||
format!(
|
||||
"{} is not a number; share links are refused until it is fixed",
|
||||
path.display()
|
||||
)
|
||||
}),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(0),
|
||||
Err(e) => Err(format!(
|
||||
"cannot read {} ({e}); share links are refused until it is fixed",
|
||||
path.display()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_epoch_floor(rt: &Runtime, epoch: u32) -> std::io::Result<()> {
|
||||
let path = epoch_floor_path(rt);
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
// Unique per write: the admin socket and the poller can both reload the revocations.
|
||||
static WRITES: AtomicU64 = AtomicU64::new(0);
|
||||
let tmp = path.with_extension(format!(
|
||||
"tmp-{}-{}",
|
||||
std::process::id(),
|
||||
WRITES.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
{
|
||||
use std::io::Write;
|
||||
let mut f = std::fs::File::create(&tmp)?;
|
||||
f.write_all(format!("{epoch}\n").as_bytes())?;
|
||||
f.sync_all()?;
|
||||
}
|
||||
std::fs::rename(&tmp, &path)?;
|
||||
match path.parent() {
|
||||
Some(dir) => std::fs::File::open(dir)?.sync_all(),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn poisoned() -> AdminError {
|
||||
AdminError::Conflict("internal state is unavailable".into())
|
||||
}
|
||||
|
||||
fn short(sha: &str) -> &str {
|
||||
sha.get(..12).unwrap_or(sha)
|
||||
}
|
||||
+14
-1
@@ -14,9 +14,14 @@ use rustls::sign::CertifiedKey;
|
||||
use rustls_pki_types::pem::PemObject;
|
||||
use rustls_pki_types::{CertificateDer, PrivateKeyDer};
|
||||
|
||||
/// Lives as long as the process: Domi certificates are replaced as a set on every reload,
|
||||
/// ACME certificates are added by the ACME service and kept across reloads.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CertStore {
|
||||
/// ACME certificates (and anything inserted one by one).
|
||||
certs: ArcSwap<HashMap<String, Arc<CertifiedKey>>>,
|
||||
/// Domi certificates of the current config.
|
||||
files: ArcSwap<HashMap<String, Arc<CertifiedKey>>>,
|
||||
}
|
||||
|
||||
impl CertStore {
|
||||
@@ -29,8 +34,13 @@ impl CertStore {
|
||||
});
|
||||
}
|
||||
|
||||
/// Replace the Domi certificates (on reload).
|
||||
pub fn replace_files(&self, files: HashMap<String, Arc<CertifiedKey>>) {
|
||||
self.files.store(Arc::new(files));
|
||||
}
|
||||
|
||||
pub fn has(&self, host: &str) -> bool {
|
||||
self.certs.load().contains_key(host)
|
||||
self.files.load().contains_key(host) || self.certs.load().contains_key(host)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +48,9 @@ impl ResolvesServerCert for CertStore {
|
||||
fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
|
||||
// No SNI or an unknown name: no certificate, the handshake fails (as with Caddy).
|
||||
let name = hello.server_name()?.to_ascii_lowercase();
|
||||
if let Some(k) = self.files.load().get(&name) {
|
||||
return Some(k.clone());
|
||||
}
|
||||
self.certs.load().get(&name).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
+128
-29
@@ -4,20 +4,26 @@
|
||||
|
||||
//! Runs the real `ianitor-edge` binary on 127.0.0.1 with a compiled config, a test CA for
|
||||
//! `tls = "domi"` hosts and a credentials directory. stderr goes to a file the tests inspect.
|
||||
//! Every edge also gets an admin socket and a share-link revocation file in its directory.
|
||||
|
||||
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use ianitor_core::compile::{self, CompileOptions};
|
||||
use ianitor_core::{SourceFile, TlsMode, load};
|
||||
use ianitor_testkit::more::{JsonResp, unix_json};
|
||||
use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port};
|
||||
use ianitor_testkit::tls::TestCa;
|
||||
use rustls::RootCertStore;
|
||||
|
||||
/// The share-link key written as the `share-link-key` credential of every test edge.
|
||||
pub const SHARE_KEY: &[u8] = b"edge-test-share-key-0123456789abcdef0123456789";
|
||||
|
||||
pub struct Edge {
|
||||
pub child: ChildGuard,
|
||||
pub http: SocketAddr,
|
||||
@@ -25,6 +31,7 @@ pub struct Edge {
|
||||
pub dir: TempDir,
|
||||
pub ca: TestCa,
|
||||
pub config_text: String,
|
||||
pub opts: CompileOptions,
|
||||
}
|
||||
|
||||
impl Edge {
|
||||
@@ -53,6 +60,44 @@ impl Edge {
|
||||
pub fn exited(&mut self) -> Option<std::process::ExitStatus> {
|
||||
self.child.0.try_wait().unwrap()
|
||||
}
|
||||
|
||||
pub fn admin_socket(&self) -> PathBuf {
|
||||
self.dir.join("admin.sock")
|
||||
}
|
||||
|
||||
pub fn config_path(&self) -> PathBuf {
|
||||
self.dir.join("edge.json")
|
||||
}
|
||||
|
||||
pub fn trial_path(&self) -> PathBuf {
|
||||
self.dir.join("edge.json.trial")
|
||||
}
|
||||
|
||||
pub fn revocations_path(&self) -> PathBuf {
|
||||
self.dir.join("share-revocations.json")
|
||||
}
|
||||
|
||||
/// Compile routes with this edge's options (same ports, same directories).
|
||||
pub fn compile(&self, site: &str, hosts: &[(String, String)]) -> String {
|
||||
compile_with(&self.dir, &self.ca, &self.opts, site, hosts)
|
||||
}
|
||||
|
||||
/// Call the admin socket.
|
||||
pub async fn admin(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<serde_json::Value>,
|
||||
) -> JsonResp {
|
||||
unix_json(&self.admin_socket(), method, path, body.as_ref())
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("admin {method} {path}: {e}\n{}", self.stderr()))
|
||||
}
|
||||
|
||||
pub fn write_revocations(&self, epoch: u32, deny: &[String]) {
|
||||
let v = serde_json::json!({ "epoch": epoch, "deny": deny });
|
||||
std::fs::write(self.revocations_path(), v.to_string()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EdgeSpec<'a> {
|
||||
@@ -78,14 +123,15 @@ impl Default for EdgeSpec<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Compile, write certificates and credentials, start the binary. Does not wait for readiness.
|
||||
pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
|
||||
let dir = TempDir::new("edge");
|
||||
for d in ["certs", "state", "creds", "logs"] {
|
||||
std::fs::create_dir_all(dir.join(d)).unwrap();
|
||||
}
|
||||
let sources: Vec<SourceFile> = spec
|
||||
.hosts
|
||||
/// Load and compile; write a Domi certificate for every `tls = "domi"` host that has none.
|
||||
fn compile_with(
|
||||
dir: &TempDir,
|
||||
ca: &TestCa,
|
||||
opts: &CompileOptions,
|
||||
site: &str,
|
||||
hosts: &[(String, String)],
|
||||
) -> String {
|
||||
let sources: Vec<SourceFile> = hosts
|
||||
.iter()
|
||||
.map(|(n, c)| SourceFile {
|
||||
name: n,
|
||||
@@ -95,27 +141,38 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
|
||||
let model = load(
|
||||
&SourceFile {
|
||||
name: "ianitor.toml",
|
||||
contents: spec.site,
|
||||
contents: site,
|
||||
},
|
||||
&sources,
|
||||
)
|
||||
.expect("valid routes");
|
||||
|
||||
let ca = TestCa::new("Ianitor Test CA");
|
||||
for h in model.hosts() {
|
||||
if h.tls == TlsMode::Domi {
|
||||
let crt = dir.join(&format!("certs/{}.crt", h.hostname));
|
||||
if h.tls == TlsMode::Domi && !crt.exists() {
|
||||
let leaf = ca.issue(&[h.hostname.as_str()]);
|
||||
std::fs::write(
|
||||
dir.join(&format!("certs/{}.crt", h.hostname)),
|
||||
leaf.cert_pem,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(&crt, leaf.cert_pem).unwrap();
|
||||
std::fs::write(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap();
|
||||
}
|
||||
}
|
||||
compile::edge(&model, opts).unwrap()
|
||||
}
|
||||
|
||||
/// Compile, write certificates and credentials, start the binary. Does not wait for readiness.
|
||||
pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
|
||||
let dir = TempDir::new("edge");
|
||||
for d in ["certs", "state", "creds", "logs"] {
|
||||
std::fs::create_dir_all(dir.join(d)).unwrap();
|
||||
}
|
||||
let ca = TestCa::new("Ianitor Test CA");
|
||||
std::fs::write(dir.join("creds/share-link-key"), SHARE_KEY).unwrap();
|
||||
for (name, value) in &spec.secrets {
|
||||
std::fs::write(dir.join(&format!("creds/{name}")), value).unwrap();
|
||||
}
|
||||
std::fs::write(
|
||||
dir.join("share-revocations.json"),
|
||||
"{\"epoch\": 0, \"deny\": []}",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let http = local(spec.http_port.unwrap_or_else(free_port));
|
||||
let https = local(free_port());
|
||||
@@ -128,18 +185,10 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
|
||||
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
|
||||
caddy_admin: None,
|
||||
};
|
||||
let config_text = compile::edge(&model, &opts).unwrap();
|
||||
let config_text = compile_with(&dir, &ca, &opts, spec.site, &spec.hosts);
|
||||
std::fs::write(dir.join("edge.json"), &config_text).unwrap();
|
||||
|
||||
let stderr = std::fs::File::create(dir.join("edge.stderr")).unwrap();
|
||||
let mut cmd = Command::new(env!("CARGO_BIN_EXE_ianitor-edge"));
|
||||
cmd.arg("--config").arg(dir.join("edge.json"));
|
||||
cmd.args(&spec.extra_args);
|
||||
cmd.env("CREDENTIALS_DIRECTORY", dir.join("creds"));
|
||||
cmd.env("IANITOR_LOG", spec.log_level);
|
||||
cmd.stdout(Stdio::from(stderr.try_clone().unwrap()))
|
||||
.stderr(Stdio::from(stderr));
|
||||
let child = ChildGuard(cmd.spawn().expect("spawn ianitor-edge"));
|
||||
let child = launch(&dir, &spec.extra_args, spec.log_level);
|
||||
Edge {
|
||||
child,
|
||||
http,
|
||||
@@ -147,15 +196,65 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
|
||||
dir,
|
||||
ca,
|
||||
config_text,
|
||||
opts,
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawn and wait until both listeners accept connections.
|
||||
fn launch(dir: &TempDir, extra_args: &[String], log_level: &str) -> ChildGuard {
|
||||
let stderr = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(dir.join("edge.stderr"))
|
||||
.unwrap();
|
||||
let mut cmd = Command::new(env!("CARGO_BIN_EXE_ianitor-edge"));
|
||||
cmd.arg("--config").arg(dir.join("edge.json"));
|
||||
cmd.arg("--admin-socket").arg(dir.join("admin.sock"));
|
||||
cmd.arg("--share-revocations")
|
||||
.arg(dir.join("share-revocations.json"));
|
||||
cmd.args(extra_args);
|
||||
cmd.env("CREDENTIALS_DIRECTORY", dir.join("creds"));
|
||||
cmd.env("IANITOR_LOG", log_level);
|
||||
cmd.stdout(Stdio::from(stderr.try_clone().unwrap()))
|
||||
.stderr(Stdio::from(stderr));
|
||||
ChildGuard(cmd.spawn().expect("spawn ianitor-edge"))
|
||||
}
|
||||
|
||||
impl Edge {
|
||||
/// Stop edge and start it again on the same directory, config and ports.
|
||||
pub fn restart(&mut self) {
|
||||
let _ = self.child.0.kill();
|
||||
let _ = self.child.0.wait();
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(10);
|
||||
while std::net::TcpStream::connect(self.https).is_ok()
|
||||
&& std::time::Instant::now() < deadline
|
||||
{
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
let _ = std::fs::remove_file(self.admin_socket());
|
||||
self.child = launch(&self.dir, &[], "info");
|
||||
let ok = wait_for_port(self.https, Duration::from_secs(20));
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while !self.admin_socket().exists() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert!(
|
||||
ok && self.admin_socket().exists(),
|
||||
"edge did not restart:\n{}",
|
||||
self.stderr()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawn and wait until both listeners and the admin socket accept connections.
|
||||
pub fn start(spec: EdgeSpec<'_>) -> Edge {
|
||||
let mut e = spawn(spec);
|
||||
let ok = wait_for_port(e.https, Duration::from_secs(20))
|
||||
&& wait_for_port(e.http, Duration::from_secs(5));
|
||||
if !ok || e.exited().is_some() {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while !e.admin_socket().exists() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
if !ok || !e.admin_socket().exists() || e.exited().is_some() {
|
||||
panic!("ianitor-edge did not start:\n{}", e.stderr());
|
||||
}
|
||||
e
|
||||
|
||||
@@ -0,0 +1,470 @@
|
||||
// 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/.
|
||||
|
||||
//! Reload (ROADMAP §8.4, tests first): edge swaps its config in process, so a reload under
|
||||
//! load drops no request and no keep-alive connection; an invalid config is refused and the
|
||||
//! old one keeps serving; a trial config reverts by itself unless control confirms it; the
|
||||
//! admin socket reports health per host and upstream.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
#[cfg(unix)]
|
||||
mod common;
|
||||
|
||||
#[cfg(not(unix))]
|
||||
#[test]
|
||||
fn skipped_on_windows() {
|
||||
eprintln!(
|
||||
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
|
||||
file!()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
mod unix {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::common::{Edge, EdgeSpec, host_file, start};
|
||||
use ianitor_testkit::client::{self, Req};
|
||||
use ianitor_testkit::more::KeepAlive;
|
||||
use ianitor_testkit::upstream::Echo;
|
||||
use serde_json::json;
|
||||
|
||||
fn gen_host(echo: &Echo, generation: &str) -> Vec<(String, String)> {
|
||||
vec![host_file(
|
||||
"app.test",
|
||||
&format!(
|
||||
"upstreams = [\"{}\"]\n[[response_headers]]\naction = \"set\"\nname = \"X-Generation\"\nvalue = \"{generation}\"\n",
|
||||
echo.url()
|
||||
),
|
||||
)]
|
||||
}
|
||||
|
||||
async fn generation(edge: &Edge) -> String {
|
||||
let r = client::https(
|
||||
edge.https,
|
||||
"app.test",
|
||||
edge.roots(),
|
||||
&Req::get("app.test", "/"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.status, 200, "{}", r.text());
|
||||
r.header("x-generation").unwrap_or("none").to_owned()
|
||||
}
|
||||
|
||||
fn sha256(text: &str) -> String {
|
||||
ring::digest::digest(&ring::digest::SHA256, text.as_bytes())
|
||||
.as_ref()
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
|
||||
async fn reload_under_load_drops_nothing() {
|
||||
let echo = Echo::start("app").await;
|
||||
let edge = start(EdgeSpec {
|
||||
hosts: gen_host(&echo, "a"),
|
||||
log_level: "warn",
|
||||
..Default::default()
|
||||
});
|
||||
let config_a = edge.config_text.clone();
|
||||
let config_b = edge.compile("", &gen_host(&echo, "b"));
|
||||
|
||||
let clients: usize = std::env::var("IANITOR_RELOAD_CLIENTS")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(32);
|
||||
let secs: u64 = std::env::var("IANITOR_RELOAD_SECS")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(10);
|
||||
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let ok = Arc::new(AtomicU64::new(0));
|
||||
let errors = Arc::new(AtomicU64::new(0));
|
||||
let resets = Arc::new(AtomicU64::new(0));
|
||||
let mut tasks = Vec::new();
|
||||
for _ in 0..clients {
|
||||
let (stop, ok, errors, resets) =
|
||||
(stop.clone(), ok.clone(), errors.clone(), resets.clone());
|
||||
let (addr, roots) = (edge.https, edge.roots());
|
||||
tasks.push(tokio::spawn(async move {
|
||||
let mut conn = KeepAlive::connect(addr, "app.test", roots).await.unwrap();
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut latencies = Vec::new();
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
let t = Instant::now();
|
||||
match conn.send(&Req::get("app.test", "/load")).await {
|
||||
Ok(r) if r.status == 200 => {
|
||||
ok.fetch_add(1, Ordering::Relaxed);
|
||||
seen.insert(r.header("x-generation").unwrap_or("none").to_owned());
|
||||
latencies.push(t.elapsed());
|
||||
}
|
||||
Ok(_) => {
|
||||
errors.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Err(_) => {
|
||||
// The keep-alive connection is gone.
|
||||
resets.fetch_add(1, Ordering::Relaxed);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
(seen, latencies)
|
||||
}));
|
||||
}
|
||||
|
||||
let started = Instant::now();
|
||||
let mut reloads = 0u64;
|
||||
let mut refused = 0u64;
|
||||
while started.elapsed() < Duration::from_secs(secs) {
|
||||
let text = if reloads.is_multiple_of(2) {
|
||||
&config_b
|
||||
} else {
|
||||
&config_a
|
||||
};
|
||||
let tmp = edge.config_path().with_extension("tmp");
|
||||
std::fs::write(&tmp, text).unwrap();
|
||||
std::fs::rename(&tmp, edge.config_path()).unwrap();
|
||||
let r = edge.admin("POST", "/v1/reload", None).await;
|
||||
if r.status == 200 {
|
||||
reloads += 1;
|
||||
} else {
|
||||
refused += 1;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
let mut all_latencies = Vec::new();
|
||||
let mut both = 0;
|
||||
for t in tasks {
|
||||
let (seen, lat) = t.await.unwrap();
|
||||
if seen.contains("a") && seen.contains("b") {
|
||||
both += 1;
|
||||
}
|
||||
all_latencies.extend(lat);
|
||||
}
|
||||
all_latencies.sort();
|
||||
let pct = |p: f64| {
|
||||
all_latencies
|
||||
.get(((all_latencies.len() as f64 - 1.0) * p) as usize)
|
||||
.copied()
|
||||
.unwrap_or_default()
|
||||
};
|
||||
println!(
|
||||
"RELOAD UNDER LOAD: {clients} keep-alive clients, {secs} s, {reloads} reloads ({refused} refused), \
|
||||
{} requests ok, {} errors, {} connection resets, {both}/{clients} connections saw both configs, \
|
||||
latency p50 {:?} p99 {:?} max {:?}",
|
||||
ok.load(Ordering::Relaxed),
|
||||
errors.load(Ordering::Relaxed),
|
||||
resets.load(Ordering::Relaxed),
|
||||
pct(0.5),
|
||||
pct(0.99),
|
||||
pct(1.0),
|
||||
);
|
||||
assert_eq!(refused, 0, "{}", edge.stderr());
|
||||
assert!(reloads >= secs * 5, "only {reloads} reloads");
|
||||
assert_eq!(errors.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(resets.load(Ordering::Relaxed), 0);
|
||||
assert!(ok.load(Ordering::Relaxed) > 1000);
|
||||
assert_eq!(
|
||||
both, clients,
|
||||
"every keep-alive connection must pick up new configs"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_invalid_config_is_refused_and_the_old_one_keeps_serving() {
|
||||
let echo = Echo::start("app").await;
|
||||
let edge = start(EdgeSpec {
|
||||
hosts: gen_host(&echo, "a"),
|
||||
..Default::default()
|
||||
});
|
||||
let before = edge.admin("GET", "/v1/status", None).await;
|
||||
assert_eq!(before.status, 200, "{}", before.text);
|
||||
let sha = before.json["config_sha256"].as_str().unwrap().to_owned();
|
||||
assert_eq!(sha, sha256(&edge.config_text));
|
||||
|
||||
let good_b = edge.compile("", &gen_host(&echo, "b"));
|
||||
let mut broken_cert: serde_json::Value = serde_json::from_str(&good_b).unwrap();
|
||||
broken_cert["hosts"][0]["tls"]["cert"] = json!("/nonexistent/app.test.crt");
|
||||
let mut moved: serde_json::Value = serde_json::from_str(&good_b).unwrap();
|
||||
moved["https_listen"] = json!("127.0.0.1:1");
|
||||
let mut old_version: serde_json::Value = serde_json::from_str(&good_b).unwrap();
|
||||
old_version["version"] = json!(1);
|
||||
let mut share_without_key: serde_json::Value = serde_json::from_str(&good_b).unwrap();
|
||||
share_without_key["hosts"][0]["share_links"] = json!(true);
|
||||
std::fs::remove_file(edge.dir.join("creds/share-link-key")).unwrap();
|
||||
|
||||
for (what, text) in [
|
||||
("not JSON", "{ not json".to_owned()),
|
||||
("unknown field", good_b.replace("\"hosts\"", "\"hostz\"")),
|
||||
("missing certificate", broken_cert.to_string()),
|
||||
("listen address change", moved.to_string()),
|
||||
("old version", old_version.to_string()),
|
||||
("share links without key", share_without_key.to_string()),
|
||||
] {
|
||||
std::fs::write(edge.config_path(), &text).unwrap();
|
||||
let r = edge.admin("POST", "/v1/reload", None).await;
|
||||
assert_eq!(r.status, 422, "{what}: {}", r.text);
|
||||
assert!(
|
||||
r.json["error"].as_str().is_some_and(|e| !e.is_empty()),
|
||||
"{what}: {}",
|
||||
r.text
|
||||
);
|
||||
assert_eq!(generation(&edge).await, "a", "{what}");
|
||||
let s = edge.admin("GET", "/v1/status", None).await;
|
||||
assert_eq!(s.json["config_sha256"], sha, "{what}");
|
||||
}
|
||||
// A missing file is refused too.
|
||||
std::fs::remove_file(edge.config_path()).unwrap();
|
||||
assert_eq!(edge.admin("POST", "/v1/reload", None).await.status, 422);
|
||||
assert_eq!(generation(&edge).await, "a");
|
||||
|
||||
// And a good one is taken.
|
||||
std::fs::write(edge.config_path(), &good_b).unwrap();
|
||||
let r = edge.admin("POST", "/v1/reload", None).await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
assert_eq!(r.json["config_sha256"], sha256(&good_b));
|
||||
assert_eq!(generation(&edge).await, "b");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_trial_reverts_by_itself_unless_confirmed() {
|
||||
let echo = Echo::start("app").await;
|
||||
let edge = start(EdgeSpec {
|
||||
hosts: gen_host(&echo, "a"),
|
||||
..Default::default()
|
||||
});
|
||||
let config_b = edge.compile("", &gen_host(&echo, "b"));
|
||||
std::fs::write(edge.trial_path(), &config_b).unwrap();
|
||||
|
||||
// Not confirmed: back to "a" after the deadline, without anyone asking.
|
||||
let r = edge
|
||||
.admin(
|
||||
"POST",
|
||||
"/v1/trial",
|
||||
Some(json!({ "confirm_within_secs": 2 })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
let trial_sha = r.json["config_sha256"].as_str().unwrap().to_owned();
|
||||
assert_eq!(trial_sha, sha256(&config_b));
|
||||
assert_eq!(generation(&edge).await, "b");
|
||||
let s = edge.admin("GET", "/v1/status", None).await;
|
||||
assert_eq!(s.json["trial"]["config_sha256"], trial_sha);
|
||||
// No reload and no second trial while one runs.
|
||||
assert_eq!(edge.admin("POST", "/v1/reload", None).await.status, 409);
|
||||
assert_eq!(
|
||||
edge.admin(
|
||||
"POST",
|
||||
"/v1/trial",
|
||||
Some(json!({ "confirm_within_secs": 2 }))
|
||||
)
|
||||
.await
|
||||
.status,
|
||||
409
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(3500)).await;
|
||||
assert_eq!(generation(&edge).await, "a");
|
||||
let s = edge.admin("GET", "/v1/status", None).await;
|
||||
assert!(s.json["trial"].is_null(), "{}", s.text);
|
||||
assert_eq!(s.json["config_sha256"], sha256(&edge.config_text));
|
||||
// Confirming a trial that already reverted fails.
|
||||
let r = edge
|
||||
.admin(
|
||||
"POST",
|
||||
"/v1/confirm",
|
||||
Some(json!({ "config_sha256": trial_sha })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 409, "{}", r.text);
|
||||
|
||||
// Confirmed: stays.
|
||||
let r = edge
|
||||
.admin(
|
||||
"POST",
|
||||
"/v1/trial",
|
||||
Some(json!({ "confirm_within_secs": 2 })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
let wrong = edge
|
||||
.admin(
|
||||
"POST",
|
||||
"/v1/confirm",
|
||||
Some(json!({ "config_sha256": "00" })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(wrong.status, 409);
|
||||
let r = edge
|
||||
.admin(
|
||||
"POST",
|
||||
"/v1/confirm",
|
||||
Some(json!({ "config_sha256": trial_sha })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
tokio::time::sleep(Duration::from_millis(2500)).await;
|
||||
assert_eq!(generation(&edge).await, "b");
|
||||
|
||||
// Aborted: back at once. Abort is idempotent.
|
||||
std::fs::write(edge.trial_path(), &edge.config_text).unwrap();
|
||||
let r = edge
|
||||
.admin(
|
||||
"POST",
|
||||
"/v1/trial",
|
||||
Some(json!({ "confirm_within_secs": 30 })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
assert_eq!(generation(&edge).await, "a");
|
||||
let r = edge.admin("POST", "/v1/abort", None).await;
|
||||
assert_eq!(r.status, 200);
|
||||
assert_eq!(r.json["reverted"], true);
|
||||
assert_eq!(generation(&edge).await, "b");
|
||||
let r = edge.admin("POST", "/v1/abort", None).await;
|
||||
assert_eq!(r.status, 200);
|
||||
assert_eq!(r.json["reverted"], false);
|
||||
|
||||
// A broken trial is refused and nothing changes.
|
||||
std::fs::write(edge.trial_path(), "{}").unwrap();
|
||||
let r = edge
|
||||
.admin(
|
||||
"POST",
|
||||
"/v1/trial",
|
||||
Some(json!({ "confirm_within_secs": 30 })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 422);
|
||||
assert_eq!(generation(&edge).await, "b");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn status_reports_health_per_host_and_upstream() {
|
||||
let good = Echo::start("good").await;
|
||||
let sick = Echo::start("sick").await;
|
||||
sick.health.store(503, Ordering::SeqCst);
|
||||
let closed = ianitor_testkit::upstream::closed_port();
|
||||
let plain = Echo::start("plain").await;
|
||||
let edge = start(EdgeSpec {
|
||||
hosts: vec![
|
||||
host_file(
|
||||
"mixed.test",
|
||||
&format!(
|
||||
"upstreams = [\"{}\", \"{}\", \"http://127.0.0.1:{closed}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n",
|
||||
good.url(),
|
||||
sick.url()
|
||||
),
|
||||
),
|
||||
host_file(
|
||||
"plain.test",
|
||||
&format!("upstreams = [\"{}\"]\n", plain.url()),
|
||||
),
|
||||
],
|
||||
..Default::default()
|
||||
});
|
||||
tokio::time::sleep(Duration::from_millis(2500)).await;
|
||||
let s = edge.admin("GET", "/v1/status", None).await;
|
||||
assert_eq!(s.status, 200, "{}", s.text);
|
||||
let hosts = s.json["hosts"].as_array().unwrap();
|
||||
let mixed = hosts
|
||||
.iter()
|
||||
.find(|h| h["hostname"] == "mixed.test")
|
||||
.unwrap();
|
||||
assert_eq!(mixed["health_check"], true);
|
||||
let ups = mixed["upstreams"].as_array().unwrap();
|
||||
assert_eq!(ups.len(), 3);
|
||||
assert_eq!(ups[0]["healthy"], true, "{}", s.text);
|
||||
assert_eq!(ups[1]["healthy"], false);
|
||||
assert_eq!(ups[2]["healthy"], false);
|
||||
let last = |u: &serde_json::Value| u["checks"].as_array().unwrap().last().unwrap().clone();
|
||||
assert_eq!(last(&ups[0])["ok"], true);
|
||||
assert!(last(&ups[0])["latency_ms"].is_u64());
|
||||
assert_eq!(last(&ups[1])["kind"], "server_error");
|
||||
assert_eq!(last(&ups[1])["status"], 503);
|
||||
assert_eq!(last(&ups[2])["kind"], "refused");
|
||||
assert!(ups[0]["checks"].as_array().unwrap().len() <= 5);
|
||||
assert!(mixed["certificate"]["state"] == "ok");
|
||||
let plain_h = hosts
|
||||
.iter()
|
||||
.find(|h| h["hostname"] == "plain.test")
|
||||
.unwrap();
|
||||
assert_eq!(plain_h["health_check"], false);
|
||||
assert!(
|
||||
plain_h["upstreams"][0]["checks"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
// During a trial, watched hosts without a health check get `GET /` probes; any answer
|
||||
// below 500 counts as alive. Hosts with one are checked at least every `every_secs`.
|
||||
std::fs::write(edge.trial_path(), &edge.config_text).unwrap();
|
||||
let r = edge
|
||||
.admin(
|
||||
"POST",
|
||||
"/v1/trial",
|
||||
Some(json!({ "confirm_within_secs": 30, "watch_hosts": ["plain.test"], "watch_every_secs": 1 })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
tokio::time::sleep(Duration::from_millis(2500)).await;
|
||||
let s = edge.admin("GET", "/v1/status", None).await;
|
||||
let plain_h = s.json["hosts"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|h| h["hostname"] == "plain.test")
|
||||
.unwrap()
|
||||
.clone();
|
||||
let checks = plain_h["upstreams"][0]["checks"].as_array().unwrap();
|
||||
assert!(!checks.is_empty(), "{}", s.text);
|
||||
assert_eq!(checks.last().unwrap()["ok"], true);
|
||||
assert_eq!(checks.last().unwrap()["source"], "watch");
|
||||
assert!(
|
||||
plain
|
||||
.requests()
|
||||
.iter()
|
||||
.any(|r| r.path == "/" && r.header("host") == Some(b"plain.test".as_slice()))
|
||||
);
|
||||
edge.admin("POST", "/v1/abort", None).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_admin_socket_is_private() {
|
||||
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
|
||||
let echo = Echo::start("app").await;
|
||||
let edge = start(EdgeSpec {
|
||||
hosts: gen_host(&echo, "a"),
|
||||
..Default::default()
|
||||
});
|
||||
let meta = std::fs::metadata(edge.admin_socket()).unwrap();
|
||||
assert!(meta.file_type().is_socket());
|
||||
assert_eq!(meta.permissions().mode() & 0o007, 0, "no access for others");
|
||||
// Unknown paths and bad bodies get typed errors, not a crash.
|
||||
assert_eq!(edge.admin("GET", "/v1/nope", None).await.status, 404);
|
||||
let r = edge
|
||||
.admin(
|
||||
"POST",
|
||||
"/v1/trial",
|
||||
Some(json!({ "confirm_within_secs": 2, "extra": 1 })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 400, "{}", r.text);
|
||||
let r = edge
|
||||
.admin(
|
||||
"POST",
|
||||
"/v1/trial",
|
||||
Some(json!({ "confirm_within_secs": 0 })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 400, "{}", r.text);
|
||||
assert_eq!(generation(&edge).await, "a");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
// 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/.
|
||||
|
||||
//! Share links in edge (ROADMAP §6 phase 2, tests first): a valid link lets the visitor in on
|
||||
//! its host and prefix only, without forward-auth; the token travels in the URL once and is
|
||||
//! then a path-scoped cookie; it never reaches the upstream or a log; expired, altered,
|
||||
//! wrong-host, wrong-path, stopped and password-less tokens are refused; wrong passwords are
|
||||
//! throttled; no path trick escapes the prefix.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
#[cfg(unix)]
|
||||
mod common;
|
||||
|
||||
#[cfg(not(unix))]
|
||||
#[test]
|
||||
fn skipped_on_windows() {
|
||||
eprintln!(
|
||||
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
|
||||
file!()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
mod unix {
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::common::{Edge, EdgeSpec, SHARE_KEY, host_file, start};
|
||||
use ianitor_core::share::{LinkSpec, ShareId, ShareKey, mint};
|
||||
use ianitor_testkit::authelia::MockAuthelia;
|
||||
use ianitor_testkit::client::{self, Req, Resp};
|
||||
use ianitor_testkit::more::https_raw;
|
||||
use ianitor_testkit::upstream::Echo;
|
||||
|
||||
const HOST: &str = "share.test";
|
||||
|
||||
fn now() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs()
|
||||
}
|
||||
|
||||
fn key() -> ShareKey {
|
||||
ShareKey::new(SHARE_KEY).unwrap()
|
||||
}
|
||||
|
||||
fn link(host: &str, id: u8, prefix: &str, expires_at: u64, password: Option<&str>) -> String {
|
||||
mint(
|
||||
&key(),
|
||||
host,
|
||||
&LinkSpec {
|
||||
id: ShareId([id; 16]),
|
||||
epoch: 0,
|
||||
expires_at,
|
||||
prefix,
|
||||
password,
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
struct Env {
|
||||
edge: Edge,
|
||||
echo: Echo,
|
||||
auth: MockAuthelia,
|
||||
}
|
||||
|
||||
async fn env() -> Env {
|
||||
let auth = MockAuthelia::start().await;
|
||||
let echo = Echo::start("app").await;
|
||||
let site = format!("[forward_auth]\nurl = \"{}\"\n", auth.url());
|
||||
let edge = start(EdgeSpec {
|
||||
site: &site,
|
||||
hosts: vec![
|
||||
host_file(
|
||||
HOST,
|
||||
&format!(
|
||||
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\nshare_links = true\naccess_log = \"truncated\"\n",
|
||||
echo.url()
|
||||
),
|
||||
),
|
||||
host_file(
|
||||
"closed.test",
|
||||
&format!(
|
||||
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\nshare_links = false\n",
|
||||
echo.url()
|
||||
),
|
||||
),
|
||||
],
|
||||
log_level: "debug",
|
||||
..Default::default()
|
||||
});
|
||||
Env { edge, echo, auth }
|
||||
}
|
||||
|
||||
impl Env {
|
||||
async fn get(&self, host: &str, path: &str, cookie: Option<&str>) -> Resp {
|
||||
let mut req = Req::get(host, path);
|
||||
if let Some(c) = cookie {
|
||||
req = req.header("cookie", c);
|
||||
}
|
||||
client::https(self.edge.https, host, self.edge.roots(), &req)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn post_password(&self, token: &str, password: &str) -> Resp {
|
||||
let body = format!("t={}&password={}", urlencode(token), urlencode(password));
|
||||
let req = Req::new("POST", HOST, "/.well-known/ianitor/share")
|
||||
.header("content-type", "application/x-www-form-urlencoded")
|
||||
.body(body.as_bytes());
|
||||
client::https(self.edge.https, HOST, self.edge.roots(), &req)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Requests the upstream saw (health checks excluded).
|
||||
fn upstream_paths(&self) -> Vec<String> {
|
||||
self.echo.proxied().iter().map(|r| r.path.clone()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn urlencode(s: &str) -> String {
|
||||
s.bytes()
|
||||
.map(|b| {
|
||||
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
|
||||
(b as char).to_string()
|
||||
} else {
|
||||
format!("%{b:02X}")
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `name=value` part of the share cookie a response sets.
|
||||
fn share_cookie(r: &Resp) -> String {
|
||||
let sc = r
|
||||
.header_all("set-cookie")
|
||||
.into_iter()
|
||||
.find(|c| c.starts_with("__Secure-ianitor-share="))
|
||||
.unwrap_or_else(|| panic!("no share cookie in {:?}", r.headers));
|
||||
sc.split(';').next().unwrap().to_owned()
|
||||
}
|
||||
|
||||
fn assert_visitor_page(r: &Resp, status: u16, heading: &str) {
|
||||
assert_eq!(r.status, status, "{}", r.text());
|
||||
assert!(r.text().contains(heading), "{heading}: {}", r.text());
|
||||
assert_eq!(r.header("cache-control"), Some("no-store"));
|
||||
assert_eq!(r.header("referrer-policy"), Some("no-referrer"));
|
||||
assert!(
|
||||
r.header("content-security-policy")
|
||||
.is_some_and(|c| c.contains("default-src 'none'"))
|
||||
);
|
||||
assert!(r.header("content-type").unwrap().starts_with("text/html"));
|
||||
assert!(!r.text().contains("<script"), "no JavaScript");
|
||||
assert!(
|
||||
!r.text().contains("http://") && !r.text().contains("https://"),
|
||||
"no external requests"
|
||||
);
|
||||
assert!(r.body.len() < 8 * 1024);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_valid_link_lets_the_visitor_in_without_forward_auth() {
|
||||
let e = env().await;
|
||||
let t = link(HOST, 1, "/albums", now() + 3600, None);
|
||||
|
||||
let r = e
|
||||
.get(HOST, &format!("/albums/summer?x=1&share={t}&y=2"), None)
|
||||
.await;
|
||||
assert_eq!(r.status, 303, "{}", r.text());
|
||||
assert_eq!(r.header("location"), Some("/albums/summer?x=1&y=2"));
|
||||
assert_eq!(r.header("referrer-policy"), Some("no-referrer"));
|
||||
let set = r
|
||||
.header_all("set-cookie")
|
||||
.into_iter()
|
||||
.find(|c| c.starts_with("__Secure-ianitor-share="))
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
for attr in [
|
||||
"Path=/albums",
|
||||
"HttpOnly",
|
||||
"Secure",
|
||||
"SameSite=Lax",
|
||||
"Max-Age=",
|
||||
] {
|
||||
assert!(set.contains(attr), "{attr} missing in {set}");
|
||||
}
|
||||
assert!(!set.contains(&t), "the cookie is not the link token");
|
||||
assert!(
|
||||
e.upstream_paths().is_empty(),
|
||||
"the token request never reached the upstream"
|
||||
);
|
||||
let auth_calls = e.auth.requests().len();
|
||||
|
||||
let cookie = share_cookie(&r);
|
||||
let r = e
|
||||
.get(
|
||||
HOST,
|
||||
"/albums/summer?x=1&y=2",
|
||||
Some(&format!("{cookie}; other=1")),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text());
|
||||
assert_eq!(
|
||||
e.auth.requests().len(),
|
||||
auth_calls,
|
||||
"no forward-auth for a share visitor"
|
||||
);
|
||||
let seen = e.echo.proxied();
|
||||
let last = seen.last().unwrap();
|
||||
assert_eq!(last.path, "/albums/summer");
|
||||
let cookie_sent = last
|
||||
.header("cookie")
|
||||
.map(|c| String::from_utf8_lossy(c).into_owned())
|
||||
.unwrap_or_default();
|
||||
assert!(
|
||||
!cookie_sent.contains("ianitor-share"),
|
||||
"share cookie stripped: {cookie_sent}"
|
||||
);
|
||||
assert!(
|
||||
cookie_sent.contains("other=1"),
|
||||
"other cookies kept: {cookie_sent}"
|
||||
);
|
||||
assert!(last.header("referer").is_none());
|
||||
|
||||
// The prefix itself and deeper paths are covered.
|
||||
assert_eq!(e.get(HOST, "/albums", Some(&cookie)).await.status, 200);
|
||||
assert_eq!(
|
||||
e.get(HOST, "/albums/a/b/c.jpg", Some(&cookie)).await.status,
|
||||
200
|
||||
);
|
||||
|
||||
// Neither the token nor the cookie appears in any log.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let logs = e.edge.all_output();
|
||||
assert!(!logs.contains(&t[5..40]), "token in logs");
|
||||
assert!(!logs.contains(&cookie[30..60]), "cookie in logs");
|
||||
assert!(
|
||||
!e.edge.access_log().contains("share="),
|
||||
"query in access log"
|
||||
);
|
||||
for r in e.echo.requests() {
|
||||
for (_, v) in &r.headers {
|
||||
assert!(!String::from_utf8_lossy(v).contains(&t[5..40]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn bad_tokens_get_plain_english_pages() {
|
||||
let e = env().await;
|
||||
// Expired: the signature proves the date.
|
||||
let t = link(HOST, 2, "/", now() - 10, None);
|
||||
let r = e.get(HOST, &format!("/?share={t}"), None).await;
|
||||
assert_visitor_page(&r, 410, "This link has expired");
|
||||
// Another host's token, an altered token, a token made with another key.
|
||||
let other = link("closed.test", 3, "/", now() + 3600, None);
|
||||
let mut altered = link(HOST, 4, "/", now() + 3600, None);
|
||||
let last = altered.pop().unwrap();
|
||||
altered.push(if last == 'A' { 'B' } else { 'A' });
|
||||
let foreign = mint(
|
||||
&ShareKey::new(b"another-key-another-key-another-key-0000").unwrap(),
|
||||
HOST,
|
||||
&LinkSpec {
|
||||
id: ShareId([5; 16]),
|
||||
epoch: 0,
|
||||
expires_at: now() + 3600,
|
||||
prefix: "/",
|
||||
password: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
for bad in [other, altered, foreign, "ish1.garbage".to_owned()] {
|
||||
let r = e.get(HOST, &format!("/?share={bad}"), None).await;
|
||||
assert_visitor_page(&r, 403, "This link no longer works");
|
||||
}
|
||||
// Escaping: only the hostname and the date come from the request.
|
||||
let r = e.get(HOST, "/?share=ish1.%3Cscript%3E", None).await;
|
||||
assert!(!r.text().contains("<script>"));
|
||||
assert!(e.upstream_paths().is_empty());
|
||||
|
||||
// A `share` parameter that is not ours is left alone (goes to the normal sign-in).
|
||||
let r = e.get(HOST, "/?share=holiday", None).await;
|
||||
assert_eq!(r.status, 302, "forward-auth portal redirect");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_link_outside_its_prefix_falls_back_to_sign_in_and_never_leaks() {
|
||||
let e = env().await;
|
||||
let t = link(HOST, 6, "/albums", now() + 3600, None);
|
||||
let r = e.get(HOST, &format!("/private?share={t}"), None).await;
|
||||
assert_eq!(r.status, 302, "normal sign-in: {}", r.text());
|
||||
// Signed in, the request goes through, but the token is not passed on.
|
||||
let r = e
|
||||
.get(
|
||||
HOST,
|
||||
&format!("/private?a=1&share={t}"),
|
||||
Some("authelia_session=good"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 200);
|
||||
let body: serde_json::Value = serde_json::from_slice(&r.body).unwrap();
|
||||
assert_eq!(body["query"], "a=1", "token stripped before the upstream");
|
||||
|
||||
// On a host without share links the token gives nothing.
|
||||
let t2 = link("closed.test", 7, "/", now() + 3600, None);
|
||||
let r = e.get("closed.test", &format!("/?share={t2}"), None).await;
|
||||
assert_eq!(r.status, 302);
|
||||
// ...and is not passed on to the auth server or the upstream either.
|
||||
let r = e
|
||||
.get(
|
||||
"closed.test",
|
||||
&format!("/x?b=2&share={t2}"),
|
||||
Some("authelia_session=good"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 200);
|
||||
let body: serde_json::Value = serde_json::from_slice(&r.body).unwrap();
|
||||
assert_eq!(body["query"], "b=2");
|
||||
for req in e.auth.requests() {
|
||||
for (_, v) in &req.headers {
|
||||
assert!(
|
||||
!String::from_utf8_lossy(v).contains("ish1."),
|
||||
"token sent to the auth server"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_password_link_asks_checks_and_throttles() {
|
||||
let e = env().await;
|
||||
let t = link(HOST, 8, "/docs", now() + 3600, Some("correct horse"));
|
||||
|
||||
let r = e.get(HOST, &format!("/docs/a?share={t}"), None).await;
|
||||
assert_visitor_page(&r, 401, "This link is protected");
|
||||
assert!(r.text().contains("share.test"));
|
||||
assert!(r.text().contains("action=\"/.well-known/ianitor/share\""));
|
||||
assert!(r.text().contains("name=\"password\""));
|
||||
assert!(r.text().contains("The link works until"));
|
||||
assert!(share_cookie_absent(&r));
|
||||
|
||||
let r = e.post_password(&t, "wrong password").await;
|
||||
assert_visitor_page(&r, 401, "That password is not right");
|
||||
assert!(share_cookie_absent(&r));
|
||||
|
||||
let r = e.post_password(&t, "correct horse").await;
|
||||
assert_eq!(r.status, 303, "{}", r.text());
|
||||
assert_eq!(r.header("location"), Some("/docs"));
|
||||
let cookie = share_cookie(&r);
|
||||
assert_eq!(e.get(HOST, "/docs/a", Some(&cookie)).await.status, 200);
|
||||
|
||||
// The cookie of a password link cannot be turned into a link that skips the password.
|
||||
let v = cookie.split_once('=').unwrap().1.to_owned();
|
||||
let r = e
|
||||
.get(
|
||||
HOST,
|
||||
&format!("/docs?share={}", v.replacen("iss1.", "ish1.", 1)),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_ne!(r.status, 303);
|
||||
|
||||
// Five wrong tries a minute, then a pause (the right password too).
|
||||
let t2 = link(HOST, 9, "/docs", now() + 3600, Some("correct horse"));
|
||||
for _ in 0..5 {
|
||||
assert_eq!(e.post_password(&t2, "nope nope").await.status, 401);
|
||||
}
|
||||
let r = e.post_password(&t2, "nope nope").await;
|
||||
assert_visitor_page(&r, 429, "Too many tries");
|
||||
let r = e.post_password(&t2, "correct horse").await;
|
||||
assert_eq!(r.status, 429);
|
||||
// Other links are not affected.
|
||||
let t3 = link(HOST, 10, "/docs", now() + 3600, Some("correct horse"));
|
||||
assert_eq!(e.post_password(&t3, "correct horse").await.status, 303);
|
||||
// The password never reaches a log.
|
||||
assert!(!e.edge.all_output().contains("correct horse"));
|
||||
}
|
||||
|
||||
fn share_cookie_absent(r: &Resp) -> bool {
|
||||
!r.header_all("set-cookie")
|
||||
.iter()
|
||||
.any(|c| c.starts_with("__Secure-ianitor-share="))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn no_path_trick_escapes_the_cookie_prefix() {
|
||||
let e = env().await;
|
||||
let t = link(HOST, 11, "/a", now() + 3600, None);
|
||||
let r = e.get(HOST, &format!("/a?share={t}"), None).await;
|
||||
let cookie = share_cookie(&r);
|
||||
let before = e.upstream_paths().len();
|
||||
for path in [
|
||||
"/ab",
|
||||
"/A",
|
||||
"/A/x",
|
||||
"/b",
|
||||
"/a/../b",
|
||||
"/a/%2e%2e/b",
|
||||
"/a/%2E%2E/b",
|
||||
"/a/%252e%252e/b",
|
||||
"/a%2f..%2fb",
|
||||
"/a//b",
|
||||
"//a/b",
|
||||
"/a/..;/b",
|
||||
"/a/\\..\\b",
|
||||
"/a\\..\\b",
|
||||
] {
|
||||
let raw = format!(
|
||||
"GET {path} HTTP/1.1\r\nHost: {HOST}\r\nCookie: {cookie}\r\nConnection: close\r\n\r\n"
|
||||
);
|
||||
let r = https_raw(e.edge.https, HOST, e.edge.roots(), raw.as_bytes())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(r.status, 200, "{path} got through: {}", r.text());
|
||||
}
|
||||
assert_eq!(
|
||||
e.upstream_paths().len(),
|
||||
before,
|
||||
"no escaped request reached the upstream: {:?}",
|
||||
e.upstream_paths()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn stopped_links_and_stop_all_take_effect_at_once() {
|
||||
let e = env().await;
|
||||
let t = link(HOST, 12, "/", now() + 3600, None);
|
||||
let keep = link(HOST, 13, "/", now() + 3600, None);
|
||||
let cookie = share_cookie(&e.get(HOST, &format!("/?share={t}"), None).await);
|
||||
let keep_cookie = share_cookie(&e.get(HOST, &format!("/?share={keep}"), None).await);
|
||||
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200);
|
||||
|
||||
e.edge.write_revocations(0, &[ShareId([12; 16]).to_hex()]);
|
||||
let r = e
|
||||
.edge
|
||||
.admin("POST", "/v1/share-revocations/reload", None)
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
assert_eq!(
|
||||
e.get(HOST, "/", Some(&cookie)).await.status,
|
||||
302,
|
||||
"back to sign-in"
|
||||
);
|
||||
let r = e.get(HOST, &format!("/?share={t}"), None).await;
|
||||
assert_visitor_page(&r, 403, "This link no longer works");
|
||||
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 200);
|
||||
|
||||
// Stop all: a new epoch ends every older link.
|
||||
e.edge.write_revocations(1, &[]);
|
||||
e.edge
|
||||
.admin("POST", "/v1/share-revocations/reload", None)
|
||||
.await;
|
||||
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 302);
|
||||
|
||||
// The epoch never goes back: a lower one is refused and the old state kept, so a
|
||||
// control that lost its records cannot revive stopped links.
|
||||
let fresh = mint(
|
||||
&key(),
|
||||
HOST,
|
||||
&LinkSpec {
|
||||
id: ShareId([14; 16]),
|
||||
epoch: 1,
|
||||
expires_at: now() + 3600,
|
||||
prefix: "/",
|
||||
password: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let fresh_cookie = share_cookie(&e.get(HOST, &format!("/?share={fresh}"), None).await);
|
||||
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200);
|
||||
e.edge.write_revocations(0, &[]);
|
||||
let r = e
|
||||
.edge
|
||||
.admin("POST", "/v1/share-revocations/reload", None)
|
||||
.await;
|
||||
assert_eq!(r.status, 422, "{}", r.text);
|
||||
assert!(r.text.contains("epoch"), "{}", r.text);
|
||||
assert_eq!(
|
||||
e.get(HOST, "/", Some(&keep_cookie)).await.status,
|
||||
302,
|
||||
"still stopped"
|
||||
);
|
||||
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200);
|
||||
|
||||
// Without the admin call, edge notices a changed file within 5 s.
|
||||
e.edge.write_revocations(1, &[ShareId([14; 16]).to_hex()]);
|
||||
tokio::time::sleep(Duration::from_secs(6)).await;
|
||||
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 302);
|
||||
// ...and a lower epoch written behind its back is refused there too.
|
||||
e.edge.write_revocations(0, &[]);
|
||||
tokio::time::sleep(Duration::from_secs(6)).await;
|
||||
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 302);
|
||||
assert!(e.edge.stderr().contains("epoch"), "the refusal is logged");
|
||||
|
||||
// Edge remembers the highest epoch in its own state: after a restart a lower one
|
||||
// (control's files rolled back) is still refused.
|
||||
e.edge.write_revocations(1, &[]);
|
||||
e.edge
|
||||
.admin("POST", "/v1/share-revocations/reload", None)
|
||||
.await;
|
||||
let mut e = e;
|
||||
e.edge.restart();
|
||||
e.edge.write_revocations(0, &[]);
|
||||
let r = e
|
||||
.edge
|
||||
.admin("POST", "/v1/share-revocations/reload", None)
|
||||
.await;
|
||||
assert_eq!(r.status, 422, "{}", r.text);
|
||||
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 302);
|
||||
|
||||
// A broken file keeps the last good state; a missing one stops all share access.
|
||||
e.edge.write_revocations(1, &[]);
|
||||
e.edge
|
||||
.admin("POST", "/v1/share-revocations/reload", None)
|
||||
.await;
|
||||
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200);
|
||||
std::fs::write(e.edge.revocations_path(), "{ broken").unwrap();
|
||||
let r = e
|
||||
.edge
|
||||
.admin("POST", "/v1/share-revocations/reload", None)
|
||||
.await;
|
||||
assert_eq!(r.status, 422);
|
||||
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200);
|
||||
std::fs::remove_file(e.edge.revocations_path()).unwrap();
|
||||
e.edge
|
||||
.admin("POST", "/v1/share-revocations/reload", None)
|
||||
.await;
|
||||
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 302);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_unreadable_epoch_floor_refuses_share_links() {
|
||||
let mut e = env().await;
|
||||
let t = link(HOST, 15, "/", now() + 3600, None);
|
||||
let cookie = share_cookie(&e.get(HOST, &format!("/?share={t}"), None).await);
|
||||
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200);
|
||||
std::fs::write(e.edge.dir.join("state/share-epoch-floor"), "garbage").unwrap();
|
||||
e.edge.restart();
|
||||
assert_eq!(
|
||||
e.get(HOST, "/", Some(&cookie)).await.status,
|
||||
302,
|
||||
"fails closed"
|
||||
);
|
||||
let r = e
|
||||
.edge
|
||||
.admin("POST", "/v1/share-revocations/reload", None)
|
||||
.await;
|
||||
assert_eq!(r.status, 422, "{}", r.text);
|
||||
assert!(e.edge.stderr().contains("share-epoch-floor"));
|
||||
// A missing floor is simply 0.
|
||||
std::fs::remove_file(e.edge.dir.join("state/share-epoch-floor")).unwrap();
|
||||
e.edge.restart();
|
||||
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// 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 wrong-password throttle (QC fix round 1, M1): the id it keys on is unproven (anyone can
|
||||
//! forge a token with any id), so it must not be possible to reset a real link's counter by
|
||||
//! flooding it with made-up ids, and a full table refuses instead of forgetting.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::net::IpAddr;
|
||||
|
||||
use ianitor_core::share::ShareId;
|
||||
use ianitor_edge::share::Throttle;
|
||||
|
||||
fn junk(n: u32) -> ShareId {
|
||||
let mut id = [0u8; 16];
|
||||
id[..4].copy_from_slice(&n.to_be_bytes());
|
||||
id[15] = 1;
|
||||
ShareId(id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junk_ids_from_the_same_network_cannot_flush_a_link_counter() {
|
||||
let t = Throttle::default();
|
||||
let victim = ShareId([7; 16]);
|
||||
let ip: IpAddr = "192.0.2.10".parse().unwrap();
|
||||
for _ in 0..5 {
|
||||
t.failed(victim, Some(ip));
|
||||
}
|
||||
assert!(!t.allowed(victim, Some(ip)), "locked after 5 failures");
|
||||
for n in 0u32..10_000 {
|
||||
t.failed(junk(n), Some(ip));
|
||||
}
|
||||
assert!(
|
||||
!t.allowed(victim, Some(ip)),
|
||||
"10,000 junk failures reset the victim's counter"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_network_is_limited_across_all_links() {
|
||||
let t = Throttle::default();
|
||||
let ip: IpAddr = "192.0.2.10".parse().unwrap();
|
||||
let neighbour: IpAddr = "192.0.2.77".parse().unwrap();
|
||||
let elsewhere: IpAddr = "198.51.100.1".parse().unwrap();
|
||||
let mut n = 0;
|
||||
while t.allowed(junk(n), Some(ip)) {
|
||||
t.failed(junk(n), Some(ip));
|
||||
n += 1;
|
||||
assert!(n < 1000, "no limit per network");
|
||||
}
|
||||
assert!(n <= 20, "{n} wrong passwords a minute from one network");
|
||||
// The same /24 is limited for a link it never tried; other networks are not.
|
||||
assert!(!t.allowed(ShareId([9; 16]), Some(neighbour)));
|
||||
assert!(t.allowed(ShareId([9; 16]), Some(elsewhere)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_table_refuses_new_visitors_instead_of_forgetting_old_ones() {
|
||||
let t = Throttle::default();
|
||||
let victim = ShareId([7; 16]);
|
||||
let ip: IpAddr = "192.0.2.10".parse().unwrap();
|
||||
for _ in 0..5 {
|
||||
t.failed(victim, Some(ip));
|
||||
}
|
||||
// Fill the table from many networks, one failure each.
|
||||
for n in 0u32..20_000 {
|
||||
let other = IpAddr::from([10, (n >> 16) as u8, (n >> 8) as u8, n as u8]);
|
||||
t.failed(junk(n), Some(other));
|
||||
}
|
||||
assert!(
|
||||
!t.allowed(victim, Some(ip)),
|
||||
"the victim's counter survived"
|
||||
);
|
||||
let newcomer = IpAddr::from([203, 0, 113, 5]);
|
||||
assert!(
|
||||
!t.allowed(ShareId([3; 16]), Some(newcomer)),
|
||||
"full table: refuse, don't forget"
|
||||
);
|
||||
}
|
||||
+40
-2
@@ -113,6 +113,16 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit
|
||||
3. Does Pingora build on Windows? If not, develop in WSL2 and note it in CLAUDE.md. (phase 1)
|
||||
**Answer: it compiles and the unit tests run on Windows (MSVC, Rust 1.99), but the README calls Windows support "preliminary by community's best effort only".** Unix-only parts include graceful upgrade, the in-process runner and the integration tests. Caddy and Pebble are not on this Windows box. So the edge integration tests, the diff suite and the ACME test run in WSL2 Debian, as noted in CLAUDE.md. One gotcha: libz-ng-sys's CMake build fails under a very deep CARGO_TARGET_DIR (MSBuild path length). [S github.com/cloudflare/pingora README; local builds 2026-11-07]
|
||||
4. Pingora graceful reload behaviour under load. (phase 2)
|
||||
**Answer: no Pingora graceful upgrade for config changes; edge swaps its config in process.** A reload builds a complete new runtime from the config file (secrets, certificates, share-link key) and installs it with one atomic pointer swap (`arc-swap`); listeners, TLS sessions and keep-alive connections are untouched, each request keeps the runtime it started with, and the next request on the same connection uses the new one. A config that fails to build is refused and the old one keeps serving; listen addresses change only with a restart. Control triggers it through edge's admin Unix socket (mode 0660, never a TCP port) as a *trial* that edge reverts by itself unless control confirms it in time, so a control crash mid-apply cannot strand edge on an unverified config. Pingora's graceful upgrade (new process takes the listening sockets, old one drains for the grace period) stays for binary upgrades only: it needs a second process and fd passing, and idle keep-alive connections on the old process are closed after the drain, which clients see as a reset on their next request; it was not measured. [J]
|
||||
Measured (`crates/edge/tests/reload.rs`, debug build, WSL2 Debian, 16 cores, one local upstream; alternating two configs that differ in a response header, `POST /v1/reload` every 100 ms, each client one TLS keep-alive connection sending requests back to back):
|
||||
|
||||
| Clients | Duration | Reloads | Requests | Errors | Connection resets | Connections that saw both configs | p50 / p99 / max latency |
|
||||
|--:|--:|--:|--:|--:|--:|--:|:--|
|
||||
| 32 | 10 s | 98 | 30,198 | 0 | 0 | 32/32 | 10.5 / 17.2 / 132 ms |
|
||||
| 64 | 30 s | 294 | 95,229 | 0 | 0 | 64/64 | 20.0 / 31.9 / 190 ms |
|
||||
| 128 | 30 s | 292 | 87,796 | 0 | 0 | 128/128 | 43.1 / 69.1 / 215 ms |
|
||||
|
||||
Reproduce: `IANITOR_RELOAD_CLIENTS=64 IANITOR_RELOAD_SECS=30 cargo test -p ianitor-edge --test reload -- --exact unix::reload_under_load_drops_nothing --nocapture`. Not measured: a release build, HTTP/2 clients, long-lived websockets across reloads (they keep the runtime they started with until they close), and Pingora graceful upgrade for comparison. [S local runs 2026-11-07]
|
||||
5. Authelia forward-auth endpoint and headers to mirror exactly. (phase 1)
|
||||
**Answer: `GET /api/authz/forward-auth` (ForwardAuth implementation; legacy `/api/verify` not used).** Edge sends X-Forwarded-Method, -Proto, -Host, -URI (required) and X-Forwarded-For, and always sets them itself. It also forwards the client's headers (Cookie, Authorization) without hop-by-hop headers or body. A 2xx answer copies Remote-User, Remote-Groups, Remote-Email and Remote-Name onto the request (client copies removed). Any other answer (302 portal, 401 + WWW-Authenticate, 403) goes back to the client verbatim. An unreachable, silent (10 s deadline), oversized (>1 MiB), broken or `101` auth answer fails closed with 502; 1xx heads are skipped. Client-sent Remote-* headers are always stripped on forward-auth hosts, whatever copy_headers says. This mirrors `caddy adapt` output for Authelia's documented `forward_auth` snippet; tested against a mock, not a real Authelia. [S authelia.com/reference/guides/proxy-authorization, authelia.com/integration/proxies/caddy]
|
||||
6. Custos CSR-signing operation with match-code approval. (phase 3)
|
||||
@@ -122,14 +132,42 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit
|
||||
| Phase | State | Notes |
|
||||
|:--|:--|:--|
|
||||
| 1 Core and engine | Done, except the Let's Encrypt staging check | Merged to main 2026-11-07. Tests run in WSL2; ACME checked only against Pebble. LE staging needs a public domain: Mark to decide whether to defer it to phase 3 or give a domain now. |
|
||||
| 2 Control plane | Not started | |
|
||||
| 2 Control plane | Done, pending merge | Built on control/phase-2: routes repo, journaled apply with trial/watch/revert, undo, restore, share links, API tokens, REST API + OpenAPI, `--dev`. Four QC rounds; every finding fixed or listed in Handover. Real Gitea, systemd credentials and Authelia not exercised. |
|
||||
| 3 Web UI, PKI, NixOS | Not started | UI design drafted: claude.ai/artifact/GEiCCPcGC1hiCkA2NrrH9u ("murex" palette on the Domi system). |
|
||||
| 4 Hardening and release | Not started | Known gaps carried here: see Handover. |
|
||||
|
||||
## 10. Handover
|
||||
(Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.)
|
||||
|
||||
**2026-11-07: Phase 1, design draft.**
|
||||
**2026-11-07: Phase 2, control plane.**
|
||||
- **Changed:**
|
||||
- Phase 2 on branch control/phase-2: crates/control (routes repo through the `git` binary, journaled apply with edge trial reloads, 60 s watch and revert, undo/redo, restore, push with retry, share links, API tokens, REST API with OpenAPI, `--dev`), edge in-process reload over an admin Unix socket, share-link checks and visitor pages in edge, share tokens and the exact `hosts/<hostname>.toml` loader in core.
|
||||
- docs/api.md (curl examples, run end to end against `--dev`) and docs/ui-api.md (the designer's contract for phase 3, with the deviations listed at its end).
|
||||
- §8.4 answered with load numbers. Tests: core 86, edge 43, control 42, diff 3 (diff after each of six applies: 0 new differences), testkit 1; hook self-test 55.
|
||||
- Four QC rounds. Fixed along the way: password-throttle flush, CLI revoke lost to a server write, a pause lost on a full disk (three variants), revocation epoch rollback, Unicode and encoded `..` escapes in share paths, credentials echoed in errors, a port race in the test harness.
|
||||
- **Deployed:** nothing. The server is unchanged and no nixos-rebuild is needed.
|
||||
- **Not verified:**
|
||||
- Push to the real Gitea over HTTPS (askpass) — a local bare repo stood in.
|
||||
- systemd LoadCredential (a credentials-dir override stood in); a real Authelia (mock only).
|
||||
- A release build, HTTP/2 clients and websockets across reloads; Pingora graceful upgrade (kept for binary upgrades only, not measured).
|
||||
- A lost confirm answer from edge is tested only indirectly (edge stopped during the watch, not a late answer).
|
||||
- Everything from the phase 1 list below that is still open.
|
||||
- **Known gaps for later phases:**
|
||||
- Share links work only on Pingora; under the Caddy fallback a visitor gets the normal sign-in (G7, phase 3).
|
||||
- The "site not reachable" visitor page is not built: it needs a matching Caddy `handle_errors` to keep the diff suite equal.
|
||||
- The crash and write-failure test hooks (`IANITOR_TEST_CRASH_AT`, `IANITOR_TEST_FAIL_WRITE`) are in the release binary, gated only by environment; move them behind a default feature that the Nix release build turns off. (phase 3)
|
||||
- Control trusts only API tokens; forwarded `Remote-User` headers get 401 until the UI sign-in is designed (G14, phase 3).
|
||||
- Edge config is version 2; a phase-1 edge refuses it.
|
||||
- Workspace `rust-version` is now 1.89 (`File::lock`).
|
||||
- One open flake: in one full run `apply_sequence` timed out waiting for Caddy on the chunked-body case (Ianitor answered 200). The diff suite alone passed 5/5 afterwards; cause not found.
|
||||
- **Needs Mark:**
|
||||
- (f) The share-link deny list is a separate file outside git (`share-revocations.json`, plus an epoch for "stop all"), not part of the compiled edge config, so Stop never waits behind a 60 s apply.
|
||||
- (g) §3 says "(+ optional password hash)"; the token carries no hash, and the password is mixed into the MAC so it cannot be guessed offline. §3 left unchanged until you agree.
|
||||
- (h) The UI contract roughly doubled phase 2's scope; all of it is built.
|
||||
- (a)–(e) from phase 1 below are still open.
|
||||
- **Next step:** Phase 3, starting with the open points (a) LE staging, (b) the engine switch, (c) the 4th clicks, (d) the palette, and §8.6 (Custos CSR signing).
|
||||
|
||||
**2026-11-07: Phase 1, design draft** (kept for its open items).
|
||||
- **Changed:**
|
||||
- Phase 1 on branch core/phase-1: workspace, `.githooks/pre-commit`, crates/core (schema and both compilers), crates/edge (Pingora with rustls), tests/diff (60 cases against Caddy 2.11.7), tests/support.
|
||||
- Reviewed by a separate QC pass, two rounds; every finding fixed or listed below.
|
||||
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
# Ianitor control API
|
||||
|
||||
`ianitor-control` serves a REST + JSON API on loopback only (`127.0.0.1:7878` by default),
|
||||
under `/api/v1`. The OpenAPI document is generated from the code: `GET /api/v1/openapi.json`,
|
||||
or `ianitor-control openapi` without a running server. The web UI's contract is
|
||||
[docs/ui-api.md](ui-api.md); its last section lists where this API differs.
|
||||
|
||||
Everything below was run end to end on loopback against `--dev` with a real edge
|
||||
(2026-11-07, WSL2 Debian); the outputs are trimmed with `jq`, never edited.
|
||||
|
||||
## Ground rules
|
||||
|
||||
- **Token.** Every call needs `Authorization: Bearer <API token>`. Nothing else identifies a
|
||||
caller (no `Remote-User`). Without a valid token: `401` with `token.missing`,
|
||||
`token.unknown`, `token.expired` or `token.revoked`. 120 calls a minute per token.
|
||||
- **Host header.** Only `127.0.0.1:<port>`, `localhost:<port>`, `[::1]:<port>` and the
|
||||
configured `allowed_hosts` are answered (DNS rebinding). A browser write (`Origin` or
|
||||
`Sec-Fetch-Site` present) also needs `X-Ianitor-UI: 1` (CSRF).
|
||||
- **Bodies** are JSON, at most 64 KiB, with no unknown fields. Errors about the request
|
||||
itself (bad JSON, a wrong type, an odd field name, a path that is no hostname) never repeat
|
||||
what you sent. Errors about a host can repeat its values (hostname, upstream, header name)
|
||||
in `params` and `detail`, but never a URL's user name and password (shown as `…@`), a secret
|
||||
value or a token.
|
||||
- **Errors** have one shape; `code` is stable, `message` is plain English, `field` points at
|
||||
the form field, `params` holds the values in the message, `detail` is the technical text:
|
||||
|
||||
```json
|
||||
{ "error": { "code": "host.hostname.uppercase", "message": "Use lowercase letters only: wiki.dev.test.",
|
||||
"field": "hostname", "params": { "hostname": "Wiki.dev.test", "suggestion": "wiki.dev.test" },
|
||||
"retry_after_s": null, "detail": "hosts/Wiki.dev.test.toml: `Wiki.dev.test` is not a valid hostname: it must be lowercase" },
|
||||
"errors": [ ... one per field problem ... ], "request_id": "9c1f…", "server_time": "2026-11-07T17:19:40Z" }
|
||||
```
|
||||
- **`server_time`** is in every JSON object answer. Times are RFC 3339 UTC.
|
||||
- **Changes are applies.** Adding, changing, removing a host, Undo and Restore answer
|
||||
`202 {"apply": {...}}` at once; poll `GET /applies/{id}` (every second) until `state` is
|
||||
`kept`, `reverted`, `failed` or `needs_attention`. Applies run one at a time, in order;
|
||||
the others are `queued`.
|
||||
- **`Idempotency-Key`** on a write: a retry with the same key gets the same apply back. While
|
||||
the first request with a key is still being handled, a retry gets `409 request.in_progress`
|
||||
(retry after 1 s). Keys are held in memory for 24 h (at most 2,000; then `429`).
|
||||
- **`base_rev`** (from `GET /hosts/{h}` or the overview's `rev`): the change is refused with
|
||||
`409 change.conflict` only if the same host file changed since.
|
||||
|
||||
## Start
|
||||
|
||||
Development, everything temporary on 127.0.0.1 (removed on Ctrl-C):
|
||||
|
||||
```sh
|
||||
cargo build -p ianitor-edge -p ianitor-control # so --dev finds ianitor-edge next to it
|
||||
cargo run -p ianitor-control -- --dev
|
||||
```
|
||||
|
||||
```text
|
||||
Ianitor control (dev) on http://127.0.0.1:7878/api/v1
|
||||
Routes repository: /tmp/ianitor-dev-1523/routes.git
|
||||
Dev proxy: …/ianitor-edge on https://127.0.0.1:18443 (HTTP 18080). tls = "domi" works for app.dev.test, wiki.dev.test, photos.dev.test; CA: /tmp/ianitor-dev-1523/certs/dev-ca.crt
|
||||
API token (shown once): ian_06484a2c0a6ec73b_vceenNC…
|
||||
Press Ctrl-C to stop and remove /tmp/ianitor-dev-1523
|
||||
```
|
||||
|
||||
Without `ianitor-edge` (or with `--edge-bin` pointing nowhere) applies are only validated,
|
||||
compiled and written. In dev mode the health watch lasts 10 s (`--watch-secs`); in
|
||||
production 60 s.
|
||||
|
||||
Production: the first token comes from the CLI on the server, never over the network:
|
||||
|
||||
```sh
|
||||
ianitor-control token create --name mark-laptop --config /etc/ianitor/control.toml
|
||||
```
|
||||
|
||||
The examples use:
|
||||
|
||||
```sh
|
||||
TOKEN=ian_… # from the line above
|
||||
API=http://127.0.0.1:7878/api/v1
|
||||
H="Authorization: Bearer $TOKEN"
|
||||
CA=/tmp/ianitor-dev-1523/certs/dev-ca.crt
|
||||
visit() { curl -s -o /dev/null -w '%{http_code}\n' --cacert "$CA" --resolve "$1:18443:127.0.0.1" "${@:2}"; }
|
||||
python3 -m http.server 3000 --bind 127.0.0.1 & # a test upstream
|
||||
```
|
||||
|
||||
## Add a host
|
||||
|
||||
```sh
|
||||
curl -s -H "$H" -H 'Content-Type: application/json' -H 'Idempotency-Key: add-app-1' \
|
||||
-X POST "$API/hosts" -d '{"host": {"hostname": "app.dev.test",
|
||||
"upstreams": ["http://127.0.0.1:3000"], "tls": "domi", "auth": "none",
|
||||
"health_check": {"path": "/", "interval_secs": 5}}}' | jq '{state: .apply.state, id: .apply.id}'
|
||||
```
|
||||
```json
|
||||
{ "state": "queued", "id": "ch_b720484831a9" }
|
||||
```
|
||||
```sh
|
||||
curl -s -H "$H" "$API/applies/ch_b720484831a9" | jq '{state, summary, reason: .reason.message, steps: [.steps[] | "\(.key)=\(.state)"]}'
|
||||
```
|
||||
```json
|
||||
{ "state": "kept", "summary": "Added app.dev.test",
|
||||
"reason": "app.dev.test is live. Health checks passed for 10 s.",
|
||||
"steps": ["validate=done", "compile=done", "write=done", "reload=done", "watch=done", "push=skipped"] }
|
||||
```
|
||||
```sh
|
||||
visit app.dev.test https://app.dev.test:18443/ # 200
|
||||
```
|
||||
|
||||
The same request with the same `Idempotency-Key` returns `ch_b720484831a9` again and changes
|
||||
nothing. A host that fails its health check during the watch is reverted: `state:
|
||||
"reverted"`, and `reason` says why, e.g. `"a.test was not changed. 127.0.0.1:41999 answered
|
||||
with an error page on 3 of 3 checks. Ianitor undid the change."` The routes repository then
|
||||
holds the change and its revert commit; edge and the files never left the last good config.
|
||||
|
||||
A form error comes back at once, field by field:
|
||||
|
||||
```sh
|
||||
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/hosts" \
|
||||
-d '{"host": {"hostname": "Wiki.dev.test", "upstreams": ["http://10.0.0.23"]}}' \
|
||||
| jq '{code: .error.code, errors: [.errors[] | {code, field, message}]}'
|
||||
```
|
||||
```json
|
||||
{ "code": "apply.failed.validation",
|
||||
"errors": [{ "code": "host.hostname.uppercase", "field": "hostname", "message": "Use lowercase letters only: wiki.dev.test." }] }
|
||||
```
|
||||
|
||||
`POST /hosts/validate?mode=create` checks a body without applying it; `PUT /hosts/{h}` with
|
||||
`{"host": …, "base_rev": …}` changes a host; `PATCH /hosts/{h}` with `{"share_links": true}`
|
||||
turns share links on; `DELETE /hosts/{h}` removes one.
|
||||
|
||||
## Undo
|
||||
|
||||
Undo always names what it will undo; the POST must name the same change, or it is refused
|
||||
with `409 undo.target_moved`. Undo right after an Undo is a redo, and `effect` says so.
|
||||
|
||||
```sh
|
||||
curl -s -H "$H" "$API/undo" | jq '{available, target: .target.summary, effect}'
|
||||
```
|
||||
```json
|
||||
{ "available": true, "target": "Added app.dev.test", "effect": "Removes app.dev.test" }
|
||||
```
|
||||
```sh
|
||||
TARGET=$(curl -s -H "$H" "$API/undo" | jq -r .target.change_id)
|
||||
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/undo" \
|
||||
-d "{\"target_change_id\": \"$TARGET\"}" | jq -r .apply.id
|
||||
# then poll /applies/{id}:
|
||||
```
|
||||
```json
|
||||
{ "state": "kept", "summary": "Undid: Added app.dev.test", "reason": "app.dev.test is removed.",
|
||||
"steps": ["validate=done", "compile=done", "write=done", "reload=done", "watch=skipped", "push=skipped"] }
|
||||
```
|
||||
```sh
|
||||
visit app.dev.test https://app.dev.test:18443/ # 000: no certificate is served for a removed host
|
||||
```
|
||||
|
||||
## History and Restore
|
||||
|
||||
One entry per action (a reverted attempt is one `reverted` entry):
|
||||
|
||||
```sh
|
||||
curl -s -H "$H" "$API/history?limit=5" | jq '[.entries[] | {change_id, summary, state}]'
|
||||
```
|
||||
```json
|
||||
[ { "change_id": "ch_cf0b434ecb4c", "summary": "Undid: Added app.dev.test", "state": "kept" },
|
||||
{ "change_id": "ch_b720484831a9", "summary": "Added app.dev.test", "state": "kept" } ]
|
||||
```
|
||||
```sh
|
||||
curl -s -H "$H" "$API/history/ch_b720484831a9/restore-preview" | jq '{restorable, changes}'
|
||||
```
|
||||
```json
|
||||
{ "restorable": true, "changes": [{ "effect": "added", "fields": [], "hostname": "app.dev.test" }] }
|
||||
```
|
||||
```sh
|
||||
REV=$(curl -s -H "$H" "$API/overview" | jq -r .rev)
|
||||
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/restore" \
|
||||
-d "{\"change_id\": \"ch_b720484831a9\", \"base_rev\": \"$REV\"}" | jq -r .apply.id
|
||||
# then poll /applies/{id}:
|
||||
```
|
||||
```json
|
||||
{ "state": "kept", "summary": "Restored the version of 7 November 2026",
|
||||
"reason": "app.dev.test is live. Health checks passed for 10 s." }
|
||||
```
|
||||
```sh
|
||||
visit app.dev.test https://app.dev.test:18443/ # 200
|
||||
```
|
||||
|
||||
## Share link
|
||||
|
||||
A host with `auth = "forward-auth"` and `share_links = true` (dev mode points sign-in at an
|
||||
Authelia on 127.0.0.1:9091 that is not running, so without a link the request fails closed):
|
||||
|
||||
```sh
|
||||
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/hosts" \
|
||||
-d '{"host": {"hostname": "wiki.dev.test", "upstreams": ["http://127.0.0.1:3000"],
|
||||
"tls": "domi", "auth": "forward-auth", "share_links": true}}' # poll until kept
|
||||
visit wiki.dev.test https://wiki.dev.test:18443/ # 502: sign-in unreachable, fails closed
|
||||
|
||||
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/hosts/wiki.dev.test/share-links" \
|
||||
-d '{"path_prefix": "/", "expires_in_s": 86400}'
|
||||
```
|
||||
```json
|
||||
{ "id": "ec724bb1420da0d8d81ee897e1e5344b", "expires_at": "2026-11-08T17:20:05Z", "path_prefix": "/",
|
||||
"has_password": false, "url": "https://wiki.dev.test:18443/?share=ish1.…", "warning": null }
|
||||
```
|
||||
|
||||
The URL is shown once: control never stores the token on disk; only an `Idempotency-Key`
|
||||
retry of this request gets the same answer again, from memory, for 24 h. The first visit trades the token for a
|
||||
path-scoped `HttpOnly; Secure; SameSite=Lax` cookie and redirects to the same URL without it:
|
||||
|
||||
```sh
|
||||
curl -s -o /dev/null -w '%{http_code} -> %{redirect_url}\n' --cacert "$CA" \
|
||||
--resolve wiki.dev.test:18443:127.0.0.1 -c jar "$URL" # 303 -> https://wiki.dev.test:18443/
|
||||
visit wiki.dev.test -b jar https://wiki.dev.test:18443/ # 200, no sign-in
|
||||
```
|
||||
|
||||
Stop it; edge refuses it at once (and within 5 s even if control's nudge is lost):
|
||||
|
||||
```sh
|
||||
curl -s -H "$H" -X DELETE -o /dev/null -w '%{http_code}\n' "$API/share-links/ec724bb1420da0d8d81ee897e1e5344b" # 204
|
||||
visit wiki.dev.test -b jar https://wiki.dev.test:18443/ # 502: back to sign-in
|
||||
visit wiki.dev.test "$URL" # 403: "This link no longer works"
|
||||
```
|
||||
|
||||
Options: `"password": "at least 8 characters"` (the visitor gets a password page; 5 wrong
|
||||
tries a minute per link and network), `"replaces": "<id>"` stops an earlier link,
|
||||
`POST /share-links/stop-all` stops every link made so far, `GET /share-links` lists them
|
||||
(without tokens).
|
||||
|
||||
## Tokens
|
||||
|
||||
```sh
|
||||
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/tokens" -d '{"name": "backup script"}'
|
||||
# 201 {"id": "…", "name": "backup script", "token": "ian_…", "expires_at": "2027-11-07T…"} (shown once)
|
||||
curl -s -H "$H" "$API/tokens" # ids, names, dates; never a value or hash
|
||||
curl -s -H "$H" -X DELETE "$API/tokens/<id>" # 204; anything using it stops now
|
||||
curl -s "$API/overview" | jq .error.code # "token.missing"
|
||||
```
|
||||
|
||||
## All calls
|
||||
|
||||
| Call | Does |
|
||||
|:--|:--|
|
||||
| `GET /overview` | the main screen in one call (hosts with health, engine, last apply, undo, active apply, repo, site); `ETag`/`304` |
|
||||
| `GET /hosts`, `GET /hosts/{h}` | hosts; one host with `rev`, its TOML, health and certificate |
|
||||
| `POST /hosts/validate?mode=create\|edit` | check a host body |
|
||||
| `POST /hosts`, `PUT /hosts/{h}`, `PATCH /hosts/{h}`, `DELETE /hosts/{h}?base_rev=` | applies |
|
||||
| `POST /hosts/{h}/certificate/retry` | try Let's Encrypt again now |
|
||||
| `GET /applies`, `GET /applies/{id}`, `DELETE /applies/{id}` | apply records; cancel a queued one |
|
||||
| `GET /history`, `GET /history/{id}`, `GET /history/{id}/restore-preview` | history, one entry, restore preview |
|
||||
| `GET /undo`, `POST /undo`, `POST /restore` | undo and restore |
|
||||
| `POST /repo/push`, `GET /settings` | push now; settings |
|
||||
| `GET/POST /tokens`, `PATCH/DELETE /tokens/{id}` | API tokens |
|
||||
| `POST /hosts/{h}/share-links`, `GET /share-links`, `DELETE /share-links/{id}`, `POST /share-links/stop-all` | share links |
|
||||
| `GET /health` | edge reachability, config hash, trial, paused state, hosts |
|
||||
| `GET /openapi.json` | the OpenAPI document |
|
||||
+510
@@ -0,0 +1,510 @@
|
||||
> This file is the web UI's contract with the control API for Phase 3 (from the designer; deviations are listed at the end).
|
||||
|
||||
# Ianitor Domi: what the web UI needs from the Phase 2 API
|
||||
|
||||
From the UI design (claude.ai/artifact/GEiCCPcGC1hiCkA2NrrH9u, 9 boards) and ROADMAP §3, §4, §6, §10.
|
||||
Shapes are resource + method + fields, not OpenAPI. Sources: [D] drawn on a board, [R] ROADMAP, [C] current code, [J] my call.
|
||||
|
||||
## 0. Ground rules for every call
|
||||
|
||||
- Base path `/api/v1`, JSON, times RFC 3339 UTC. The UI formats times in the browser's zone ("Today 14:02").
|
||||
- Every response carries `server_time`. The UI counts down from `ends_at - server_time`, never from the browser clock.
|
||||
- Errors use one envelope:
|
||||
```
|
||||
{ "error": { "code": "host.hostname.taken", "message": "<plain English, shown as is>",
|
||||
"field": "hostname" | null, "params": { ... }, "retry_after_s": null },
|
||||
"errors": [ ...same shape, for several field errors... ], "request_id": "01J..." }
|
||||
```
|
||||
`code` is stable and is what the UI switches on. `message` is the §3 text, filled by the server, so curl users get the same words.
|
||||
`params` holds the values in the message (hostname, address, counts, dates) so the UI can bold them.
|
||||
A technical detail (core's own error text, log lines) goes only in `detail`, shown behind "Show details". It never holds a secret value or a token.
|
||||
- Writes take an `Idempotency-Key` header, one per click. An apply can reload the proxy the UI talks through, so a dropped POST gets retried, and the retry must not apply twice.
|
||||
- Writes that change routes take `base_rev`: the routes-tree commit the form was loaded from. The server refuses only if *the same host file* changed since then (§3 `change.conflict`). A change elsewhere in the tree is fine, so queued applies don't refuse each other.
|
||||
- The UI sends `X-Ianitor-UI: 1` on every request, as a CSRF guard: control refuses browser-origin writes without it. Who the user is comes from the Authelia `Remote-User` that edge forwards (see gap G14).
|
||||
|
||||
## 1. Per flow
|
||||
|
||||
### 1.1 Main screen (desktop and phone boards) [D]
|
||||
|
||||
**One call: `GET /overview`.** Yes, one call is possible, as long as control keeps a cached copy of health (edge pushes it or control pulls every 2 s; see G1). The request must never wait on a live probe.
|
||||
|
||||
| Block | Fields | Shown as |
|
||||
|:--|:--|:--|
|
||||
| `counts` | `hosts, healthy, degraded, down, unknown` | "7 hosts · 5 healthy, 1 degraded, 1 down" |
|
||||
| `hosts[]` | `hostname, upstreams[] (url), tls ("domi"\|"letsencrypt"), auth ("none"\|"forward-auth"), websockets, share_links, added_at` | row, chips, "Added today" |
|
||||
| `hosts[].health` | `state ("healthy"\|"degraded"\|"down"\|"unknown"\|"pending"), last_check_at, latency_ms (nullable), since, failure {kind, upstream, count, of} \| null, upstreams[] {url, state, last_check_at, latency_ms, failure_kind}` | dot + word, "Checked 8 s ago · 42 ms", "Connection refused for 6 minutes" |
|
||||
| `hosts[].certificate` | `state ("ok"\|"pending"\|"failed"), not_after, error_code` | extra line only when not `ok` |
|
||||
| `engine` | `running ("pingora"\|"caddy"), state ("running"\|"switching"\|"stopped"), since, fallback_ready {built_at, compared, matched} \| null` | engine chip; popover (switch flow) |
|
||||
| `last_apply` | the most recent apply record (§2), any outcome, or null | last-change bar: state word, summary, sub-line |
|
||||
| `undo` | see §2.3 | the Undo button and its name |
|
||||
| `active_apply` | `{id, state, summary, seconds_left}` \| null, plus `queued` (count) | "Applying wiki.home.example: 41 s left" when the user comes back to the main screen |
|
||||
| `repo` | `name, last_push_at, unpushed (count), push_error_code` \| null | footer "Last pushed to Gitea at 14:03" |
|
||||
| `intermediate` | `not_after, days_left, renewal {request_id, state, match_code, expires_at} \| null`; **null until Phase 3** | banner when `days_left <= 30` or `renewal` is open |
|
||||
| `site` | `forward_auth_configured, acme_configured, secrets[] (names only), watch_seconds (60)` | add-host form: disables "Sign in first" if Authelia is not set up; secret picker in headers |
|
||||
| `paused` | `{code, message}` \| null | full-width notice; disables + Host, Undo, Restore |
|
||||
|
||||
Health `state` rules for the UI [J]: `healthy` = every upstream passed its last check. `degraded` = some passed, some failed, or the last 5 checks were mixed. `down` = no upstream passed the last check. `unknown` = no health check set. `pending` = added but not yet checked. The drawn "slow: 2.8 s, limit is 2 s" has no basis in the schema (see G2).
|
||||
|
||||
Polling: every 5 s while the tab is visible, every 30 s when hidden. Send `If-None-Match` with the ETag and expect `304` when nothing changed.
|
||||
|
||||
Clicks on the main screen:
|
||||
|
||||
| Click | Call |
|
||||
|:--|:--|
|
||||
| + Host | none (opens the panel) |
|
||||
| Undo | `POST /undo` (§1.3) |
|
||||
| Renew (banner) | `POST /certs/intermediate/renewal` (Phase 3, §1.8) |
|
||||
| ⋯ on a row | none (menu) |
|
||||
| ⋯ → Edit host | `GET /hosts/{hostname}` → returns the full host (all §3 ROADMAP fields) + `rev` |
|
||||
| ⋯ → Show in history | `GET /history?host={hostname}` |
|
||||
| ⋯ → Remove host | `DELETE /hosts/{hostname}?base_rev=` → `202` apply. No confirmation dialog: Undo restores the host in 1 click [J] |
|
||||
| Engine chip | none (popover from `engine`) |
|
||||
|
||||
### 1.2 Add host: + Host → fill → Apply = 2 clicks [D][R]
|
||||
|
||||
| State | Call | Shows |
|
||||
|:--|:--|:--|
|
||||
| Panel open | none; values come from `overview.site` | hostname focused; form defaults Domi certificate, Sign in first [D] (the UI always sends explicit values; schema defaults are letsencrypt and none [C]) |
|
||||
| Typing (field blur, not a click) | `POST /hosts/validate` body = host, `?mode=create` | inline field errors (§3.1), including a taken hostname, before Apply |
|
||||
| **Apply (click 2)** | `POST /hosts` body = `{host, base_rev}` | `422` with `errors[]` → keep the panel, mark the fields. `202 {apply}` → the panel shows the apply steps (§2) |
|
||||
| Watching | `GET /applies/{id}` every 1 s (§2.2) | checklist + "41 s left" + progress bar |
|
||||
| Kept | (final poll) | panel closes; the row appears; the bar shows `kept` + Undo |
|
||||
| Reverted | (final poll) | panel stays open with the user's values; banner with the reason; "Edit and try again" focuses the field the reason names (`reason.field`, e.g. `upstreams[0]`) |
|
||||
|
||||
Host body (mirrors the TOML [C]):
|
||||
`hostname, upstreams[] (strings), tls, auth, websockets, share_links, access_log ("off"|"truncated"), health_check {path, interval_secs} | null, request_headers[] / response_headers[] {action ("set"|"remove"), name, value | secret}`.
|
||||
|
||||
### 1.3 Undo last change = 1 click [D][R]
|
||||
|
||||
- Data: `overview.undo` (§2.3). The button reads **Undo** with the target's name beside it in the bar.
|
||||
- Click: `POST /undo {target_change_id}` → `202 {apply}`, with the same states as any apply. The server refuses with `409 undo.target_moved` if the target is no longer the latest kept change, so Undo never undoes something it did not name.
|
||||
- During its own watch, Undo is disabled with "Wait for the check to finish (41 s)". If a *different* apply is running, Undo is queued like any change.
|
||||
|
||||
### 1.4 Restore: History → pick → Restore = 3 clicks [D][R]
|
||||
|
||||
| Click | Call | Fields shown |
|
||||
|:--|:--|:--|
|
||||
| 1 History | `GET /history?limit=50` (`before=` for more) | `entries[] {change_id, summary, kind ("add"\|"edit"\|"remove"\|"undo"\|"restore"\|"share_links"), state ("kept"\|"reverted"\|"failed"\|"queued"\|"running"), at, commit_short, hosts[], reason_short}` ("port refused") |
|
||||
| 2 pick | `GET /history/{change_id}/restore-preview` | `restorable` (false for reverted or failed entries, which instead offer "Edit and try again" using `GET /history/{id}` → `attempted_host`), `same_as_current`, `changes[] {hostname, effect ("added"\|"removed"\|"changed"), fields[] {field, from, to}}` |
|
||||
| 3 Restore this version | `POST /restore {change_id, base_rev}` | `202 {apply}` → bar: "Restored the version of 3 Nov, 09:30" |
|
||||
|
||||
- History must show one entry per user action. An attempt that was reverted is one `reverted` entry, not a commit row plus a revert row. Control groups them.
|
||||
- The UI writes the preview sentences from `fields[]` with this label map, so the wording is the same everywhere: hostname "address", upstreams "sends traffic to", tls "certificate", auth "who can open it", health_check.path "health check address", health_check.interval_secs "checks every", share_links "share links", access_log "visit log", websockets "websockets", headers "header rules".
|
||||
- Drop the drawn line "wiki.home.example is not affected (never kept)". The preview lists only real differences.
|
||||
|
||||
### 1.5 Share link: ⋯ → Share link → Copy = 3 clicks [D][R]
|
||||
|
||||
| Click | Call | Fields |
|
||||
|:--|:--|:--|
|
||||
| 1 ⋯ | none | menu; "Share link" is enabled when the host's `share_links` is true (from overview) |
|
||||
| 2 Share link | `POST /hosts/{hostname}/share-links {path_prefix: "/", expires_in_s: 604800}` → `201` | `id, url, expires_at, path_prefix, has_password` |
|
||||
| 3 Copy link | none (client clipboard only, so the copy happens inside the click) | "Copied. Expires on 14 November 2026 at 14:20." |
|
||||
| Change expiry or prefix, add a password (extra clicks) | `POST /hosts/{h}/share-links {..., replaces: <previous id>}` | the new link; the server stops the one it replaces. A link minted on open and never copied doesn't stay valid |
|
||||
|
||||
- Expiry options in the UI: 1, 7, 30 days. The server accepts 1 hour to 90 days [J].
|
||||
- Password: `password` in the POST body; at least 8 characters [J]; never returned.
|
||||
- Links off for this host: the dialog shows "Turn on share links and apply". Clicking it calls `PATCH /hosts/{h} {share_links: true, base_rev}` → `202 {apply}`. After `kept`, the UI auto-calls the mint POST and shows the link; Copy is click 4 (G10).
|
||||
- Host with `auth = none`: the dialog says anyone can already open it. Mint anyway if asked; the UI does not block it.
|
||||
- Settings → Share links: `GET /share-links` → `items[] {id, hostname, path_prefix, created_at, expires_at, has_password, state ("active"|"expired"|"stopped")}`. "Stop this link" calls `DELETE /share-links/{id}` → `204`. "Stop all share links" calls `POST /share-links/stop-all` (G8).
|
||||
|
||||
### 1.6 API token: ⚙ → API → New token = 3 clicks [D][R]
|
||||
|
||||
| Click | Call | Fields |
|
||||
|:--|:--|:--|
|
||||
| 1 Settings | `GET /settings` | `repo {name, last_push_at}, watch_seconds` (read-only in v1) |
|
||||
| 2 API tab | `GET /tokens` | `items[] {id, name, created_at, last_used_at, expires_at \| null}`; never a hash or a prefix |
|
||||
| 3 New token | `POST /tokens {name?}` → `201 {id, name, token, expires_at}` | the token is shown once and returned only in this response. The UI drops it from memory when the dialog closes |
|
||||
| Rename (optional) | `PATCH /tokens/{id} {name}` | |
|
||||
| Revoke | `DELETE /tokens/{id}` → `204` | the row goes to "Revoked today 14:40" until the next reload |
|
||||
|
||||
- Recommendation that removes the 4th click (G12): click 3 is **Make and copy token**. The UI calls `navigator.clipboard.write([new ClipboardItem({"text/plain": tokenPromise})])` inside the click, so the copy belongs to that click even though the POST is async. The POST must answer in under 1 s. The dialog then says "Copied. Paste it into Custos now." and keeps a Copy again button.
|
||||
- Default lifetime 365 days, or "Never expires" as an option [J]. Expiry is needed for the expired-token message in §3.
|
||||
|
||||
### 1.7 Device certificate (Phase 3): Certificates → + Device → Issue = 3 clicks [D][R]
|
||||
|
||||
| State | Call | Fields |
|
||||
|:--|:--|:--|
|
||||
| 1 Certificates | `GET /certs` | `intermediate {subject, not_after, days_left}`, `root {offline: true}`, `devices[] {id, name, kind ("phone"\|"computer"\|"app"), not_after, state ("valid"\|"revoked"\|"expired")}`, `device_lifetime_days` |
|
||||
| 2 + Device | none | form |
|
||||
| 3 Issue | `POST /certs/devices {name, kind}` → `202 {request_id, match_code, expires_at}` | "47 19 83", "The request stays open for 10 minutes" |
|
||||
| Waiting | `GET /pki-requests/{id}` every 2 s | `state ("waiting"\|"approved"\|"denied"\|"expired"\|"cancelled"\|"failed"), approved_at, device_id` |
|
||||
| Cancel request | `DELETE /pki-requests/{id}` | |
|
||||
| Issued, install (click 4) | `POST /certs/devices/{id}/bundle {format: "p12"\|"qr"}` → `{download_url, one_time_password, expires_at}` | one download only, then deleted; QR encodes `download_url` (G15) |
|
||||
| Revoke a device | `DELETE /certs/devices/{id}` | |
|
||||
|
||||
### 1.8 Renew intermediate (Phase 3): banner Renew = 1 click [D][R]
|
||||
|
||||
- Click: `POST /certs/intermediate/renewal` → `202 {request_id, match_code, expires_at}`. The banner turns into the match code and "Approve it in Custos".
|
||||
- Then `GET /pki-requests/{id}` every 2 s. Once `approved`, `overview.intermediate.not_after` moves on and the banner says "Renewed. The Domi intermediate certificate is now valid until 30 November 2027." for this session.
|
||||
- Banner states the UI needs: `due` (≤ 30 days), `urgent` (≤ 7 days, uses the `down` colour), `waiting` (match code), `expired`, `failed` (§3.6).
|
||||
|
||||
### 1.9 Switch engine (not in this brief's scope, but on the main screen)
|
||||
|
||||
`overview.engine` is enough to draw the chip and the popover. The switch call (`POST /engine {target}` → `202`, polled like an apply) waits on Mark's decision (b) in §10.
|
||||
|
||||
## 2. Apply outcomes
|
||||
|
||||
### 2.1 The apply record
|
||||
|
||||
`GET /applies/{id}` (also embedded as `last_apply` and in every `202`):
|
||||
|
||||
```
|
||||
id, change_id, kind, summary ("Added wiki.home.example"), hosts[], state, created_at, finished_at,
|
||||
steps[] { key ("validate"|"compile"|"write"|"reload"|"watch"|"push"), state ("pending"|"running"|"done"|"failed"|"skipped") },
|
||||
queue { position, waiting_for { apply_id, summary, seconds_left } } | null,
|
||||
watch { ends_at, seconds_left, hosts[] { hostname, passed, failed, total } } | null,
|
||||
reason { code, message, hostname, upstream, field, count, of } | null,
|
||||
commit_short | null, push { state ("pushed"|"pending"|"failed"), at, error_code, next_try_at } | null,
|
||||
undo_of | null, restore_of | null
|
||||
```
|
||||
|
||||
| `state` | When | The UI shows (copy in §3.2) |
|
||||
|:--|:--|:--|
|
||||
| `queued` | another apply is running | "Waiting for 'Added recipes.home.example' to finish (about 40 s)." + Cancel (`DELETE /applies/{id}`, allowed only while queued) |
|
||||
| `validating` | checking the files again in the queue | step 1 running |
|
||||
| `applying` | compile, write, reload | steps 2–3 running |
|
||||
| `watching` | the 60 s health watch | step 4, "41 s left", progress `60 - seconds_left` of 60 |
|
||||
| `kept` | passed; committed | bar `kept`; push sub-state below |
|
||||
| `kept` + `push.state = failed` | kept, but Gitea refused or did not answer | bar `kept` + "Not yet saved to Gitea" + Try now (`POST /repo/push`) |
|
||||
| `reverted` | failed the watch; undone | banner `reverted` + `reason.message` + Edit and try again |
|
||||
| `failed` | never went live (validation in the queue, compile, reload refused) | banner + reason; nothing changed |
|
||||
| `interrupted` → `reverted` | control restarted mid-apply | reason `apply.interrupted` |
|
||||
| `needs_attention` | the revert itself failed | red banner, Restore last kept version (§3.2) |
|
||||
|
||||
Watch rule recommendation [J]: watch only the hosts this change touches. A host that was already down before the change is no reason to revert. A touched host fails if it has no healthy upstream for 3 checks in a row, or none at the end of the 60 s. During the watch, edge checks touched hosts every 5 s whatever their interval, so a watch has about 12 checks, not 6. Removing a host has nothing to watch: `watch` is `skipped` and the result is `kept`. Hosts without a health check: see G3.
|
||||
|
||||
### 2.2 How the UI learns progress: polling, 1 s
|
||||
|
||||
**Pick: polling `GET /applies/{id}` every 1 s while the state is queued, validating, applying or watching; then stop.**
|
||||
|
||||
Why not SSE:
|
||||
1. The browser reaches control *through the proxy the apply reloads*: edge with forward-auth, or Caddy after a switch. A graceful reload either holds the old process open for a long-lived stream or cuts it at the drain timeout. A revert reloads a second time. Every apply would break the SSE stream at its most important moment. A 1 s poll just retries.
|
||||
2. Engine switches and control restarts drop every connection too. Polling needs no resume logic; SSE needs `Last-Event-ID` replay.
|
||||
3. Cost is trivial: one small JSON per second on loopback, 60 per apply, one apply at a time.
|
||||
4. Smoothness: the UI counts down locally from `watch.ends_at - server_time` between polls, so the seconds tick evenly even if a poll is late.
|
||||
|
||||
Errors while polling: retry quietly for 10 s (a reload takes about 2 s), then show `ui.lost_contact` and keep polling every 5 s.
|
||||
|
||||
### 2.3 What the Undo bar needs
|
||||
|
||||
`overview.undo`:
|
||||
```
|
||||
available, target { change_id, summary, kept_at, commit_short } | null,
|
||||
effect ("Removes recipes.home.example"), blocked { code, message } | null
|
||||
```
|
||||
- The target is always the latest **kept** change, never a reverted or failed one.
|
||||
- Right after a reverted apply, the bar has two lines. Line 1 is `last_apply`: "`reverted` wiki.home.example was not added. Reason: …". Line 2 is the Undo button labelled with `undo.target.summary`: "Undo: Added recipes.home.example". The two lines come from two fields, so the bar always names what Undo will touch.
|
||||
- After an Undo is kept, the latest kept change *is* the undo, so Undo again redoes it. `summary` for an undo reads "Undid: Added recipes.home.example", and `effect` reads "Adds recipes.home.example back". The button then says "Undo: Undid Added recipes.home.example", with the effect line under it.
|
||||
- `blocked` codes: `undo.nothing` (no kept change yet), `undo.watching` (its own apply is still running), `undo.paused` (§3.2 needs_attention or repo paused).
|
||||
|
||||
## 3. Every user-facing message
|
||||
|
||||
`{x}` are `params`. Bold in the UI: hostnames and addresses. Tone: say what happened, what still works, and what to do. No "error", "failed to", "invalid", status codes, or protocol names.
|
||||
|
||||
### 3.1 Host form validation (one row per core error [C]; `field` in brackets)
|
||||
|
||||
| Code | Field | Message | UI offers |
|
||||
|:--|:--|:--|:--|
|
||||
| `host.hostname.missing` | hostname | Enter the address people will type, like wiki.home.example. | focus |
|
||||
| `host.hostname.uppercase` | hostname | Use lowercase letters only: {suggestion}. | "Use {suggestion}" (fills it) |
|
||||
| `host.hostname.characters` | hostname | Use only letters a–z, digits, dots and dashes. | focus |
|
||||
| `host.hostname.spaces` | hostname | Remove the spaces from the address. | focus |
|
||||
| `host.hostname.wildcard` | hostname | Addresses with * are not supported yet. Add each name as its own host. | focus |
|
||||
| `host.hostname.trailing_dot` | hostname | Remove the dot at the end. | "Use {suggestion}" |
|
||||
| `host.hostname.empty_label` | hostname | There are two dots in a row. Remove one. | focus |
|
||||
| `host.hostname.label_dash` | hostname | A part of the address cannot start or end with a dash. | focus |
|
||||
| `host.hostname.label_long` | hostname | Each part between dots can be at most 63 characters. | focus |
|
||||
| `host.hostname.too_long` | hostname | The address can be at most 253 characters. | focus |
|
||||
| `host.hostname.numeric` | hostname | That looks like an IP address. Use a name, like wiki.home.example. | focus |
|
||||
| `host.hostname.taken` | hostname | {hostname} is already a host. | "Open {hostname}" (edit form) |
|
||||
| `host.upstreams.missing` | upstreams | Enter where Ianitor should send traffic, like http://10.0.0.23:3000. | focus |
|
||||
| `host.upstream.not_url` | upstreams[i] | Write it as a full address, like http://10.0.0.23:3000. | focus |
|
||||
| `host.upstream.scheme` | upstreams[i] | Start the address with http:// or https://. | focus |
|
||||
| `host.upstream.no_host` | upstreams[i] | Add the server's name or IP address after http://. | focus |
|
||||
| `host.upstream.no_port` | upstreams[i] | Add the port at the end, like :3000. | focus |
|
||||
| `host.upstream.port_zero` | upstreams[i] | Port 0 cannot be used. Enter the port the service listens on. | focus |
|
||||
| `host.upstream.path` | upstreams[i] | Leave out the path after the port. Visitors keep their own path. | "Use {suggestion}" |
|
||||
| `host.upstream.query` / `.fragment` | upstreams[i] | Leave out everything after ? or #. | "Use {suggestion}" |
|
||||
| `host.upstream.credentials` | upstreams[i] | Leave out the user name and password. Put them in a header rule with a secret instead. | open More options → Headers |
|
||||
| `host.upstream.duplicate` | upstreams[i] | This address is listed twice. | "Remove it" |
|
||||
| `host.upstream.mixed_schemes` | upstreams | All addresses for one host must start the same way: all http:// or all https://. | focus |
|
||||
| `host.upstream.too_many` | upstreams | One host can send traffic to at most {max} addresses. | — |
|
||||
| `host.auth.not_configured` | auth | Sign-in is not set up on this server yet, so choose Anyone for now. To set it up, add the Authelia address to ianitor.toml in the routes repository. | the option is disabled up front when `site.forward_auth_configured` is false; the hint says why |
|
||||
| `host.header.name` | {list}[i].name | "{name}" cannot be a header name. Use letters, digits and dashes. | focus |
|
||||
| `host.header.value` | {list}[i].value | This value has characters a header cannot carry. Use visible characters and spaces only. | focus |
|
||||
| `host.header.empty` | {list}[i].value | Enter a value, or choose Remove to drop the header. | switch to Remove |
|
||||
| `host.header.protected` | {list}[i].name | Ianitor sets {name} itself, so a rule cannot change it. | — |
|
||||
| `host.header.duplicate` | {list}[i].name | {name} already has a rule in this list. | jump to that rule |
|
||||
| `host.header.both` | {list}[i] | Choose a fixed value or a secret, not both. | — |
|
||||
| `host.header.remove_value` | {list}[i] | Remove needs only the header name. | clear the value |
|
||||
| `host.header.secret_unknown` | {list}[i].secret | There is no secret named {secret}. Secrets are listed in ianitor.toml and loaded from the server's credentials. | picker shows `site.secrets` |
|
||||
| `host.header.secret_response` | response_headers[i] | Secrets can only be sent to your service, never back to visitors. | move to request headers |
|
||||
| `host.health.path` | health_check.path | Start with / and use plain characters, like /health. | focus |
|
||||
| `host.health.interval` | health_check.interval_secs | Check every 1 to 3600 seconds. | focus |
|
||||
| `host.field.unknown` | {field} | Ianitor does not know the setting "{field}". | (API clients only) |
|
||||
| `change.conflict` | — | {hostname} was changed at {time} ("{summary}") after you opened it. Your edits are still here. Check them, then Apply again. | "Show the new version" |
|
||||
| `host.not_found` | — | {hostname} is no longer a host. It was removed at {time}. | back to the list |
|
||||
|
||||
Warning, not an error: `host.share.no_signin`: "Anyone can already open {hostname}, so a share link changes nothing." It appears in the share dialog and the form; it doesn't block anything.
|
||||
|
||||
### 3.2 Apply, undo, restore, repository
|
||||
|
||||
| Code | Message | UI offers |
|
||||
|:--|:--|:--|
|
||||
| `apply.queued` | Waiting for "{summary}" to finish, about {seconds} s. | Cancel |
|
||||
| `apply.kept` | {hostname} is live. Health checks passed for 60 s. Saved and sent to Gitea. | Undo |
|
||||
| `apply.kept.no_watch` | {hostname} is live. It has no health check, so Ianitor only checked that it answers. | Add a health check (edit form) |
|
||||
| `apply.reverted.refused` | {hostname} was not {verb}. {upstream} refused the connection on {count} of {of} checks. Ianitor undid the change; every other host kept running. | Edit and try again |
|
||||
| `apply.reverted.timeout` | {hostname} was not {verb}. {upstream} did not answer within 5 seconds on {count} of {of} checks. Ianitor undid the change. | Edit and try again |
|
||||
| `apply.reverted.not_found` | {hostname} was not {verb}. {upstream} says {path} does not exist. Check the health check address. Ianitor undid the change. | Edit health check |
|
||||
| `apply.reverted.server_error` | {hostname} was not {verb}. {upstream} answered with an error page on {count} of {of} checks. Ianitor undid the change. | Edit and try again |
|
||||
| `apply.reverted.redirect` | {hostname} was not {verb}. {upstream} sent visitors elsewhere instead of answering {path}. Use an address that answers directly, like /health. | Edit health check |
|
||||
| `apply.reverted.sign_in` | {hostname} was not {verb}. {upstream} asked for a sign-in on {path}. Use an address that answers without signing in. | Edit health check |
|
||||
| `apply.reverted.name` | {hostname} was not {verb}. The name {upstream_host} could not be found on this network. | Edit and try again |
|
||||
| `apply.reverted.tls` | {hostname} was not {verb}. {upstream} uses https://, but its certificate could not be checked. | Edit and try again |
|
||||
| `apply.failed.reload` | {engine} did not take the new settings, so nothing changed. Every host kept running. | Show details |
|
||||
| `apply.failed.build` | Ianitor could not build the settings for this change, so nothing changed. | Show details |
|
||||
| `apply.failed.validation` | This change no longer fits with the routes: {first_error}. Nothing changed. | Edit and try again |
|
||||
| `apply.interrupted` | Ianitor restarted during the check, so it undid the change to be safe. | Try again |
|
||||
| `apply.needs_attention` | The change failed its check, and Ianitor could not undo it by itself. Visitors are served the last good settings, but the routes repository still has the change. | Restore last kept version (1 click, `POST /restore` with `undo.target`) |
|
||||
| `push.failed.unreachable` | Kept, but not yet saved to Gitea: Gitea did not answer. Ianitor tries again at {time}. | Try now |
|
||||
| `push.failed.rejected` | Kept, but Gitea has changes Ianitor does not have, so nothing was sent. Nothing is lost on this server. | Show details |
|
||||
| `push.failed.auth` | Kept, but Gitea refused Ianitor's access key. Check the key in Custos. | Try now |
|
||||
| `undo.nothing` | Nothing to undo yet. | — |
|
||||
| `undo.watching` | Wait for the check to finish ({seconds} s). | — |
|
||||
| `undo.target_moved` | The last change is now "{summary}", so Undo did nothing. Look again and choose. | bar refreshes |
|
||||
| `restore.same` | This version is the same as the current one. Nothing to restore. | Close |
|
||||
| `restore.not_kept` | This change was undone at the time, so there is nothing to go back to. | Edit and try again |
|
||||
| `repo.unreadable` | {file} in the routes repository cannot be read (line {line}). Changes are paused until it is fixed. | Show details |
|
||||
|
||||
`{verb}` is "added", "changed" or "removed", from the change kind. `{engine}` is "Pingora" or "Caddy"; product names are allowed.
|
||||
|
||||
### 3.3 Host health lines (main screen) and visitor errors
|
||||
|
||||
| `failure.kind` | Row line |
|
||||
|:--|:--|
|
||||
| `refused` | Connection refused for {duration}. Visitors see a "not reachable" page. |
|
||||
| `timeout` | Not answering for {duration}. Visitors see a "not reachable" page. |
|
||||
| `name` | The name {upstream_host} cannot be found. Visitors see a "not reachable" page. |
|
||||
| `tls` | The certificate of {upstream} cannot be checked. |
|
||||
| `bad_answer` | Answering with an error page for {duration}. |
|
||||
| partial (degraded) | {n} of {m} addresses answer. Visitors are sent to the ones that do. |
|
||||
| `unknown` | No health check set for this host. |
|
||||
| `pending` | Waiting for the first check. |
|
||||
| cert `pending` | Waiting for Let's Encrypt to issue the certificate. |
|
||||
| cert `failed` | Let's Encrypt could not confirm {hostname}. The name must point to this server, and port 80 must be open from the internet. — offers Try again |
|
||||
| `health.unavailable` (global) | Ianitor cannot read health from {engine} right now. Traffic is not affected. |
|
||||
|
||||
### 3.4 Share links
|
||||
|
||||
Admin side:
|
||||
|
||||
| Code | Message | UI offers |
|
||||
|:--|:--|:--|
|
||||
| `share.disabled` | Share links are off for {hostname}. Turning them on is a change to the host, checked like any other. | Turn on share links and apply |
|
||||
| `share.prefix` | Start with /, like /share/summer-2026. / shares the whole site. | focus |
|
||||
| `share.expiry` | Choose between 1 hour and 90 days. | — |
|
||||
| `share.password_short` | Use at least 8 characters. | focus |
|
||||
| `share.stopped` | Stopped. The link stops working within a few seconds. | — |
|
||||
| `share.stopped_all` | All share links are stopped. New ones work as usual. | — |
|
||||
| `share.engine_caddy` | Share links are paused while Caddy serves. They work again after switching back. (Only if G7 is not solved.) | — |
|
||||
|
||||
Visitor side (pages in §4):
|
||||
|
||||
| Code | Heading | Text | Offers |
|
||||
|:--|:--|:--|:--|
|
||||
| `share.visit.password` | This link is protected | Someone shared {hostname} with you. Enter the password they gave you. | Password field, Open |
|
||||
| `share.visit.wrong_password` | (same page) | That password is not right. Check it with the person who sent the link. | field cleared and focused |
|
||||
| `share.visit.too_many` | (same page) | Too many tries. Wait a minute, then try again. | button disabled |
|
||||
| `share.visit.expired` | This link has expired | It worked until {date}. Ask the person who sent it for a new one. | Have an account? Sign in |
|
||||
| `share.visit.invalid` (stopped, altered, other host, share links turned off) | This link no longer works | It may have been stopped, or not copied in full. Ask the person who sent it for a new one. | Have an account? Sign in |
|
||||
| outside the prefix | — (no page) | the request goes to the normal sign-in, as if there were no link | — |
|
||||
| `visit.unreachable` | This site is not reachable right now | The service behind this address is not answering. It is not your connection. Try again in a few minutes. | Try again |
|
||||
|
||||
Don't tell "stopped" apart from "altered": both use `invalid`. "Expired" is told apart because the signature proves the date.
|
||||
|
||||
### 3.5 API tokens, sign-in, limits, connection
|
||||
|
||||
| Code | Message | Who sees it | Offers |
|
||||
|:--|:--|:--|:--|
|
||||
| `token.missing` | This request needs an API token. Make one in Settings, API. | script | — |
|
||||
| `token.unknown` | This API token is not one Ianitor issued, or it was copied incompletely. | script | — |
|
||||
| `token.expired` | This API token expired on {date}. Make a new one in Settings, API, then revoke this one. | script | — |
|
||||
| `token.revoked` | This API token was revoked on {date}. | script | — |
|
||||
| `token.created` | Copied. Paste it into Custos now. Ianitor cannot show it again. | UI | Copy again, I have saved it |
|
||||
| `token.revoke_done` | Revoked. Anything using "{name}" stops working now. | UI | — |
|
||||
| `rate.limited` | Too many requests in a short time. Try again in {seconds} s. | both; UI retries once by itself first | — |
|
||||
| `ui.signed_out` | Your sign-in has ended. Sign in again; this page keeps what you typed. | UI | Sign in |
|
||||
| `ui.lost_contact` | Ianitor's control service is not answering. Traffic keeps flowing; changes wait until it is back. | UI | retries every 5 s |
|
||||
| `control.paused` | Changes are paused: {reason}. Traffic keeps flowing. | UI | per reason |
|
||||
|
||||
Detecting sign-out: when Authelia's session ends, edge returns its portal redirect as is. The UI uses `fetch(..., {redirect: "manual"})` and treats an `opaqueredirect` or a `401` as `ui.signed_out`. Nothing from control is needed.
|
||||
|
||||
Rate limits [J]: 120 requests a minute per signed-in user or token; share-link mint 30 a minute; token creation 10 an hour. Wrong share passwords: 5 a minute per link and visitor /24. Answers carry `retry_after_s`.
|
||||
|
||||
### 3.6 PKI (Phase 3)
|
||||
|
||||
| Code | Message | Offers |
|
||||
|:--|:--|:--|
|
||||
| `pki.waiting` | Open Custos on your phone. Approve only if it shows the same code: {code}. | Cancel request |
|
||||
| `pki.denied` | The request was turned down in Custos. Nothing was issued. | Try again |
|
||||
| `pki.expired` | Nobody approved it within 10 minutes, so the request closed. Nothing was issued. | Try again |
|
||||
| `pki.custos_unreachable` | Custos is not answering, so the request could not be sent. | Try again |
|
||||
| `pki.device_name_taken` | A device named "{name}" already has a certificate. Use another name, or revoke the old one first. | Show it |
|
||||
| `pki.issued` | {name} has a certificate. Approved in Custos at {time}. | Show QR code, Download file |
|
||||
| `pki.bundle_used` | This download was already used. Make a new one from the device's row. | — |
|
||||
| `pki.renew_due` | The Domi intermediate certificate expires in {days} days, on {date}. | Renew |
|
||||
| `pki.renew_urgent` | The Domi intermediate certificate expires in {days} days. After that, Domi certificates stop working. | Renew |
|
||||
| `pki.intermediate_expired` | The Domi intermediate certificate expired on {date}. Hosts with a Domi certificate are not trusted until it is renewed. | Renew |
|
||||
| `pki.renewed` | Renewed. The Domi intermediate certificate is now valid until {date}. | — |
|
||||
|
||||
## 4. Share-link visitor pages (served by edge)
|
||||
|
||||
These are four pages: password prompt (with its wrong-password and too-many states), link expired, link no longer works, and service not reachable.
|
||||
|
||||
**Build constraints**
|
||||
- One self-contained HTML file per page with inline CSS, under 8 KB. No JavaScript, no external requests, no web fonts. These pages must work on a visitor's phone with nothing else loaded. System font stack: `system-ui, -apple-system, "Segoe UI", Roboto, sans-serif`.
|
||||
- Headers: `Cache-Control: no-store`, `Referrer-Policy: no-referrer`, `X-Robots-Tag: noindex`, `Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; form-action 'self'`. `lang="en"`. Status codes are not visible to visitors: prompt 401, expired 410, invalid 403, not reachable 502.
|
||||
- Password form: `POST` to a reserved path `/.well-known/ianitor/share` with hidden `t` (the token) and `password`. On success, edge sets an HttpOnly, Secure, SameSite=Lax cookie scoped to the host and `path_prefix` until the link's expiry. It then redirects to the prefix *without* `?share=` so the token never sits in the address bar or a referrer. A link without a password takes the same redirect at once.
|
||||
- Only the hostname and the expiry date come from the request. Escape both. Nothing else from the request is echoed.
|
||||
|
||||
**Layout** (murex palette, same on all four)
|
||||
- `body`: background `#0c0b0f` (ground), text `#f1edf3`, margin 0. Centre one card vertically and horizontally; on a phone it sits 16 px from each edge.
|
||||
- Card: max-width 420 px, padding 32 px (24 px under 480 px wide), background `#18151d` (surface), border 1 px `#3c3445`, radius 18 px.
|
||||
- Top of the card: the hostname in `#cfc6d4`, 0.95 rem, weight 600, the only line that changes per host. Then the heading, 1.5 rem, weight 700, `#f1edf3`. Then body text, 1 rem, line-height 1.5, `#cfc6d4`.
|
||||
- A 40 px stroke icon above the heading: a lock for the prompt, a clock for expired, a broken link for invalid, a cloud with a slash for not reachable. Expired and invalid icons in `#d99a35`; not reachable in `#e2683a`; the lock in `#e0a3dc`.
|
||||
- Password field: label "Password" above it, `#cfc6d4` 0.9 rem. Field height 48 px, background `#0c0b0f`, border 1 px `#7d7189`, radius 10 px, text `#f1edf3`. Focus: border `#e0a3dc` plus a 4 px ring `rgba(224,163,220,0.16)`. `autocomplete="current-password"`, `autofocus`.
|
||||
- Primary button "Open": full width, 48 px high, radius 12 px. Fill: gradient top to bottom `#8d3b89` → `#76306f` 55% → `#5c2257`. Edge 1 px `#c77cc1`; label `#ffffff`, weight 700. Focus ring `#f2c9ee`.
|
||||
- Error line under the field (wrong password, too many tries): `#e2683a`, 0.92 rem, with a small ring icon, announced with `role="alert"`. Never colour alone; the words carry it.
|
||||
- Secondary link "Have an account? Sign in": `#e0a3dc`, underlined, 44 px tall hit area. It points to the host root without `?share=`.
|
||||
- "Try again" on the not-reachable page: an outline button (border `#7d7189`, text `#f1edf3`), as a plain link to the same URL.
|
||||
- Footer under the card, outside it: "IANITOR DOMI" in `#a99eb1`, 0.72 rem, letter-spacing 0.2em, uppercase. Small and plain; no other branding.
|
||||
|
||||
**Copy, exactly**
|
||||
|
||||
Password prompt:
|
||||
> photos.home.example
|
||||
> **This link is protected**
|
||||
> Someone shared photos.home.example with you. Enter the password they gave you.
|
||||
> Password [__________]
|
||||
> [ Open ]
|
||||
> The link works until 14 November 2026.
|
||||
|
||||
Wrong password: the same page, with "That password is not right. Check it with the person who sent the link." under the field, which comes back empty.
|
||||
Too many tries: the same page, with "Too many tries. Wait a minute, then try again." The Open button is disabled for that response.
|
||||
|
||||
Link expired:
|
||||
> photos.home.example
|
||||
> **This link has expired**
|
||||
> It worked until 14 November 2026. Ask the person who sent it for a new one.
|
||||
> Have an account? Sign in
|
||||
|
||||
Link no longer works:
|
||||
> photos.home.example
|
||||
> **This link no longer works**
|
||||
> It may have been stopped, or not copied in full. Ask the person who sent it for a new one.
|
||||
> Have an account? Sign in
|
||||
|
||||
Not reachable (any host, shared or not; the main screen points to it):
|
||||
> photos.home.example
|
||||
> **This site is not reachable right now**
|
||||
> The service behind this address is not answering. It is not your connection. Try again in a few minutes.
|
||||
> [ Try again ]
|
||||
|
||||
## 5. Gaps, and what I recommend
|
||||
|
||||
| # | Gap | Recommendation |
|
||||
|:--|:--|:--|
|
||||
| G1 | Edge keeps health in memory with no way out [C: edge/src/health.rs keeps one healthy bit per upstream, no latency, no failure kind, no history]. The main screen, the watch and the revert reasons all need it. | Edge exposes a read-only status endpoint on a Unix socket only control can read. Per upstream: state, last check time, latency, failure kind, the last 5 results. Control caches it for `/overview`. Under Caddy, map the admin API's `/reverse_proxy/upstreams`; latency and failure kind are null there, and the UI hides them. |
|
||||
| G2 | The boards show "degraded: slow, 2.8 s, limit is 2 s" and a history entry "health limit 2 s", but the schema has no latency limit (fixed 5 s timeout [C]). | No limit in v1. Degraded = some upstreams fail, or mixed results in the last 5 checks. I will correct the boards in Phase 3. |
|
||||
| G3 | A host without a health check gives the 60 s watch nothing to judge, so "auto-kept or auto-reverted" is empty. A default check on / would revert apps that redirect to a login page (edge counts only 2xx as healthy [C]). | During the watch only, test each touched host without a health check by connecting and sending `GET /`; any answer below 500 counts as alive. Message `apply.kept.no_watch`. Don't add a default health check to new hosts. |
|
||||
| G4 | ROADMAP doesn't say which hosts the watch judges. | Only the hosts the change touches; a host that was already down never triggers a revert. Check every 5 s during the watch. |
|
||||
| G5 | Let's Encrypt issuance can take longer than 60 s and is not part of keep or revert. | Keep it out of the watch; report it as `hosts[].certificate` with its own messages and Try again. |
|
||||
| G6 | Core validation errors are written per file in schema words (`{file}: upstream \`x\` is not usable: …`, "TOML") and carry no field path or stable code [C: core/src/error.rs]. | Add `code()`, `field()` and `params()` to `ValidationError`, using §3.1's codes and field paths. Keep the existing text as `detail`. The API maps code to the §3.1 message. |
|
||||
| G7 | Under the Caddy fallback no one checks share tokens. Caddy cannot verify them, yet the engine popover promises "share links stay the same". | Compile share-link hosts for Caddy with `forward_auth` to a small validator on loopback, from the same core code. If that is too much for v1, show `share.engine_caddy` and change the popover copy. |
|
||||
| G8 | ROADMAP revokes share links "by key rotation or a small deny list", but the key comes from systemd credentials, which control cannot rotate at runtime. A deny list that goes through the routes repo would make Stop wait 60 s and add a git commit. | Stop one link: a deny-list file outside git that edge reloads within 5 s, with no watch. Stop all: an `epoch` number inside every token and in the edge config; raising it ends every old link without changing the key. |
|
||||
| G9 | "Optional password hash" inside a stateless token lets anyone holding the link guess the password offline. | The token carries only a "needs a password" flag. Edge checks `HMAC(key, link_id ‖ password)`, so guessing needs the server. Rate-limit in edge (§3.5). |
|
||||
| G10 | Share link when links are off for the host: 4 clicks (handover c). Turning them on is an apply with a 60 s watch, and the clipboard needs a click after it. | Accept 4 for that path and say so in §4: "3 clicks, 4 if share links are off". The common path stays 3. |
|
||||
| G11 | The link is minted when the dialog opens, so changing expiry or prefix would leave unused valid links behind. | `replaces` on the mint call stops the previous one (§1.5). |
|
||||
| G12 | API token: copying is a 4th click (handover c). | Click 3 "Make and copy token" uses an async `ClipboardItem`; that needs the POST to answer in under 1 s. If Mark rejects writing a secret to the clipboard in the same click, accept 4. |
|
||||
| G13 | Device cert: install is a 4th click (handover c), because approval in Custos is asynchronous. | Accept "3 to issue, +1 to install" in §4. No API change removes it. |
|
||||
| G14 | The UI is identified by `Remote-User` from edge, but any local process can send that header to control on loopback. | The admin host's file sets a request header from a systemd-credential secret (an existing feature), and control requires it on every request. Alternatively, control listens on a Unix socket that only edge can reach. Plus the `X-Ianitor-UI` header against CSRF. |
|
||||
| G15 | A device QR code must point to a download the tablet can reach, and control is loopback only. | A one-time download route on the admin host, served by edge to control, valid for 10 minutes and one use. Phase 3. |
|
||||
| G16 | ROADMAP doesn't define Undo after an Undo. | "Revert the last kept commit" means a redo. Name it with `effect` (§2.3), so the button never surprises. |
|
||||
| G17 | A reverted attempt is a commit plus a revert in git, but the UI shows one entry, and "Edit and try again" needs what was tried. | Control groups them into one history entry and keeps `attempted_host` for each reverted or failed change. |
|
||||
| G18 | Engine switch: §1.6 and §3/§4 disagree (handover b). | `overview.engine` now, read only. The switch call waits on Mark's answer. |
|
||||
| G19 | `websockets` defaults to true [C], so a "Websockets" chip would show on almost every row. | The UI shows a chip only when websockets are off ("No websockets"); the API needs no change. |
|
||||
|
||||
## 6. Where the Phase 2 API differs from this contract
|
||||
|
||||
Recorded by the Phase 2 implementation (branch `control/phase-2`). docs/api.md has curl
|
||||
examples; `GET /api/v1/openapi.json` has every shape. Everything not listed here is built as
|
||||
written above.
|
||||
|
||||
**Not built in Phase 2 (Phase 3 items):**
|
||||
- G7: share links work only while Pingora serves. The Caddy JSON ignores `share_links`, so
|
||||
under the fallback a share visitor gets the normal sign-in (fails closed). `share.engine_caddy`
|
||||
is not emitted yet.
|
||||
- G12, G13, G15 (clicks, device certificates and their downloads); §1.7, §1.8 and §3.6 (PKI).
|
||||
- G14: control authenticates with API tokens only and trusts no `Remote-*` header; the UI in
|
||||
Phase 3 needs the G14 mechanism (or a token) to call it.
|
||||
- G18: `overview.engine` is read-only (`running: "pingora"`, `state: "running" | "stopped"`,
|
||||
`fallback_ready: null`); no `POST /engine`.
|
||||
- The "This site is not reachable right now" page (§4): edge still answers an unreachable
|
||||
upstream with an empty `502`, exactly like Caddy, so the differential suite stays exact.
|
||||
Serving the page needs the same page from Caddy's `handle_errors`.
|
||||
- `overview.intermediate` is always `null`.
|
||||
|
||||
**Shapes and behaviour that differ:**
|
||||
- Apply states: there is no `interrupted` state. An apply cut off by a control restart ends as
|
||||
`reverted` with `reason.code = "apply.interrupted"`; one that was still queued ends as
|
||||
`failed` with `apply.interrupted.queued`; a cancelled one as `failed` with `apply.cancelled`.
|
||||
- A change identical to what is live is refused with `409 change.unchanged` instead of
|
||||
becoming a no-op apply.
|
||||
- `reason` is `{code, message, hostname, upstream, field, count, of, detail, params}`; an
|
||||
apply also carries `errors[]`, the full `commit`, `effect` (undo), `actor` (token name) and
|
||||
`attempted_host`. `push` is present only on kept applies; with no remote configured the
|
||||
`push` step is `skipped`.
|
||||
- `apply.kept` says "Health checks passed for {seconds} s." only; the push result is in
|
||||
`push` / `repo`, not in that sentence. Extra codes: `apply.kept.no_watch` (host without a
|
||||
health check), `apply.kept.removed`, `apply.kept.no_edge` (dev mode without a proxy),
|
||||
`apply.reverted.no_answer`, `apply.reverted.edge_lost` (edge restarted or vanished during
|
||||
the watch), `apply.failed.edge_unreachable`.
|
||||
- The watch: touched hosts are probed every `watch_every_secs` (5 s by default). A touched host
|
||||
is reverted when every one of its upstreams failed its last 3 checks, or none passed its
|
||||
last check at the end; hosts that were already `down` before the change are not judged.
|
||||
- `undo.blocked = undo.watching` only while an Undo itself is running; any other running apply
|
||||
just queues the Undo.
|
||||
- `GET /tokens` lists `id`; the id is the non-secret first part of the token
|
||||
(`ian_<id>_<secret>`), so it is a prefix of the token string, but reveals nothing of the
|
||||
secret. `POST /tokens` takes `{name?, expires_in_days?, never_expires?}`.
|
||||
- `GET /history` entries have `reason_short` as the last word of the reason code (e.g.
|
||||
"server error"), and paging uses `before=<change_id>` with `next_before` in the answer.
|
||||
`GET /history/{id}` returns the full apply.
|
||||
- `GET /history/{id}/restore-preview` field keys are `hostname`, `upstreams`, `tls`, `auth`,
|
||||
`websockets`, `share_links`, `access_log`, `health_check.path`,
|
||||
`health_check.interval_secs` and `headers`; it also has `blocked` (`restore.same`,
|
||||
`restore.not_kept`).
|
||||
- Share-link mint answers include `warning` (`host.share.no_signin`) for a host without
|
||||
sign-in. The token is in `?share=`; edge only takes values starting `ish1.`, so an
|
||||
upstream's own `share` parameter still works. The password page's "too many tries" answer
|
||||
is `429`. For a password link the expired page is decided from the token's (unproven) date,
|
||||
because nothing in the token can be proven before the password is given.
|
||||
- `overview.site.acme_configured` is always `true` (Let's Encrypt is the default issuer);
|
||||
extra fields `overview.rev`, `overview.health_error` and `site.share_links_available`.
|
||||
- Health: one admin Unix socket (mode 0660) carries both the read-only `GET /v1/status` and
|
||||
control's reload/trial calls, instead of a separate read-only socket. Edge keeps the last 5
|
||||
results per upstream; `health.since` is tracked by control and restarts with it.
|
||||
- `Idempotency-Key`s are remembered in memory for 24 h; a control restart forgets them. A
|
||||
retry while the first request is still running gets `409 request.in_progress`; with 2,000
|
||||
keys held, a new key gets `429 rate.limited`.
|
||||
- Share links: at most 2,000 active links (`409 share.too_many`). A token in `?share=` on a
|
||||
host without share links is removed before the request goes on.
|
||||
- Wrong share passwords are also limited to 20 a minute per visitor network, whatever the
|
||||
link; when the throttle's table is full, new visitors wait a minute rather than anyone's
|
||||
count being forgotten.
|
||||
- Extra error codes: `change.unchanged`, `host.hostname.mismatch`, `host.upstream.host_name`,
|
||||
`request.*`, `repo.unexpected_file`, `repo.no_remote`, `share.unavailable`,
|
||||
`share.not_found`, `share.replaces`, `share.password_long`, `share.too_many`,
|
||||
`request.in_progress`, `control.files_unwritten`, `token.not_found`, `token.name`,
|
||||
`token.expiry`, `file.*`, `site.*` (problems in `ianitor.toml`).
|
||||
@@ -15,5 +15,8 @@ tokio.workspace = true
|
||||
serde_json.workspace = true
|
||||
rustls.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
ianitor-control = { path = "../../crates/control" }
|
||||
|
||||
[lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
+63
-12
@@ -37,6 +37,9 @@ pub struct Env {
|
||||
pub dir: TempDir,
|
||||
pub ca: TestCa,
|
||||
pub model: Model,
|
||||
/// The routes behind `model`: the site file and `(hosts/<name>.toml, contents)`.
|
||||
pub site: String,
|
||||
pub hosts: Vec<(String, String)>,
|
||||
_upstreams: (Echo, Echo, Echo, Echo, WsEcho, MockAuthelia),
|
||||
}
|
||||
|
||||
@@ -146,6 +149,8 @@ impl Env {
|
||||
dir,
|
||||
ca,
|
||||
model,
|
||||
site,
|
||||
hosts,
|
||||
_upstreams: (app, sick, rr_a, rr_b, ws, auth),
|
||||
}
|
||||
}
|
||||
@@ -197,10 +202,10 @@ pub fn start_edge(env: &Env, name: &'static str, config_text: &str) -> Target {
|
||||
cfg.http_listen.parse().unwrap(),
|
||||
cfg.https_listen.parse().unwrap(),
|
||||
);
|
||||
let rt = Arc::new(
|
||||
ianitor_edge::runtime::build(cfg, Some(&env.dir.join("creds"))).expect("edge runtime"),
|
||||
);
|
||||
let server = ianitor_edge::server(rt, &ianitor_edge::Options::default()).expect("edge server");
|
||||
let rt = ianitor_edge::runtime::build(cfg, Some(&env.dir.join("creds"))).expect("edge runtime");
|
||||
let opts = ianitor_edge::Options::default();
|
||||
let shared = ianitor_edge::shared_for(rt, &opts);
|
||||
let server = ianitor_edge::server(shared, &opts).expect("edge server");
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
std::thread::spawn(move || ianitor_edge::run_until(server, rx));
|
||||
assert!(
|
||||
@@ -219,8 +224,28 @@ pub fn start_edge(env: &Env, name: &'static str, config_text: &str) -> Target {
|
||||
}
|
||||
}
|
||||
|
||||
/// Start `caddy run` on a generated Caddy JSON.
|
||||
/// Start `caddy run` on a generated Caddy JSON; a start that does not come up is retried
|
||||
/// (twice), since a port can be briefly unavailable right after the previous server on it.
|
||||
pub fn start_caddy(env: &Env, name: &'static str, caddy: &std::path::Path, json: &str) -> Target {
|
||||
let mut last = String::new();
|
||||
for _ in 0..3 {
|
||||
match try_start_caddy(env, name, caddy, json) {
|
||||
Ok(t) => return t,
|
||||
Err(e) => {
|
||||
last = e;
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("{last}")
|
||||
}
|
||||
|
||||
fn try_start_caddy(
|
||||
env: &Env,
|
||||
name: &'static str,
|
||||
caddy: &std::path::Path,
|
||||
json: &str,
|
||||
) -> Result<Target, String> {
|
||||
let v: serde_json::Value = serde_json::from_str(json).unwrap();
|
||||
let servers = &v["apps"]["http"]["servers"];
|
||||
let https: SocketAddr = servers["ianitor_https"]["listen"][0]
|
||||
@@ -247,18 +272,21 @@ pub fn start_caddy(env: &Env, name: &'static str, caddy: &std::path::Path, json:
|
||||
.stderr(Stdio::from(log))
|
||||
.spawn()
|
||||
.expect("spawn caddy");
|
||||
let guard = ChildGuard(child);
|
||||
if !wait_for_port(https, Duration::from_secs(20)) {
|
||||
let mut guard = ChildGuard(child);
|
||||
if !wait_for_port(https, Duration::from_secs(20))
|
||||
|| !wait_for_port(http, Duration::from_secs(5))
|
||||
{
|
||||
let _ = guard.0.kill();
|
||||
let _ = guard.0.wait();
|
||||
let out = std::fs::read_to_string(env.dir.join(&format!("{name}.log"))).unwrap_or_default();
|
||||
panic!("caddy did not listen on {https}:\n{out}");
|
||||
return Err(format!("caddy did not listen on {https} / {http}:\n{out}"));
|
||||
}
|
||||
assert!(wait_for_port(http, Duration::from_secs(5)));
|
||||
Target {
|
||||
Ok(Target {
|
||||
name,
|
||||
http,
|
||||
https,
|
||||
_guard: Guard::Caddy(guard),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub enum Action {
|
||||
@@ -877,10 +905,33 @@ fn short(o: &Observation) -> Observation {
|
||||
o
|
||||
}
|
||||
|
||||
/// The host a case is about (its SNI, or the Host header of plain-HTTP cases).
|
||||
pub fn case_host(case: &Case) -> String {
|
||||
match &case.action {
|
||||
Action::Https { sni, .. } | Action::Websocket { sni, .. } => (*sni).to_owned(),
|
||||
Action::Http { req } => req
|
||||
.headers
|
||||
.iter()
|
||||
.find(|(n, _)| n == "host")
|
||||
.map(|(_, v)| v.to_ascii_lowercase())
|
||||
.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Send every case to both targets, one after the other (round robin needs a stable order).
|
||||
pub async fn run_corpus(ianitor: &Target, caddy: &Target, roots: Arc<RootCertStore>) -> Report {
|
||||
run_cases(ianitor, caddy, roots, |_| true).await
|
||||
}
|
||||
|
||||
/// Like [`run_corpus`], for the cases `keep` selects.
|
||||
pub async fn run_cases(
|
||||
ianitor: &Target,
|
||||
caddy: &Target,
|
||||
roots: Arc<RootCertStore>,
|
||||
keep: impl Fn(&Case) -> bool,
|
||||
) -> Report {
|
||||
let mut outcomes = Vec::new();
|
||||
for case in corpus() {
|
||||
for case in corpus().into_iter().filter(|c| keep(c)) {
|
||||
let i = run_case(&case, ianitor, roots.clone()).await;
|
||||
let c = run_case(&case, caddy, roots.clone()).await;
|
||||
outcomes.push(Outcome {
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
// 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 differential suite after every apply (ROADMAP §6 phase 2, "Done"): control applies a
|
||||
//! sequence of changes to a routes repository; after each one, Ianitor runs the edge config
|
||||
//! control wrote and Caddy runs the Caddy JSON control wrote, and the corpus (the cases for
|
||||
//! hosts that exist at that point) must get the same answers from both.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
#[cfg(not(unix))]
|
||||
#[test]
|
||||
fn skipped_on_windows() {
|
||||
eprintln!(
|
||||
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy); run it in WSL2",
|
||||
file!()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
mod unix {
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use ianitor_control::config::{Caddy, Compile, Config, Edge, Routes};
|
||||
use ianitor_control::engine::{Change, Control};
|
||||
use ianitor_control::hostspec::HostSpec;
|
||||
use ianitor_control::repo::{Repo, RouteTree};
|
||||
use ianitor_diff::{Env, case_host, run_cases, settle, start_caddy, start_edge};
|
||||
use ianitor_testkit::proc::require_binary;
|
||||
|
||||
fn compile_of(o: &ianitor_core::compile::CompileOptions) -> Compile {
|
||||
Compile {
|
||||
http_listen: o.http_listen,
|
||||
https_listen: o.https_listen,
|
||||
cert_dir: o.cert_dir.clone(),
|
||||
state_dir: o.state_dir.clone(),
|
||||
access_log: o.access_log.clone(),
|
||||
caddy_credentials_dir: o.caddy_credentials_dir.clone(),
|
||||
caddy_admin: o.caddy_admin,
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_free(addrs: &[SocketAddr]) {
|
||||
let deadline = Instant::now() + Duration::from_secs(15);
|
||||
while addrs
|
||||
.iter()
|
||||
.any(|a| std::net::TcpStream::connect(a).is_ok())
|
||||
&& Instant::now() < deadline
|
||||
{
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
|
||||
async fn apply(ctl: &Control, change: Change) {
|
||||
let rec = ctl
|
||||
.submit(change, None, "diff")
|
||||
.unwrap_or_else(|f| panic!("{f:?}"));
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
let r = ctl.record(&rec.id).unwrap();
|
||||
if !r.is_active() {
|
||||
assert_eq!(r.state, "kept", "{} : {:?}", r.summary, r.reason);
|
||||
return;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "apply did not finish");
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn spec(env: &Env, name: &str) -> HostSpec {
|
||||
let (_, text) = env
|
||||
.hosts
|
||||
.iter()
|
||||
.find(|(p, _)| p == &format!("hosts/{name}.toml"))
|
||||
.unwrap();
|
||||
HostSpec::from_toml(text).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn the_diff_suite_is_green_after_every_apply() {
|
||||
let Some(caddy_bin) = require_binary("caddy") else {
|
||||
return;
|
||||
};
|
||||
let env = Env::start().await;
|
||||
let edge_opts = env.options("edge");
|
||||
let caddy_opts = env.options("caddy");
|
||||
let d = |p: &str| env.dir.join(p);
|
||||
for p in ["ctl-state", "ctl-edge", "ctl-caddy"] {
|
||||
std::fs::create_dir_all(d(p)).unwrap();
|
||||
}
|
||||
let cfg = Config {
|
||||
listen: "127.0.0.1:1".parse().unwrap(),
|
||||
allowed_hosts: Vec::new(),
|
||||
state_dir: d("ctl-state"),
|
||||
credentials_dir: Some(d("creds")),
|
||||
git: PathBuf::from("git"),
|
||||
watch_secs: 1,
|
||||
watch_every_secs: 1,
|
||||
trial_margin_secs: 1,
|
||||
health_poll_secs: 1,
|
||||
routes: Routes {
|
||||
repo: d("routes.git"),
|
||||
branch: "main".into(),
|
||||
remote: None,
|
||||
remote_name: "Gitea".into(),
|
||||
push_username: "ianitor".into(),
|
||||
push_credential: None,
|
||||
},
|
||||
// No edge attached: control writes both files, and each file is tested below.
|
||||
edge: Edge {
|
||||
config: d("ctl-edge/edge.json"),
|
||||
trial: None,
|
||||
admin_socket: None,
|
||||
share_revocations: d("ctl-edge/share-revocations.json"),
|
||||
},
|
||||
caddy: Caddy {
|
||||
config: d("ctl-caddy/caddy.json"),
|
||||
},
|
||||
compile: compile_of(&edge_opts),
|
||||
compile_caddy: Some(compile_of(&caddy_opts)),
|
||||
};
|
||||
|
||||
// Start from the site file and every host except three; then a sequence of applies
|
||||
// ends at the full diff routes.
|
||||
let later = ["hc.test", "hcdown.test", "rr.test"];
|
||||
let repo = Repo::open_seeded(
|
||||
&cfg.git,
|
||||
&cfg.routes.repo,
|
||||
&cfg.state_dir,
|
||||
"main",
|
||||
&env.site,
|
||||
)
|
||||
.unwrap();
|
||||
let head = repo.head_required().unwrap();
|
||||
let mut tree: RouteTree = (*repo.tree(&head).unwrap()).clone();
|
||||
for (p, c) in &env.hosts {
|
||||
if !later.iter().any(|l| p == &format!("hosts/{l}.toml")) {
|
||||
tree.files.insert(p.clone(), c.clone());
|
||||
}
|
||||
}
|
||||
let t = repo.write_tree(&tree, None).unwrap();
|
||||
let c = repo.commit(&t, &[&head], "Diff routes", "test").unwrap();
|
||||
repo.update_ref(&c, Some(&head)).unwrap();
|
||||
drop(repo);
|
||||
|
||||
let ctl = Control::open(cfg.clone()).await.unwrap();
|
||||
tokio::spawn(ctl.clone().worker());
|
||||
|
||||
let steps: Vec<(&str, Option<Change>)> = vec![
|
||||
("start", None),
|
||||
(
|
||||
"add hc.test",
|
||||
Some(Change::Put {
|
||||
spec: spec(&env, "hc.test"),
|
||||
create: true,
|
||||
}),
|
||||
),
|
||||
(
|
||||
"add hcdown.test",
|
||||
Some(Change::Put {
|
||||
spec: spec(&env, "hcdown.test"),
|
||||
create: true,
|
||||
}),
|
||||
),
|
||||
(
|
||||
"remove nows.test",
|
||||
Some(Change::Delete {
|
||||
hostname: "nows.test".into(),
|
||||
}),
|
||||
),
|
||||
(
|
||||
"add rr.test",
|
||||
Some(Change::Put {
|
||||
spec: spec(&env, "rr.test"),
|
||||
create: true,
|
||||
}),
|
||||
),
|
||||
(
|
||||
"restore nows.test",
|
||||
Some(Change::Put {
|
||||
spec: spec(&env, "nows.test"),
|
||||
create: true,
|
||||
}),
|
||||
),
|
||||
];
|
||||
let all_hosts: Vec<String> = env
|
||||
.model
|
||||
.hosts()
|
||||
.iter()
|
||||
.map(|h| h.hostname.to_string())
|
||||
.collect();
|
||||
let mut ran = 0;
|
||||
for (label, change) in steps {
|
||||
if let Some(ch) = change {
|
||||
apply(&ctl, ch).await;
|
||||
}
|
||||
let edge_text = std::fs::read_to_string(&cfg.edge.config).unwrap();
|
||||
let caddy_text = std::fs::read_to_string(&cfg.caddy.config).unwrap();
|
||||
let present: Vec<String> = {
|
||||
let v: serde_json::Value = serde_json::from_str(&edge_text).unwrap();
|
||||
v["hosts"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|h| h["hostname"].as_str().unwrap().to_owned())
|
||||
.collect()
|
||||
};
|
||||
{
|
||||
let ianitor = start_edge(&env, "ianitor", &edge_text);
|
||||
let caddy = start_caddy(&env, "caddy", &caddy_bin, &caddy_text);
|
||||
settle().await;
|
||||
// Cases for hosts that exist now, plus the ones about unknown hosts.
|
||||
let report = run_cases(&ianitor, &caddy, env.roots(), |c| {
|
||||
let h = case_host(c);
|
||||
present.contains(&h) || !all_hosts.contains(&h)
|
||||
})
|
||||
.await;
|
||||
println!("{}", report.render(&format!("after: {label}")));
|
||||
assert!(report.outcomes.len() >= 5, "{label}: too few cases");
|
||||
assert!(report.mismatches().is_empty(), "{}", report.render(label));
|
||||
ran += report.outcomes.len();
|
||||
}
|
||||
wait_free(&[
|
||||
edge_opts.https_listen,
|
||||
edge_opts.http_listen,
|
||||
caddy_opts.https_listen,
|
||||
caddy_opts.http_listen,
|
||||
]);
|
||||
}
|
||||
// The last step is the full routes: every corpus case ran there.
|
||||
assert!(ran > ianitor_diff::corpus().len());
|
||||
let records = ctl.records();
|
||||
assert_eq!(records.iter().filter(|r| r.state == "kept").count(), 5);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
pub mod authelia;
|
||||
pub mod client;
|
||||
pub mod more;
|
||||
pub mod proc;
|
||||
pub mod raw;
|
||||
pub mod tls;
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
// 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/.
|
||||
|
||||
//! Clients the phase 2 tests need: raw request bytes over TLS (for paths a URI type refuses,
|
||||
//! like backslashes), a keep-alive HTTP/1.1 connection that is reused across requests, and
|
||||
//! JSON over a Unix socket (edge's admin socket) or loopback TCP (the control API).
|
||||
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use http_body_util::{BodyExt, Full};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use rustls::RootCertStore;
|
||||
use rustls_pki_types::ServerName;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use crate::client::{Req, Resp, tls_connector};
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
fn other(e: impl std::fmt::Display) -> io::Error {
|
||||
io::Error::other(e.to_string())
|
||||
}
|
||||
|
||||
/// Parse a complete HTTP/1.1 response (Content-Length, chunked or read-to-close).
|
||||
pub fn parse_response(raw: &[u8]) -> io::Result<Resp> {
|
||||
let end = raw
|
||||
.windows(4)
|
||||
.position(|w| w == b"\r\n\r\n")
|
||||
.ok_or_else(|| other("no complete response head"))?;
|
||||
let head = String::from_utf8_lossy(&raw[..end]).into_owned();
|
||||
let mut lines = head.split("\r\n");
|
||||
let status_line = lines.next().unwrap_or_default();
|
||||
let status: u16 = status_line
|
||||
.split(' ')
|
||||
.nth(1)
|
||||
.and_then(|s| s.parse().ok())
|
||||
.ok_or_else(|| other(format!("bad status line {status_line:?}")))?;
|
||||
let headers: Vec<(String, String)> = lines
|
||||
.filter_map(|l| l.split_once(':'))
|
||||
.map(|(n, v)| (n.trim().to_ascii_lowercase(), v.trim().to_owned()))
|
||||
.collect();
|
||||
let mut body = raw[end + 4..].to_vec();
|
||||
if headers
|
||||
.iter()
|
||||
.any(|(n, v)| n == "transfer-encoding" && v.eq_ignore_ascii_case("chunked"))
|
||||
{
|
||||
let mut out = Vec::new();
|
||||
let mut rest = &body[..];
|
||||
while let Some(p) = rest.windows(2).position(|w| w == b"\r\n") {
|
||||
let size = usize::from_str_radix(
|
||||
String::from_utf8_lossy(&rest[..p])
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap_or("0")
|
||||
.trim(),
|
||||
16,
|
||||
)
|
||||
.map_err(other)?;
|
||||
rest = &rest[p + 2..];
|
||||
if size == 0 || rest.len() < size {
|
||||
break;
|
||||
}
|
||||
out.extend_from_slice(&rest[..size]);
|
||||
rest = &rest[(size + 2).min(rest.len())..];
|
||||
}
|
||||
body = out;
|
||||
} else if let Some(len) = headers
|
||||
.iter()
|
||||
.find(|(n, _)| n == "content-length")
|
||||
.and_then(|(_, v)| v.parse::<usize>().ok())
|
||||
{
|
||||
body.truncate(len);
|
||||
}
|
||||
Ok(Resp {
|
||||
status,
|
||||
headers,
|
||||
body,
|
||||
})
|
||||
}
|
||||
|
||||
/// Send `request` (complete raw bytes, which should ask for `Connection: close`) over a fresh
|
||||
/// TLS connection and read until the server closes.
|
||||
pub async fn https_raw(
|
||||
addr: SocketAddr,
|
||||
sni: &str,
|
||||
roots: Arc<RootCertStore>,
|
||||
request: &[u8],
|
||||
) -> io::Result<Resp> {
|
||||
tokio::time::timeout(TIMEOUT, async {
|
||||
let tcp = TcpStream::connect(addr).await?;
|
||||
let name = ServerName::try_from(sni.to_owned()).map_err(other)?;
|
||||
let mut s = tls_connector(roots).connect(name, tcp).await?;
|
||||
s.write_all(request).await?;
|
||||
let mut buf = Vec::new();
|
||||
// A close_notify-less close is fine here.
|
||||
let _ = s.read_to_end(&mut buf).await;
|
||||
parse_response(&buf)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||
}
|
||||
|
||||
/// One HTTP/1.1 connection over TLS, reused for every request until it fails.
|
||||
pub struct KeepAlive {
|
||||
sender: hyper::client::conn::http1::SendRequest<Full<Bytes>>,
|
||||
}
|
||||
|
||||
impl KeepAlive {
|
||||
pub async fn connect(
|
||||
addr: SocketAddr,
|
||||
sni: &str,
|
||||
roots: Arc<RootCertStore>,
|
||||
) -> io::Result<KeepAlive> {
|
||||
let tcp = TcpStream::connect(addr).await?;
|
||||
tcp.set_nodelay(true)?;
|
||||
let name = ServerName::try_from(sni.to_owned()).map_err(other)?;
|
||||
let s = tls_connector(roots).connect(name, tcp).await?;
|
||||
let (sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(s))
|
||||
.await
|
||||
.map_err(other)?;
|
||||
tokio::spawn(async move {
|
||||
let _ = conn.await;
|
||||
});
|
||||
Ok(KeepAlive { sender })
|
||||
}
|
||||
|
||||
/// Send one request on this connection. An `Err` means the connection is gone.
|
||||
pub async fn send(&mut self, req: &Req) -> io::Result<Resp> {
|
||||
self.sender.ready().await.map_err(other)?;
|
||||
let mut b = hyper::Request::builder()
|
||||
.method(req.method.as_str())
|
||||
.uri(req.path.as_str());
|
||||
for (n, v) in &req.headers {
|
||||
b = b.header(n.as_str(), v.as_str());
|
||||
}
|
||||
let request = b
|
||||
.body(Full::new(Bytes::from(req.body.clone())))
|
||||
.map_err(other)?;
|
||||
let resp = tokio::time::timeout(TIMEOUT, self.sender.send_request(request))
|
||||
.await
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||
.map_err(other)?;
|
||||
let status = resp.status().as_u16();
|
||||
let headers = resp
|
||||
.headers()
|
||||
.iter()
|
||||
.map(|(n, v)| {
|
||||
(
|
||||
n.as_str().to_owned(),
|
||||
String::from_utf8_lossy(v.as_bytes()).into_owned(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let body = resp
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.map_err(other)?
|
||||
.to_bytes()
|
||||
.to_vec();
|
||||
Ok(Resp {
|
||||
status,
|
||||
headers,
|
||||
body,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A JSON answer: status and parsed body (`Null` when the body is empty or not JSON).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct JsonResp {
|
||||
pub status: u16,
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub json: serde_json::Value,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
impl JsonResp {
|
||||
pub fn header(&self, name: &str) -> Option<&str> {
|
||||
self.headers
|
||||
.iter()
|
||||
.find(|(n, _)| n.eq_ignore_ascii_case(name))
|
||||
.map(|(_, v)| v.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
fn json_resp(r: Resp) -> JsonResp {
|
||||
let text = String::from_utf8_lossy(&r.body).into_owned();
|
||||
JsonResp {
|
||||
status: r.status,
|
||||
headers: r.headers,
|
||||
json: serde_json::from_str(&text).unwrap_or(serde_json::Value::Null),
|
||||
text,
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_request(
|
||||
method: &str,
|
||||
path: &str,
|
||||
host: &str,
|
||||
headers: &[(&str, &str)],
|
||||
body: Option<&serde_json::Value>,
|
||||
) -> Vec<u8> {
|
||||
let body = body.map(|b| b.to_string()).unwrap_or_default();
|
||||
let mut out = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
|
||||
for (n, v) in headers {
|
||||
out.push_str(&format!("{n}: {v}\r\n"));
|
||||
}
|
||||
if !body.is_empty() || method != "GET" {
|
||||
out.push_str("Content-Type: application/json\r\n");
|
||||
out.push_str(&format!("Content-Length: {}\r\n", body.len()));
|
||||
}
|
||||
out.push_str("\r\n");
|
||||
out.push_str(&body);
|
||||
out.into_bytes()
|
||||
}
|
||||
|
||||
/// A request over a Unix socket (edge's admin socket).
|
||||
#[cfg(unix)]
|
||||
pub async fn unix_json(
|
||||
socket: &std::path::Path,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<&serde_json::Value>,
|
||||
) -> io::Result<JsonResp> {
|
||||
tokio::time::timeout(TIMEOUT, async {
|
||||
let mut s = tokio::net::UnixStream::connect(socket).await?;
|
||||
s.write_all(&raw_request(method, path, "localhost", &[], body))
|
||||
.await?;
|
||||
let mut buf = Vec::new();
|
||||
s.read_to_end(&mut buf).await?;
|
||||
parse_response(&buf).map(json_resp)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||
}
|
||||
|
||||
/// A request over plain TCP (the control API on loopback), with extra headers.
|
||||
pub async fn tcp_json(
|
||||
addr: SocketAddr,
|
||||
method: &str,
|
||||
path: &str,
|
||||
headers: &[(&str, &str)],
|
||||
body: Option<&serde_json::Value>,
|
||||
) -> io::Result<JsonResp> {
|
||||
tokio::time::timeout(Duration::from_secs(120), async {
|
||||
let mut s = TcpStream::connect(addr).await?;
|
||||
s.write_all(&raw_request(method, path, &addr.to_string(), headers, body))
|
||||
.await?;
|
||||
let mut buf = Vec::new();
|
||||
s.read_to_end(&mut buf).await?;
|
||||
parse_response(&buf).map(json_resp)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||
}
|
||||
|
||||
/// Send raw bytes over plain TCP and parse the answer (for malformed requests).
|
||||
pub async fn tcp_raw(addr: SocketAddr, request: &[u8]) -> io::Result<Resp> {
|
||||
tokio::time::timeout(TIMEOUT, async {
|
||||
let mut s = TcpStream::connect(addr).await?;
|
||||
s.write_all(request).await?;
|
||||
let mut buf = Vec::new();
|
||||
s.read_to_end(&mut buf).await?;
|
||||
parse_response(&buf)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||
}
|
||||
@@ -10,13 +10,57 @@ use std::process::Child;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A port on 127.0.0.1 that was free a moment ago.
|
||||
/// The kernel's ephemeral port range (ports it hands to `bind(:0)` and outgoing connections).
|
||||
fn ephemeral_range() -> (u16, u16) {
|
||||
std::fs::read_to_string("/proc/sys/net/ipv4/ip_local_port_range")
|
||||
.ok()
|
||||
.and_then(|s| {
|
||||
let mut it = s.split_whitespace().filter_map(|x| x.parse::<u16>().ok());
|
||||
Some((it.next()?, it.next()?))
|
||||
})
|
||||
.unwrap_or((32768, 60999))
|
||||
}
|
||||
|
||||
/// A port on 127.0.0.1 that is free now, never handed out before by this process, and (where
|
||||
/// possible) outside the ephemeral range, so the kernel does not give it to another socket
|
||||
/// between this call and the server binding it, or while a server restarts on it.
|
||||
pub fn free_port() -> u16 {
|
||||
std::net::TcpListener::bind("127.0.0.1:0")
|
||||
.unwrap()
|
||||
.local_addr()
|
||||
.unwrap()
|
||||
.port()
|
||||
static GIVEN: std::sync::Mutex<Vec<u16>> = std::sync::Mutex::new(Vec::new());
|
||||
let (low, high) = ephemeral_range();
|
||||
let (from, to) = if low > 12_000 {
|
||||
(10_000u32, u32::from(low))
|
||||
} else {
|
||||
(u32::from(high) + 1, 65_000)
|
||||
};
|
||||
let seed = std::process::id().wrapping_mul(2_654_435_761)
|
||||
^ std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.subsec_nanos())
|
||||
.unwrap_or(0);
|
||||
let span = to.saturating_sub(from).max(1);
|
||||
let mut given = GIVEN.lock().unwrap();
|
||||
for k in 0..span {
|
||||
let port = (from + (seed.wrapping_add(k.wrapping_mul(7919))) % span) as u16;
|
||||
if given.contains(&port) {
|
||||
continue;
|
||||
}
|
||||
if std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() {
|
||||
given.push(port);
|
||||
return port;
|
||||
}
|
||||
}
|
||||
// Everything outside the ephemeral range is taken: fall back to the kernel's choice.
|
||||
loop {
|
||||
let port = std::net::TcpListener::bind("127.0.0.1:0")
|
||||
.unwrap()
|
||||
.local_addr()
|
||||
.unwrap()
|
||||
.port();
|
||||
if !given.contains(&port) {
|
||||
given.push(port);
|
||||
return port;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn local(port: u16) -> SocketAddr {
|
||||
|
||||
Reference in New Issue
Block a user