[edge] Reload and share links: in-process config swap with self-reverting trials, admin socket with health and certificate status, share-link cookies, visitor pages and throttle

This commit is contained in:
2026-11-07 17:49:53 +01:00
parent c0ed9c65c5
commit 6ce1fe9d2b
18 changed files with 2137 additions and 186 deletions
Generated
+4
View File
@@ -1038,7 +1038,11 @@ dependencies = [
"arc-swap",
"async-trait",
"bytes",
"form_urlencoded",
"http",
"http-body-util",
"hyper",
"hyper-util",
"ianitor-core",
"ianitor-testkit",
"instant-acme",
+5
View File
@@ -27,6 +27,11 @@ arc-swap = "1.7"
instant-acme = { version = "0.8.5", default-features = false, features = ["ring", "hyper-rustls", "rcgen"] }
x509-parser = "0.18"
thiserror.workspace = true
ring.workspace = true
hyper.workspace = true
hyper-util.workspace = true
http-body-util.workspace = true
form_urlencoded = "1.2"
[dev-dependencies]
ianitor-testkit.workspace = true
+89 -31
View File
@@ -21,13 +21,14 @@ use pingora::server::ShutdownWatch;
use pingora::services::background::BackgroundService;
use crate::logging::now_secs;
use crate::runtime::Runtime;
use crate::tls::{CertStore, certified_key, not_after};
use crate::shared::{CertState, Shared};
use crate::tls::{certified_key, not_after};
const RENEW_BEFORE_SECS: f64 = 30.0 * 86_400.0;
const CHECK_EVERY: Duration = Duration::from_secs(12 * 3600);
const FIRST_RETRY: Duration = Duration::from_secs(30);
const MAX_RETRY: Duration = Duration::from_secs(3600);
const MIN_GAP: Duration = Duration::from_secs(5);
/// HTTP-01 tokens → key authorizations, shared with the HTTP listener.
#[derive(Default)]
@@ -52,8 +53,7 @@ impl Challenges {
}
pub struct AcmeService {
pub rt: Arc<Runtime>,
pub certs: Arc<CertStore>,
pub shared: Arc<Shared>,
pub challenges: Arc<Challenges>,
/// Extra trust root for the ACME directory (tests against Pebble only).
pub ca_root: Option<PathBuf>,
@@ -84,7 +84,7 @@ fn fnv(data: &[u8]) -> String {
impl AcmeService {
fn dir(&self) -> PathBuf {
self.rt.acme_dir()
self.shared.current().acme_dir()
}
fn paths(&self, host: &str) -> (PathBuf, PathBuf) {
@@ -102,7 +102,8 @@ impl AcmeService {
let expiry = not_after(&cert_pem)?;
match certified_key(&cert_pem, &key_pem) {
Ok(ck) => {
self.certs.insert(host, ck);
self.shared.certs.insert(host, ck);
self.ok(host, expiry);
Some(expiry)
}
Err(e) => {
@@ -207,18 +208,30 @@ impl AcmeService {
let (crt, key) = self.paths(host);
write_private(&key, key_pem.as_bytes())?;
write_private(&crt, chain_pem.as_bytes())?;
self.certs.insert(host, ck);
self.shared.certs.insert(host, ck);
self.ok(host, expiry);
log::info!(target: "ianitor::acme", "{host}: certificate issued, valid until {expiry}");
Ok(expiry)
}
/// One pass over every ACME host. Returns false if any host failed.
fn ok(&self, host: &str, expiry: i64) {
self.shared.set_cert_state(
host,
CertState {
state: "ok",
not_after: Some(expiry),
error: None,
},
);
}
async fn round(&self, expiries: &mut HashMap<String, i64>) -> bool {
let Some(acme) = &self.rt.cfg.acme else {
let rt = self.shared.current();
let Some(acme) = &rt.cfg.acme else {
return true;
};
let due: Vec<String> = self
.rt
let due: Vec<String> = rt
.acme_hosts()
.into_iter()
.filter(|h| {
@@ -230,10 +243,25 @@ impl AcmeService {
if due.is_empty() {
return true;
}
for h in &due {
if !expiries.contains_key(h) {
self.shared.set_cert_state(
h,
CertState {
state: "pending",
not_after: None,
error: None,
},
);
}
}
let account = match self.account(&acme.directory, acme.email.as_deref()).await {
Ok(a) => a,
Err(e) => {
log::error!(target: "ianitor::acme", "{e}");
for h in &due {
self.failed(h, expiries.get(h).copied(), &e);
}
return false;
}
};
@@ -245,43 +273,73 @@ impl AcmeService {
}
Err(e) => {
log::error!(target: "ianitor::acme", "{host}: could not obtain a certificate: {e}");
self.failed(&host, expiries.get(&host).copied(), &e);
ok = false;
}
}
}
ok
}
/// A host that still has a valid certificate stays `ok` while renewal retries.
fn failed(&self, host: &str, expiry: Option<i64>, error: &str) {
let still_valid = expiry.is_some_and(|e| (e as f64) > now_secs());
self.shared.set_cert_state(
host,
CertState {
state: if still_valid { "ok" } else { "failed" },
not_after: expiry,
error: Some(error.chars().take(300).collect()),
},
);
}
}
#[async_trait]
impl BackgroundService for AcmeService {
async fn start(&self, mut shutdown: ShutdownWatch) {
if self.rt.acme_hosts().is_empty() {
return;
}
let dir = self.dir();
if let Err(e) = std::fs::create_dir_all(&dir) {
log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display());
return;
}
let mut expiries = HashMap::new();
for h in self.rt.acme_hosts() {
if let Some(e) = self.load_stored(&h) {
expiries.insert(h, e);
}
}
let mut retry = FIRST_RETRY;
let mut last: Option<std::time::Instant> = None;
loop {
let wait = if self.round(&mut expiries).await {
retry = FIRST_RETRY;
CHECK_EVERY
} else {
let w = retry;
retry = (retry * 2).min(MAX_RETRY);
w
};
// Reloads can come many times a second; ACME rounds at most every 5 s.
if let Some(l) = last
&& l.elapsed() < MIN_GAP
{
tokio::select! {
_ = tokio::time::sleep(MIN_GAP - l.elapsed()) => {}
_ = shutdown.changed() => return,
}
}
last = Some(std::time::Instant::now());
let hosts = self.shared.current().acme_hosts();
let mut wait = CHECK_EVERY;
if !hosts.is_empty() {
let dir = self.dir();
if let Err(e) = std::fs::create_dir_all(&dir) {
log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display());
} else {
for h in hosts {
if !expiries.contains_key(&h)
&& let Some(e) = self.load_stored(&h)
{
expiries.insert(h, e);
}
}
wait = if self.round(&mut expiries).await {
retry = FIRST_RETRY;
CHECK_EVERY
} else {
let w = retry;
retry = (retry * 2).min(MAX_RETRY);
w
};
}
}
// Woken early by a reload (new hosts) or a "try again" from control.
tokio::select! {
_ = tokio::time::sleep(wait) => {}
_ = self.shared.acme_wake.notified() => {}
_ = shutdown.changed() => return,
}
}
+326
View File
@@ -0,0 +1,326 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The admin socket: a Unix socket (mode 0660, so only edge's user and group, i.e. control,
//! can connect; never a TCP port) speaking small JSON over HTTP/1.1.
//!
//! | Request | Does |
//! |:--|:--|
//! | `GET /v1/status` | config hash, trial, revocations, health per host and upstream, certificates |
//! | `POST /v1/reload` | reload the config file (refused while a trial runs) |
//! | `POST /v1/trial {confirm_within_secs, watch_hosts?, watch_every_secs?}` | serve the trial file until confirmed |
//! | `POST /v1/confirm {config_sha256}` | keep the running trial |
//! | `POST /v1/abort` | back to the config before the trial (idempotent) |
//! | `POST /v1/share-revocations/reload` | re-read the share-link revocation file |
//! | `POST /v1/acme/retry` | try Let's Encrypt again now |
//!
//! Bodies are at most 4 KiB with no unknown fields. Answers never carry a secret.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use bytes::Bytes;
use http_body_util::{BodyExt, Full, Limited};
use hyper::body::Incoming;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use pingora::server::ShutdownWatch;
use pingora::services::background::BackgroundService;
use serde::Deserialize;
use serde_json::{Value, json};
use crate::shared::{AdminError, Shared, WatchSpec};
const MAX_BODY: usize = 4096;
/// Longest trial the admin socket accepts.
const MAX_TRIAL_SECS: u64 = 3600;
pub struct AdminSocket {
pub shared: Arc<Shared>,
pub path: PathBuf,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TrialBody {
confirm_within_secs: u64,
#[serde(default)]
watch_hosts: Vec<String>,
watch_every_secs: Option<u64>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ConfirmBody {
config_sha256: String,
}
type Resp = Response<Full<Bytes>>;
fn reply(status: StatusCode, v: Value) -> Resp {
let mut r = Response::new(Full::new(Bytes::from(v.to_string())));
*r.status_mut() = status;
r.headers_mut().insert(
http::header::CONTENT_TYPE,
http::HeaderValue::from_static("application/json"),
);
r
}
fn error(status: StatusCode, message: impl std::fmt::Display) -> Resp {
reply(status, json!({ "error": message.to_string() }))
}
fn admin_error(e: AdminError) -> Resp {
match e {
AdminError::Refused(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
AdminError::Conflict(m) => error(StatusCode::CONFLICT, m),
}
}
/// The status document.
pub fn status(shared: &Shared) -> Value {
let rt = shared.current();
let mut hosts: Vec<&String> = rt.hosts.keys().collect();
hosts.sort();
let hosts: Vec<Value> = hosts
.into_iter()
.filter_map(|name| rt.hosts.get(name))
.map(|h| {
let name = &h.cfg.hostname;
let cert = match &h.cfg.tls {
ianitor_core::edge_config::EdgeTls::Files { .. } => json!({
"state": "ok",
"not_after": rt.file_cert_expiry.get(name),
"error": null,
}),
ianitor_core::edge_config::EdgeTls::Acme => match shared.cert_state(name) {
Some(c) => {
json!({ "state": c.state, "not_after": c.not_after, "error": c.error })
}
None => json!({ "state": "pending", "not_after": null, "error": null }),
},
};
json!({
"hostname": name,
"health_check": h.cfg.health_check.is_some(),
"upstreams": h.upstreams.iter().map(|u| json!({
"address": u.authority,
"healthy": u.healthy.load(std::sync::atomic::Ordering::Relaxed),
"checks": u.health.checks(),
})).collect::<Vec<_>>(),
"certificate": cert,
})
})
.collect();
let rev = shared.revocations();
json!({
"generation": shared.generation(),
"config_sha256": rt.sha256,
"started_at": shared.started_at,
"trial": shared.trial_info().map(|(sha, left, prev)| json!({
"config_sha256": sha,
"seconds_left": left,
"previous_sha256": prev,
})),
"share_revocations": {
"loaded": rev.loaded,
"epoch": rev.revocations.epoch,
"stopped": rev.revocations.deny.len(),
"error": rev.error,
},
"hosts": hosts,
})
}
async fn body<T: for<'de> Deserialize<'de>>(
req: Request<Incoming>,
) -> Result<Option<T>, Box<Resp>> {
let bytes = Limited::new(req.into_body(), MAX_BODY)
.collect()
.await
.map_err(|_| {
error(
StatusCode::PAYLOAD_TOO_LARGE,
"the body is larger than 4 KiB",
)
})?
.to_bytes();
if bytes.is_empty() {
return Ok(None);
}
serde_json::from_slice(&bytes)
.map(Some)
.map_err(|e| Box::new(error(StatusCode::BAD_REQUEST, format!("bad body: {e}"))))
}
async fn handle(shared: Arc<Shared>, req: Request<Incoming>) -> Resp {
let method = req.method().clone();
let path = req.uri().path().to_owned();
match (method.as_str(), path.as_str()) {
("GET", "/v1/status") => reply(StatusCode::OK, status(&shared)),
("POST", "/v1/reload") => {
let r = tokio::task::spawn_blocking({
let s = shared.clone();
move || s.reload()
})
.await;
match r {
Ok(Ok(rt)) => reply(
StatusCode::OK,
json!({ "config_sha256": rt.sha256, "generation": shared.generation() }),
),
Ok(Err(e)) => admin_error(e),
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
}
}
("POST", "/v1/trial") => {
let b: TrialBody = match body(req).await {
Ok(Some(b)) => b,
Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"),
Err(r) => return *r,
};
if !(1..=MAX_TRIAL_SECS).contains(&b.confirm_within_secs) {
return error(
StatusCode::BAD_REQUEST,
"confirm_within_secs must be between 1 and 3600",
);
}
let every = b.watch_every_secs.unwrap_or(5);
if !(1..=60).contains(&every) || b.watch_hosts.len() > 1000 {
return error(StatusCode::BAD_REQUEST, "watch_every_secs must be 1 to 60");
}
let watch = (!b.watch_hosts.is_empty()).then(|| WatchSpec {
hosts: b.watch_hosts,
every: Duration::from_secs(every),
});
let within = Duration::from_secs(b.confirm_within_secs);
let r = tokio::task::spawn_blocking({
let s = shared.clone();
move || s.start_trial(within, watch)
})
.await;
match r {
Ok(Ok((id, rt))) => {
let s = shared.clone();
tokio::spawn(async move {
if let Some(deadline) = s.trial_deadline(id) {
tokio::time::sleep_until(deadline.into()).await;
s.expire_trial(id);
}
});
reply(
StatusCode::OK,
json!({ "config_sha256": rt.sha256, "generation": shared.generation() }),
)
}
Ok(Err(e)) => admin_error(e),
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
}
}
("POST", "/v1/confirm") => {
let b: ConfirmBody = match body(req).await {
Ok(Some(b)) => b,
Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"),
Err(r) => return *r,
};
match shared.confirm(&b.config_sha256) {
Ok(()) => reply(StatusCode::OK, json!({ "confirmed": true })),
Err(e) => admin_error(e),
}
}
("POST", "/v1/abort") => reply(StatusCode::OK, json!({ "reverted": shared.abort() })),
("POST", "/v1/share-revocations/reload") => match shared.reload_revocations() {
Ok(()) => {
let r = shared.revocations();
reply(
StatusCode::OK,
json!({ "epoch": r.revocations.epoch, "stopped": r.revocations.deny.len() }),
)
}
Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
},
("POST", "/v1/acme/retry") => {
shared.acme_wake.notify_one();
reply(StatusCode::OK, json!({ "retrying": true }))
}
(_, "/v1/status" | "/v1/reload" | "/v1/trial" | "/v1/confirm" | "/v1/abort") => {
error(StatusCode::METHOD_NOT_ALLOWED, "method not allowed")
}
_ => error(StatusCode::NOT_FOUND, "no such admin request"),
}
}
fn bind(path: &Path) -> std::io::Result<tokio::net::UnixListener> {
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
// A socket left over from a previous run is removed; anything else at the path is not.
if let Ok(meta) = std::fs::symlink_metadata(path) {
if meta.file_type().is_socket() {
std::fs::remove_file(path)?;
} else {
return Err(std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
format!("{} exists and is not a socket", path.display()),
));
}
}
let l = tokio::net::UnixListener::bind(path)?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o660))?;
Ok(l)
}
#[async_trait]
impl BackgroundService for AdminSocket {
async fn start(&self, mut shutdown: ShutdownWatch) {
let listener = match bind(&self.path) {
Ok(l) => l,
Err(e) => {
log::error!(target: "ianitor::admin", "cannot listen on {}: {e}; control cannot reach edge", self.path.display());
return;
}
};
log::info!(target: "ianitor::admin", "admin socket at {}", self.path.display());
loop {
tokio::select! {
_ = shutdown.changed() => break,
a = listener.accept() => {
let Ok((stream, _)) = a else { continue };
let shared = self.shared.clone();
tokio::spawn(async move {
let svc = service_fn(move |req| {
let shared = shared.clone();
async move { Ok::<_, std::convert::Infallible>(handle(shared, req).await) }
});
let _ = http1::Builder::new()
.serve_connection(TokioIo::new(stream), svc)
.await;
});
}
}
}
let _ = std::fs::remove_file(&self.path);
}
}
/// Re-reads the share-link revocation file when it changes (every 5 s), so a stopped link
/// stops even if control's reload request was lost.
pub struct RevocationPoller {
pub shared: Arc<Shared>,
}
#[async_trait]
impl BackgroundService for RevocationPoller {
async fn start(&self, mut shutdown: ShutdownWatch) {
loop {
tokio::select! {
_ = shutdown.changed() => return,
_ = tokio::time::sleep(Duration::from_secs(5)) => self.shared.poll_revocations(),
}
}
}
}
+188 -49
View File
@@ -4,57 +4,153 @@
//! Active health checks, like Caddy's `health_checks.active`: `GET <path>` with the upstream
//! address as Host, healthy on 2xx, 5 s timeout, one result flips the state. The first round
//! runs at startup; upstreams start healthy.
//! runs when a config is loaded; upstreams start healthy.
//!
//! Every result is also recorded (time, latency, why it failed) for the admin socket.
//! During a trial, the watched hosts are probed at least every `every` seconds; a watched
//! host without a health check gets `GET /` with its own hostname as Host, and any answer
//! below 500 counts as alive (docs/ui-api.md G3). Those watch probes never change routing.
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::{Duration, Instant};
use async_trait::async_trait;
use pingora::connectors::http::Connector;
use pingora::http::RequestHeader;
use pingora::server::ShutdownWatch;
use pingora::services::background::BackgroundService;
use pingora::{Error, ErrorType};
use crate::fetch::fetch;
use crate::runtime::{HostRt, Runtime, UpstreamRt};
use crate::logging::now_secs;
use crate::runtime::{Check, HostRt, UpstreamRt};
use crate::shared::Shared;
const TIMEOUT: Duration = Duration::from_secs(5);
pub struct HealthChecks {
pub rt: Arc<Runtime>,
pub shared: Arc<Shared>,
}
async fn probe(connector: &Connector, u: &UpstreamRt, path: &str) -> bool {
let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else {
return false;
/// Why a probe failed, in the words of docs/ui-api.md §3.3.
pub fn failure_kind(e: &Error) -> &'static str {
match e.etype() {
ErrorType::ConnectRefused | ErrorType::ConnectError | ErrorType::ConnectionClosed => {
"refused"
}
ErrorType::ConnectTimedout
| ErrorType::ReadTimedout
| ErrorType::WriteTimedout
| ErrorType::TLSHandshakeTimedout => "timeout",
ErrorType::ConnectNoRoute => "name",
ErrorType::TLSHandshakeFailure | ErrorType::InvalidCert | ErrorType::HandshakeError => {
"tls"
}
_ => "bad_answer",
}
}
fn status_kind(status: u16) -> &'static str {
match status {
300..=399 => "redirect",
401 | 403 => "sign_in",
404 => "not_found",
500..=599 => "server_error",
_ => "bad_answer",
}
}
/// One probe. `watch` probes count any answer below 500 as alive.
async fn probe(
connector: &Connector,
u: &UpstreamRt,
path: &str,
host: &str,
watch: bool,
) -> Check {
let started = Instant::now();
let at = now_secs() as u64;
let source = if watch { "watch" } else { "health_check" };
let fail = |kind: &'static str, status: Option<u16>, latency: Option<u64>| Check {
seq: 0,
at,
ok: false,
source,
kind: Some(kind),
status,
latency_ms: latency,
};
if req
.insert_header(http::header::HOST, u.authority.as_str())
.is_err()
{
return false;
let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else {
return fail("bad_answer", None, None);
};
if req.insert_header(http::header::HOST, host).is_err() {
return fail("bad_answer", None, None);
}
match fetch(connector, u, req, 64 * 1024, TIMEOUT).await {
Ok(f) => f.header.status.is_success(),
Err(_) => false,
Ok(f) => {
let status = f.header.status.as_u16();
let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
let ok = if watch {
(100..500).contains(&status)
} else {
f.header.status.is_success()
};
if ok {
Check {
seq: 0,
at,
ok: true,
source,
kind: None,
status: Some(status),
latency_ms: Some(latency),
}
} else {
fail(status_kind(status), Some(status), Some(latency))
}
}
Err(e) => fail(failure_kind(&e), None, None),
}
}
/// One round over a host's upstreams. Each probe runs in its own task, so a panic inside a
/// probe (e.g. a library bug on an odd answer) marks that upstream unhealthy instead of
/// ending health checks.
async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>) {
async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>, watch: bool) {
for i in 0..host.upstreams.len() {
let (h, p, c) = (host.clone(), path.to_owned(), connector.clone());
let ok = match tokio::spawn(async move { probe(&c, &h.upstreams[i], &p).await }).await {
Ok(ok) => ok,
let probe_host = if watch {
host.cfg.hostname.clone()
} else {
host.upstreams[i].authority.clone()
};
let check = match tokio::spawn(async move {
probe(&c, &h.upstreams[i], &p, &probe_host, watch).await
})
.await
{
Ok(c) => c,
Err(e) => {
log::error!(target: "ianitor::health", "{}: health check of {} crashed ({e}); counting it as failed", host.cfg.hostname, host.upstreams[i].authority);
false
Check {
seq: 0,
at: now_secs() as u64,
ok: false,
source: if watch { "watch" } else { "health_check" },
kind: Some("bad_answer"),
status: None,
latency_ms: None,
}
}
};
let u = &host.upstreams[i];
let ok = check.ok;
u.health.record(check);
if watch {
// Watch probes only report; routing follows the host's own health check.
continue;
}
if u.healthy.swap(ok, Ordering::Relaxed) != ok {
if ok {
log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority);
@@ -65,50 +161,93 @@ async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>) {
}
}
async fn watch(host: Arc<HostRt>, path: String, every: Duration) {
async fn watcher(host: Arc<HostRt>, path: String, every: Duration, watch: bool) {
let connector = Arc::new(Connector::new(None));
loop {
round(&host, &path, &connector).await;
round(&host, &path, &connector, watch).await;
tokio::time::sleep(every).await;
}
}
struct Job {
host: Arc<HostRt>,
path: String,
every: Duration,
watch: bool,
}
fn jobs(shared: &Shared) -> Vec<Job> {
let rt = shared.current();
let spec = shared.watch_spec();
let watched = |h: &str| {
spec.as_ref()
.is_some_and(|s| s.hosts.iter().any(|w| w == h))
};
let every = spec.as_ref().map(|s| s.every);
let mut out = Vec::new();
for h in rt.hosts.values() {
let name = &h.cfg.hostname;
match &h.cfg.health_check {
Some(hc) => {
let mut interval = Duration::from_secs(u64::from(hc.interval_secs.max(1)));
if watched(name)
&& let Some(e) = every
{
interval = interval.min(e);
}
out.push(Job {
host: h.clone(),
path: hc.path.clone(),
every: interval,
watch: false,
});
}
None if watched(name) => out.push(Job {
host: h.clone(),
path: "/".into(),
every: every.unwrap_or(Duration::from_secs(5)),
watch: true,
}),
None => {}
}
}
out
}
#[async_trait]
impl BackgroundService for HealthChecks {
async fn start(&self, mut shutdown: ShutdownWatch) {
let checked: Vec<(Arc<HostRt>, String, Duration)> = self
.rt
.hosts
.values()
.filter_map(|h| {
h.cfg.health_check.as_ref().map(|hc| {
(
h.clone(),
hc.path.clone(),
Duration::from_secs(u64::from(hc.interval_secs.max(1))),
)
})
})
.collect();
let mut tasks = tokio::task::JoinSet::new();
let mut which = std::collections::HashMap::new();
for (i, (h, p, every)) in checked.iter().enumerate() {
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i);
}
// A watcher never returns; if one ends anyway, say so and start it again.
let mut changes = self.shared.subscribe();
loop {
tokio::select! {
_ = shutdown.changed() => break,
Some(done) = tasks.join_next_with_id() => {
let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() };
if let Some(i) = which.remove(&id) {
let (h, p, every) = &checked[i];
log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", h.cfg.hostname);
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i);
let jobs = jobs(&self.shared);
let mut tasks = tokio::task::JoinSet::new();
let mut which = std::collections::HashMap::new();
for (i, j) in jobs.iter().enumerate() {
let id = tasks
.spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch))
.id();
which.insert(id, i);
}
// Run until the config or the watch changes; a watcher never returns, and if one
// ends anyway, say so and start it again.
let stop = loop {
tokio::select! {
_ = shutdown.changed() => break true,
r = changes.changed() => break r.is_err(),
Some(done) = tasks.join_next_with_id() => {
let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() };
if let Some(i) = which.remove(&id) {
let j = &jobs[i];
log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", j.host.cfg.hostname);
which.insert(tasks.spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch)).id(), i);
}
}
}
};
tasks.abort_all();
if stop {
return;
}
}
tasks.abort_all();
}
}
+6 -5
View File
@@ -19,10 +19,10 @@ use pingora::server::ShutdownWatch;
use crate::acme::Challenges;
use crate::logging::{AccessRecord, now_secs, truncate_ip};
use crate::proxy::{host_header, hostname};
use crate::runtime::Runtime;
use crate::shared::Shared;
pub struct HttpApp {
pub rt: Arc<Runtime>,
pub shared: Arc<Shared>,
pub challenges: Arc<Challenges>,
}
@@ -75,6 +75,7 @@ impl HttpServerApp for HttpApp {
impl HttpApp {
async fn response(&self, session: &mut ServerSession) -> Response<Vec<u8>> {
let start = Instant::now();
let rt = self.shared.current();
let req = session.req_header();
let hh = host_header(req);
let name = hostname(&hh);
@@ -92,11 +93,11 @@ impl HttpApp {
return r;
}
let Some(host) = self.rt.host(&name) else {
let Some(host) = rt.host(&name) else {
return empty(StatusCode::NOT_FOUND);
};
let uri = req.uri.path_and_query().map_or("/", |p| p.as_str());
let port = self.rt.cfg.https_port;
let port = rt.cfg.https_port;
let location = if port == 443 {
format!("https://{name}{uri}")
} else {
@@ -110,7 +111,7 @@ impl HttpApp {
Err(_) => return empty(StatusCode::BAD_REQUEST),
}
if host.cfg.access_log
&& let Some(log) = &self.rt.access_log
&& let Some(log) = &rt.access_log
{
log.write(&AccessRecord {
ts: now_secs(),
+80 -15
View File
@@ -5,23 +5,29 @@
//! Ianitor edge: the Pingora data plane. It reads the config compiled by `ianitor-core`
//! and serves it; it never decides policy.
//!
//! Services: HTTPS reverse proxy (SNI certificates, forward-auth, websockets, header rules,
//! round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and redirects),
//! health checks, ACME issuance and renewal.
//! Services: HTTPS reverse proxy (SNI certificates, forward-auth, share links, websockets,
//! header rules, round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and
//! redirects), health checks, ACME issuance and renewal, and the admin socket through which
//! control reloads the config in process (see `shared`).
pub mod acme;
#[cfg(unix)]
pub mod admin;
pub mod error;
pub mod fetch;
pub mod forward_auth;
pub mod health;
pub mod http_app;
pub mod logging;
pub mod pages;
pub mod proxy;
pub mod runtime;
pub mod secrets;
pub mod share;
pub mod shared;
pub mod tls;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use pingora::connectors::http::Connector;
@@ -34,24 +40,63 @@ use pingora::services::listening::Service;
pub use error::EdgeError;
pub use runtime::Runtime;
pub use shared::Shared;
#[derive(Debug, Clone, Default)]
pub struct Options {
/// The compiled edge config (`ianitor-core` edge compiler output).
pub config: PathBuf,
/// The trial config control writes before an apply; default `<config>.trial`.
pub trial_config: Option<PathBuf>,
/// Admin socket for control (Unix only); none when `None`.
pub admin_socket: Option<PathBuf>,
/// The share-link revocation file control writes; without it, share links are refused.
pub share_revocations: Option<PathBuf>,
/// Extra trust root for the ACME directory's TLS (Pebble in tests).
pub acme_root: Option<PathBuf>,
}
impl Options {
pub fn trial_path(&self) -> PathBuf {
self.trial_config
.clone()
.unwrap_or_else(|| default_trial_path(&self.config))
}
}
/// `<config>.trial`, next to the config.
pub fn default_trial_path(config: &Path) -> PathBuf {
let mut name = config.file_name().unwrap_or_default().to_os_string();
name.push(".trial");
config.with_file_name(name)
}
fn credentials_dir() -> Option<PathBuf> {
std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from)
}
/// Read the config, load secrets from `$CREDENTIALS_DIRECTORY`, load certificates.
pub fn prepare(opts: &Options) -> Result<Arc<Runtime>, EdgeError> {
let cfg = runtime::read_config(&opts.config)?;
let creds = std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from);
runtime::build(cfg, creds.as_deref()).map(Arc::new)
pub fn prepare(opts: &Options) -> Result<Arc<Shared>, EdgeError> {
let creds = credentials_dir();
let rt = runtime::build_file(&opts.config, creds.as_deref())?;
Ok(shared_for(rt, opts))
}
/// Wrap an already built runtime (tests run edge in process this way).
pub fn shared_for(rt: Runtime, opts: &Options) -> Arc<Shared> {
Shared::new(
rt,
shared::Paths {
config: opts.config.clone(),
trial: opts.trial_path(),
revocations: opts.share_revocations.clone(),
},
credentials_dir(),
)
}
/// Assemble the Pingora server with all services. Listeners bind when it runs.
pub fn server(rt: Arc<Runtime>, opts: &Options) -> Result<Server, EdgeError> {
pub fn server(shared: Arc<Shared>, opts: &Options) -> Result<Server, EdgeError> {
pingora::tls::install_default_crypto_provider();
let conf = ServerConf {
threads: 2,
@@ -63,11 +108,12 @@ pub fn server(rt: Arc<Runtime>, opts: &Options) -> Result<Server, EdgeError> {
server.bootstrap();
let challenges = Arc::new(acme::Challenges::default());
let rt = shared.current();
let mut https = http_proxy_service(
&server.configuration,
proxy::EdgeProxy {
rt: rt.clone(),
shared: shared.clone(),
connector: Connector::new(None),
},
);
@@ -75,14 +121,14 @@ pub fn server(rt: Arc<Runtime>, opts: &Options) -> Result<Server, EdgeError> {
address: rt.cfg.https_listen.clone(),
reason: e.to_string(),
})?;
tls.set_cert_resolver(rt.certs.clone());
tls.set_cert_resolver(shared.certs.clone());
tls.enable_h2();
https.add_tls_with_settings(&rt.cfg.https_listen, None, tls);
let mut http = Service::new(
"ianitor http".to_owned(),
http_app::HttpApp {
rt: rt.clone(),
shared: shared.clone(),
challenges: challenges.clone(),
},
);
@@ -92,17 +138,36 @@ pub fn server(rt: Arc<Runtime>, opts: &Options) -> Result<Server, EdgeError> {
server.add_service(http);
server.add_service(background_service(
"ianitor health checks",
health::HealthChecks { rt: rt.clone() },
health::HealthChecks {
shared: shared.clone(),
},
));
server.add_service(background_service(
"ianitor acme",
acme::AcmeService {
rt: rt.clone(),
certs: rt.certs.clone(),
shared: shared.clone(),
challenges,
ca_root: opts.acme_root.clone(),
},
));
#[cfg(unix)]
{
server.add_service(background_service(
"ianitor share revocations",
admin::RevocationPoller {
shared: shared.clone(),
},
));
if let Some(path) = &opts.admin_socket {
server.add_service(background_service(
"ianitor admin socket",
admin::AdminSocket {
shared: shared.clone(),
path: path.clone(),
},
));
}
}
Ok(server)
}
+10 -5
View File
@@ -2,7 +2,8 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! `ianitor-edge --config <edge.json> [--check] [--acme-root <ca.pem>]`
//! `ianitor-edge --config <edge.json> [--check] [--admin-socket <path>] [--trial-config <path>]
//! [--share-revocations <path>] [--acme-root <ca.pem>]`
//!
//! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG`
//! (error, warn, info, debug, trace; libraries are capped at info).
@@ -21,10 +22,14 @@ fn parse_args() -> Result<(Options, bool), EdgeError> {
match a.to_str() {
Some("--config") => config = args.next().map(PathBuf::from),
Some("--acme-root") => opts.acme_root = args.next().map(PathBuf::from),
Some("--admin-socket") => opts.admin_socket = args.next().map(PathBuf::from),
Some("--trial-config") => opts.trial_config = args.next().map(PathBuf::from),
Some("--share-revocations") => opts.share_revocations = args.next().map(PathBuf::from),
Some("--check") => check = true,
Some("--help" | "-h") => {
println!(
"usage: ianitor-edge --config <edge.json> [--check] [--acme-root <ca.pem>]"
"usage: ianitor-edge --config <edge.json> [--check] [--admin-socket <path>] \
[--trial-config <path>] [--share-revocations <path>] [--acme-root <ca.pem>]"
);
std::process::exit(0);
}
@@ -44,12 +49,12 @@ fn parse_args() -> Result<(Options, bool), EdgeError> {
fn main() -> ExitCode {
ianitor_edge::logging::init(std::env::var("IANITOR_LOG").ok().as_deref());
let started = parse_args().and_then(|(opts, check)| {
let rt = ianitor_edge::prepare(&opts)?;
log::info!(target: "ianitor::edge", "config {} loaded: {} hosts", opts.config.display(), rt.hosts.len());
let shared = ianitor_edge::prepare(&opts)?;
log::info!(target: "ianitor::edge", "config {} loaded: {} hosts", opts.config.display(), shared.current().hosts.len());
if check {
return Ok(None);
}
ianitor_edge::server(rt, &opts).map(Some)
ianitor_edge::server(shared, &opts).map(Some)
});
match started {
Ok(None) => ExitCode::SUCCESS,
+211
View File
@@ -0,0 +1,211 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The share-link visitor pages (docs/ui-api.md §4): one self-contained HTML page each, inline
//! CSS, no JavaScript, no external requests, under 8 KB. Only the hostname and a date come
//! from the request side, both escaped; the token is echoed only into the password form's
//! hidden field (it is already in the visitor's address bar at that point), escaped too.
use ianitor_core::share::PASSWORD_PATH;
use ianitor_core::time::long_date;
pub enum Problem {
WrongPassword,
TooMany,
}
pub enum Page<'a> {
Password {
host: &'a str,
token: &'a str,
until: u64,
problem: Option<Problem>,
},
Expired {
host: &'a str,
until: u64,
},
Invalid {
host: &'a str,
},
}
impl Page<'_> {
pub fn status(&self) -> u16 {
match self {
Page::Password {
problem: Some(Problem::TooMany),
..
} => 429,
Page::Password { .. } => 401,
Page::Expired { .. } => 410,
Page::Invalid { .. } => 403,
}
}
}
pub fn escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
c if c.is_control() => {}
c => out.push(c),
}
}
out
}
const STYLE: &str = "\
*{box-sizing:border-box}\
body{margin:0;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;\
background:#0c0b0f;color:#f1edf3;font-family:system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif;padding:16px}\
.card{width:100%;max-width:420px;padding:32px;background:#18151d;border:1px solid #3c3445;border-radius:18px}\
@media (max-width:480px){.card{padding:24px}}\
.host{color:#cfc6d4;font-size:.95rem;font-weight:600;margin:0 0 16px;overflow-wrap:anywhere}\
svg{display:block;margin:0 0 12px}\
h1{font-size:1.5rem;font-weight:700;color:#f1edf3;margin:0 0 8px}\
p{font-size:1rem;line-height:1.5;color:#cfc6d4;margin:0 0 16px}\
label{display:block;color:#cfc6d4;font-size:.9rem;margin:0 0 6px}\
input[type=password]{width:100%;height:48px;background:#0c0b0f;border:1px solid #7d7189;border-radius:10px;\
color:#f1edf3;font-size:1rem;padding:0 12px}\
input[type=password]:focus{outline:none;border-color:#e0a3dc;box-shadow:0 0 0 4px rgba(224,163,220,.16)}\
.err{color:#e2683a;font-size:.92rem;margin:8px 0 0;display:flex;gap:6px;align-items:center}\
button{margin-top:16px;width:100%;height:48px;border-radius:12px;border:1px solid #c77cc1;color:#fff;font-weight:700;\
font-size:1rem;background:linear-gradient(#8d3b89,#76306f 55%,#5c2257)}\
button:focus{outline:2px solid #f2c9ee;outline-offset:2px}\
button:disabled{opacity:.5}\
.small{font-size:.92rem;margin:16px 0 0}\
a{color:#e0a3dc;display:inline-flex;align-items:center;min-height:44px}\
footer{color:#a99eb1;font-size:.72rem;letter-spacing:.2em;text-transform:uppercase;margin-top:16px}";
fn icon(kind: &str) -> String {
let (colour, body) = match kind {
// lock
"lock" => (
"#e0a3dc",
"<rect x=\"8\" y=\"18\" width=\"24\" height=\"16\" rx=\"3\"/><path d=\"M13 18v-5a7 7 0 0 1 14 0v5\"/>",
),
// clock
"clock" => (
"#d99a35",
"<circle cx=\"20\" cy=\"20\" r=\"14\"/><path d=\"M20 12v8l5 4\"/>",
),
// broken link
_ => (
"#d99a35",
"<path d=\"M17 23l-3 3a5 5 0 0 1-7-7l3-3\"/><path d=\"M23 17l3-3a5 5 0 0 0-7-7l-3 3\"/><path d=\"M8 8l3 3M29 29l3 3M28 12h4M8 28H12\"/>",
),
};
format!(
"<svg width=\"40\" height=\"40\" viewBox=\"0 0 40 40\" fill=\"none\" stroke=\"{colour}\" stroke-width=\"2.2\" \
stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">{body}</svg>"
)
}
const RING: &str = "<svg width=\"14\" height=\"14\" viewBox=\"0 0 14 14\" fill=\"none\" stroke=\"#e2683a\" stroke-width=\"2\" aria-hidden=\"true\"><circle cx=\"7\" cy=\"7\" r=\"5\"/></svg>";
fn shell(host: &str, inner: &str, title: &str) -> String {
format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
<meta name=\"referrer\" content=\"no-referrer\"><meta name=\"robots\" content=\"noindex\">\
<title>{title}</title><style>{STYLE}</style></head><body><main class=\"card\">\
<p class=\"host\">{}</p>{inner}</main><footer>Ianitor Domi</footer></body></html>",
escape(host)
)
}
pub fn render(p: &Page<'_>) -> String {
match p {
Page::Password {
host,
token,
until,
problem,
} => {
let h = escape(host);
let (msg, disabled) = match problem {
Some(Problem::WrongPassword) => (
format!(
"<p class=\"err\" role=\"alert\">{RING}That password is not right. Check it with the person who sent the link.</p>"
),
"",
),
Some(Problem::TooMany) => (
format!(
"<p class=\"err\" role=\"alert\">{RING}Too many tries. Wait a minute, then try again.</p>"
),
" disabled",
),
None => (String::new(), ""),
};
let inner = format!(
"{}<h1>This link is protected</h1>\
<p>Someone shared {h} with you. Enter the password they gave you.</p>\
<form method=\"post\" action=\"{PASSWORD_PATH}\">\
<input type=\"hidden\" name=\"t\" value=\"{}\">\
<label for=\"pw\">Password</label>\
<input id=\"pw\" type=\"password\" name=\"password\" autocomplete=\"current-password\" autofocus required>\
{msg}<button type=\"submit\"{disabled}>Open</button></form>\
<p class=\"small\">The link works until {}.</p>",
icon("lock"),
escape(token),
long_date(*until)
);
shell(host, &inner, "This link is protected")
}
Page::Expired { host, until } => {
let inner = format!(
"{}<h1>This link has expired</h1>\
<p>It worked until {}. Ask the person who sent it for a new one.</p>\
<a href=\"/\">Have an account? Sign in</a>",
icon("clock"),
long_date(*until)
);
shell(host, &inner, "This link has expired")
}
Page::Invalid { host } => {
let inner = format!(
"{}<h1>This link no longer works</h1>\
<p>It may have been stopped, or not copied in full. Ask the person who sent it for a new one.</p>\
<a href=\"/\">Have an account? Sign in</a>",
icon("broken")
);
shell(host, &inner, "This link no longer works")
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pages_are_small_and_escaped() {
for p in [
Page::Password {
host: "<b>x</b>",
token: "\"><script>",
until: 1_794_666_000,
problem: Some(Problem::WrongPassword),
},
Page::Expired {
host: "a.test",
until: 0,
},
Page::Invalid { host: "a.test" },
] {
let html = render(&p);
assert!(html.len() < 8 * 1024, "{}", html.len());
assert!(!html.contains("<script"));
assert!(!html.contains("<b>x"));
assert!(!html.contains("http://") && !html.contains("https://"));
}
}
}
+47 -9
View File
@@ -22,13 +22,17 @@ use crate::fetch;
use crate::forward_auth::{self, Outcome};
use crate::logging::{AccessRecord, now_secs, truncate_ip};
use crate::runtime::{HostRt, Op, Runtime};
use crate::share::{self, Decision};
use crate::shared::Shared;
pub struct EdgeProxy {
pub rt: Arc<Runtime>,
pub shared: Arc<Shared>,
pub connector: Connector,
}
pub struct Ctx {
/// The runtime current when the request started; used for the whole request.
rt: Option<Arc<Runtime>>,
host: Option<Arc<HostRt>>,
/// Chosen upstream and its resolved addresses; connect failures move to the next address.
upstream: Option<usize>,
@@ -113,6 +117,7 @@ impl ProxyHttp for EdgeProxy {
fn new_ctx(&self) -> Ctx {
Ctx {
rt: None,
host: None,
upstream: None,
addrs: Vec::new(),
@@ -123,15 +128,37 @@ impl ProxyHttp for EdgeProxy {
}
async fn request_filter(&self, session: &mut Session, ctx: &mut Ctx) -> Result<bool> {
let rt = self.shared.current();
ctx.rt = Some(rt.clone());
ctx.host_header = host_header(session.req_header());
let Some(host) = self.rt.host(&hostname(&ctx.host_header)).cloned() else {
let Some(host) = rt.host(&hostname(&ctx.host_header)).cloned() else {
respond_empty(session, 404).await?;
return Ok(true);
};
ctx.host = Some(host.clone());
let mut shared_access = false;
if host.cfg.share_links {
let ip = client_ip(session);
let revs = self.shared.revocations();
match share::handle(
session,
&host.cfg.hostname,
rt.share_key.as_deref(),
&revs,
&self.shared.throttle,
ip,
)
.await?
{
Decision::Answered => return Ok(true),
Decision::Allowed => shared_access = true,
Decision::Continue => {}
}
}
if host.cfg.forward_auth {
let fa = self.rt.forward_auth.as_ref().ok_or_else(|| {
let fa = rt.forward_auth.as_ref().ok_or_else(|| {
Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured")
})?;
// Client-sent identity headers never survive, whatever copy_headers says.
@@ -139,6 +166,10 @@ impl ProxyHttp for EdgeProxy {
for name in &fa.strip_headers {
req.remove_header(name);
}
if shared_access {
// A valid share link stands in for the sign-in on its prefix.
return self.after_auth(session, &host).await;
}
let ip = client_ip(session).map(|i| i.to_string());
let outcome = match forward_auth::check(
&self.connector,
@@ -180,11 +211,7 @@ impl ProxyHttp for EdgeProxy {
}
}
if !host.cfg.websockets && is_websocket_upgrade(session.req_header()) {
respond_empty(session, 403).await?;
return Ok(true);
}
Ok(false)
self.after_auth(session, &host).await
}
async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result<Box<HttpPeer>> {
@@ -350,7 +377,7 @@ impl ProxyHttp for EdgeProxy {
if !host.cfg.access_log {
return;
}
let Some(log) = &self.rt.access_log else {
let Some(log) = ctx.rt.as_ref().and_then(|rt| rt.access_log.as_ref()) else {
return;
};
let req = session.req_header();
@@ -372,6 +399,17 @@ impl ProxyHttp for EdgeProxy {
}
}
impl EdgeProxy {
/// The steps after the sign-in check: websocket refusal.
async fn after_auth(&self, session: &mut Session, host: &HostRt) -> Result<bool> {
if !host.cfg.websockets && is_websocket_upgrade(session.req_header()) {
respond_empty(session, 403).await?;
return Ok(true);
}
Ok(false)
}
}
pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
}
+161 -20
View File
@@ -2,31 +2,81 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The compiled edge config turned into ready-to-serve state: resolved upstream addresses,
//! parsed header names, secrets loaded, certificates loaded. Built once at startup.
//! The compiled edge config turned into ready-to-serve state: parsed upstreams and header
//! names, secrets loaded, certificates loaded, the share-link key loaded. Built at startup
//! and again on every reload; a reload swaps the whole [`Runtime`] at once (see `shared`).
use std::collections::{BTreeSet, HashMap};
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use http::{HeaderName, HeaderValue};
use ianitor_core::edge_config::{
EDGE_CONFIG_VERSION, EdgeConfig, EdgeHeaderOp, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
};
use ianitor_core::share::{KEY_CREDENTIAL, ShareKey};
use rustls::sign::CertifiedKey;
use serde::Serialize;
use crate::error::EdgeError;
use crate::logging::AccessLog;
use crate::secrets::Secrets;
use crate::tls::{CertStore, certified_key};
use crate::tls::{certified_key, not_after};
pub enum Op {
Set(HeaderName, HeaderValue),
Remove(HeaderName),
}
/// One health probe result, as reported on the admin socket.
#[derive(Debug, Clone, Serialize)]
pub struct Check {
/// Increases by one per probe of this upstream.
pub seq: u64,
/// Unix seconds.
pub at: u64,
pub ok: bool,
/// `health_check` (the host's own check) or `watch` (`GET /` during a trial).
pub source: &'static str,
/// `refused`, `timeout`, `name`, `tls`, `server_error`, `not_found`, `redirect`,
/// `sign_in` or `bad_answer`; `None` when `ok`.
pub kind: Option<&'static str>,
pub status: Option<u16>,
pub latency_ms: Option<u64>,
}
/// The last few probe results of one upstream.
#[derive(Default)]
pub struct HealthRecord {
inner: Mutex<(u64, VecDeque<Check>)>,
}
/// How many results are kept per upstream.
pub const KEPT_CHECKS: usize = 5;
impl HealthRecord {
pub fn record(&self, mut c: Check) {
if let Ok(mut g) = self.inner.lock() {
g.0 += 1;
c.seq = g.0;
g.1.push_back(c);
while g.1.len() > KEPT_CHECKS {
g.1.pop_front();
}
}
}
pub fn checks(&self) -> Vec<Check> {
self.inner
.lock()
.map(|g| g.1.iter().cloned().collect())
.unwrap_or_default()
}
}
pub struct UpstreamRt {
/// Host name or IP literal (IPv6 without brackets).
pub host: String,
@@ -36,6 +86,7 @@ pub struct UpstreamRt {
pub tls: bool,
pub sni: String,
pub healthy: AtomicBool,
pub health: HealthRecord,
}
pub struct HostRt {
@@ -61,7 +112,15 @@ pub struct Runtime {
pub hosts: HashMap<String, Arc<HostRt>>,
pub forward_auth: Option<ForwardAuthRt>,
pub access_log: Option<AccessLog>,
pub certs: Arc<CertStore>,
/// Domi certificates (`tls = "domi"`), by hostname.
pub file_certs: HashMap<String, Arc<CertifiedKey>>,
/// `notAfter` (Unix seconds) of each Domi certificate.
pub file_cert_expiry: HashMap<String, i64>,
/// Loaded when any host has share links.
pub share_key: Option<Arc<ShareKey>>,
/// SHA-256 (hex) of the config file bytes this runtime was built from; empty when it was
/// built from a parsed config.
pub sha256: String,
}
impl Runtime {
@@ -83,12 +142,45 @@ impl Runtime {
}
}
pub fn read_config(path: &Path) -> Result<EdgeConfig, EdgeError> {
let text = std::fs::read_to_string(path).map_err(|source| EdgeError::Read {
pub fn sha256_hex(data: &[u8]) -> String {
ring::digest::digest(&ring::digest::SHA256, data)
.as_ref()
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
/// Largest config file read.
const MAX_CONFIG_BYTES: u64 = 16 << 20;
/// Read and parse a config file; returns the parsed config and the SHA-256 of its bytes.
pub fn read_config_file(path: &Path) -> Result<(EdgeConfig, String), EdgeError> {
let read_err = |source| EdgeError::Read {
path: path.to_owned(),
source,
};
let meta = std::fs::metadata(path).map_err(read_err)?;
if meta.len() > MAX_CONFIG_BYTES {
return Err(EdgeError::Config {
path: path.to_owned(),
message: "the file is larger than 16 MiB".into(),
});
}
let bytes = std::fs::read(path).map_err(read_err)?;
let text = std::str::from_utf8(&bytes).map_err(|_| EdgeError::Config {
path: path.to_owned(),
message: "the file is not UTF-8".into(),
})?;
let cfg: EdgeConfig = serde_json::from_str(&text).map_err(|e| EdgeError::Config {
let cfg = parse_config(path, text)?;
Ok((cfg, sha256_hex(&bytes)))
}
pub fn read_config(path: &Path) -> Result<EdgeConfig, EdgeError> {
read_config_file(path).map(|(c, _)| c)
}
fn parse_config(path: &Path, text: &str) -> Result<EdgeConfig, EdgeError> {
let cfg: EdgeConfig = serde_json::from_str(text).map_err(|e| EdgeError::Config {
path: path.to_owned(),
message: e.to_string(),
})?;
@@ -125,6 +217,7 @@ fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
tls: u.tls,
sni: u.sni.clone(),
healthy: AtomicBool::new(true),
health: HealthRecord::default(),
})
}
@@ -221,10 +314,18 @@ fn ops(
.collect()
}
/// Load secrets and certificates and resolve upstreams. Fails on the first problem; edge never
/// starts half-configured.
/// Read, parse and build a config file. Fails on the first problem; edge never serves a
/// half-built config.
pub fn build_file(path: &Path, credentials_dir: Option<&Path>) -> Result<Runtime, EdgeError> {
let (cfg, sha) = read_config_file(path)?;
let mut rt = build(cfg, credentials_dir)?;
rt.sha256 = sha;
Ok(rt)
}
/// Load secrets, certificates and the share-link key. Fails on the first problem.
pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime, EdgeError> {
let names: BTreeSet<String> = cfg
let mut names: BTreeSet<String> = cfg
.hosts
.iter()
.flat_map(|h| h.request_headers.iter().chain(&h.response_headers))
@@ -236,9 +337,23 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
_ => None,
})
.collect();
let wants_share = cfg.hosts.iter().any(|h| h.share_links);
if wants_share {
names.insert(KEY_CREDENTIAL.to_owned());
}
let secrets = Secrets::load(&names, credentials_dir)?;
let share_key = match secrets.get(KEY_CREDENTIAL) {
Some(s) if wants_share => Some(Arc::new(ShareKey::new(s.as_bytes()).map_err(|_| {
EdgeError::Secret {
name: KEY_CREDENTIAL.into(),
reason: "the share-link key must be at least 32 characters",
}
})?)),
_ => None,
};
let certs = Arc::new(CertStore::default());
let mut file_certs = HashMap::new();
let mut file_cert_expiry = HashMap::new();
let mut hosts = HashMap::new();
for h in &cfg.hosts {
if let EdgeTls::Files { cert, key } = &h.tls {
@@ -248,12 +363,15 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
source,
})
};
let pair =
certified_key(&read(cert)?, &read(key)?).map_err(|reason| EdgeError::Cert {
host: h.hostname.clone(),
reason,
})?;
certs.insert(&h.hostname, pair);
let cert_pem = read(cert)?;
let pair = certified_key(&cert_pem, &read(key)?).map_err(|reason| EdgeError::Cert {
host: h.hostname.clone(),
reason,
})?;
if let Some(exp) = not_after(&cert_pem) {
file_cert_expiry.insert(h.hostname.clone(), exp);
}
file_certs.insert(h.hostname.clone(), Arc::new(pair));
}
let mut secret_values = Vec::new();
let request_ops = ops(&h.request_headers, &secrets, &mut secret_values)?;
@@ -317,7 +435,10 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
hosts,
forward_auth,
access_log,
certs,
file_certs,
file_cert_expiry,
share_key,
sha256: String::new(),
})
}
@@ -361,4 +482,24 @@ mod resolve_tests {
.await;
assert_eq!(got.unwrap_err().kind(), std::io::ErrorKind::NotFound);
}
#[test]
fn health_records_keep_the_last_five() {
let r = HealthRecord::default();
for i in 0..8 {
r.record(Check {
seq: 0,
at: i,
ok: i % 2 == 0,
source: "health_check",
kind: None,
status: None,
latency_ms: None,
});
}
let c = r.checks();
assert_eq!(c.len(), KEPT_CHECKS);
assert_eq!(c.first().unwrap().seq, 4);
assert_eq!(c.last().unwrap().seq, 8);
}
}
+428
View File
@@ -0,0 +1,428 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Share links on hosts with `share_links = true` (tokens: `ianitor_core::share`).
//!
//! 1. `GET <path>?share=ish1.…` within the link's prefix: edge checks the token and answers
//! `303` to the same URL without `share=`, setting the session cookie (`__Secure-`, Path =
//! prefix, HttpOnly, Secure, SameSite=Lax, Max-Age = time left). The token is in a URL once.
//! A password link instead gets the password page; its form posts the token and the
//! password to [`PASSWORD_PATH`], and on success edge sets the cookie and redirects to
//! the prefix.
//! 2. A request carrying a valid session cookie for a path within its prefix skips
//! forward-auth. The cookie (and any `share=` token) is removed before the request goes on,
//! so neither the upstream nor the auth server ever sees it.
//! 3. A token outside its prefix, or one for a host without share links, is ignored: the
//! request takes the normal sign-in, without the `share=` parameter.
//!
//! SameSite=Lax, not Strict: a visitor arrives by clicking a link in another site or app, and
//! browsers do not send Strict cookies on the redirect that follows such a navigation.
//! Wrong passwords are limited to 5 a minute per link and visitor /24 (and /48).
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use bytes::Bytes;
use http::header;
use ianitor_core::share::{
COOKIE_NAME, Claims, LINK_PREFIX, PASSWORD_PATH, QUERY_PARAM, Rejection, ShareId, ShareKey,
path_within, peek, session_value, verify_link, verify_session,
};
use pingora::http::ResponseHeader;
use pingora::proxy::Session;
use pingora::{Error, ErrorType, Result};
use crate::logging::{now_secs, truncate_ip};
use crate::pages::{self, Page};
use crate::shared::RevocationState;
const WINDOW: Duration = Duration::from_secs(60);
const MAX_FAILURES: u32 = 5;
const MAX_ENTRIES: usize = 10_000;
const MAX_FORM: usize = 8 * 1024;
/// Wrong-password counters per (link, visitor network).
#[derive(Default)]
pub struct Throttle {
map: Mutex<HashMap<(ShareId, IpAddr), (Instant, u32)>>,
}
impl Throttle {
fn key(id: ShareId, ip: Option<IpAddr>) -> (ShareId, IpAddr) {
let ip = ip.map_or(IpAddr::from([0, 0, 0, 0]), truncate_ip);
(id, ip)
}
/// True when this visitor may try a password for this link now.
pub fn allowed(&self, id: ShareId, ip: Option<IpAddr>) -> bool {
let Ok(m) = self.map.lock() else { return false };
match m.get(&Self::key(id, ip)) {
Some((start, n)) => start.elapsed() >= WINDOW || *n < MAX_FAILURES,
None => true,
}
}
pub fn failed(&self, id: ShareId, ip: Option<IpAddr>) {
let Ok(mut m) = self.map.lock() else { return };
if m.len() >= MAX_ENTRIES {
m.retain(|_, (start, _)| start.elapsed() < WINDOW);
}
if m.len() >= MAX_ENTRIES {
// Full of live entries: forget the oldest rather than grow without bound.
if let Some(oldest) = m.iter().min_by_key(|(_, (s, _))| *s).map(|(k, _)| *k) {
m.remove(&oldest);
}
}
let e = m.entry(Self::key(id, ip)).or_insert((Instant::now(), 0));
if e.0.elapsed() >= WINDOW {
*e = (Instant::now(), 0);
}
e.1 += 1;
}
}
/// What the share layer decided for a request.
pub enum Decision {
/// Answered here (redirect or visitor page); stop.
Answered,
/// A valid session cookie covers this path: skip forward-auth.
Allowed,
/// Nothing to do with share links: continue as usual.
Continue,
}
fn now() -> u64 {
now_secs() as u64
}
/// Remove every share cookie from the request; return their values.
fn take_cookies(session: &mut Session) -> Result<Vec<String>> {
let req = session.req_header_mut();
let all: Vec<String> = req
.headers
.get_all(header::COOKIE)
.iter()
.map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned())
.collect();
if all.is_empty() {
return Ok(Vec::new());
}
let mut ours = Vec::new();
let mut rest = Vec::new();
for line in &all {
for part in line.split(';') {
let p = part.trim();
if p.is_empty() {
continue;
}
match p.split_once('=') {
Some((n, v)) if n.trim() == COOKIE_NAME => ours.push(v.trim().to_owned()),
_ => rest.push(p.to_owned()),
}
}
}
if ours.is_empty() {
return Ok(ours);
}
req.remove_header(&header::COOKIE);
if !rest.is_empty() {
req.insert_header(header::COOKIE, rest.join("; "))?;
}
Ok(ours)
}
/// Split the query into our token (the first `share=ish1.…`) and everything else, kept in
/// its original encoding.
fn split_query(query: &str) -> (Option<String>, String) {
let mut token = None;
let mut rest = Vec::new();
for pair in query.split('&') {
if token.is_none()
&& let Some(v) = pair
.strip_prefix(QUERY_PARAM)
.and_then(|r| r.strip_prefix('='))
{
let decoded: String = form_urlencoded::parse(format!("x={v}").as_bytes())
.next()
.map(|(_, v)| v.into_owned())
.unwrap_or_default();
if decoded.starts_with(LINK_PREFIX) {
token = Some(decoded);
continue;
}
}
if !pair.is_empty() {
rest.push(pair);
}
}
(token, rest.join("&"))
}
fn with_query(path: &str, query: &str) -> String {
if query.is_empty() {
path.to_owned()
} else {
format!("{path}?{query}")
}
}
/// Drop the `share=` token from the request target, so the upstream never sees it.
fn strip_token(session: &mut Session, path: &str, rest: &str) -> Result<()> {
let uri = with_query(path, rest)
.parse::<http::Uri>()
.map_err(|_| Error::explain(ErrorType::HTTPStatus(400), "bad request target"))?;
session.req_header_mut().set_uri(uri);
Ok(())
}
fn cookie(value: &str, claims: &Claims) -> String {
let left = claims.expires_at.saturating_sub(now());
format!(
"{COOKIE_NAME}={value}; Path={}; Max-Age={left}; HttpOnly; Secure; SameSite=Lax",
claims.prefix
)
}
async fn redirect(session: &mut Session, location: &str, set_cookie: Option<String>) -> Result<()> {
let mut resp = ResponseHeader::build(303, Some(5))?;
resp.insert_header(header::LOCATION, location)?;
resp.insert_header(header::CACHE_CONTROL, "no-store")?;
resp.insert_header("Referrer-Policy", "no-referrer")?;
resp.insert_header(header::CONTENT_LENGTH, "0")?;
if let Some(c) = set_cookie {
resp.insert_header(header::SET_COOKIE, c)?;
}
session.write_response_header(Box::new(resp), true).await
}
async fn page(session: &mut Session, p: Page<'_>) -> Result<()> {
let html = pages::render(&p);
let mut resp = ResponseHeader::build(p.status(), Some(8))?;
resp.insert_header(header::CONTENT_TYPE, "text/html; charset=utf-8")?;
resp.insert_header(header::CACHE_CONTROL, "no-store")?;
resp.insert_header("Referrer-Policy", "no-referrer")?;
resp.insert_header("X-Robots-Tag", "noindex")?;
resp.insert_header(
"Content-Security-Policy",
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'",
)?;
resp.insert_header(header::CONTENT_LENGTH, html.len().to_string())?;
let head = session.req_header().method == http::Method::HEAD;
session.write_response_header(Box::new(resp), head).await?;
if !head {
session
.write_response_body(Some(Bytes::from(html)), true)
.await?;
}
Ok(())
}
fn rejected_page(r: Rejection, host: &str) -> Page<'_> {
match r {
Rejection::Expired { expires_at } => Page::Expired {
host,
until: expires_at,
},
_ => Page::Invalid { host },
}
}
async fn read_form(session: &mut Session) -> Result<Option<Vec<u8>>> {
let mut body = Vec::new();
while let Some(chunk) = session.read_request_body().await? {
if body.len() + chunk.len() > MAX_FORM {
return Ok(None);
}
body.extend_from_slice(&chunk);
}
Ok(Some(body))
}
/// The share layer for one request on a host with share links.
pub async fn handle(
session: &mut Session,
host: &str,
key: Option<&ShareKey>,
revocations: &RevocationState,
throttle: &Throttle,
client_ip: Option<IpAddr>,
) -> Result<Decision> {
let cookies = take_cookies(session)?;
let path = session.req_header().uri.path().to_owned();
let query = session.req_header().uri.query().unwrap_or("").to_owned();
// Without the key or a readable revocation file, no share link is honoured.
let usable = key.filter(|_| revocations.loaded);
let revs = &revocations.revocations;
if path == PASSWORD_PATH {
let Some(key) = usable else {
page(session, Page::Invalid { host }).await?;
return Ok(Decision::Answered);
};
if session.req_header().method != http::Method::POST {
page(session, Page::Invalid { host }).await?;
return Ok(Decision::Answered);
}
let Some(body) = read_form(session).await? else {
page(session, Page::Invalid { host }).await?;
return Ok(Decision::Answered);
};
let mut token = String::new();
let mut password = String::new();
for (k, v) in form_urlencoded::parse(&body) {
match k.as_ref() {
"t" => token = v.into_owned(),
"password" => password = v.into_owned(),
_ => {}
}
}
let Ok(claimed) = peek(&token) else {
page(session, Page::Invalid { host }).await?;
return Ok(Decision::Answered);
};
if !throttle.allowed(claimed.id, client_ip) {
page(
session,
Page::Password {
host,
token: &token,
until: claimed.expires_at,
problem: Some(pages::Problem::TooMany),
},
)
.await?;
return Ok(Decision::Answered);
}
match verify_link(key, host, &token, Some(&password), now(), revs) {
Ok(c) => {
let v = session_value(key, host, &c);
redirect(session, &c.prefix, Some(cookie(&v, &c))).await?;
}
Err(Rejection::Invalid) => {
throttle.failed(claimed.id, client_ip);
page(
session,
Page::Password {
host,
token: &token,
until: claimed.expires_at,
problem: Some(pages::Problem::WrongPassword),
},
)
.await?;
}
Err(r) => page(session, rejected_page(r, host)).await?,
}
return Ok(Decision::Answered);
}
let (token, rest) = split_query(&query);
if let Some(token) = token {
let claimed = peek(&token);
let within = claimed
.as_ref()
.is_ok_and(|c| path_within(&c.prefix, &path));
if claimed.is_ok() && !within {
// Outside its prefix: as if there were no link, minus the token.
strip_token(session, &path, &rest)?;
return Ok(Decision::Continue);
}
let Some(key) = usable else {
page(session, Page::Invalid { host }).await?;
return Ok(Decision::Answered);
};
let claimed = match claimed {
Ok(c) => c,
Err(_) => {
page(session, Page::Invalid { host }).await?;
return Ok(Decision::Answered);
}
};
if claimed.password {
if now() >= claimed.expires_at {
page(
session,
Page::Expired {
host,
until: claimed.expires_at,
},
)
.await?;
} else {
let problem =
(!throttle.allowed(claimed.id, client_ip)).then_some(pages::Problem::TooMany);
page(
session,
Page::Password {
host,
token: &token,
until: claimed.expires_at,
problem,
},
)
.await?;
}
return Ok(Decision::Answered);
}
match verify_link(key, host, &token, None, now(), revs) {
Ok(c) => {
let v = session_value(key, host, &c);
redirect(session, &with_query(&path, &rest), Some(cookie(&v, &c))).await?;
}
Err(r) => page(session, rejected_page(r, host)).await?,
}
return Ok(Decision::Answered);
}
if let Some(key) = usable {
let t = now();
for v in &cookies {
if let Ok(c) = verify_session(key, host, v, t, revs)
&& path_within(&c.prefix, &path)
{
return Ok(Decision::Allowed);
}
}
}
Ok(Decision::Continue)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_token_is_split_from_the_query() {
assert_eq!(
split_query("a=1&share=ish1.abc&b=2"),
(Some("ish1.abc".into()), "a=1&b=2".into())
);
assert_eq!(split_query("share=holiday"), (None, "share=holiday".into()));
assert_eq!(
split_query("x=%20&share=ish1.a%2Db"),
(Some("ish1.a-b".into()), "x=%20".into())
);
assert_eq!(split_query(""), (None, String::new()));
assert_eq!(split_query("sharex=ish1.a"), (None, "sharex=ish1.a".into()));
}
#[test]
fn the_throttle_allows_five_failures_a_minute_per_link_and_network() {
let t = Throttle::default();
let id = ShareId([1; 16]);
let ip: IpAddr = "192.0.2.10".parse().unwrap_or(IpAddr::from([0, 0, 0, 0]));
let same_net: IpAddr = "192.0.2.99".parse().unwrap_or(IpAddr::from([0, 0, 0, 0]));
let other_net: IpAddr = "198.51.100.1".parse().unwrap_or(IpAddr::from([0, 0, 0, 0]));
for _ in 0..5 {
assert!(t.allowed(id, Some(ip)));
t.failed(id, Some(ip));
}
assert!(!t.allowed(id, Some(ip)));
assert!(!t.allowed(id, Some(same_net)));
assert!(t.allowed(id, Some(other_net)));
assert!(t.allowed(ShareId([2; 16]), Some(ip)));
}
}
+403
View File
@@ -0,0 +1,403 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! State that lives as long as the process, across config reloads (ROADMAP §8.4).
//!
//! A reload builds a complete new [`Runtime`] from the config file and swaps it in with one
//! atomic pointer store. Listeners, TLS sessions and keep-alive connections are untouched:
//! each request takes the runtime that is current when it starts and keeps it until it ends,
//! so nothing in flight sees a half-applied config, and the next request on the same
//! connection already uses the new one. A config that fails to build is refused and the old
//! one keeps serving.
//!
//! A **trial** is a reload control has not confirmed yet: edge keeps the previous runtime and
//! swaps it back by itself when the deadline passes without a confirmation. So if control
//! dies in the middle of an apply, edge returns to the last good config on its own, and
//! because the trial is read from a separate file, a restarted edge reads the last good
//! config too.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use arc_swap::ArcSwap;
use ianitor_core::share::{Revocations, ShareId};
use serde::Deserialize;
use crate::error::EdgeError;
use crate::logging::now_secs;
use crate::runtime::{self, Runtime};
use crate::tls::CertStore;
/// Health probes of watched hosts during a trial.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WatchSpec {
pub hosts: Vec<String>,
pub every: Duration,
}
struct Trial {
id: u64,
sha256: String,
previous: Arc<Runtime>,
deadline: Instant,
}
/// The share-link revocation file as edge last read it.
#[derive(Debug, Clone, Default)]
pub struct RevocationState {
pub revocations: Revocations,
/// False when the file is missing or never read: share links are then refused.
pub loaded: bool,
pub error: Option<String>,
/// SHA-256 of the file as last read; the poller re-reads when it changes.
stamp: Option<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RevocationFile {
epoch: u32,
deny: Vec<String>,
}
/// Most ids on the deny list.
pub const MAX_DENY: usize = 10_000;
/// Certificate state per host, for control (docs/ui-api.md G5).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CertState {
/// `ok`, `pending` or `failed`.
pub state: &'static str,
pub not_after: Option<i64>,
pub error: Option<String>,
}
pub struct Paths {
pub config: PathBuf,
pub trial: PathBuf,
pub revocations: Option<PathBuf>,
}
/// Why an admin request was refused.
#[derive(Debug, thiserror::Error)]
pub enum AdminError {
#[error("{0}")]
Refused(#[from] EdgeError),
#[error("{0}")]
Conflict(String),
}
pub struct Shared {
current: ArcSwap<Runtime>,
pub certs: Arc<CertStore>,
generation: AtomicU64,
changed: tokio::sync::watch::Sender<u64>,
trial: Mutex<Option<Trial>>,
trial_ids: AtomicU64,
watch: Mutex<Option<WatchSpec>>,
pub paths: Paths,
credentials_dir: Option<PathBuf>,
revocations: ArcSwap<RevocationState>,
pub throttle: crate::share::Throttle,
cert_states: Mutex<HashMap<String, CertState>>,
pub acme_wake: tokio::sync::Notify,
pub started_at: u64,
}
fn same_listeners(a: &Runtime, b: &Runtime) -> Result<(), EdgeError> {
if a.cfg.http_listen != b.cfg.http_listen || a.cfg.https_listen != b.cfg.https_listen {
return Err(EdgeError::Config {
path: PathBuf::from("<new config>"),
message: "the listen addresses can only change with a restart".into(),
});
}
Ok(())
}
impl Shared {
pub fn new(rt: Runtime, paths: Paths, credentials_dir: Option<PathBuf>) -> Arc<Shared> {
let certs = Arc::new(CertStore::default());
certs.replace_files(rt.file_certs.clone());
let (changed, _) = tokio::sync::watch::channel(1);
let s = Arc::new(Shared {
current: ArcSwap::from_pointee(rt),
certs,
generation: AtomicU64::new(1),
changed,
trial: Mutex::new(None),
trial_ids: AtomicU64::new(0),
watch: Mutex::new(None),
paths,
credentials_dir,
revocations: ArcSwap::from_pointee(RevocationState::default()),
throttle: crate::share::Throttle::default(),
cert_states: Mutex::new(HashMap::new()),
acme_wake: tokio::sync::Notify::new(),
started_at: now_secs() as u64,
});
if let Err(e) = s.reload_revocations() {
log::error!(target: "ianitor::share", "{e}; share links are refused until it is fixed");
}
s
}
/// The runtime serving new requests now.
pub fn current(&self) -> Arc<Runtime> {
self.current.load_full()
}
pub fn generation(&self) -> u64 {
self.generation.load(Ordering::SeqCst)
}
/// Changes whenever the runtime or the trial watch changes.
pub fn subscribe(&self) -> tokio::sync::watch::Receiver<u64> {
self.changed.subscribe()
}
pub fn watch_spec(&self) -> Option<WatchSpec> {
self.watch.lock().ok().and_then(|w| w.clone())
}
fn notify(&self) {
self.changed.send_replace(self.generation());
}
fn install(&self, rt: Arc<Runtime>) {
self.certs.replace_files(rt.file_certs.clone());
self.current.store(rt);
self.generation.fetch_add(1, Ordering::SeqCst);
self.notify();
self.acme_wake.notify_one();
}
fn build(&self, path: &Path) -> Result<Runtime, EdgeError> {
let rt = runtime::build_file(path, self.credentials_dir.as_deref())?;
same_listeners(&self.current(), &rt)?;
Ok(rt)
}
/// Reload from the config file. Refused while a trial runs.
pub fn reload(&self) -> Result<Arc<Runtime>, AdminError> {
let guard = self.trial.lock().map_err(|_| poisoned())?;
if guard.is_some() {
return Err(AdminError::Conflict(
"a trial config is running; confirm or abort it first".into(),
));
}
let rt = Arc::new(self.build(&self.paths.config)?);
self.install(rt.clone());
drop(guard);
log::info!(target: "ianitor::reload", "config reloaded ({} hosts, sha256 {})", rt.hosts.len(), short(&rt.sha256));
Ok(rt)
}
/// Serve the trial config until [`Shared::confirm`] or the deadline. Returns the trial id
/// (for [`Shared::expire_trial`]) and the runtime.
pub fn start_trial(
&self,
confirm_within: Duration,
watch: Option<WatchSpec>,
) -> Result<(u64, Arc<Runtime>), AdminError> {
let mut guard = self.trial.lock().map_err(|_| poisoned())?;
if guard.is_some() {
return Err(AdminError::Conflict(
"a trial config is already running".into(),
));
}
let rt = Arc::new(self.build(&self.paths.trial)?);
let id = self.trial_ids.fetch_add(1, Ordering::SeqCst) + 1;
*guard = Some(Trial {
id,
sha256: rt.sha256.clone(),
previous: self.current(),
deadline: Instant::now() + confirm_within,
});
if let Ok(mut w) = self.watch.lock() {
*w = watch;
}
self.install(rt.clone());
log::info!(target: "ianitor::reload", "trial config {} running; reverts in {confirm_within:?} unless confirmed", short(&rt.sha256));
Ok((id, rt))
}
/// Keep the trial config. Fails unless a trial with this hash is running.
pub fn confirm(&self, sha256: &str) -> Result<(), AdminError> {
let mut guard = self.trial.lock().map_err(|_| poisoned())?;
match guard.as_ref() {
Some(t) if t.sha256 == sha256 => {}
Some(_) => {
return Err(AdminError::Conflict(
"the running trial has another config".into(),
));
}
None => return Err(AdminError::Conflict("no trial config is running".into())),
}
*guard = None;
self.end_watch();
log::info!(target: "ianitor::reload", "trial config {} confirmed", short(sha256));
Ok(())
}
fn end_watch(&self) {
if let Ok(mut w) = self.watch.lock() {
*w = None;
}
self.notify();
}
/// Go back to the config before the trial. Returns whether there was a trial.
pub fn abort(&self) -> bool {
self.revert_trial(None, "aborted")
}
/// Called when a trial's deadline passes.
pub fn expire_trial(&self, id: u64) {
self.revert_trial(Some(id), "not confirmed in time");
}
fn revert_trial(&self, id: Option<u64>, why: &str) -> bool {
let Ok(mut guard) = self.trial.lock() else {
return false;
};
let matches = guard.as_ref().is_some_and(|t| id.is_none_or(|i| i == t.id));
if !matches {
return false;
}
let Some(t) = guard.take() else { return false };
self.install(t.previous.clone());
self.end_watch();
log::warn!(target: "ianitor::reload", "trial config {} {why}; back to {}", short(&t.sha256), short(&t.previous.sha256));
true
}
/// (sha256, seconds left, previous sha256) of the running trial.
pub fn trial_info(&self) -> Option<(String, u64, String)> {
let g = self.trial.lock().ok()?;
g.as_ref().map(|t| {
(
t.sha256.clone(),
t.deadline
.saturating_duration_since(Instant::now())
.as_secs(),
t.previous.sha256.clone(),
)
})
}
pub fn trial_deadline(&self, id: u64) -> Option<Instant> {
let g = self.trial.lock().ok()?;
g.as_ref().filter(|t| t.id == id).map(|t| t.deadline)
}
// ------------------------------------------------------------ share-link revocations
pub fn revocations(&self) -> Arc<RevocationState> {
self.revocations.load_full()
}
/// Re-read the revocation file. A missing file means "refuse every share link"; a broken
/// one keeps the last good state.
pub fn reload_revocations(&self) -> Result<(), EdgeError> {
let Some(path) = &self.paths.revocations else {
self.revocations.store(Arc::new(RevocationState {
error: Some("no revocation file is configured".into()),
..RevocationState::default()
}));
return Ok(());
};
let meta = match std::fs::metadata(path) {
Ok(m) => m,
Err(source) => {
self.revocations.store(Arc::new(RevocationState {
error: Some(format!("cannot read {}: {source}", path.display())),
..RevocationState::default()
}));
return Err(EdgeError::Read {
path: path.clone(),
source,
});
}
};
let fail = |message: String| {
let mut old = RevocationState::clone(&self.revocations());
old.error = Some(message.clone());
self.revocations.store(Arc::new(old));
EdgeError::Config {
path: path.clone(),
message,
}
};
if meta.len() > 1 << 20 {
return Err(fail("the revocation file is larger than 1 MiB".into()));
}
let text = std::fs::read_to_string(path).map_err(|e| fail(e.to_string()))?;
let file: RevocationFile =
serde_json::from_str(&text).map_err(|e| fail(format!("not a revocation file: {e}")))?;
if file.deny.len() > MAX_DENY {
return Err(fail(format!("more than {MAX_DENY} stopped links")));
}
let mut deny = std::collections::BTreeSet::new();
for id in &file.deny {
deny.insert(
ShareId::from_hex(id)
.ok_or_else(|| fail("a link id is not 32 hex digits".into()))?,
);
}
let stamp = Some(runtime::sha256_hex(text.as_bytes()));
self.revocations.store(Arc::new(RevocationState {
revocations: Revocations {
epoch: file.epoch,
deny,
},
loaded: true,
error: None,
stamp,
}));
log::info!(target: "ianitor::share", "share-link revocations loaded: epoch {}, {} stopped", file.epoch, file.deny.len());
Ok(())
}
/// Re-read the revocation file if it changed (or vanished) since the last read.
pub fn poll_revocations(&self) {
let Some(path) = &self.paths.revocations else {
return;
};
// Content, not mtime: two writes within one timer tick have the same mtime.
let now = std::fs::metadata(path)
.ok()
.filter(|m| m.len() <= 1 << 20)
.and_then(|_| std::fs::read(path).ok())
.map(|b| runtime::sha256_hex(&b));
let state = self.revocations();
if (now != state.stamp || (now.is_none() && state.loaded))
&& let Err(e) = self.reload_revocations()
{
log::error!(target: "ianitor::share", "{e}");
}
}
// ------------------------------------------------------------ certificates
pub fn set_cert_state(&self, host: &str, state: CertState) {
if let Ok(mut m) = self.cert_states.lock() {
m.insert(host.to_owned(), state);
}
}
pub fn cert_state(&self, host: &str) -> Option<CertState> {
self.cert_states.lock().ok()?.get(host).cloned()
}
}
fn poisoned() -> AdminError {
AdminError::Conflict("internal state is unavailable".into())
}
fn short(sha: &str) -> &str {
sha.get(..12).unwrap_or(sha)
}
+14 -1
View File
@@ -14,9 +14,14 @@ use rustls::sign::CertifiedKey;
use rustls_pki_types::pem::PemObject;
use rustls_pki_types::{CertificateDer, PrivateKeyDer};
/// Lives as long as the process: Domi certificates are replaced as a set on every reload,
/// ACME certificates are added by the ACME service and kept across reloads.
#[derive(Debug, Default)]
pub struct CertStore {
/// ACME certificates (and anything inserted one by one).
certs: ArcSwap<HashMap<String, Arc<CertifiedKey>>>,
/// Domi certificates of the current config.
files: ArcSwap<HashMap<String, Arc<CertifiedKey>>>,
}
impl CertStore {
@@ -29,8 +34,13 @@ impl CertStore {
});
}
/// Replace the Domi certificates (on reload).
pub fn replace_files(&self, files: HashMap<String, Arc<CertifiedKey>>) {
self.files.store(Arc::new(files));
}
pub fn has(&self, host: &str) -> bool {
self.certs.load().contains_key(host)
self.files.load().contains_key(host) || self.certs.load().contains_key(host)
}
}
@@ -38,6 +48,9 @@ impl ResolvesServerCert for CertStore {
fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
// No SNI or an unknown name: no certificate, the handshake fails (as with Caddy).
let name = hello.server_name()?.to_ascii_lowercase();
if let Some(k) = self.files.load().get(&name) {
return Some(k.clone());
}
self.certs.load().get(&name).cloned()
}
}
+89 -22
View File
@@ -44,9 +44,14 @@ mod unix {
}
async fn generation(edge: &Edge) -> String {
let r = client::https(edge.https, "app.test", edge.roots(), &Req::get("app.test", "/"))
.await
.unwrap();
let r = client::https(
edge.https,
"app.test",
edge.roots(),
&Req::get("app.test", "/"),
)
.await
.unwrap();
assert_eq!(r.status, 200, "{}", r.text());
r.header("x-generation").unwrap_or("none").to_owned()
}
@@ -118,7 +123,11 @@ mod unix {
let mut reloads = 0u64;
let mut refused = 0u64;
while started.elapsed() < Duration::from_secs(secs) {
let text = if reloads % 2 == 0 { &config_b } else { &config_a };
let text = if reloads.is_multiple_of(2) {
&config_b
} else {
&config_a
};
let tmp = edge.config_path().with_extension("tmp");
std::fs::write(&tmp, text).unwrap();
std::fs::rename(&tmp, edge.config_path()).unwrap();
@@ -237,7 +246,11 @@ mod unix {
// Not confirmed: back to "a" after the deadline, without anyone asking.
let r = edge
.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 2 })))
.admin(
"POST",
"/v1/trial",
Some(json!({ "confirm_within_secs": 2 })),
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
let trial_sha = r.json["config_sha256"].as_str().unwrap().to_owned();
@@ -248,9 +261,13 @@ mod unix {
// No reload and no second trial while one runs.
assert_eq!(edge.admin("POST", "/v1/reload", None).await.status, 409);
assert_eq!(
edge.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 2 })))
.await
.status,
edge.admin(
"POST",
"/v1/trial",
Some(json!({ "confirm_within_secs": 2 }))
)
.await
.status,
409
);
tokio::time::sleep(Duration::from_millis(3500)).await;
@@ -260,21 +277,37 @@ mod unix {
assert_eq!(s.json["config_sha256"], sha256(&edge.config_text));
// Confirming a trial that already reverted fails.
let r = edge
.admin("POST", "/v1/confirm", Some(json!({ "config_sha256": trial_sha })))
.admin(
"POST",
"/v1/confirm",
Some(json!({ "config_sha256": trial_sha })),
)
.await;
assert_eq!(r.status, 409, "{}", r.text);
// Confirmed: stays.
let r = edge
.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 2 })))
.admin(
"POST",
"/v1/trial",
Some(json!({ "confirm_within_secs": 2 })),
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
let wrong = edge
.admin("POST", "/v1/confirm", Some(json!({ "config_sha256": "00" })))
.admin(
"POST",
"/v1/confirm",
Some(json!({ "config_sha256": "00" })),
)
.await;
assert_eq!(wrong.status, 409);
let r = edge
.admin("POST", "/v1/confirm", Some(json!({ "config_sha256": trial_sha })))
.admin(
"POST",
"/v1/confirm",
Some(json!({ "config_sha256": trial_sha })),
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
tokio::time::sleep(Duration::from_millis(2500)).await;
@@ -283,7 +316,11 @@ mod unix {
// Aborted: back at once. Abort is idempotent.
std::fs::write(edge.trial_path(), &edge.config_text).unwrap();
let r = edge
.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 30 })))
.admin(
"POST",
"/v1/trial",
Some(json!({ "confirm_within_secs": 30 })),
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
assert_eq!(generation(&edge).await, "a");
@@ -298,7 +335,11 @@ mod unix {
// A broken trial is refused and nothing changes.
std::fs::write(edge.trial_path(), "{}").unwrap();
let r = edge
.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 30 })))
.admin(
"POST",
"/v1/trial",
Some(json!({ "confirm_within_secs": 30 })),
)
.await;
assert_eq!(r.status, 422);
assert_eq!(generation(&edge).await, "b");
@@ -321,7 +362,10 @@ mod unix {
sick.url()
),
),
host_file("plain.test", &format!("upstreams = [\"{}\"]\n", plain.url())),
host_file(
"plain.test",
&format!("upstreams = [\"{}\"]\n", plain.url()),
),
],
..Default::default()
});
@@ -329,7 +373,10 @@ mod unix {
let s = edge.admin("GET", "/v1/status", None).await;
assert_eq!(s.status, 200, "{}", s.text);
let hosts = s.json["hosts"].as_array().unwrap();
let mixed = hosts.iter().find(|h| h["hostname"] == "mixed.test").unwrap();
let mixed = hosts
.iter()
.find(|h| h["hostname"] == "mixed.test")
.unwrap();
assert_eq!(mixed["health_check"], true);
let ups = mixed["upstreams"].as_array().unwrap();
assert_eq!(ups.len(), 3);
@@ -344,9 +391,17 @@ mod unix {
assert_eq!(last(&ups[2])["kind"], "refused");
assert!(ups[0]["checks"].as_array().unwrap().len() <= 5);
assert!(mixed["certificate"]["state"] == "ok");
let plain_h = hosts.iter().find(|h| h["hostname"] == "plain.test").unwrap();
let plain_h = hosts
.iter()
.find(|h| h["hostname"] == "plain.test")
.unwrap();
assert_eq!(plain_h["health_check"], false);
assert!(plain_h["upstreams"][0]["checks"].as_array().unwrap().is_empty());
assert!(
plain_h["upstreams"][0]["checks"]
.as_array()
.unwrap()
.is_empty()
);
// During a trial, watched hosts without a health check get `GET /` probes; any answer
// below 500 counts as alive. Hosts with one are checked at least every `every_secs`.
@@ -372,8 +427,12 @@ mod unix {
assert!(!checks.is_empty(), "{}", s.text);
assert_eq!(checks.last().unwrap()["ok"], true);
assert_eq!(checks.last().unwrap()["source"], "watch");
assert!(plain.requests().iter().any(|r| r.path == "/"
&& r.header("host") == Some(b"plain.test".as_slice())));
assert!(
plain
.requests()
.iter()
.any(|r| r.path == "/" && r.header("host") == Some(b"plain.test".as_slice()))
);
edge.admin("POST", "/v1/abort", None).await;
}
@@ -391,11 +450,19 @@ mod unix {
// Unknown paths and bad bodies get typed errors, not a crash.
assert_eq!(edge.admin("GET", "/v1/nope", None).await.status, 404);
let r = edge
.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 2, "extra": 1 })))
.admin(
"POST",
"/v1/trial",
Some(json!({ "confirm_within_secs": 2, "extra": 1 })),
)
.await;
assert_eq!(r.status, 400, "{}", r.text);
let r = edge
.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 0 })))
.admin(
"POST",
"/v1/trial",
Some(json!({ "confirm_within_secs": 0 })),
)
.await;
assert_eq!(r.status, 400, "{}", r.text);
assert_eq!(generation(&edge).await, "a");
+66 -20
View File
@@ -107,11 +107,7 @@ mod unix {
}
async fn post_password(&self, token: &str, password: &str) -> Resp {
let body = format!(
"t={}&password={}",
urlencode(token),
urlencode(password)
);
let body = format!("t={}&password={}", urlencode(token), urlencode(password));
let req = Req::new("POST", HOST, "/.well-known/ianitor/share")
.header("content-type", "application/x-www-form-urlencoded")
.body(body.as_bytes());
@@ -159,7 +155,10 @@ mod unix {
);
assert!(r.header("content-type").unwrap().starts_with("text/html"));
assert!(!r.text().contains("<script"), "no JavaScript");
assert!(!r.text().contains("http://") && !r.text().contains("https://"), "no external requests");
assert!(
!r.text().contains("http://") && !r.text().contains("https://"),
"no external requests"
);
assert!(r.body.len() < 8 * 1024);
}
@@ -180,19 +179,36 @@ mod unix {
.find(|c| c.starts_with("__Secure-ianitor-share="))
.unwrap()
.to_owned();
for attr in ["Path=/albums", "HttpOnly", "Secure", "SameSite=Lax", "Max-Age="] {
for attr in [
"Path=/albums",
"HttpOnly",
"Secure",
"SameSite=Lax",
"Max-Age=",
] {
assert!(set.contains(attr), "{attr} missing in {set}");
}
assert!(!set.contains(&t), "the cookie is not the link token");
assert!(e.upstream_paths().is_empty(), "the token request never reached the upstream");
assert!(
e.upstream_paths().is_empty(),
"the token request never reached the upstream"
);
let auth_calls = e.auth.requests().len();
let cookie = share_cookie(&r);
let r = e
.get(HOST, "/albums/summer?x=1&y=2", Some(&format!("{cookie}; other=1")))
.get(
HOST,
"/albums/summer?x=1&y=2",
Some(&format!("{cookie}; other=1")),
)
.await;
assert_eq!(r.status, 200, "{}", r.text());
assert_eq!(e.auth.requests().len(), auth_calls, "no forward-auth for a share visitor");
assert_eq!(
e.auth.requests().len(),
auth_calls,
"no forward-auth for a share visitor"
);
let seen = e.echo.proxied();
let last = seen.last().unwrap();
assert_eq!(last.path, "/albums/summer");
@@ -200,20 +216,32 @@ mod unix {
.header("cookie")
.map(|c| String::from_utf8_lossy(c).into_owned())
.unwrap_or_default();
assert!(!cookie_sent.contains("ianitor-share"), "share cookie stripped: {cookie_sent}");
assert!(cookie_sent.contains("other=1"), "other cookies kept: {cookie_sent}");
assert!(
!cookie_sent.contains("ianitor-share"),
"share cookie stripped: {cookie_sent}"
);
assert!(
cookie_sent.contains("other=1"),
"other cookies kept: {cookie_sent}"
);
assert!(last.header("referer").is_none());
// The prefix itself and deeper paths are covered.
assert_eq!(e.get(HOST, "/albums", Some(&cookie)).await.status, 200);
assert_eq!(e.get(HOST, "/albums/a/b/c.jpg", Some(&cookie)).await.status, 200);
assert_eq!(
e.get(HOST, "/albums/a/b/c.jpg", Some(&cookie)).await.status,
200
);
// Neither the token nor the cookie appears in any log.
tokio::time::sleep(Duration::from_millis(200)).await;
let logs = e.edge.all_output();
assert!(!logs.contains(&t[5..40]), "token in logs");
assert!(!logs.contains(&cookie[30..60]), "cookie in logs");
assert!(!e.edge.access_log().contains("share="), "query in access log");
assert!(
!e.edge.access_log().contains("share="),
"query in access log"
);
for r in e.echo.requests() {
for (_, v) in &r.headers {
assert!(!String::from_utf8_lossy(v).contains(&t[5..40]));
@@ -309,7 +337,11 @@ mod unix {
// The cookie of a password link cannot be turned into a link that skips the password.
let v = cookie.split_once('=').unwrap().1.to_owned();
let r = e
.get(HOST, &format!("/docs?share={}", v.replacen("iss1.", "ish1.", 1)), None)
.get(
HOST,
&format!("/docs?share={}", v.replacen("iss1.", "ish1.", 1)),
None,
)
.await;
assert_ne!(r.status, 303);
@@ -384,16 +416,25 @@ mod unix {
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200);
e.edge.write_revocations(0, &[ShareId([12; 16]).to_hex()]);
let r = e.edge.admin("POST", "/v1/share-revocations/reload", None).await;
let r = e
.edge
.admin("POST", "/v1/share-revocations/reload", None)
.await;
assert_eq!(r.status, 200, "{}", r.text);
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 302, "back to sign-in");
assert_eq!(
e.get(HOST, "/", Some(&cookie)).await.status,
302,
"back to sign-in"
);
let r = e.get(HOST, &format!("/?share={t}"), None).await;
assert_visitor_page(&r, 403, "This link no longer works");
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 200);
// Stop all: a new epoch ends every older link.
e.edge.write_revocations(1, &[]);
e.edge.admin("POST", "/v1/share-revocations/reload", None).await;
e.edge
.admin("POST", "/v1/share-revocations/reload", None)
.await;
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 302);
// Without the admin call, edge notices a changed file within 5 s.
@@ -403,11 +444,16 @@ mod unix {
// A broken file keeps the last good state; a missing one stops all share access.
std::fs::write(e.edge.revocations_path(), "{ broken").unwrap();
let r = e.edge.admin("POST", "/v1/share-revocations/reload", None).await;
let r = e
.edge
.admin("POST", "/v1/share-revocations/reload", None)
.await;
assert_eq!(r.status, 422);
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 200);
std::fs::remove_file(e.edge.revocations_path()).unwrap();
e.edge.admin("POST", "/v1/share-revocations/reload", None).await;
e.edge
.admin("POST", "/v1/share-revocations/reload", None)
.await;
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 302);
}
}
+4 -4
View File
@@ -197,10 +197,10 @@ pub fn start_edge(env: &Env, name: &'static str, config_text: &str) -> Target {
cfg.http_listen.parse().unwrap(),
cfg.https_listen.parse().unwrap(),
);
let rt = Arc::new(
ianitor_edge::runtime::build(cfg, Some(&env.dir.join("creds"))).expect("edge runtime"),
);
let server = ianitor_edge::server(rt, &ianitor_edge::Options::default()).expect("edge server");
let rt = ianitor_edge::runtime::build(cfg, Some(&env.dir.join("creds"))).expect("edge runtime");
let opts = ianitor_edge::Options::default();
let shared = ianitor_edge::shared_for(rt, &opts);
let server = ianitor_edge::server(shared, &opts).expect("edge server");
let (tx, rx) = tokio::sync::oneshot::channel();
std::thread::spawn(move || ianitor_edge::run_until(server, rx));
assert!(
+6 -5
View File
@@ -52,12 +52,13 @@ pub fn parse_response(raw: &[u8]) -> io::Result<Resp> {
{
let mut out = Vec::new();
let mut rest = &body[..];
loop {
let Some(p) = rest.windows(2).position(|w| w == b"\r\n") else {
break;
};
while let Some(p) = rest.windows(2).position(|w| w == b"\r\n") {
let size = usize::from_str_radix(
String::from_utf8_lossy(&rest[..p]).split(';').next().unwrap_or("0").trim(),
String::from_utf8_lossy(&rest[..p])
.split(';')
.next()
.unwrap_or("0")
.trim(),
16,
)
.map_err(other)?;