//! `/admin/keys`: the token-signing keys, with a rotation now and the retirement of a key that is still //! published. //! //! A key's state is read from the same rules the signer uses (`im_core::keys`): the current key signs, the //! published keys are in the JWKS, and a retired key is no longer published. The store refuses to retire the //! current key, so a token can always be signed. use im_core::model::AuditAction; use im_core::time::now_stamp; use serde::Deserialize; use serde_json::json; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::{SeeOther, not_found}; use topcoat::router::{page, route}; use topcoat::view::{View, component, view}; use crate::audit::{Actor, record}; use crate::auth::{require_admin, require_admin_csrf}; use crate::i18n::Lang; use crate::i18n::admin::{A, text}; use crate::oidc::signing; use crate::pages::admin::{ FlashQuery, Tab, action_button, changed, done, error_text, flash_messages, frame_info, notice_text, refused, tabs, }; use crate::pages::path_param; use crate::state::AppState; use crate::views::{ViewerInfo, shell}; /// The form of the key actions: only the CSRF token. #[derive(Deserialize, Default)] struct CsrfForm { #[serde(default)] csrf: String, } /// Where a key stands now. #[derive(Clone, Copy, PartialEq, Eq)] enum KeyState { Current, Published, Retired, Pending, } /// One key, with its times and its state resolved. struct KeyRow { kid: String, created: String, activates: String, retires: String, state: KeyState, /// True when the store will retire the key: not yet retired, not current, and already active. retirable: bool, } /// `GET /admin/keys`. #[page("/admin/keys")] async fn keys_page(cx: &Cx, Form(query): Form) -> Result { let viewer = require_admin(cx).await?; let state = app_context::(cx); let (lang, info) = frame_info(cx, &viewer); let now = now_stamp(); let keys = state.store.signing_keys().await?; let current = im_core::keys::current(&keys, &now).map(|key| key.kid.clone()); let published: Vec = im_core::keys::published(&keys, &now) .iter() .map(|key| key.kid.clone()) .collect(); let rows: Vec = keys .iter() .map(|key| { let is_current = Some(&key.kid) == current.as_ref(); let state = if is_current { KeyState::Current } else if published.contains(&key.kid) { KeyState::Published } else if key.activates_at > now { KeyState::Pending } else { KeyState::Retired }; KeyRow { kid: key.kid.clone(), created: key.created_at.clone(), activates: key.activates_at.clone(), retires: key.retires_at.clone().unwrap_or_default(), state, retirable: key.retires_at.is_none() && !is_current && key.activates_at <= now, } }) .collect(); Ok(keys_view( cx, lang, info, viewer.session.csrf_token.clone(), rows, notice_text(lang, &query.notice).map(str::to_owned), error_text(lang, &query.error).map(str::to_owned), )) } /// `POST /admin/keys/rotate`: the new key signs from now on, and every other key is withdrawn at once. #[route(POST "/admin/keys/rotate")] async fn rotate_keys(cx: &Cx, Form(form): Form) -> Result { let viewer = require_admin_csrf(cx, &form.csrf).await?; let state = app_context::(cx); let (kid, withdrawn) = signing::rotate_now(&state.store, &state.key).await?; record( cx, Actor::User(&viewer.user.id), AuditAction::KeyRotated, Some(("signing_key", &kid)), json!({ "withdrawn": withdrawn }), ) .await; changed(&state.live); Ok(done("/admin/keys", "key-rotated")) } /// `POST /admin/keys/{kid}/retire`. #[route(POST "/admin/keys/{kid}/retire")] async fn retire_key(cx: &Cx, Form(form): Form) -> Result { let viewer = require_admin_csrf(cx, &form.csrf).await?; let kid = key_id(cx)?; let state = app_context::(cx); if state.store.retire_signing_key(&kid).await? { record( cx, Actor::User(&viewer.user.id), AuditAction::KeyRetired, Some(("signing_key", &kid)), json!({}), ) .await; changed(&state.live); return Ok(done("/admin/keys", "key-retired")); } Ok(refused("/admin/keys", "key-current")) } /// The key id in the path. Key ids are letters, digits, `-` and `_`; anything else is a 404. fn key_id(cx: &Cx) -> Result { match path_param(cx, "kid") { Some(kid) if !kid.is_empty() && kid.len() <= 64 && kid .bytes() .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') => { Ok(kid) } _ => Err(not_found().into()), } } /// The text of a key state. fn state_text(lang: Lang, state: KeyState) -> &'static str { match state { KeyState::Current => text(lang, A::KeyCurrent), KeyState::Published => text(lang, A::KeyPublished), KeyState::Retired => text(lang, A::KeyRetired), KeyState::Pending => text(lang, A::KeyPending), } } /// The keys page: the rotation button, then one row per key. fn keys_view( cx: &Cx, lang: Lang, info: ViewerInfo, csrf: String, rows: Vec, success: Option, problem: Option, ) -> impl View { view! { cx => shell(title: text(lang, A::KeysTitle), lang: lang, viewer: Some(info), tabs(lang: lang, current: Tab::Keys)

(text(lang, A::KeysTitle))

(text(lang, A::KeysIntro))

flash_messages(success: success, problem: problem) action_button(action: "/admin/keys/rotate".to_owned(), csrf: csrf.clone(), label: text(lang, A::RotateNow), class: "button primary", on: "")

(text(lang, A::RotateWarning))

    for row in rows { key_item(lang: lang, csrf: csrf.clone(), row: row) }
) } } /// One key: its id, its times, its state, and the retire button when the store allows it. #[component] async fn key_item(lang: Lang, csrf: String, row: KeyRow) -> Result { let state = state_text(lang, row.state); let retire = format!("/admin/keys/{}/retire", row.kid); Ok(view! {
  • (row.kid.clone())
    (text(lang, A::KeyCreated))": "(row.created.clone()) " · "(text(lang, A::KeyActivates))": "(row.activates.clone()) if !row.retires.is_empty() { " · "(text(lang, A::KeyRetires))": "(row.retires.clone()) } " · "(state)
    if row.retirable { action_button(action: retire, csrf: csrf.clone(), label: text(lang, A::RetireKey), class: "button danger", on: "") }
  • }) }