[control] Mark's UI decisions: Remote-Name shown with the proof, [ui] logout_url for Sign out, openssl signing files for the manual intermediate step, engine.not_ready, server sentences for the eight generic codes

This commit is contained in:
2026-11-07 23:48:43 +01:00
parent 3e326e85a0
commit 9933f55242
11 changed files with 225 additions and 13 deletions
+2 -1
View File
@@ -184,6 +184,7 @@ pub async fn overview(
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() && c.engine_running() != "caddy",
auth_logout_url: c.cfg.ui.as_ref().and_then(|u| u.logout_url.clone()),
});
let es = super::pki::engine_view(c);
let on_caddy = es.running == "caddy";
@@ -1339,7 +1340,7 @@ impl Modify for Bearer {
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,
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::get_csr, super::pki::get_ext, 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(
+15 -4
View File
@@ -352,7 +352,8 @@ enum UiIdentity {
Forged,
/// The right proof but no usable `Remote-User`.
NoUser,
User(String),
/// The Authelia user name, and the name to show (`Remote-Name` when it is usable).
User(String, String),
}
fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity {
@@ -376,7 +377,16 @@ fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity {
&& u.len() <= 64
&& u.bytes().all(|c| c.is_ascii_graphic() && c != b':') =>
{
UiIdentity::User(u.to_owned())
let display = headers
.get("remote-name")
.and_then(|v| v.to_str().ok())
.map(str::trim)
.filter(|n| {
!n.is_empty() && n.chars().count() <= 64 && !n.chars().any(char::is_control)
})
.unwrap_or(u)
.to_owned();
UiIdentity::User(u.to_owned(), display)
}
_ => UiIdentity::NoUser,
},
@@ -434,7 +444,7 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
Params::new(),
));
}
UiIdentity::User(user) => {
UiIdentity::User(user, display) => {
// Cookie-based sign-in: every write carries the UI header, browser or not.
if write && !ui {
return Err(ApiError::new(
@@ -450,7 +460,7 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
})?;
req.extensions_mut().insert(Actor {
token_id: format!("user:{user}"),
name: user,
name: display,
});
return Ok(next.run(req).await);
}
@@ -601,6 +611,7 @@ pub fn router(st: Arc<AppState>) -> Router {
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}/ext", get(pki::get_ext))
.route(
"/api/v1/pki-requests/{id}/certificate",
axum::routing::put(pki::put_certificate),
+44 -6
View File
@@ -86,6 +86,8 @@ pub struct PkiRequestView {
pub message: String,
/// The command that approves it on the server (manual approval).
pub approve_command: Option<String>,
/// Renewals: the base name of the files (`<base>.csr`, `<base>.ext`, `<base>.crt`).
pub file_base: Option<String>,
/// Why it failed, when it did.
pub problem: Option<String>,
}
@@ -141,15 +143,24 @@ pub fn request_view(c: &Control, r: &Request) -> PkiRequestView {
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()
ianitor_core::pki::openssl_sign_command(&file_base(r))
} else {
format!("ianitor-control pki approve {}", r.match_code)
}
}),
file_base: (r.kind == "intermediate").then(|| file_base(r)),
problem: r.error.clone(),
}
}
/// `domi-intermediate-2026-11-07`, from the day the request was made.
pub fn file_base(r: &Request) -> String {
format!(
"domi-intermediate-{}",
rfc3339(r.created_at).get(..10).unwrap_or("request")
)
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct IntermediateView {
/// `ok`, `due` (≤ 30 days), `urgent` (≤ 7 days), `expired` or `missing`.
@@ -384,19 +395,19 @@ pub async fn get_csr(State(st): Shared, Path(id): Path<String>) -> Result<Respon
let csr = blocking(&st, move |c| {
pki(c)?
.request(&id, now())?
.and_then(|r| r.csr_pem)
.and_then(|r| r.csr_pem.clone().map(|c| (c, file_base(&r))))
.ok_or(PkiFail::Code("pki.request_not_found"))
})
.await?;
let (csr, base) = csr;
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\""),
);
if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{base}.csr\"")) {
r.headers_mut().insert(header::CONTENT_DISPOSITION, v);
}
Ok(r)
}
@@ -685,3 +696,30 @@ pub async fn switch_engine(
log::info!(target: "ianitor::engine", "switch to {} asked by {}", engine_name(&target), actor.token_id);
Ok(json(StatusCode::ACCEPTED, &engine_view(&st.ctl)))
}
/// The openssl extensions file for signing a renewal by hand (the same profile Custos will
/// use; docs/pki.md).
#[utoipa::path(get, path = "/api/v1/pki-requests/{id}/ext", tag = "certs",
responses((status = 200, description = "openssl -extfile"), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn get_ext(State(st): Shared, Path(id): Path<String>) -> Result<Response, ApiError> {
if !plain_id(&id) {
return Err(not_found("pki.request_not_found"));
}
let r = blocking(&st, move |c| {
pki(c)?
.request(&id, now())?
.filter(|r| r.kind == "intermediate")
.ok_or(PkiFail::Code("pki.request_not_found"))
})
.await?;
let mut resp = ianitor_core::pki::INTERMEDIATE_OPENSSL_EXT.into_response();
resp.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/plain; charset=utf-8"),
);
if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{}.ext\"", file_base(&r)))
{
resp.headers_mut().insert(header::CONTENT_DISPOSITION, v);
}
Ok(resp)
}
+2
View File
@@ -513,6 +513,8 @@ pub struct SiteView {
pub secrets: Vec<String>,
pub watch_seconds: u64,
pub share_links_available: bool,
/// Authelia's logout address, for "Sign out" (`[ui] logout_url`); `null` hides the link.
pub auth_logout_url: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
+3
View File
@@ -321,6 +321,9 @@ pub struct UiConfig {
pub proof_credential: Option<String>,
/// The built web UI (served at `/`).
pub static_dir: Option<PathBuf>,
/// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out".
#[serde(default)]
pub logout_url: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
+1
View File
@@ -160,6 +160,7 @@ pub async fn run(args: &[String]) -> Result<(), String> {
hostname: None,
proof_credential: None,
static_dir: Some(PathBuf::from(d)),
logout_url: None,
}),
engine: None,
};
+26
View File
@@ -306,6 +306,32 @@ fn template(code: &str) -> &'static str {
"engine.switch_failed" => {
"{engine} did not start, so Ianitor went back to {previous}. Traffic is served as before."
}
"engine.not_ready" => {
"Caddy is not ready: its settings could not be built from the current routes."
}
// The eight codes the UI hand-off gave sentences for (handoff §12.2, decision Q12).
"repo.duplicate_file" => {
"Two files in the routes repository describe {hostname}. Remove one, then Ianitor picks it up."
}
"file.syntax" => {
"{file} in the routes repository has a typing mistake. Changes are paused until it is fixed."
}
"file.too_large" => {
"{file} in the routes repository is too large to read. Changes are paused until it is fixed."
}
"site.field.unknown" => "ianitor.toml has a setting Ianitor does not know: \"{field}\".",
"site.forward_auth" => {
"The sign-in settings in ianitor.toml cannot be used. Show details to see why."
}
"site.forward_auth.header" => {
"ianitor.toml asks sign-in to pass on \"{name}\", which cannot be a header name."
}
"site.secret.name" => {
"\"{name}\" cannot be a secret name in ianitor.toml. Use letters, digits, dashes and underscores."
}
"site.acme" => {
"The Let's Encrypt settings in ianitor.toml cannot be used. Show details to see why."
}
"engine.caddy" => "Caddy is serving. Changes wait until you switch back to Pingora.",
"share.engine_caddy" => {
"Share links are paused while Caddy serves. They work again after switching back."
+10
View File
@@ -201,6 +201,9 @@ impl Control {
if self.engine_cfg().is_none() || self.units.is_none() {
return Err(Fail::new(409, "engine.unmanaged", Params::new()));
}
if target == "caddy" && !self.fallback_buildable() {
return Err(Fail::new(409, "engine.not_ready", Params::new()));
}
if target != "pingora" && target != "caddy" {
return Err(Fail::new(
422,
@@ -385,6 +388,13 @@ impl Control {
Ok(())
}
/// Can Caddy's settings be built from the current tree? (Otherwise `engine.not_ready`.)
pub fn fallback_buildable(&self) -> bool {
self.head_model().ok().is_some_and(|(_, _, m)| {
ianitor_core::compile::caddy(&m, &self.cfg.caddy_compile().options()).is_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())
+91 -2
View File
@@ -50,6 +50,11 @@ mod unix {
async fn env_with_pki() -> (Env, Offline) {
let (root_pem, root_key) = pki::create_root(now()).unwrap();
let env = env_with_root(&root_pem).await;
(env, Offline { root_pem, root_key })
}
async fn env_with_root(root_pem: &str) -> Env {
// Only the root certificate goes next to control; the key stays in this test.
let extra = |dir: &Path| {
format!(
@@ -58,12 +63,12 @@ mod unix {
)
};
let mut env = Env::new(EnvSpec::default()).await;
std::fs::write(env.dir.join("offline-root.crt"), &root_pem).unwrap();
std::fs::write(env.dir.join("offline-root.crt"), root_pem).unwrap();
std::fs::write(env.dir.join("creds/pki-password"), PASSWORD).unwrap();
let text = std::fs::read_to_string(env.config_path()).unwrap() + &extra(&env.dir.join("."));
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
(env, Offline { root_pem, root_key })
env
}
async fn wait_request(env: &Env, id: &str, want: &str) -> Value {
@@ -406,6 +411,90 @@ mod unix {
assert!(!err.contains("PRIVATE KEY"), "{err}");
}
/// The accepted manual step (Mark, 2026-11-07, Q6): the offline machine runs openssl.
/// A root made with openssl signs control's CSR with the extensions file control serves,
/// and control installs the result.
#[tokio::test(flavor = "multi_thread")]
async fn an_intermediate_signed_with_openssl_is_installed() {
let Some(openssl) = ianitor_testkit::proc::require_binary("openssl") else {
return;
};
let off = ianitor_testkit::proc::TempDir::new("openssl-root");
let run = |args: &[&str]| {
let o = std::process::Command::new(&openssl)
.args(args)
.current_dir(off.join("."))
.output()
.unwrap();
assert!(
o.status.success(),
"openssl {args:?}: {}",
String::from_utf8_lossy(&o.stderr)
);
};
run(&[
"req",
"-x509",
"-new",
"-newkey",
"ec",
"-pkeyopt",
"ec_paramgen_curve:P-256",
"-nodes",
"-keyout",
"domi-root.key",
"-out",
"domi-root.crt",
"-days",
"3653",
"-subj",
"/CN=Domi PKI Root/O=Fabrica Domi",
"-addext",
"basicConstraints=critical,CA:TRUE,pathlen:1",
"-addext",
"keyUsage=critical,keyCertSign,cRLSign",
]);
let root_pem = std::fs::read_to_string(off.join("domi-root.crt")).unwrap();
let env = env_with_root(&root_pem).await;
let r = env
.call(
"POST",
"/api/v1/certs/intermediate/renewal",
Some(json!({})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let rid = r.json["request_id"].as_str().unwrap().to_owned();
let base = r.json["file_base"].as_str().unwrap().to_owned();
let cmd = r.json["approve_command"].as_str().unwrap().to_owned();
assert!(cmd.starts_with("openssl x509 -req"), "{cmd}");
std::fs::write(
off.join(&format!("{base}.csr")),
r.json["csr_pem"].as_str().unwrap(),
)
.unwrap();
let ext = env
.call("GET", &format!("/api/v1/pki-requests/{rid}/ext"), None)
.await;
assert_eq!(ext.status, 200, "{}", ext.text);
std::fs::write(off.join(&format!("{base}.ext")), &ext.text).unwrap();
// Exactly the command control shows.
let args: Vec<&str> = cmd.split_whitespace().skip(1).collect();
run(&args);
let signed = std::fs::read_to_string(off.join(&format!("{base}.crt"))).unwrap();
let info = pki::inspect(&signed).unwrap();
assert_eq!(info.path_len, Some(0));
let r = env
.call(
"PUT",
&format!("/api/v1/pki-requests/{rid}/certificate"),
Some(json!({"certificate_pem": signed})),
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
assert_eq!(r.json["state"], "approved");
}
fn walk(dir: &Path) -> Vec<std::path::PathBuf> {
let mut out = Vec::new();
let mut stack = vec![dir.to_path_buf()];
+16
View File
@@ -203,6 +203,22 @@ pub fn intermediate_csr(key: &KeyPair, cn: &str) -> Result<String, PkiError> {
.map_err(build)
}
/// The extensions for signing an intermediate with openssl on the offline machine (the
/// accepted manual step until Custos can sign, docs/pki.md): the same profile as
/// [`sign_intermediate`]. Use with `openssl x509 -req … -days 365 -extfile <this file>`.
pub const INTERMEDIATE_OPENSSL_EXT: &str = "basicConstraints = critical, CA:TRUE, pathlen:0\n\
keyUsage = critical, keyCertSign, cRLSign, digitalSignature\n\
subjectKeyIdentifier = hash\n\
authorityKeyIdentifier = keyid:always\n";
/// The openssl command that signs a renewal on the offline machine (files named after the
/// request). OpenSSL 3 picks a random serial.
pub fn openssl_sign_command(base: &str) -> String {
format!(
"openssl x509 -req -in {base}.csr -CA domi-root.crt -CAkey domi-root.key -days {INTERMEDIATE_DAYS} -sha256 -extfile {base}.ext -out {base}.crt"
)
}
/// Sign an intermediate CSR with the root (offline, or in Custos once it can). Only the CSR's
/// public key and CN are used; the CN must start with [`INTERMEDIATE_CN`].
pub fn sign_intermediate(
+15
View File
@@ -0,0 +1,15 @@
# Mark's answers to open-questions.md (2026-11-07)
- Q1 Share link on a host with links off: **keep the 4-click path** (button "Turn on share links", Copy appears when the apply is kept). No `turn_on` API change. Record it in ROADMAP §4 as an accepted 4th click.
- Q2 UI auth (G14): **(a) secret header from edge** on the admin host, from a systemd credential; control requires it, then trusts Remote-User/Remote-Name from Authelia. Keep X-Ianitor-UI against CSRF. Add `site.auth_logout_url` for "Sign out". Unix socket (b) is Phase 4 hardening.
- Q3 Engine switch: **allow with differences listed** under "Show details"; refuse only `engine.not_ready`. Switch waits in the same queue as applies.
- Q4 Share links under Caddy: **off for v1**, said plainly in the engine popover, the share dialog and Settings. Validator Caddy calls via forward_auth before v1.1 (note in ROADMAP).
- Q5 Device certificates without Custos: **server-command fallback** `sudo ianitor-control pki approve <code>`, match code shown in the UI.
- Q6 Manual intermediate signing: **accepted as a §4 exception** while Custos lacks the operation; the offline machine runs openssl.
- Q7 Device certificate lifetime: **1 year**, "renew soon" 30 days before, never past the intermediate's end date.
- Q8 Inline confirmation on "Stop all share links" and on "Revoke" token: **yes**.
- Q9 Stop polling after 15 min in a hidden tab: **yes**.
- Q10 "New tokens expire after: 1 year | Never" choice, default 1 year: **yes**.
- Q11 "Open to anyone" chip on auth = none hosts: **yes**.
- Q12 Add the handoff's sentences for the 8 generic codes to control's messages.rs: yes (orchestrator default; no owner decision needed).
- Q13 Self-host the fonts in packages/ui: yes (orchestrator default; the UI makes no outside requests).