[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,33 +179,71 @@ pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result<Response,
|
|||||||
acme_configured: true,
|
acme_configured: true,
|
||||||
secrets: m.site().secrets.iter().map(|s| s.to_string()).collect(),
|
secrets: m.site().secrets.iter().map(|s| s.to_string()).collect(),
|
||||||
watch_seconds: c.cfg.watch_secs,
|
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 {
|
let ov = Overview {
|
||||||
counts,
|
counts,
|
||||||
hosts,
|
hosts,
|
||||||
engine: EngineView {
|
engine: EngineView {
|
||||||
running: "pingora".into(),
|
state: if es.state == "switching" {
|
||||||
state: if status.is_some() && error.is_none() {
|
"switching".into()
|
||||||
"running"
|
} else if on_caddy || (status.is_some() && error.is_none()) {
|
||||||
|
"running".into()
|
||||||
} else {
|
} else {
|
||||||
"stopped"
|
"stopped".into()
|
||||||
}
|
},
|
||||||
.into(),
|
since: if on_caddy || es.state == "switching" {
|
||||||
since: status.as_ref().map(|s| rfc3339(s.started_at)),
|
Some(es.since.clone())
|
||||||
fallback_ready: None,
|
} 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,
|
last_apply,
|
||||||
undo: undo_view(c),
|
undo: undo_view(c),
|
||||||
active_apply: active,
|
active_apply: active,
|
||||||
repo: Some(repo_view(c, &head)),
|
repo: Some(repo_view(c, &head)),
|
||||||
intermediate: None,
|
intermediate: super::pki::intermediate_view(c),
|
||||||
site,
|
site,
|
||||||
paused: c.paused().map(|p| Blocked {
|
paused: c.effective_pause().map(|p| {
|
||||||
|
if p.code == "engine.caddy" {
|
||||||
|
Blocked {
|
||||||
|
code: p.code,
|
||||||
|
message: p.message,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Blocked {
|
||||||
code: "control.paused".into(),
|
code: "control.paused".into(),
|
||||||
message: message("control.paused", &messages::params([("reason", p.message)])),
|
message: message("control.paused", &messages::params([("reason", p.message)])),
|
||||||
|
}
|
||||||
|
}
|
||||||
}),
|
}),
|
||||||
health_error: error.filter(|_| c.edge.attached()).map(|_| Blocked {
|
// 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(),
|
code: "health.unavailable".into(),
|
||||||
message: message(
|
message: message(
|
||||||
"health.unavailable",
|
"health.unavailable",
|
||||||
@@ -1038,6 +1076,14 @@ async fn mint_inner(
|
|||||||
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
|
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
|
||||||
})?;
|
})?;
|
||||||
let c = &st.ctl;
|
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 (_, _, model) = c.head_model()?;
|
||||||
let Some(host) = model
|
let Some(host) = model
|
||||||
.hosts()
|
.hosts()
|
||||||
@@ -1278,19 +1324,26 @@ impl Modify for Bearer {
|
|||||||
overview, list_hosts, get_host, validate_host, create_host, update_host, patch_host, delete_host,
|
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,
|
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,
|
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(
|
components(schemas(
|
||||||
HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate,
|
HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate,
|
||||||
TokenRename, MintBody, ErrorEnvelope, ErrorBody, ApplyAccepted, ApplyView, ApplyList, Step, WatchHost,
|
TokenRename, MintBody, ErrorEnvelope, ErrorBody, ApplyAccepted, ApplyView, ApplyList, Step, WatchHost,
|
||||||
Reason, FieldError, Overview, HostList, HostDetail, History, RestorePreview, UndoView, TokenList,
|
Reason, FieldError, Overview, HostList, HostDetail, History, RestorePreview, UndoView, TokenList,
|
||||||
TokenView, CreatedToken, ShareLinkList, ShareLinkView, MintedLink, StoppedAll, Settings, RepoView,
|
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),
|
modifiers(&Bearer),
|
||||||
tags(
|
tags(
|
||||||
(name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"),
|
(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;
|
pub struct ApiDoc;
|
||||||
|
|||||||
@@ -16,6 +16,8 @@
|
|||||||
#![allow(clippy::result_large_err)]
|
#![allow(clippy::result_large_err)]
|
||||||
|
|
||||||
pub mod handlers;
|
pub mod handlers;
|
||||||
|
pub mod pki;
|
||||||
|
pub mod ui;
|
||||||
pub mod views;
|
pub mod views;
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -317,7 +319,7 @@ fn body_error(e: &serde_json::Error) -> ApiError {
|
|||||||
|
|
||||||
// ---------------------------------------------------------------- middleware
|
// ---------------------------------------------------------------- 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 {
|
let Some(host) = headers.get(header::HOST).and_then(|h| h.to_str().ok()) else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
@@ -328,7 +330,14 @@ fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
|
|||||||
format!("127.0.0.1:{port}"),
|
format!("127.0.0.1:{port}"),
|
||||||
format!("[::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
|
|| ctl
|
||||||
.cfg
|
.cfg
|
||||||
.allowed_hosts
|
.allowed_hosts
|
||||||
@@ -336,6 +345,45 @@ fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
|
|||||||
.any(|a| a.eq_ignore_ascii_case(host))
|
.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.
|
/// 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 {
|
async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) -> Response {
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
@@ -367,6 +415,46 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
|
|||||||
Params::new(),
|
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
|
let auth = req
|
||||||
.headers()
|
.headers()
|
||||||
.get(header::AUTHORIZATION)
|
.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) {
|
let out = match serde_json::from_slice::<serde_json::Value>(&bytes) {
|
||||||
Ok(serde_json::Value::Object(mut m)) => {
|
Ok(serde_json::Value::Object(mut m)) => {
|
||||||
m.insert("server_time".into(), rfc3339(now()).into());
|
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());
|
m.insert("request_id".into(), request_id.into());
|
||||||
}
|
}
|
||||||
serde_json::to_vec(&m).unwrap_or_else(|_| bytes.to_vec())
|
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),
|
post(h::stop_all_share_links),
|
||||||
)
|
)
|
||||||
.route("/api/v1/share-links/{id}", delete(h::stop_share_link))
|
.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/health", get(h::health))
|
||||||
.route("/api/v1/openapi.json", get(h::openapi))
|
.route("/api/v1/openapi.json", get(h::openapi))
|
||||||
.method_not_allowed_fallback(method_not_allowed)
|
.method_not_allowed_fallback(method_not_allowed)
|
||||||
.fallback(not_found)
|
.fallback(not_found)
|
||||||
.layer(middleware::from_fn_with_state(st.clone(), guard))
|
.layer(middleware::from_fn_with_state(st.clone(), guard))
|
||||||
.layer(DefaultBodyLimit::max(MAX_BODY))
|
.layer(DefaultBodyLimit::max(MAX_BODY))
|
||||||
.with_state(st);
|
.with_state(st.clone());
|
||||||
api.layer(middleware::from_fn(finish))
|
// 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.
|
/// 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 auth: String,
|
||||||
pub websockets: bool,
|
pub websockets: bool,
|
||||||
pub share_links: bool,
|
pub share_links: bool,
|
||||||
|
/// Visitors need a Domi device certificate.
|
||||||
|
pub device_certs: bool,
|
||||||
pub added_at: Option<String>,
|
pub added_at: Option<String>,
|
||||||
pub health: HealthView,
|
pub health: HealthView,
|
||||||
pub certificate: CertView,
|
pub certificate: CertView,
|
||||||
@@ -439,13 +441,28 @@ pub struct Counts {
|
|||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, ToSchema)]
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
pub struct EngineView {
|
pub struct EngineView {
|
||||||
/// `pingora` (the Caddy switch waits on Mark, ROADMAP §10 (b)).
|
/// `pingora` or `caddy`.
|
||||||
pub running: String,
|
pub running: String,
|
||||||
/// `running` or `stopped` (control cannot reach it).
|
/// `running`, `switching` or `stopped` (control cannot reach it).
|
||||||
pub state: String,
|
pub state: String,
|
||||||
pub since: Option<String>,
|
pub since: Option<String>,
|
||||||
#[schema(value_type = Option<Object>)]
|
/// The engine a running switch goes to.
|
||||||
pub fallback_ready: Option<serde_json::Value>,
|
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)]
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
@@ -507,9 +524,8 @@ pub struct Overview {
|
|||||||
pub undo: UndoView,
|
pub undo: UndoView,
|
||||||
pub active_apply: Option<ActiveApply>,
|
pub active_apply: Option<ActiveApply>,
|
||||||
pub repo: Option<RepoView>,
|
pub repo: Option<RepoView>,
|
||||||
/// The Domi intermediate; arrives in phase 3.
|
/// The Domi intermediate; `null` when the Domi CA is not set up (`[pki]`).
|
||||||
#[schema(value_type = Option<Object>)]
|
pub intermediate: Option<super::pki::IntermediateView>,
|
||||||
pub intermediate: Option<serde_json::Value>,
|
|
||||||
pub site: Option<SiteView>,
|
pub site: Option<SiteView>,
|
||||||
pub paused: Option<Blocked>,
|
pub paused: Option<Blocked>,
|
||||||
/// Set when control cannot read health from edge (`health.unavailable`).
|
/// 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 {
|
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 {
|
Some(Blocked {
|
||||||
code: "undo.paused".into(),
|
code: "undo.paused".into(),
|
||||||
message: message("undo.paused", &messages::Params::new()) + " " + &p.message,
|
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(),
|
auth: spec.as_ref().map(|s| s.auth.clone()).unwrap_or_default(),
|
||||||
websockets: spec.as_ref().is_none_or(|s| s.websockets),
|
websockets: spec.as_ref().is_none_or(|s| s.websockets),
|
||||||
share_links: spec.as_ref().is_some_and(|s| s.share_links),
|
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),
|
added_at: added_at(c, &h),
|
||||||
health: health_view(st, spec.as_ref(), since.get(&h).copied()),
|
health: health_view(st, spec.as_ref(), since.get(&h).copied()),
|
||||||
certificate: cert_view(st, spec.as_ref()),
|
certificate: cert_view(st, spec.as_ref()),
|
||||||
|
|||||||
@@ -143,6 +143,8 @@ pub struct Control {
|
|||||||
pub share_key: Option<ShareKey>,
|
pub share_key: Option<ShareKey>,
|
||||||
/// The Domi CA, when `[pki]` is configured.
|
/// The Domi CA, when `[pki]` is configured.
|
||||||
pub pki: Option<crate::pki::Pki>,
|
pub pki: Option<crate::pki::Pki>,
|
||||||
|
/// The per-boot secret edge adds on the admin host (`X-Ianitor-Proof`), from `[ui]`.
|
||||||
|
pub ui_proof: Option<Vec<u8>>,
|
||||||
/// Which engine serves (see `switch`).
|
/// Which engine serves (see `switch`).
|
||||||
pub engine: Mutex<crate::switch::EngineState>,
|
pub engine: Mutex<crate::switch::EngineState>,
|
||||||
/// How control starts and stops the engines; `None` without `[engine]`.
|
/// How control starts and stops the engines; `None` without `[engine]`.
|
||||||
@@ -238,6 +240,12 @@ impl Control {
|
|||||||
repo,
|
repo,
|
||||||
edge,
|
edge,
|
||||||
share_key,
|
share_key,
|
||||||
|
ui_proof: cfg
|
||||||
|
.ui
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|u| u.proof_credential.as_deref())
|
||||||
|
.and_then(|n| cfg.credential(n))
|
||||||
|
.filter(|p| p.len() >= 32),
|
||||||
pki,
|
pki,
|
||||||
engine: Mutex::new(crate::switch::EngineState {
|
engine: Mutex::new(crate::switch::EngineState {
|
||||||
running: cfg
|
running: cfg
|
||||||
|
|||||||
@@ -26,6 +26,9 @@ pub struct HostSpec {
|
|||||||
pub websockets: bool,
|
pub websockets: bool,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub share_links: bool,
|
pub share_links: bool,
|
||||||
|
/// Visitors need a Domi device certificate (mTLS).
|
||||||
|
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||||
|
pub device_certs: bool,
|
||||||
/// `off` or `truncated`.
|
/// `off` or `truncated`.
|
||||||
#[serde(default = "off")]
|
#[serde(default = "off")]
|
||||||
pub access_log: String,
|
pub access_log: String,
|
||||||
@@ -115,6 +118,11 @@ impl HostSpec {
|
|||||||
to.share_links.to_string(),
|
to.share_links.to_string(),
|
||||||
);
|
);
|
||||||
push("access_log", self.access_log.clone(), to.access_log.clone());
|
push("access_log", self.access_log.clone(), to.access_log.clone());
|
||||||
|
push(
|
||||||
|
"device_certs",
|
||||||
|
self.device_certs.to_string(),
|
||||||
|
to.device_certs.to_string(),
|
||||||
|
);
|
||||||
let hc =
|
let hc =
|
||||||
|h: &Option<HealthCheckSpec>| h.as_ref().map(|h| (h.path.clone(), h.interval_secs));
|
|h: &Option<HealthCheckSpec>| h.as_ref().map(|h| (h.path.clone(), h.interval_secs));
|
||||||
let (a, b) = (hc(&self.health_check), hc(&to.health_check));
|
let (a, b) = (hc(&self.health_check), hc(&to.health_check));
|
||||||
@@ -157,6 +165,7 @@ mod tests {
|
|||||||
auth: "none".into(),
|
auth: "none".into(),
|
||||||
websockets: false,
|
websockets: false,
|
||||||
share_links: true,
|
share_links: true,
|
||||||
|
device_certs: true,
|
||||||
access_log: "truncated".into(),
|
access_log: "truncated".into(),
|
||||||
health_check: Some(HealthCheckSpec {
|
health_check: Some(HealthCheckSpec {
|
||||||
path: "/health".into(),
|
path: "/health".into(),
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ pub async fn serve(
|
|||||||
tokio::spawn(ctl.clone().worker());
|
tokio::spawn(ctl.clone().worker());
|
||||||
tokio::spawn(ctl.clone().health_poller());
|
tokio::spawn(ctl.clone().health_poller());
|
||||||
tokio::spawn(ctl.clone().pusher());
|
tokio::spawn(ctl.clone().pusher());
|
||||||
|
tokio::spawn(ctl.clone().pki_poller());
|
||||||
let app = api::router(api::AppState::new(ctl.clone()));
|
let app = api::router(api::AppState::new(ctl.clone()));
|
||||||
if !listen.ip().is_loopback() {
|
if !listen.ip().is_loopback() {
|
||||||
return Err("ianitor-control only listens on loopback".into());
|
return Err("ianitor-control only listens on loopback".into());
|
||||||
|
|||||||
@@ -9,6 +9,11 @@
|
|||||||
//! ianitor-control token list (--config <c> | --state-dir <d>)
|
//! ianitor-control token list (--config <c> | --state-dir <d>)
|
||||||
//! ianitor-control token revoke <id> (--config <c> | --state-dir <d>)
|
//! ianitor-control token revoke <id> (--config <c> | --state-dir <d>)
|
||||||
//! ianitor-control openapi print the OpenAPI document
|
//! ianitor-control openapi print the OpenAPI document
|
||||||
|
//! ianitor-control pki approve|deny <code> (--config <c> | --state-dir <d>) approve a device request
|
||||||
|
//! ianitor-control pki install <intermediate.crt> (--config <c>) install a signed intermediate
|
||||||
|
//! ianitor-control pki status (--config <c>) open requests
|
||||||
|
//! ianitor-control ca init --out <dir> [--passphrase-file <f>] the offline root (never on the server)
|
||||||
|
//! ianitor-control ca sign --root <dir> --csr <f> --out <f> [--yes] sign an intermediate offline
|
||||||
//! ianitor-control check --config <control.toml> check the config and exit
|
//! ianitor-control check --config <control.toml> check the config and exit
|
||||||
//! ```
|
//! ```
|
||||||
//! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`),
|
//! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`),
|
||||||
@@ -197,6 +202,168 @@ fn token(args: &[String]) -> Result<(), String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn arg_after(args: &[String], name: &str) -> Option<String> {
|
||||||
|
let mut it = args.iter();
|
||||||
|
while let Some(a) = it.next() {
|
||||||
|
if a == name {
|
||||||
|
return it.next().cloned();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A passphrase from `--passphrase-file`, or asked on the terminal without echo.
|
||||||
|
fn passphrase(args: &[String], confirm: bool) -> Result<String, String> {
|
||||||
|
if let Some(f) = arg_after(args, "--passphrase-file") {
|
||||||
|
let v = std::fs::read_to_string(&f).map_err(|e| format!("cannot read {f}: {e}"))?;
|
||||||
|
let v = v.trim_end_matches(['\r', '\n']).to_owned();
|
||||||
|
if v.chars().count() < 12 {
|
||||||
|
return Err("the passphrase must have at least 12 characters".into());
|
||||||
|
}
|
||||||
|
return Ok(v);
|
||||||
|
}
|
||||||
|
let p = rpassword::prompt_password("Root key passphrase: ").map_err(|e| e.to_string())?;
|
||||||
|
if p.chars().count() < 12 {
|
||||||
|
return Err("the passphrase must have at least 12 characters".into());
|
||||||
|
}
|
||||||
|
if confirm {
|
||||||
|
let again = rpassword::prompt_password("Again: ").map_err(|e| e.to_string())?;
|
||||||
|
if again != p {
|
||||||
|
return Err("the two passphrases differ".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `ca init` and `ca sign`: the offline root (ROADMAP §1.2; docs/pki.md). Never run on the
|
||||||
|
/// server.
|
||||||
|
fn ca(args: &[String]) -> Result<(), String> {
|
||||||
|
use ianitor_core::pki;
|
||||||
|
let now = ianitor_control::util::now() as i64;
|
||||||
|
match args.first().map(String::as_str) {
|
||||||
|
Some("init") => {
|
||||||
|
let out = PathBuf::from(arg_after(args, "--out").ok_or("ca init --out <dir>")?);
|
||||||
|
let crt = out.join("domi-root.crt");
|
||||||
|
let key = out.join("domi-root.key");
|
||||||
|
if crt.exists() || key.exists() {
|
||||||
|
return Err(format!(
|
||||||
|
"{} already has a root; refusing to replace it",
|
||||||
|
out.display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;
|
||||||
|
let pass = passphrase(args, true)?;
|
||||||
|
let (cert, k) = pki::create_root(now).map_err(|e| e.to_string())?;
|
||||||
|
let sealed = pki::encrypt_key(&k, pass.as_bytes()).map_err(|e| e.to_string())?;
|
||||||
|
ianitor_control::util::write_atomic(&key, sealed.as_bytes(), 0o600)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
ianitor_control::util::write_atomic(&crt, cert.as_bytes(), 0o644)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let info = pki::inspect(&cert).map_err(|e| e.to_string())?;
|
||||||
|
eprintln!(
|
||||||
|
"Domi root created in {}: {} (valid until {}).\nSHA-256 {}\n\
|
||||||
|
Copy domi-root.crt to the server's configuration (services.ianitor.pki.rootCertificate).\n\
|
||||||
|
Keep domi-root.key and its passphrase offline (Custos, once it can hold it).",
|
||||||
|
out.display(),
|
||||||
|
info.subject_cn,
|
||||||
|
ianitor_core::time::long_date(info.not_after.max(0) as u64),
|
||||||
|
info.sha256_hex
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some("sign") => {
|
||||||
|
let root = PathBuf::from(
|
||||||
|
arg_after(args, "--root")
|
||||||
|
.ok_or("ca sign --root <dir> --csr <file> --out <file>")?,
|
||||||
|
);
|
||||||
|
let csr_path = arg_after(args, "--csr").ok_or("--csr <file> is required")?;
|
||||||
|
let out = PathBuf::from(arg_after(args, "--out").ok_or("--out <file> is required")?);
|
||||||
|
let csr = std::fs::read_to_string(&csr_path)
|
||||||
|
.map_err(|e| format!("cannot read {csr_path}: {e}"))?;
|
||||||
|
let code = pki::match_code(&pki::csr_der(&csr).map_err(|e| e.to_string())?);
|
||||||
|
eprintln!("This request's code is {code}. It must be the code Ianitor shows.");
|
||||||
|
if !args.iter().any(|a| a == "--yes") {
|
||||||
|
let typed = rpassword::prompt_password("Type the code to sign (no echo): ")
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
if ianitor_control::pki::normalise_code(&typed)
|
||||||
|
!= ianitor_control::pki::normalise_code(&code)
|
||||||
|
{
|
||||||
|
return Err("the code does not match; nothing was signed".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let cert =
|
||||||
|
std::fs::read_to_string(root.join("domi-root.crt")).map_err(|e| e.to_string())?;
|
||||||
|
let sealed =
|
||||||
|
std::fs::read_to_string(root.join("domi-root.key")).map_err(|e| e.to_string())?;
|
||||||
|
let pass = passphrase(args, false)?;
|
||||||
|
let key = pki::decrypt_key(&sealed, pass.as_bytes()).map_err(|e| e.to_string())?;
|
||||||
|
let signed =
|
||||||
|
pki::sign_intermediate(&cert, &key, &csr, now).map_err(|e| e.to_string())?;
|
||||||
|
ianitor_control::util::write_atomic(&out, signed.as_bytes(), 0o644)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let info = pki::inspect(&signed).map_err(|e| e.to_string())?;
|
||||||
|
eprintln!(
|
||||||
|
"Signed {} until {}. Install it on the server: ianitor-control pki install {}",
|
||||||
|
info.subject_cn,
|
||||||
|
ianitor_core::time::long_date(info.not_after.max(0) as u64),
|
||||||
|
out.display()
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
_ => Err("ca init --out <dir> | ca sign --root <dir> --csr <file> --out <file>".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `pki approve|deny|install|status` on the server, as the user control runs as.
|
||||||
|
fn pki_cli(args: &[String]) -> Result<(), String> {
|
||||||
|
let dir = state_dir(args)?;
|
||||||
|
same_owner(&dir)?;
|
||||||
|
let now = ianitor_control::util::now();
|
||||||
|
match args.first().map(String::as_str) {
|
||||||
|
Some(verb @ ("approve" | "deny")) => {
|
||||||
|
// The code may be given as one word or three (47 19 83).
|
||||||
|
let code: String = args
|
||||||
|
.iter()
|
||||||
|
.skip(1)
|
||||||
|
.take_while(|a| !a.starts_with("--"))
|
||||||
|
.cloned()
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("");
|
||||||
|
let r = ianitor_control::pki::cli_approve(&dir, &code, verb == "deny", now)?;
|
||||||
|
eprintln!(
|
||||||
|
"{} the request for \"{}\" ({}). Control acts on it within a few seconds.",
|
||||||
|
if verb == "deny" { "Turned down" } else { "Approved" },
|
||||||
|
r.name.unwrap_or_default(),
|
||||||
|
r.id
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some("install") => {
|
||||||
|
let f = args.get(1).filter(|a| !a.starts_with("--")).ok_or("pki install <intermediate.crt>")?;
|
||||||
|
let pem = std::fs::read_to_string(f).map_err(|e| format!("cannot read {f}: {e}"))?;
|
||||||
|
let r = ianitor_control::pki::cli_install(&dir, &pem, now)?;
|
||||||
|
eprintln!("Handed to renewal {}. Control installs it within a few seconds.", r.id);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some("status") => {
|
||||||
|
let rs: Vec<ianitor_control::pki::Request> =
|
||||||
|
ianitor_control::util::read_json(&ianitor_control::pki::requests_path(&dir))?.unwrap_or_default();
|
||||||
|
for r in rs.iter().filter(|r| r.state == "waiting" && r.expires_at > now) {
|
||||||
|
println!(
|
||||||
|
"{} {} {} code {} until {}",
|
||||||
|
r.id,
|
||||||
|
r.kind,
|
||||||
|
r.name.clone().unwrap_or_default(),
|
||||||
|
r.match_code,
|
||||||
|
ianitor_control::util::rfc3339(r.expires_at)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
_ => Err("pki approve <code> | pki deny <code> | pki install <cert> | pki status (--config <c> | --state-dir <d>)".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn main() -> ExitCode {
|
fn main() -> ExitCode {
|
||||||
if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") {
|
if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") {
|
||||||
return askpass();
|
return askpass();
|
||||||
@@ -215,6 +382,8 @@ fn main() -> ExitCode {
|
|||||||
};
|
};
|
||||||
let result = match args.first().map(String::as_str) {
|
let result = match args.first().map(String::as_str) {
|
||||||
Some("token") => token(&args[1..]),
|
Some("token") => token(&args[1..]),
|
||||||
|
Some("pki") => pki_cli(&args[1..]),
|
||||||
|
Some("ca") => ca(&args[1..]),
|
||||||
Some("openapi") => {
|
Some("openapi") => {
|
||||||
println!("{}", ianitor_control::api::openapi_json());
|
println!("{}", ianitor_control::api::openapi_json());
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -279,12 +279,7 @@ impl Pki {
|
|||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
{
|
{
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
let mode = if d.ends_with("approvals") {
|
let _ = std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700));
|
||||||
0o700
|
|
||||||
} else {
|
|
||||||
0o700
|
|
||||||
};
|
|
||||||
let _ = std::fs::set_permissions(&d, std::fs::Permissions::from_mode(mode));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Pki {
|
Ok(Pki {
|
||||||
|
|||||||
@@ -22,6 +22,9 @@
|
|||||||
//!
|
//!
|
||||||
//! The systemd calls go through [`Units`], so tests use a fake.
|
//! The systemd calls go through [`Units`], so tests use a fake.
|
||||||
|
|
||||||
|
// A refusal is built once per request; boxing it buys nothing.
|
||||||
|
#![allow(clippy::result_large_err)]
|
||||||
|
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
@@ -382,6 +385,11 @@ impl Control {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Any reason changes wait now: Caddy serving, or a pause.
|
||||||
|
pub fn effective_pause(&self) -> Option<Reason> {
|
||||||
|
self.engine_pause().or_else(|| self.paused())
|
||||||
|
}
|
||||||
|
|
||||||
/// Changes wait while Caddy serves.
|
/// Changes wait while Caddy serves.
|
||||||
pub fn engine_pause(&self) -> Option<Reason> {
|
pub fn engine_pause(&self) -> Option<Reason> {
|
||||||
(self.engine_running() == "caddy").then(|| reason("engine.caddy", Params::new()))
|
(self.engine_running() == "caddy").then(|| reason("engine.caddy", Params::new()))
|
||||||
|
|||||||
@@ -34,6 +34,11 @@ mod unix {
|
|||||||
fn routes(doc: &Value) -> Vec<(String, String)> {
|
fn routes(doc: &Value) -> Vec<(String, String)> {
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
for (path, item) in doc["paths"].as_object().unwrap() {
|
for (path, item) in doc["paths"].as_object().unwrap() {
|
||||||
|
// The one-time device download is the one call without a token: the link is
|
||||||
|
// the secret (G15). Every other call needs one.
|
||||||
|
if path.starts_with("/api/v1/device-bundles/") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
for method in ["get", "post", "put", "patch", "delete"] {
|
for method in ["get", "post", "put", "patch", "delete"] {
|
||||||
if item.get(method).is_some() {
|
if item.get(method).is_some() {
|
||||||
let p = path
|
let p = path
|
||||||
@@ -118,14 +123,14 @@ mod unix {
|
|||||||
vec![("Authorization".into(), "Bearer ".into())],
|
vec![("Authorization".into(), "Bearer ".into())],
|
||||||
"token.unknown",
|
"token.unknown",
|
||||||
),
|
),
|
||||||
// Identity headers do not authenticate (docs/ui-api.md G14).
|
// Identity headers without edge's proof are refused (docs/ui-api.md G14).
|
||||||
(
|
(
|
||||||
"remote-user".into(),
|
"remote-user".into(),
|
||||||
vec![
|
vec![
|
||||||
("Remote-User".into(), "mark".into()),
|
("Remote-User".into(), "mark".into()),
|
||||||
("Remote-Groups".into(), "admins".into()),
|
("Remote-Groups".into(), "admins".into()),
|
||||||
],
|
],
|
||||||
"token.missing",
|
"ui.no_proof",
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
for (what, headers, code) in &cases {
|
for (what, headers, code) in &cases {
|
||||||
@@ -147,7 +152,8 @@ mod unix {
|
|||||||
env.call_with("GET", "/api/v1/nope", &[], None).await.status,
|
env.call_with("GET", "/api/v1/nope", &[], None).await.status,
|
||||||
401
|
401
|
||||||
);
|
);
|
||||||
assert_eq!(env.call_with("GET", "/", &[], None).await.status, 401);
|
// Outside /api/ only the built UI is served (no data, no token); none is set up here.
|
||||||
|
assert_eq!(env.call_with("GET", "/", &[], None).await.status, 404);
|
||||||
|
|
||||||
// A wrong Host header (DNS rebinding) is refused even with a good token.
|
// A wrong Host header (DNS rebinding) is refused even with a good token.
|
||||||
let auth = format!("Bearer {}", env.token);
|
let auth = format!("Bearer {}", env.token);
|
||||||
|
|||||||
@@ -116,7 +116,16 @@ mod unix {
|
|||||||
let r2 = env
|
let r2 = env
|
||||||
.call("GET", &format!("/api/v1/pki-requests/{rid}/csr"), None)
|
.call("GET", &format!("/api/v1/pki-requests/{rid}/csr"), None)
|
||||||
.await;
|
.await;
|
||||||
assert_eq!(r2.status, 200);
|
assert_eq!(
|
||||||
|
r2.status,
|
||||||
|
200,
|
||||||
|
"{}
|
||||||
|
{}
|
||||||
|
{}",
|
||||||
|
r.text,
|
||||||
|
r2.text,
|
||||||
|
env.control_log()
|
||||||
|
);
|
||||||
assert_eq!(r2.text, csr);
|
assert_eq!(r2.text, csr);
|
||||||
let signed = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap();
|
let signed = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap();
|
||||||
let f = env.dir.join("signed.crt");
|
let f = env.dir.join("signed.crt");
|
||||||
@@ -170,7 +179,8 @@ mod unix {
|
|||||||
i64::from(pki::SERVER_DAYS) - 1
|
i64::from(pki::SERVER_DAYS) - 1
|
||||||
);
|
);
|
||||||
|
|
||||||
// No root key anywhere control writes.
|
// No root key anywhere control writes. (The start of a P-256 PKCS#8 body is the same
|
||||||
|
// for every key, so the unique end is compared.)
|
||||||
let key_pem = off.root_key.serialize_pem();
|
let key_pem = off.root_key.serialize_pem();
|
||||||
let body: String = key_pem
|
let body: String = key_pem
|
||||||
.lines()
|
.lines()
|
||||||
@@ -181,7 +191,7 @@ mod unix {
|
|||||||
let bytes = std::fs::read(&f).unwrap();
|
let bytes = std::fs::read(&f).unwrap();
|
||||||
let text = String::from_utf8_lossy(&bytes);
|
let text = String::from_utf8_lossy(&bytes);
|
||||||
assert!(
|
assert!(
|
||||||
!text.contains(&body[..40]),
|
!text.contains(&body[body.len() - 40..]),
|
||||||
"root key material in {}",
|
"root key material in {}",
|
||||||
f.display()
|
f.display()
|
||||||
);
|
);
|
||||||
@@ -407,7 +417,7 @@ mod unix {
|
|||||||
let p = e.path();
|
let p = e.path();
|
||||||
if p.is_dir() {
|
if p.is_dir() {
|
||||||
stack.push(p);
|
stack.push(p);
|
||||||
} else {
|
} else if p.is_file() {
|
||||||
out.push(p);
|
out.push(p);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -235,6 +235,10 @@ async fn handle(shared: Arc<Shared>, req: Request<Incoming>) -> Resp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
("POST", "/v1/abort") => reply(StatusCode::OK, json!({ "reverted": shared.abort() })),
|
("POST", "/v1/abort") => reply(StatusCode::OK, json!({ "reverted": shared.abort() })),
|
||||||
|
("POST", "/v1/device-certs/reload") => match shared.reload_device_trust() {
|
||||||
|
Ok(n) => reply(StatusCode::OK, json!({ "reloaded": true, "allowed": n })),
|
||||||
|
Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
|
||||||
|
},
|
||||||
("POST", "/v1/share-revocations/reload") => match shared.reload_revocations() {
|
("POST", "/v1/share-revocations/reload") => match shared.reload_revocations() {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
let r = shared.revocations();
|
let r = shared.revocations();
|
||||||
|
|||||||
@@ -131,7 +131,9 @@ impl ProxyHttp for EdgeProxy {
|
|||||||
let rt = self.shared.current();
|
let rt = self.shared.current();
|
||||||
ctx.rt = Some(rt.clone());
|
ctx.rt = Some(rt.clone());
|
||||||
ctx.host_header = host_header(session.req_header());
|
ctx.host_header = host_header(session.req_header());
|
||||||
if rt.device_trust.is_some() && sni_mismatch(session, &hostname(&ctx.host_header)) {
|
if self.shared.devices.current().is_some()
|
||||||
|
&& sni_mismatch(session, &hostname(&ctx.host_header))
|
||||||
|
{
|
||||||
// Like Caddy once client certificates are configured: a request for another host
|
// Like Caddy once client certificates are configured: a request for another host
|
||||||
// than the one the TLS connection was opened for is refused, so a connection
|
// than the one the TLS connection was opened for is refused, so a connection
|
||||||
// that was never asked for a certificate cannot reach a device host.
|
// that was never asked for a certificate cannot reach a device host.
|
||||||
@@ -144,7 +146,7 @@ impl ProxyHttp for EdgeProxy {
|
|||||||
};
|
};
|
||||||
ctx.host = Some(host.clone());
|
ctx.host = Some(host.clone());
|
||||||
|
|
||||||
if host.cfg.device_certs && !has_allowed_device_cert(session, &rt) {
|
if host.cfg.device_certs && !has_allowed_device_cert(session, &self.shared) {
|
||||||
// No certificate on this connection (one that is presented but not allowed never
|
// No certificate on this connection (one that is presented but not allowed never
|
||||||
// gets here: the handshake fails). Same as Caddy's route: 403, nothing upstream.
|
// gets here: the handshake fails). Same as Caddy's route: 403, nothing upstream.
|
||||||
respond_empty(session, 403).await?;
|
respond_empty(session, 403).await?;
|
||||||
@@ -441,8 +443,8 @@ fn sni_mismatch(session: &Session, host: &str) -> bool {
|
|||||||
/// Did this connection present a device certificate that the current config allows? The
|
/// Did this connection present a device certificate that the current config allows? The
|
||||||
/// handshake already checked the chain and the list; this checks again against the runtime
|
/// handshake already checked the chain and the list; this checks again against the runtime
|
||||||
/// serving the request, so a revocation also ends requests on connections made before it.
|
/// serving the request, so a revocation also ends requests on connections made before it.
|
||||||
fn has_allowed_device_cert(session: &Session, rt: &crate::runtime::Runtime) -> bool {
|
fn has_allowed_device_cert(session: &Session, shared: &crate::shared::Shared) -> bool {
|
||||||
let Some(trust) = rt.device_trust.as_ref() else {
|
let Some(trust) = shared.devices.current() else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
session
|
session
|
||||||
|
|||||||
@@ -187,7 +187,16 @@ impl Shared {
|
|||||||
|
|
||||||
fn install(&self, rt: Arc<Runtime>) {
|
fn install(&self, rt: Arc<Runtime>) {
|
||||||
self.certs.replace_files(rt.file_certs.clone());
|
self.certs.replace_files(rt.file_certs.clone());
|
||||||
self.devices.replace(rt.device_trust.clone());
|
// Read the device files again: the runtime may be older than the latest allow list
|
||||||
|
// (a revert after a revocation must not let a revoked device back in).
|
||||||
|
let trust = match fresh_trust(&rt) {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(target: "ianitor::tls", "{e}; keeping the device check this config was built with");
|
||||||
|
rt.device_trust.clone()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.devices.replace(trust);
|
||||||
self.current.store(rt);
|
self.current.store(rt);
|
||||||
self.generation.fetch_add(1, Ordering::SeqCst);
|
self.generation.fetch_add(1, Ordering::SeqCst);
|
||||||
self.notify();
|
self.notify();
|
||||||
@@ -496,3 +505,36 @@ fn poisoned() -> AdminError {
|
|||||||
fn short(sha: &str) -> &str {
|
fn short(sha: &str) -> &str {
|
||||||
sha.get(..12).unwrap_or(sha)
|
sha.get(..12).unwrap_or(sha)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The device check for a runtime, built from the files as they are now.
|
||||||
|
fn fresh_trust(rt: &Runtime) -> Result<Option<Arc<crate::tls::DeviceTrust>>, String> {
|
||||||
|
let Some(dc) = &rt.cfg.device_certs else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let hosts: std::collections::HashSet<String> = rt
|
||||||
|
.cfg
|
||||||
|
.hosts
|
||||||
|
.iter()
|
||||||
|
.filter(|h| h.device_certs)
|
||||||
|
.map(|h| h.hostname.clone())
|
||||||
|
.collect();
|
||||||
|
if hosts.is_empty() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let ca = std::fs::read(&dc.ca).map_err(|e| format!("cannot read {}: {e}", dc.ca))?;
|
||||||
|
let allow = std::fs::read(&dc.allow).map_err(|e| format!("cannot read {}: {e}", dc.allow))?;
|
||||||
|
crate::tls::DeviceTrust::new(&ca, &allow, hosts).map(|t| Some(Arc::new(t)))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Shared {
|
||||||
|
/// Re-read the device CA bundle and allow list now (control calls this after an issue
|
||||||
|
/// or a revocation; allowed during a trial). Returns how many devices are allowed.
|
||||||
|
pub fn reload_device_trust(&self) -> Result<usize, String> {
|
||||||
|
let rt = self.current();
|
||||||
|
let t = fresh_trust(&rt)?;
|
||||||
|
let n = t.as_ref().map_or(0, |t| t.allowed());
|
||||||
|
self.devices.replace(t);
|
||||||
|
log::info!(target: "ianitor::tls", "device certificates re-read: {n} allowed");
|
||||||
|
Ok(n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -159,6 +159,10 @@ impl DeviceTrust {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn allowed(&self) -> usize {
|
||||||
|
self.allow.len()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn allows(&self, cert_sha256: &[u8]) -> bool {
|
pub fn allows(&self, cert_sha256: &[u8]) -> bool {
|
||||||
<[u8; 32]>::try_from(cert_sha256).is_ok_and(|d| self.allow.contains(&d))
|
<[u8; 32]>::try_from(cert_sha256).is_ok_and(|d| self.allow.contains(&d))
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user