[control] Phase 2 control plane: routes repo via git, journaled apply with trial/watch/revert, undo and restore, push with retry, share links, API tokens, REST API with OpenAPI, --dev
This commit is contained in:
Generated
+147
@@ -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"
|
||||
@@ -1006,13 +1056,22 @@ dependencies = [
|
||||
name = "ianitor-control"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"http",
|
||||
"ianitor-core",
|
||||
"ianitor-edge",
|
||||
"ianitor-testkit",
|
||||
"log",
|
||||
"ring",
|
||||
"rustls",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"toml",
|
||||
"utoipa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1032,6 +1091,7 @@ dependencies = [
|
||||
name = "ianitor-diff"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"ianitor-control",
|
||||
"ianitor-core",
|
||||
"ianitor-edge",
|
||||
"ianitor-testkit",
|
||||
@@ -1208,6 +1268,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown 0.17.1",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1359,6 +1421,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"
|
||||
@@ -1374,6 +1442,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"
|
||||
@@ -2327,6 +2401,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"
|
||||
@@ -2336,6 +2421,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"
|
||||
@@ -2504,6 +2601,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"
|
||||
@@ -2749,6 +2852,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"
|
||||
@@ -2859,6 +2983,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"
|
||||
|
||||
@@ -1,24 +1,39 @@
|
||||
[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"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
[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-dependencies]
|
||||
ianitor-core.workspace = true
|
||||
ianitor-edge.workspace = true
|
||||
ianitor-testkit.workspace = true
|
||||
tokio.workspace = true
|
||||
serde_json.workspace = true
|
||||
ianitor-edge.workspace = true
|
||||
rustls.workspace = true
|
||||
ring.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,467 @@
|
||||
// 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 {
|
||||
Apply(String),
|
||||
Json(u16, serde_json::Value),
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
/// Look up an Idempotency-Key. `Ok(Some)` replays, `Err` when the key was used for
|
||||
/// another request.
|
||||
pub fn idem_get(&self, key: &str, fingerprint: &str) -> Result<Option<Stored>, ApiError> {
|
||||
let Ok(m) = self.idem.lock() else {
|
||||
return Ok(None);
|
||||
};
|
||||
match m.get(key) {
|
||||
Some((fp, _, _)) if fp != fingerprint => Err(ApiError::new(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"request.idempotency",
|
||||
Params::new(),
|
||||
)),
|
||||
Some((_, Stored::Apply(id), _)) => Ok(Some(Stored::Apply(id.clone()))),
|
||||
Some((_, Stored::Json(s, v), _)) => Ok(Some(Stored::Json(*s, v.clone()))),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn idem_put(&self, key: &str, fingerprint: &str, s: Stored) {
|
||||
if let Ok(mut m) = self.idem.lock() {
|
||||
let t = now();
|
||||
m.retain(|_, (_, _, at)| t.saturating_sub(*at) < 86_400);
|
||||
if m.len() >= 2000 {
|
||||
return;
|
||||
}
|
||||
m.insert(key.to_owned(), (fingerprint.to_owned(), s, t));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 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 `") {
|
||||
let mut err = ApiError::new(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"request.body_unknown_field",
|
||||
messages::params([("field", f.clone())]),
|
||||
);
|
||||
err.body.field = Some(f);
|
||||
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());
|
||||
let tok = st.ctl.tokens.check(auth).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,27 @@
|
||||
// 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.
|
||||
|
||||
/// 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// 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};
|
||||
|
||||
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())?;
|
||||
}
|
||||
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); Domi hosts need certificates in {}",
|
||||
b.display(),
|
||||
dir.join("certs").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);
|
||||
}
|
||||
}
|
||||
+183
-5
@@ -2,11 +2,189 @@
|
||||
// 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;
|
||||
}
|
||||
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())
|
||||
}
|
||||
|
||||
fn token(args: &[String]) -> Result<(), String> {
|
||||
let dir = state_dir(args)?;
|
||||
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,274 @@
|
||||
// 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.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.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.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,563 @@
|
||||
// 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",
|
||||
"protocol.file.allow=always",
|
||||
]);
|
||||
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,233 @@
|
||||
// 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::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;
|
||||
|
||||
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,
|
||||
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())
|
||||
}
|
||||
|
||||
fn save(&self, f: &mut ShareFile) -> Result<(), String> {
|
||||
let t = now();
|
||||
f.links.retain(|l| {
|
||||
let end = l.stopped_at.unwrap_or(l.expires_at).min(l.expires_at);
|
||||
t < end.saturating_add(KEEP_SECS)
|
||||
});
|
||||
write_json(&self.path, f)?;
|
||||
self.write_revocations(f)
|
||||
}
|
||||
|
||||
/// Write the revocation file edge reads.
|
||||
pub fn write_revocations(&self, f: &ShareFile) -> Result<(), String> {
|
||||
let t = now();
|
||||
let mut deny: 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();
|
||||
deny.sort();
|
||||
deny.truncate(9_999);
|
||||
// Readable by edge (another user); it holds only random link ids.
|
||||
let text = serde_json::to_vec(&RevocationFile {
|
||||
epoch: f.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 f = self.load()?;
|
||||
self.write_revocations(&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().map_err(MintError::Store)?;
|
||||
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());
|
||||
}
|
||||
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()?;
|
||||
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()?;
|
||||
f.epoch = f.epoch.saturating_add(1);
|
||||
let e = f.epoch;
|
||||
self.save(&mut f)?;
|
||||
Ok(e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
// 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<()>,
|
||||
}
|
||||
|
||||
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(()),
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| "token store unavailable".to_owned())?;
|
||||
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> {
|
||||
Ok(self.load()?.tokens)
|
||||
}
|
||||
|
||||
pub fn revoke(&self, id: &str) -> Result<Option<TokenRecord>, String> {
|
||||
let _g = self
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| "token store unavailable".to_owned())?;
|
||||
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
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| "token store unavailable".to_owned())?;
|
||||
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.lock.lock().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,143 @@
|
||||
// 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<()> {
|
||||
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();
|
||||
name.push(format!(".tmp-{}", 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<()> {
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user