[control] Domi CA and UI sign-in: intermediate renewal by CSR with manual offline signing, domi host certificates, device requests approved by code, one-time PKCS#12 installs, revocation; Remote-User trusted only with edge's per-boot proof
This commit is contained in:
@@ -179,39 +179,77 @@ pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result<Response,
|
||||
acme_configured: true,
|
||||
secrets: m.site().secrets.iter().map(|s| s.to_string()).collect(),
|
||||
watch_seconds: c.cfg.watch_secs,
|
||||
share_links_available: c.share_key.is_some(),
|
||||
share_links_available: c.share_key.is_some() && c.engine_running() != "caddy",
|
||||
});
|
||||
let es = super::pki::engine_view(c);
|
||||
let on_caddy = es.running == "caddy";
|
||||
let caddy_built = std::fs::metadata(&c.cfg.caddy.config)
|
||||
.and_then(|m| m.modified())
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| rfc3339(d.as_secs()));
|
||||
let caddy_current = tree
|
||||
.as_ref()
|
||||
.and_then(|t| t.model().ok())
|
||||
.and_then(|m| ianitor_core::compile::caddy(&m, &c.cfg.caddy_compile().options()).ok())
|
||||
.is_some_and(|text| {
|
||||
std::fs::read_to_string(&c.cfg.caddy.config).ok().as_deref() == Some(text.as_str())
|
||||
});
|
||||
let ov = Overview {
|
||||
counts,
|
||||
hosts,
|
||||
engine: EngineView {
|
||||
running: "pingora".into(),
|
||||
state: if status.is_some() && error.is_none() {
|
||||
"running"
|
||||
state: if es.state == "switching" {
|
||||
"switching".into()
|
||||
} else if on_caddy || (status.is_some() && error.is_none()) {
|
||||
"running".into()
|
||||
} else {
|
||||
"stopped"
|
||||
}
|
||||
.into(),
|
||||
since: status.as_ref().map(|s| rfc3339(s.started_at)),
|
||||
fallback_ready: None,
|
||||
"stopped".into()
|
||||
},
|
||||
since: if on_caddy || es.state == "switching" {
|
||||
Some(es.since.clone())
|
||||
} else {
|
||||
status.as_ref().map(|s| rfc3339(s.started_at))
|
||||
},
|
||||
running: es.running,
|
||||
target: es.target,
|
||||
switchable: es.switchable,
|
||||
fallback_ready: Some(FallbackReady {
|
||||
built_at: caddy_built,
|
||||
current: caddy_current,
|
||||
}),
|
||||
last_error: es.last_error,
|
||||
notes: es.notes,
|
||||
},
|
||||
last_apply,
|
||||
undo: undo_view(c),
|
||||
active_apply: active,
|
||||
repo: Some(repo_view(c, &head)),
|
||||
intermediate: None,
|
||||
intermediate: super::pki::intermediate_view(c),
|
||||
site,
|
||||
paused: c.paused().map(|p| Blocked {
|
||||
code: "control.paused".into(),
|
||||
message: message("control.paused", &messages::params([("reason", p.message)])),
|
||||
}),
|
||||
health_error: error.filter(|_| c.edge.attached()).map(|_| Blocked {
|
||||
code: "health.unavailable".into(),
|
||||
message: message(
|
||||
"health.unavailable",
|
||||
&messages::params([("engine", "Pingora".into())]),
|
||||
),
|
||||
paused: c.effective_pause().map(|p| {
|
||||
if p.code == "engine.caddy" {
|
||||
Blocked {
|
||||
code: p.code,
|
||||
message: p.message,
|
||||
}
|
||||
} else {
|
||||
Blocked {
|
||||
code: "control.paused".into(),
|
||||
message: message("control.paused", &messages::params([("reason", p.message)])),
|
||||
}
|
||||
}
|
||||
}),
|
||||
// Under Caddy, health is not read (edge is stopped); the chip says Caddy serves.
|
||||
health_error: error
|
||||
.filter(|_| c.edge.attached() && !on_caddy)
|
||||
.map(|_| Blocked {
|
||||
code: "health.unavailable".into(),
|
||||
message: message(
|
||||
"health.unavailable",
|
||||
&messages::params([("engine", "Pingora".into())]),
|
||||
),
|
||||
}),
|
||||
rev: Some(head),
|
||||
};
|
||||
let body = serde_json::to_vec(&ov).map_err(|e| ApiError::internal(e.to_string()))?;
|
||||
@@ -1038,6 +1076,14 @@ async fn mint_inner(
|
||||
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
|
||||
})?;
|
||||
let c = &st.ctl;
|
||||
if c.engine_running() == "caddy" {
|
||||
// G7: Caddy cannot check share links; control does not serve visitors itself.
|
||||
return Err(ApiError::new(
|
||||
StatusCode::CONFLICT,
|
||||
"share.engine_caddy",
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
let (_, _, model) = c.head_model()?;
|
||||
let Some(host) = model
|
||||
.hosts()
|
||||
@@ -1278,19 +1324,26 @@ impl Modify for Bearer {
|
||||
overview, list_hosts, get_host, validate_host, create_host, update_host, patch_host, delete_host,
|
||||
retry_certificate, list_applies, get_apply, cancel_apply, history, history_entry, restore_preview,
|
||||
get_undo, undo, restore, push_now, settings, list_tokens, create_token, rename_token, revoke_token,
|
||||
mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi
|
||||
mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi,
|
||||
super::pki::get_certs, super::pki::request_device, super::pki::get_request, super::pki::cancel_request,
|
||||
super::pki::get_csr, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device,
|
||||
super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine
|
||||
),
|
||||
components(schemas(
|
||||
HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate,
|
||||
TokenRename, MintBody, ErrorEnvelope, ErrorBody, ApplyAccepted, ApplyView, ApplyList, Step, WatchHost,
|
||||
Reason, FieldError, Overview, HostList, HostDetail, History, RestorePreview, UndoView, TokenList,
|
||||
TokenView, CreatedToken, ShareLinkList, ShareLinkView, MintedLink, StoppedAll, Settings, RepoView,
|
||||
HealthReport, Done
|
||||
HealthReport, Done, super::pki::CertsView, super::pki::PkiRequestView, super::pki::IntermediateView,
|
||||
super::pki::RootView, super::pki::DeviceView, super::pki::DeviceRequestBody, super::pki::CertificateBody,
|
||||
super::pki::BundleBody, super::pki::BundleView, super::pki::EngineSwitchView, super::pki::EngineBody,
|
||||
FallbackReady
|
||||
)),
|
||||
modifiers(&Bearer),
|
||||
tags(
|
||||
(name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"),
|
||||
(name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links")
|
||||
(name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links"),
|
||||
(name = "certs"), (name = "engine")
|
||||
)
|
||||
)]
|
||||
pub struct ApiDoc;
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
#![allow(clippy::result_large_err)]
|
||||
|
||||
pub mod handlers;
|
||||
pub mod pki;
|
||||
pub mod ui;
|
||||
pub mod views;
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -317,7 +319,7 @@ fn body_error(e: &serde_json::Error) -> ApiError {
|
||||
|
||||
// ---------------------------------------------------------------- middleware
|
||||
|
||||
fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
|
||||
pub(crate) 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;
|
||||
};
|
||||
@@ -328,7 +330,14 @@ fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
|
||||
format!("127.0.0.1:{port}"),
|
||||
format!("[::1]:{port}"),
|
||||
];
|
||||
ok.iter().any(|o| o.eq_ignore_ascii_case(host))
|
||||
// The admin host edge forwards the UI on, with or without edge's HTTPS port.
|
||||
let ui = ctl.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref());
|
||||
let ui_ok = ui.is_some_and(|u| {
|
||||
let edge_port = ctl.cfg.compile.https_listen.port();
|
||||
host.eq_ignore_ascii_case(u) || host.eq_ignore_ascii_case(&format!("{u}:{edge_port}"))
|
||||
});
|
||||
ui_ok
|
||||
|| ok.iter().any(|o| o.eq_ignore_ascii_case(host))
|
||||
|| ctl
|
||||
.cfg
|
||||
.allowed_hosts
|
||||
@@ -336,6 +345,45 @@ fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
|
||||
.any(|a| a.eq_ignore_ascii_case(host))
|
||||
}
|
||||
|
||||
enum UiIdentity {
|
||||
/// No sign-in headers: an API-token request.
|
||||
None,
|
||||
/// `Remote-*` or a proof header without the right proof.
|
||||
Forged,
|
||||
/// The right proof but no usable `Remote-User`.
|
||||
NoUser,
|
||||
User(String),
|
||||
}
|
||||
|
||||
fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity {
|
||||
let names_user = headers.keys().any(|k| k.as_str().starts_with("remote-"));
|
||||
let proof = headers.get("x-ianitor-proof");
|
||||
if !names_user && proof.is_none() {
|
||||
return UiIdentity::None;
|
||||
}
|
||||
let ok = match (proof, &ctl.ui_proof) {
|
||||
(Some(p), Some(want)) => crate::util::ct_eq(p.as_bytes(), want),
|
||||
_ => false,
|
||||
};
|
||||
if !ok {
|
||||
return UiIdentity::Forged;
|
||||
}
|
||||
let users: Vec<&HeaderValue> = headers.get_all("remote-user").iter().collect();
|
||||
match users.as_slice() {
|
||||
[one] => match one.to_str() {
|
||||
Ok(u)
|
||||
if !u.is_empty()
|
||||
&& u.len() <= 64
|
||||
&& u.bytes().all(|c| c.is_ascii_graphic() && c != b':') =>
|
||||
{
|
||||
UiIdentity::User(u.to_owned())
|
||||
}
|
||||
_ => UiIdentity::NoUser,
|
||||
},
|
||||
_ => UiIdentity::NoUser,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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();
|
||||
@@ -367,6 +415,46 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
// The web UI, through edge on the admin host (docs/api.md, "Sign-in"): only a request
|
||||
// with the per-boot proof edge adds is identified by its Remote-User. Any other
|
||||
// request that names a user is refused, so a local process cannot claim to be one.
|
||||
match ui_identity(&st.ctl, req.headers()) {
|
||||
UiIdentity::None => {}
|
||||
UiIdentity::Forged => {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"ui.no_proof",
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
UiIdentity::NoUser => {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"ui.no_user",
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
UiIdentity::User(user) => {
|
||||
// Cookie-based sign-in: every write carries the UI header, browser or not.
|
||||
if write && !ui {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
"request.csrf",
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
st.limit(&format!("user:{user}"), 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: format!("user:{user}"),
|
||||
name: user,
|
||||
});
|
||||
return Ok(next.run(req).await);
|
||||
}
|
||||
}
|
||||
let auth = req
|
||||
.headers()
|
||||
.get(header::AUTHORIZATION)
|
||||
@@ -429,7 +517,7 @@ async fn finish(req: Request, next: Next) -> Response {
|
||||
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") {
|
||||
if m.get("error").is_some_and(serde_json::Value::is_object) {
|
||||
m.insert("request_id".into(), request_id.into());
|
||||
}
|
||||
serde_json::to_vec(&m).unwrap_or_else(|_| bytes.to_vec())
|
||||
@@ -503,14 +591,35 @@ pub fn router(st: Arc<AppState>) -> Router {
|
||||
post(h::stop_all_share_links),
|
||||
)
|
||||
.route("/api/v1/share-links/{id}", delete(h::stop_share_link))
|
||||
.route("/api/v1/certs", get(pki::get_certs))
|
||||
.route("/api/v1/certs/devices", post(pki::request_device))
|
||||
.route("/api/v1/certs/devices/{id}", delete(pki::revoke_device))
|
||||
.route("/api/v1/certs/devices/{id}/bundle", post(pki::make_bundle))
|
||||
.route("/api/v1/certs/intermediate/renewal", post(pki::renew))
|
||||
.route(
|
||||
"/api/v1/pki-requests/{id}",
|
||||
get(pki::get_request).delete(pki::cancel_request),
|
||||
)
|
||||
.route("/api/v1/pki-requests/{id}/csr", get(pki::get_csr))
|
||||
.route(
|
||||
"/api/v1/pki-requests/{id}/certificate",
|
||||
axum::routing::put(pki::put_certificate),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/engine",
|
||||
get(pki::get_engine).post(pki::switch_engine),
|
||||
)
|
||||
.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))
|
||||
.with_state(st.clone());
|
||||
// In front of the guard: the built UI (static files, no token: they hold no data) and
|
||||
// the one-time device downloads (the link is the secret). Both still check the Host.
|
||||
api.layer(middleware::from_fn_with_state(st, ui::front))
|
||||
.layer(middleware::from_fn(finish))
|
||||
}
|
||||
|
||||
/// The OpenAPI document.
|
||||
|
||||
@@ -0,0 +1,687 @@
|
||||
// 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/.
|
||||
|
||||
//! Certificates (docs/ui-api.md §1.7, §1.8, §3.6) and the engine switch (§1.9).
|
||||
|
||||
// An error answer is built once per failed request; boxing it buys nothing.
|
||||
#![allow(clippy::result_large_err)]
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Extension;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::{HeaderValue, StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use super::views::Blocked;
|
||||
use super::{Actor, ApiError, AppState, Body};
|
||||
use crate::engine::Control;
|
||||
use crate::messages::{self, Params, message};
|
||||
use crate::pki::{Device, PkiFail, Request};
|
||||
use crate::pki_ctl::pki_fail;
|
||||
use crate::switch::engine_name;
|
||||
use crate::util::{now, rfc3339};
|
||||
|
||||
type Shared = State<Arc<AppState>>;
|
||||
|
||||
fn json<T: serde::Serialize>(status: StatusCode, v: &T) -> Response {
|
||||
(status, axum::Json(v)).into_response()
|
||||
}
|
||||
|
||||
fn plain_id(s: &str) -> bool {
|
||||
!s.is_empty() && s.len() <= 64 && s.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')
|
||||
}
|
||||
|
||||
fn not_found(code: &str) -> ApiError {
|
||||
ApiError::new(StatusCode::NOT_FOUND, code, Params::new())
|
||||
}
|
||||
|
||||
/// Run blocking PKI work (key unlock, file writes) off the async threads.
|
||||
async fn blocking<T: Send + 'static>(
|
||||
st: &Arc<AppState>,
|
||||
f: impl FnOnce(&Control) -> Result<T, PkiFail> + Send + 'static,
|
||||
) -> Result<T, ApiError> {
|
||||
let c = st.ctl.clone();
|
||||
if c.pki.is_none() {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::CONFLICT,
|
||||
"pki.not_configured",
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
tokio::task::spawn_blocking(move || f(&c))
|
||||
.await
|
||||
.map_err(|e| ApiError::internal(e.to_string()))?
|
||||
.map_err(|e| ApiError::from(pki_fail(e)))
|
||||
}
|
||||
|
||||
fn pki(c: &Control) -> Result<&crate::pki::Pki, PkiFail> {
|
||||
c.pki.as_ref().ok_or(PkiFail::Code("pki.not_configured"))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- views
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct PkiRequestView {
|
||||
pub request_id: String,
|
||||
/// `device` or `intermediate`.
|
||||
pub kind: String,
|
||||
/// `waiting`, `approved`, `denied`, `expired`, `cancelled` or `failed`.
|
||||
pub state: String,
|
||||
pub match_code: String,
|
||||
pub created_at: String,
|
||||
pub expires_at: String,
|
||||
pub approved_at: Option<String>,
|
||||
pub device_id: Option<String>,
|
||||
pub name: Option<String>,
|
||||
/// Renewals: the request to sign offline (also `GET /pki-requests/{id}/csr`).
|
||||
pub csr_pem: Option<String>,
|
||||
/// Renewals, once installed: the new intermediate's expiry.
|
||||
pub not_after: Option<String>,
|
||||
/// What to tell the user now (`pki.waiting.manual`, `pki.renew.manual`, `pki.denied`, …).
|
||||
pub message_code: String,
|
||||
pub message: String,
|
||||
/// The command that approves it on the server (manual approval).
|
||||
pub approve_command: Option<String>,
|
||||
/// Why it failed, when it did.
|
||||
pub problem: Option<String>,
|
||||
}
|
||||
|
||||
pub fn request_view(c: &Control, r: &Request) -> PkiRequestView {
|
||||
let (message_code, message_text) = match r.state.as_str() {
|
||||
"waiting" => c.waiting_message(&r.kind, &r.match_code),
|
||||
"approved" if r.kind == "intermediate" => {
|
||||
let date = r
|
||||
.not_after
|
||||
.map(|t| ianitor_core::time::long_date(t.max(0) as u64))
|
||||
.unwrap_or_default();
|
||||
(
|
||||
"pki.renewed".to_owned(),
|
||||
message("pki.renewed", &messages::params([("date", date)])),
|
||||
)
|
||||
}
|
||||
"approved" => (
|
||||
"pki.issued".to_owned(),
|
||||
message(
|
||||
"pki.issued",
|
||||
&messages::params([("name", r.name.clone().unwrap_or_default())]),
|
||||
),
|
||||
),
|
||||
"denied" => (
|
||||
"pki.denied".to_owned(),
|
||||
message("pki.denied", &Params::new()),
|
||||
),
|
||||
"expired" => (
|
||||
"pki.expired".to_owned(),
|
||||
message("pki.expired", &Params::new()),
|
||||
),
|
||||
"cancelled" => (
|
||||
"pki.cancelled".to_owned(),
|
||||
"Cancelled. Nothing was issued.".to_owned(),
|
||||
),
|
||||
_ => ("internal".to_owned(), message("internal", &Params::new())),
|
||||
};
|
||||
let manual = c.cfg.pki.as_ref().is_none_or(|p| p.approval == "manual");
|
||||
PkiRequestView {
|
||||
request_id: r.id.clone(),
|
||||
kind: r.kind.clone(),
|
||||
state: r.state.clone(),
|
||||
match_code: r.match_code.clone(),
|
||||
created_at: rfc3339(r.created_at),
|
||||
expires_at: rfc3339(r.expires_at),
|
||||
approved_at: r.approved_at.map(rfc3339),
|
||||
device_id: r.device_id.clone(),
|
||||
name: r.name.clone(),
|
||||
csr_pem: r.csr_pem.clone(),
|
||||
not_after: r.not_after.map(|t| rfc3339(t.max(0) as u64)),
|
||||
message_code,
|
||||
message: message_text,
|
||||
approve_command: (r.state == "waiting" && manual).then(|| {
|
||||
if r.kind == "intermediate" {
|
||||
"ianitor-control ca sign --root <offline root dir> --csr request.csr --out intermediate.crt; then ianitor-control pki install intermediate.crt".to_owned()
|
||||
} else {
|
||||
format!("ianitor-control pki approve {}", r.match_code)
|
||||
}
|
||||
}),
|
||||
problem: r.error.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct IntermediateView {
|
||||
/// `ok`, `due` (≤ 30 days), `urgent` (≤ 7 days), `expired` or `missing`.
|
||||
pub state: String,
|
||||
pub subject: Option<String>,
|
||||
pub not_after: Option<String>,
|
||||
pub days_left: Option<i64>,
|
||||
pub renewal: Option<PkiRequestView>,
|
||||
/// The banner text for `due`, `urgent`, `expired` and `missing`; `null` when `ok`.
|
||||
pub banner: Option<Blocked>,
|
||||
}
|
||||
|
||||
pub fn intermediate_view(c: &Control) -> Option<IntermediateView> {
|
||||
let p = c.pki.as_ref()?;
|
||||
let s = p.status(now());
|
||||
let date = s
|
||||
.not_after
|
||||
.map(|t| ianitor_core::time::long_date(t.max(0) as u64))
|
||||
.unwrap_or_default();
|
||||
let days = s.days_left.unwrap_or(0).to_string();
|
||||
let banner = match s.state {
|
||||
"due" => Some("pki.renew_due"),
|
||||
"urgent" => Some("pki.renew_urgent"),
|
||||
"expired" => Some("pki.intermediate_expired"),
|
||||
"missing" => Some("pki.no_intermediate"),
|
||||
_ => None,
|
||||
}
|
||||
.map(|code| Blocked {
|
||||
code: code.into(),
|
||||
message: message(
|
||||
code,
|
||||
&messages::params([("days", days.clone()), ("date", date.clone())]),
|
||||
),
|
||||
});
|
||||
Some(IntermediateView {
|
||||
state: s.state.into(),
|
||||
subject: s.subject,
|
||||
not_after: s.not_after.map(|t| rfc3339(t.max(0) as u64)),
|
||||
days_left: s.days_left,
|
||||
renewal: s.renewal.as_ref().map(|r| request_view(c, r)),
|
||||
banner,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct RootView {
|
||||
/// The root key is never on this server.
|
||||
pub offline: bool,
|
||||
pub subject: String,
|
||||
pub not_after: String,
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct DeviceView {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// `phone`, `computer` or `app`.
|
||||
pub kind: String,
|
||||
pub created_at: String,
|
||||
pub not_after: String,
|
||||
/// `valid`, `revoked` or `expired`.
|
||||
pub state: String,
|
||||
pub revoked_at: Option<String>,
|
||||
pub serial: String,
|
||||
}
|
||||
|
||||
fn device_view(d: &Device, t: u64) -> DeviceView {
|
||||
DeviceView {
|
||||
id: d.id.clone(),
|
||||
name: d.name.clone(),
|
||||
kind: d.kind.clone(),
|
||||
created_at: rfc3339(d.created_at),
|
||||
not_after: rfc3339(d.not_after.max(0) as u64),
|
||||
state: d.state(t).into(),
|
||||
revoked_at: d.revoked_at.map(rfc3339),
|
||||
serial: d.serial.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct CertsView {
|
||||
pub intermediate: Option<IntermediateView>,
|
||||
pub root: RootView,
|
||||
pub devices: Vec<DeviceView>,
|
||||
pub device_lifetime_days: u32,
|
||||
pub server_lifetime_days: u32,
|
||||
/// `manual` (on the server, until Custos can) or `custos`.
|
||||
pub approval: String,
|
||||
/// Open device requests.
|
||||
pub requests: Vec<PkiRequestView>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- handlers
|
||||
|
||||
/// The certificates screen.
|
||||
#[utoipa::path(get, path = "/api/v1/certs", tag = "certs",
|
||||
responses((status = 200, body = CertsView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||
pub async fn get_certs(State(st): Shared) -> Result<Response, ApiError> {
|
||||
let view = blocking(&st, |c| {
|
||||
let p = pki(c)?;
|
||||
let t = now();
|
||||
let root = ianitor_core::pki::inspect(p.root_pem())?;
|
||||
let requests = p_requests(c, t)?;
|
||||
Ok(CertsView {
|
||||
intermediate: intermediate_view(c),
|
||||
root: RootView {
|
||||
offline: true,
|
||||
subject: root.subject_cn,
|
||||
not_after: rfc3339(root.not_after.max(0) as u64),
|
||||
sha256: root.sha256_hex,
|
||||
},
|
||||
devices: p
|
||||
.devices()?
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|d| device_view(d, t))
|
||||
.collect(),
|
||||
device_lifetime_days: ianitor_core::pki::DEVICE_DAYS,
|
||||
server_lifetime_days: ianitor_core::pki::SERVER_DAYS,
|
||||
approval: c
|
||||
.cfg
|
||||
.pki
|
||||
.as_ref()
|
||||
.map(|p| p.approval.clone())
|
||||
.unwrap_or_default(),
|
||||
requests,
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
Ok(json(StatusCode::OK, &view))
|
||||
}
|
||||
|
||||
fn p_requests(c: &Control, t: u64) -> Result<Vec<PkiRequestView>, PkiFail> {
|
||||
let path = crate::pki::requests_path(&c.cfg.state_dir);
|
||||
let rs: Vec<Request> = crate::util::read_json(&path)
|
||||
.map_err(PkiFail::Internal)?
|
||||
.unwrap_or_default();
|
||||
Ok(rs
|
||||
.iter()
|
||||
.filter(|r| r.kind == "device" && r.state == "waiting" && r.expires_at > t)
|
||||
.map(|r| request_view(c, r))
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DeviceRequestBody {
|
||||
pub name: String,
|
||||
/// `phone`, `computer` or `app`.
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
/// Ask for a device certificate; it is issued once the request is approved with its code.
|
||||
#[utoipa::path(post, path = "/api/v1/certs/devices", tag = "certs", request_body = DeviceRequestBody,
|
||||
responses((status = 202, body = PkiRequestView), (status = 409, body = super::views::ErrorEnvelope), (status = 422, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||
pub async fn request_device(
|
||||
State(st): Shared,
|
||||
Extension(actor): Extension<Actor>,
|
||||
body: Body<DeviceRequestBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
st.limit(&format!("pki:{}", actor.token_id), 20, 3600)
|
||||
.map_err(|s| {
|
||||
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
|
||||
})?;
|
||||
let b = body.value;
|
||||
let name_for_err = b.name.clone();
|
||||
let r = blocking(&st, move |c| {
|
||||
let r = pki(c)?.request_device(&b.name, &b.kind, now(), &actor.name)?;
|
||||
Ok(request_view(c, &r))
|
||||
})
|
||||
.await
|
||||
.map_err(|mut e| {
|
||||
if e.body.code == "pki.device_name_taken" || e.body.code == "pki.device_name" {
|
||||
e.body.field = Some("name".into());
|
||||
e.body
|
||||
.params
|
||||
.insert("name".into(), name_for_err.chars().take(64).collect());
|
||||
} else if e.body.code == "pki.device_kind" {
|
||||
e.body.field = Some("kind".into());
|
||||
}
|
||||
e
|
||||
})?;
|
||||
log::info!(target: "ianitor::pki", "device certificate requested ({})", r.request_id);
|
||||
Ok(json(StatusCode::ACCEPTED, &r))
|
||||
}
|
||||
|
||||
/// One approval request.
|
||||
#[utoipa::path(get, path = "/api/v1/pki-requests/{id}", tag = "certs",
|
||||
responses((status = 200, body = PkiRequestView), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||
pub async fn get_request(State(st): Shared, Path(id): Path<String>) -> Result<Response, ApiError> {
|
||||
if !plain_id(&id) {
|
||||
return Err(not_found("pki.request_not_found"));
|
||||
}
|
||||
let v = blocking(&st, move |c| {
|
||||
let r = pki(c)?
|
||||
.request(&id, now())?
|
||||
.ok_or(PkiFail::Code("pki.request_not_found"))?;
|
||||
Ok(request_view(c, &r))
|
||||
})
|
||||
.await?;
|
||||
Ok(json(StatusCode::OK, &v))
|
||||
}
|
||||
|
||||
/// Cancel a request that waits.
|
||||
#[utoipa::path(delete, path = "/api/v1/pki-requests/{id}", tag = "certs",
|
||||
responses((status = 204), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||
pub async fn cancel_request(
|
||||
State(st): Shared,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Response, ApiError> {
|
||||
if !plain_id(&id) {
|
||||
return Err(not_found("pki.request_not_found"));
|
||||
}
|
||||
blocking(&st, move |c| {
|
||||
pki(c)?
|
||||
.cancel(&id)?
|
||||
.map(|_| ())
|
||||
.ok_or(PkiFail::Code("pki.request_not_found"))
|
||||
})
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT.into_response())
|
||||
}
|
||||
|
||||
/// A renewal's CSR, as a file to carry to the offline machine.
|
||||
#[utoipa::path(get, path = "/api/v1/pki-requests/{id}/csr", tag = "certs",
|
||||
responses((status = 200, description = "PEM PKCS#10"), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||
pub async fn get_csr(State(st): Shared, Path(id): Path<String>) -> Result<Response, ApiError> {
|
||||
if !plain_id(&id) {
|
||||
return Err(not_found("pki.request_not_found"));
|
||||
}
|
||||
let csr = blocking(&st, move |c| {
|
||||
pki(c)?
|
||||
.request(&id, now())?
|
||||
.and_then(|r| r.csr_pem)
|
||||
.ok_or(PkiFail::Code("pki.request_not_found"))
|
||||
})
|
||||
.await?;
|
||||
let mut r = csr.into_response();
|
||||
r.headers_mut().insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("application/pkcs10"),
|
||||
);
|
||||
r.headers_mut().insert(
|
||||
header::CONTENT_DISPOSITION,
|
||||
HeaderValue::from_static("attachment; filename=\"ianitor-intermediate.csr\""),
|
||||
);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CertificateBody {
|
||||
/// The intermediate certificate signed by the Domi root (PEM).
|
||||
pub certificate_pem: String,
|
||||
}
|
||||
|
||||
/// Install the signed intermediate for an open renewal.
|
||||
#[utoipa::path(put, path = "/api/v1/pki-requests/{id}/certificate", tag = "certs", request_body = CertificateBody,
|
||||
responses((status = 200, body = PkiRequestView), (status = 422, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||
pub async fn put_certificate(
|
||||
State(st): Shared,
|
||||
Path(id): Path<String>,
|
||||
body: Body<CertificateBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
if !plain_id(&id) {
|
||||
return Err(not_found("pki.request_not_found"));
|
||||
}
|
||||
let pem = body.value.certificate_pem;
|
||||
if pem.len() > 16 * 1024 {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"pki.bad_certificate",
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
let v = blocking(&st, move |c| {
|
||||
let r = pki(c)?.install_intermediate(&id, &pem, now())?;
|
||||
Ok(request_view(c, &r))
|
||||
})
|
||||
.await?;
|
||||
let c = st.ctl.clone();
|
||||
tokio::spawn(async move { c.refresh_certificates(true).await });
|
||||
Ok(json(StatusCode::OK, &v))
|
||||
}
|
||||
|
||||
/// Start the renewal of the intermediate (or set up the first one).
|
||||
#[utoipa::path(post, path = "/api/v1/certs/intermediate/renewal", tag = "certs",
|
||||
responses((status = 202, body = PkiRequestView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||
pub async fn renew(
|
||||
State(st): Shared,
|
||||
Extension(actor): Extension<Actor>,
|
||||
) -> Result<Response, ApiError> {
|
||||
let v = blocking(&st, move |c| {
|
||||
let r = pki(c)?.request_renewal(now(), &actor.name)?;
|
||||
Ok(request_view(c, &r))
|
||||
})
|
||||
.await?;
|
||||
Ok(json(StatusCode::ACCEPTED, &v))
|
||||
}
|
||||
|
||||
/// Revoke a device: it is off the allow list at once.
|
||||
#[utoipa::path(delete, path = "/api/v1/certs/devices/{id}", tag = "certs",
|
||||
responses((status = 204), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||
pub async fn revoke_device(
|
||||
State(st): Shared,
|
||||
Extension(actor): Extension<Actor>,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Response, ApiError> {
|
||||
if !plain_id(&id) {
|
||||
return Err(not_found("pki.device_not_found"));
|
||||
}
|
||||
let d = blocking(&st, move |c| {
|
||||
pki(c)?
|
||||
.revoke(&id, now())?
|
||||
.ok_or(PkiFail::Code("pki.device_not_found"))
|
||||
})
|
||||
.await?;
|
||||
log::info!(target: "ianitor::pki", "device {} revoked by {}", d.id, actor.token_id);
|
||||
st.ctl.devices_changed().await;
|
||||
Ok(StatusCode::NO_CONTENT.into_response())
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct BundleBody {
|
||||
/// `p12` (a file to download) or `qr` (the same link as a QR code).
|
||||
#[serde(default = "p12")]
|
||||
pub format: String,
|
||||
}
|
||||
|
||||
fn p12() -> String {
|
||||
"p12".into()
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct BundleView {
|
||||
/// Works once, for 10 minutes.
|
||||
pub download_url: String,
|
||||
/// Asked for when the file is installed. Shown once.
|
||||
pub one_time_password: String,
|
||||
pub expires_at: String,
|
||||
pub filename: String,
|
||||
/// `format = "qr"`: the link as an SVG QR code.
|
||||
pub qr_svg: Option<String>,
|
||||
}
|
||||
|
||||
/// A one-time install file for a device (G15): PKCS#12, behind a link that works once.
|
||||
#[utoipa::path(post, path = "/api/v1/certs/devices/{id}/bundle", tag = "certs", request_body = BundleBody,
|
||||
responses((status = 200, body = BundleView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||
pub async fn make_bundle(
|
||||
State(st): Shared,
|
||||
Path(id): Path<String>,
|
||||
body: Body<BundleBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
if !plain_id(&id) {
|
||||
return Err(not_found("pki.device_not_found"));
|
||||
}
|
||||
let format = body.value.format;
|
||||
if format != "p12" && format != "qr" {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"request.body",
|
||||
messages::params([("problem", "format must be \"p12\" or \"qr\".".into())]),
|
||||
));
|
||||
}
|
||||
let (token, password, expires) =
|
||||
blocking(&st, move |c| pki(c)?.make_bundle(&id, now())).await?;
|
||||
let url = bundle_url(&st, &token).await;
|
||||
let qr_svg = if format == "qr" {
|
||||
Some(crate::pki::qr_svg(&url).map_err(|e| ApiError::from(pki_fail(e)))?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(json(
|
||||
StatusCode::OK,
|
||||
&BundleView {
|
||||
download_url: url,
|
||||
one_time_password: password,
|
||||
expires_at: rfc3339(expires),
|
||||
filename: "domi-device.p12".into(),
|
||||
qr_svg,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// Where a device downloads its file: through edge on the admin host when there is one
|
||||
/// (as a share link when that host has share links on, so a device without a sign-in can
|
||||
/// reach it; the link covers only this one-time path), else control's own address.
|
||||
async fn bundle_url(st: &AppState, token: &str) -> String {
|
||||
let c = &st.ctl;
|
||||
let path = format!("/api/v1/device-bundles/{token}");
|
||||
let Some(ui) = c.cfg.ui.as_ref().and_then(|u| u.hostname.clone()) else {
|
||||
return format!("http://{}{path}", c.cfg.listen);
|
||||
};
|
||||
let port = c.cfg.compile.https_listen.port();
|
||||
let authority = if port == 443 {
|
||||
ui.clone()
|
||||
} else {
|
||||
format!("{ui}:{port}")
|
||||
};
|
||||
let shares_on = c
|
||||
.head_model()
|
||||
.ok()
|
||||
.and_then(|(_, _, m)| {
|
||||
m.hosts()
|
||||
.iter()
|
||||
.find(|h| h.hostname.as_str() == ui)
|
||||
.map(|h| h.share_links)
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if shares_on
|
||||
&& c.engine_running() != "caddy"
|
||||
&& let Some(key) = &c.share_key
|
||||
&& let Ok(m) = c.shares.mint(
|
||||
key,
|
||||
&ui,
|
||||
&path,
|
||||
crate::shares::MIN_EXPIRY,
|
||||
None,
|
||||
None,
|
||||
"device install",
|
||||
)
|
||||
{
|
||||
return format!(
|
||||
"https://{authority}{}?{}={}",
|
||||
m.record.path_prefix,
|
||||
ianitor_core::share::QUERY_PARAM,
|
||||
m.token
|
||||
);
|
||||
}
|
||||
format!("https://{authority}{path}")
|
||||
}
|
||||
|
||||
/// The one-time download itself. The link is the secret: no token or sign-in is needed, and
|
||||
/// it works once.
|
||||
#[utoipa::path(get, path = "/api/v1/device-bundles/{token}", tag = "certs",
|
||||
responses((status = 200, description = "application/x-pkcs12"), (status = 410, body = super::views::ErrorEnvelope)))]
|
||||
pub async fn download_bundle(
|
||||
State(st): Shared,
|
||||
Path(token): Path<String>,
|
||||
) -> Result<Response, ApiError> {
|
||||
if token.len() != 64 || !token.bytes().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::GONE,
|
||||
"pki.bundle_used",
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
let (bytes, _name) = blocking(&st, move |c| pki(c)?.take_bundle(&token, now())).await?;
|
||||
log::info!(target: "ianitor::pki", "a device install file was downloaded");
|
||||
let mut r = bytes.into_response();
|
||||
let h = r.headers_mut();
|
||||
h.insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("application/x-pkcs12"),
|
||||
);
|
||||
h.insert(
|
||||
header::CONTENT_DISPOSITION,
|
||||
HeaderValue::from_static("attachment; filename=\"domi-device.p12\""),
|
||||
);
|
||||
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||
h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- engine
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct EngineSwitchView {
|
||||
/// `pingora` or `caddy`.
|
||||
pub running: String,
|
||||
/// `running`, `switching` or `stopped`.
|
||||
pub state: String,
|
||||
pub target: Option<String>,
|
||||
pub since: String,
|
||||
/// Whether this server lets control switch (an `[engine]` section and its units).
|
||||
pub switchable: bool,
|
||||
/// Why the last switch did not happen.
|
||||
pub last_error: Option<crate::records::Reason>,
|
||||
/// What changes while Caddy serves.
|
||||
pub notes: Vec<Blocked>,
|
||||
}
|
||||
|
||||
pub fn engine_view(c: &Control) -> EngineSwitchView {
|
||||
let e = c.engine_state();
|
||||
let notes = if e.running == "caddy" {
|
||||
["engine.caddy", "share.engine_caddy"]
|
||||
.iter()
|
||||
.map(|code| Blocked {
|
||||
code: (*code).into(),
|
||||
message: message(code, &Params::new()),
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
EngineSwitchView {
|
||||
running: e.running,
|
||||
state: e.state,
|
||||
target: e.target,
|
||||
since: rfc3339(e.since),
|
||||
switchable: c.engine_cfg().is_some() && c.units.is_some(),
|
||||
last_error: e.last_error,
|
||||
notes,
|
||||
}
|
||||
}
|
||||
|
||||
/// Which engine serves.
|
||||
#[utoipa::path(get, path = "/api/v1/engine", tag = "engine",
|
||||
responses((status = 200, body = EngineSwitchView)), security(("bearer" = [])))]
|
||||
pub async fn get_engine(State(st): Shared) -> Response {
|
||||
json(StatusCode::OK, &engine_view(&st.ctl))
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct EngineBody {
|
||||
/// `pingora` or `caddy`.
|
||||
pub target: String,
|
||||
}
|
||||
|
||||
/// Switch the engine. Answers at once; poll `GET /engine` until `state` is `running`.
|
||||
#[utoipa::path(post, path = "/api/v1/engine", tag = "engine", request_body = EngineBody,
|
||||
responses((status = 202, body = EngineSwitchView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||
pub async fn switch_engine(
|
||||
State(st): Shared,
|
||||
Extension(actor): Extension<Actor>,
|
||||
body: Body<EngineBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
let target = body.value.target;
|
||||
st.ctl.request_switch(&target).map_err(ApiError::from)?;
|
||||
log::info!(target: "ianitor::engine", "switch to {} asked by {}", engine_name(&target), actor.token_id);
|
||||
Ok(json(StatusCode::ACCEPTED, &engine_view(&st.ctl)))
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// 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/.
|
||||
|
||||
//! In front of the API guard: the built web UI (`[ui] static_dir`) and the one-time device
|
||||
//! downloads. The UI's files hold no data (it reads everything from the API, which the guard
|
||||
//! protects), so they need no token; the Host check still applies against DNS rebinding.
|
||||
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::body::Body as AxumBody;
|
||||
use axum::extract::{Path as AxPath, Request, State};
|
||||
use axum::http::{HeaderValue, StatusCode, header};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
|
||||
use super::{ApiError, AppState, host_allowed};
|
||||
use crate::messages::Params;
|
||||
|
||||
const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; \
|
||||
script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
|
||||
|
||||
pub async fn front(State(st): State<Arc<AppState>>, req: Request, next: Next) -> Response {
|
||||
let path = req.uri().path().to_owned();
|
||||
if let Some(token) = path.strip_prefix("/api/v1/device-bundles/") {
|
||||
if !host_allowed(&st.ctl, req.headers()) {
|
||||
return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new())
|
||||
.into_response();
|
||||
}
|
||||
if req.method() != axum::http::Method::GET {
|
||||
return ApiError::new(
|
||||
StatusCode::METHOD_NOT_ALLOWED,
|
||||
"request.method",
|
||||
Params::new(),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let token = token.to_owned();
|
||||
return super::pki::download_bundle(State(st), AxPath(token))
|
||||
.await
|
||||
.unwrap_or_else(IntoResponse::into_response);
|
||||
}
|
||||
if path.starts_with("/api/") || path == "/api" {
|
||||
return next.run(req).await;
|
||||
}
|
||||
if !host_allowed(&st.ctl, req.headers()) {
|
||||
return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new()).into_response();
|
||||
}
|
||||
let Some(dir) = st.ctl.cfg.ui.as_ref().and_then(|u| u.static_dir.clone()) else {
|
||||
return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
|
||||
.into_response();
|
||||
};
|
||||
if !matches!(req.method().as_str(), "GET" | "HEAD") {
|
||||
return ApiError::new(
|
||||
StatusCode::METHOD_NOT_ALLOWED,
|
||||
"request.method",
|
||||
Params::new(),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
serve_static(&dir, &path).await
|
||||
}
|
||||
|
||||
/// A file from the UI build. Paths with `..`, odd characters or hidden names are refused;
|
||||
/// a path without a file extension is the single-page app (`index.html`).
|
||||
async fn serve_static(dir: &Path, url_path: &str) -> Response {
|
||||
let rel = url_path.trim_start_matches('/');
|
||||
let clean = !rel.contains('\\')
|
||||
&& rel
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || b"-_./".contains(&c))
|
||||
&& Path::new(rel)
|
||||
.components()
|
||||
.all(|c| matches!(c, Component::Normal(n) if !n.to_string_lossy().starts_with('.')));
|
||||
if !clean {
|
||||
return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
|
||||
.into_response();
|
||||
}
|
||||
let has_ext = Path::new(rel).extension().is_some();
|
||||
let file: PathBuf = if rel.is_empty() || !has_ext {
|
||||
dir.join("index.html")
|
||||
} else {
|
||||
dir.join(rel)
|
||||
};
|
||||
let Ok(bytes) = tokio::fs::read(&file).await else {
|
||||
return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
|
||||
.into_response();
|
||||
};
|
||||
let ctype = match file.extension().and_then(|e| e.to_str()).unwrap_or("") {
|
||||
"html" => "text/html; charset=utf-8",
|
||||
"js" | "mjs" => "text/javascript; charset=utf-8",
|
||||
"css" => "text/css; charset=utf-8",
|
||||
"svg" => "image/svg+xml",
|
||||
"png" => "image/png",
|
||||
"ico" => "image/x-icon",
|
||||
"woff2" => "font/woff2",
|
||||
"json" | "webmanifest" => "application/json",
|
||||
"txt" => "text/plain; charset=utf-8",
|
||||
_ => "application/octet-stream",
|
||||
};
|
||||
let immutable = rel.starts_with("assets/") || rel.starts_with("_app/immutable/");
|
||||
let mut r = Response::new(AxumBody::from(bytes));
|
||||
let h = r.headers_mut();
|
||||
h.insert(header::CONTENT_TYPE, HeaderValue::from_static(ctype));
|
||||
h.insert(
|
||||
header::CACHE_CONTROL,
|
||||
HeaderValue::from_static(if immutable {
|
||||
"public, max-age=31536000, immutable"
|
||||
} else {
|
||||
"no-cache"
|
||||
}),
|
||||
);
|
||||
h.insert("content-security-policy", HeaderValue::from_static(CSP));
|
||||
h.insert(
|
||||
"x-content-type-options",
|
||||
HeaderValue::from_static("nosniff"),
|
||||
);
|
||||
h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
|
||||
h.insert("x-frame-options", HeaderValue::from_static("DENY"));
|
||||
r
|
||||
}
|
||||
@@ -406,6 +406,8 @@ pub struct HostRow {
|
||||
pub auth: String,
|
||||
pub websockets: bool,
|
||||
pub share_links: bool,
|
||||
/// Visitors need a Domi device certificate.
|
||||
pub device_certs: bool,
|
||||
pub added_at: Option<String>,
|
||||
pub health: HealthView,
|
||||
pub certificate: CertView,
|
||||
@@ -439,13 +441,28 @@ pub struct Counts {
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct EngineView {
|
||||
/// `pingora` (the Caddy switch waits on Mark, ROADMAP §10 (b)).
|
||||
/// `pingora` or `caddy`.
|
||||
pub running: String,
|
||||
/// `running` or `stopped` (control cannot reach it).
|
||||
/// `running`, `switching` 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>,
|
||||
/// The engine a running switch goes to.
|
||||
pub target: Option<String>,
|
||||
/// Whether control can switch on this server (`[engine]` in control.toml).
|
||||
pub switchable: bool,
|
||||
/// The fallback's config: when it was written and whether it is the current tree's.
|
||||
pub fallback_ready: Option<FallbackReady>,
|
||||
/// Why the last switch did not happen.
|
||||
pub last_error: Option<Reason>,
|
||||
/// What is different while Caddy serves (`engine.caddy`, `share.engine_caddy`).
|
||||
pub notes: Vec<Blocked>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
pub struct FallbackReady {
|
||||
pub built_at: Option<String>,
|
||||
/// caddy.json is the compiled current tree.
|
||||
pub current: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||
@@ -507,9 +524,8 @@ pub struct Overview {
|
||||
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>,
|
||||
/// The Domi intermediate; `null` when the Domi CA is not set up (`[pki]`).
|
||||
pub intermediate: Option<super::pki::IntermediateView>,
|
||||
pub site: Option<SiteView>,
|
||||
pub paused: Option<Blocked>,
|
||||
/// Set when control cannot read health from edge (`health.unavailable`).
|
||||
@@ -526,7 +542,7 @@ pub fn added_at(c: &Control, hostname: &str) -> Option<String> {
|
||||
}
|
||||
|
||||
pub fn undo_view(c: &Control) -> UndoView {
|
||||
let blocked = if let Some(p) = c.paused() {
|
||||
let blocked = if let Some(p) = c.effective_pause() {
|
||||
Some(Blocked {
|
||||
code: "undo.paused".into(),
|
||||
message: message("undo.paused", &messages::Params::new()) + " " + &p.message,
|
||||
@@ -621,6 +637,7 @@ pub fn host_rows(
|
||||
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),
|
||||
device_certs: spec.as_ref().is_some_and(|s| s.device_certs),
|
||||
added_at: added_at(c, &h),
|
||||
health: health_view(st, spec.as_ref(), since.get(&h).copied()),
|
||||
certificate: cert_view(st, spec.as_ref()),
|
||||
|
||||
Reference in New Issue
Block a user