From 2920fdc4533c41993b538cf75e07bbdad6495196 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 15:54:47 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=91=20keys:=20a=20manual=20rotation=20?= =?UTF-8?q?signs=20with=20the=20new=20key=20at=20once=20and=20withdraws=20?= =?UTF-8?q?every=20other=20key?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 18 ++++++-- crates/im-core/src/store/keys.rs | 34 ++++++++++++++ crates/im-web/src/cli.rs | 24 ++++++++-- crates/im-web/src/i18n/admin.rs | 9 +++- crates/im-web/src/oidc/signing.rs | 65 +++++++++++++++++++-------- crates/im-web/src/pages/admin/keys.rs | 7 +-- docs/architecture.md | 5 ++- docs/contracts.md | 7 ++- 8 files changed, 134 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 614fe98..6c2ff75 100644 --- a/README.md +++ b/README.md @@ -131,15 +131,25 @@ so stop the service first. A set written before the manifest MAC was added has n before it signs, and a retired key stays published for seven days so that tokens it signed still verify. Keys are maintained automatically. -To rotate now (for example after a suspected leak of a key file): +To rotate now, after a suspected leak of a key file: ```sh im --config /etc/im/im.toml keys rotate ``` -The new key is published at once and starts signing one day later, so every app has fetched it by then; the -previous key keeps signing until that moment and stays published for the overlap. -The admin Keys page shows every key, its state, and the same rotation. +A manual rotation is immediate. The new key signs from that moment. The previous signing key, any key still +waiting to sign, and any retired key still published are withdrawn at once: they leave the published keys, +their private seeds are erased, and they never sign or verify again. Treat them as compromised. The result is +exactly one published key. The admin Keys page offers the same rotation. Both are audited (`keys.rotated`, +listing the withdrawn key ids). + +Relying parties (`in`, `iz`) cache the JWKS for 10 minutes and refetch at most once a minute when a token names +an unknown `kid`. So new tokens work within about a minute, and tokens signed by a withdrawn key stop verifying +within 10 minutes (`im` itself stops accepting them at once). People who are signing in at that moment may need +to retry once. + +Rotation is the emergency action for a leaked signing key. If the whole server leaked (`im.key` and the +database), rotation is not enough: restore a backup onto a fresh machine and reset passwords. ## Command line diff --git a/crates/im-core/src/store/keys.rs b/crates/im-core/src/store/keys.rs index 31552a3..9d755d9 100644 --- a/crates/im-core/src/store/keys.rs +++ b/crates/im-core/src/store/keys.rs @@ -87,6 +87,40 @@ impl Store { finish(tx, outcome).await } + /// A manual rotation: the key becomes the only key row, in one transaction. Every other key, pending, + /// current or retired, is withdrawn: its row is deleted, so it is neither published nor used to verify, + /// and its sealed seed goes with it. Returns the ids of the withdrawn keys. + pub async fn replace_signing_keys(&self, key: &KeyRecord) -> Result> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result> = async { + let withdrawn = fetch_all( + &tx, + "SELECT kid FROM signing_keys ORDER BY activates_at ASC, kid ASC", + (), + |row| col_text(row, 0), + ) + .await?; + tx.execute("DELETE FROM signing_keys", ()).await.map_err(db_err)?; + tx.execute( + "INSERT INTO signing_keys (kid, private_sealed, public_raw, created_at, activates_at, \ + retires_at) VALUES (?1, ?2, ?3, ?4, ?5, NULL)", + ( + key.kid.clone(), + key.private_sealed.clone(), + key.public_raw.clone(), + key.created_at.clone(), + key.activates_at.clone(), + ), + ) + .await + .map_err(db_err)?; + Ok(withdrawn) + } + .await; + finish(tx, outcome).await + } + /// Blanks the sealed seed of every key that stopped signing at or before `now`. Verification needs only the /// public key, so a retired key keeps nothing usable. Returns how many rows were blanked. pub async fn scrub_retired_signing_seeds(&self, now: &str) -> Result { diff --git a/crates/im-web/src/cli.rs b/crates/im-web/src/cli.rs index bff485e..9f9610d 100644 --- a/crates/im-web/src/cli.rs +++ b/crates/im-web/src/cli.rs @@ -334,16 +334,34 @@ pub async fn fsck(config: &Path) -> ExitCode { .await } -/// Runs `im keys rotate`: makes a new key the signing key now. +/// Runs `im keys rotate`: the new key signs from now on, and every other key is withdrawn at once. pub async fn keys(config: &Path, words: &[String]) -> ExitCode { match words { [verb] if verb == "rotate" => { with_state(config, |state| async move { - let kid = crate::oidc::signing::rotate_now(&state.store, &state.key) + let (kid, withdrawn) = crate::oidc::signing::rotate_now(&state.store, &state.key) .await .map_err(|e| e.to_string())?; + let data = serde_json::json!({ "withdrawn": withdrawn }).to_string(); + let entry = im_core::store::audit::NewAudit { + actor_id: None, + actor_kind: "cli", + action: im_core::model::AuditAction::KeyRotated.as_str(), + target_kind: Some("signing_key"), + target_id: Some(&kid), + ip: None, + data: Some(&data), + }; + if let Err(error) = state.store.record_audit(&entry).await { + eprintln!("im: the audit entry was not written: {error}"); + } + let withdrawn = if withdrawn.is_empty() { + "none".to_owned() + } else { + withdrawn.join(", ") + }; println!( - "im: new signing key {kid} is published now and starts signing after the publish lead" + "im: new signing key {kid} signs from now on; withdrawn at once: {withdrawn}" ); Ok(()) }) diff --git a/crates/im-web/src/i18n/admin.rs b/crates/im-web/src/i18n/admin.rs index 6142dd6..b2b70c7 100644 --- a/crates/im-web/src/i18n/admin.rs +++ b/crates/im-web/src/i18n/admin.rs @@ -201,6 +201,7 @@ pub enum A { KeyRetired, KeyPending, RotateNow, + RotateWarning, RetireKey, NoticeKeyRotated, NoticeKeyRetired, @@ -614,10 +615,14 @@ fn pair(key: A) -> (&'static str, &'static str) { A::KeyRetired => ("retired", "emekli"), A::KeyPending => ("waiting to sign", "imzalamayı bekliyor"), A::RotateNow => ("Rotate now", "Şimdi döndür"), + A::RotateWarning => ( + "Rotating is the emergency action after a suspected key leak. The new key signs at once, and every other key (current, waiting or retired) is withdrawn at once: it leaves the published keys and never signs or verifies again. Apps accept the new key within about a minute, and tokens signed by a withdrawn key stop verifying within about 10 minutes. People who are signing in at that moment may need to retry once. If the whole server leaked (the key file and the database), rotation is not enough: restore onto a fresh machine and reset passwords.", + "Döndürmek, anahtarın sızdığından şüphelenildiğinde alınan acil bir önlemdir. Yeni anahtar hemen imzalamaya başlar; diğer bütün anahtarlar (güncel, bekleyen ya da emekli) hemen geri çekilir: yayımlı anahtarlardan çıkar ve bir daha imzalamaz ya da doğrulamaz. Uygulamalar yeni anahtarı yaklaşık bir dakika içinde kabul eder; geri çekilen bir anahtarla imzalanmış belirteçler yaklaşık 10 dakika içinde doğrulanmaz hale gelir. O anda oturum açmakta olan kişilerin bir kez yeniden denemesi gerekebilir. Tüm sunucu sızdıysa (anahtar dosyası ve veritabanı), döndürmek yetmez: yedeği yeni bir makineye geri yükleyin ve parolaları sıfırlayın.", + ), A::RetireKey => ("Retire", "Emekli yap"), A::NoticeKeyRotated => ( - "A new signing key is published. It starts signing in one day, and the old key signs until then.", - "Yeni imzalama anahtarı yayımlandı. Bir gün sonra imzalamaya başlar; o zamana kadar eski anahtar imzalar.", + "The new signing key signs from now on. Every other key is withdrawn at once.", + "Yeni imzalama anahtarı şimdiden itibaren imzalıyor. Diğer bütün anahtarlar hemen geri çekildi.", ), A::NoticeKeyRetired => ( "The key is retired. It stays published for the usual overlap.", diff --git a/crates/im-web/src/oidc/signing.rs b/crates/im-web/src/oidc/signing.rs index 5792395..869d339 100644 --- a/crates/im-web/src/oidc/signing.rs +++ b/crates/im-web/src/oidc/signing.rs @@ -13,7 +13,7 @@ use im_core::keys::{self, OVERLAP}; use im_core::model::KeyRecord; use im_core::secret; use im_core::store::Store; -use im_core::time::{now_stamp, stamp_minus, stamp_plus}; +use im_core::time::{now_stamp, stamp_minus}; use serde_json::{Map, Value}; use tokio::sync::watch; @@ -73,32 +73,25 @@ pub fn spawn( }) } -/// Makes a new key the signing key, one publish lead from now. It is published first and only then used: the -/// JWKS carries it before the first token it signs, and the previous key keeps signing until then. Returns the -/// new key id. Refused while another key is still waiting to activate: two pending keys would make the -/// retirement order ambiguous. -pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Result { +/// A manual rotation, from the CLI or the admin page: the new key signs from now on, and every other key is +/// withdrawn at once (a suspected leak, so nothing old may verify again). A pending key from the schedule is +/// withdrawn too. Returns the new key id and the ids of the withdrawn keys. The automatic chain is unaffected. +pub async fn rotate_now( + store: &Store, + instance_key: &[u8; 32], +) -> im_core::Result<(String, Vec)> { let fresh = keys::generate(); let now = now_stamp(); - let activates_at = stamp_plus(&now, keys::PUBLISH_LEAD).ok_or_else(|| { - im_core::Error::Crypto("the new key's activation time is out of range".into()) - })?; let record = KeyRecord { kid: fresh.kid.clone(), private_sealed: secret::seal(instance_key, secret::purpose::SIGNING_SEED, &fresh.seed)?, public_raw: fresh.public.to_vec(), - created_at: now, - activates_at, + created_at: now.clone(), + activates_at: now, retires_at: None, }; - // The store refuses while another key is pending, inside the same transaction as the insert. - if !store.add_signing_key(&record).await? { - return Err(im_core::Error::Conflict( - "another signing key is still waiting to activate; rotate after it starts signing" - .into(), - )); - } - Ok(fresh.kid) + let withdrawn = store.replace_signing_keys(&record).await?; + Ok((fresh.kid, withdrawn)) } /// The keys published now, for the JWKS document and for verifying tokens. @@ -158,3 +151,37 @@ fn seed_of(instance_key: &[u8; 32], record: &KeyRecord) -> im_core::Result<[u8; <[u8; 32]>::try_from(bytes.as_slice()) .map_err(|_| im_core::Error::Crypto("signing key has the wrong length".into())) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::boot::test_state; + use im_core::time::stamp_plus; + + #[tokio::test] + async fn a_manual_rotation_withdraws_every_other_key_including_a_pending_one() { + let (_dir, state) = test_state().await; + maintain(&state.store, &state.key).await.expect("first key"); + let old = published_keys(&state.store).await.expect("keys")[0] + .kid + .clone(); + // A pending key from the schedule, not yet signing. + let now = now_stamp(); + let pending = KeyRecord { + kid: "pending".into(), + private_sealed: String::new(), + public_raw: vec![0; 32], + created_at: now.clone(), + activates_at: stamp_plus(&now, keys::PUBLISH_LEAD).expect("stamp"), + retires_at: None, + }; + assert!(state.store.add_signing_key(&pending).await.expect("add")); + + let (kid, withdrawn) = rotate_now(&state.store, &state.key).await.expect("rotate"); + assert_eq!(withdrawn.len(), 2); + assert!(withdrawn.contains(&old) && withdrawn.contains(&"pending".to_owned())); + let published = published_keys(&state.store).await.expect("keys"); + assert_eq!(published.len(), 1); + assert_eq!(published[0].kid, kid); + } +} diff --git a/crates/im-web/src/pages/admin/keys.rs b/crates/im-web/src/pages/admin/keys.rs index d3a8b22..083fdcd 100644 --- a/crates/im-web/src/pages/admin/keys.rs +++ b/crates/im-web/src/pages/admin/keys.rs @@ -103,18 +103,18 @@ async fn keys_page(cx: &Cx, Form(query): Form) -> Result )) } -/// `POST /admin/keys/rotate`: makes a new key the signing key now. +/// `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 = signing::rotate_now(&state.store, &state.key).await?; + 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!({}), + json!({ "withdrawn": withdrawn }), ) .await; changed(&state.live); @@ -186,6 +186,7 @@ fn keys_view(

(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) diff --git a/docs/architecture.md b/docs/architecture.md index 57d6e34..0661f73 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -116,7 +116,8 @@ signed in to: drives back-channel logout and the "connected apps" list. **signing_keys**: `kid` PK (first 16 hex of SHA-256 of the public key), `private_sealed`, `public_raw` BLOB, `created_at`, `activates_at`, `retires_at` NULL. Exactly one key is "current": the newest with `activates_at <= now` and no `retires_at`. Once a key has stopped signing, `private_sealed` is blanked (empty), so -only the public key is kept; the row is deleted after the 7-day overlap. +only the public key is kept; the row is deleted after the 7-day overlap. A manual rotation deletes every other +row in the same transaction (a withdrawn key leaves no row, so no seed or public key remains). **invites**: `token_hash` PK, `email_folded`, `is_admin`, `invited_by` NULL FK SET NULL, `created_at`, `expires_at`, `accepted_at` NULL. Creating a new invite for an address deletes its older pending invites. @@ -178,7 +179,7 @@ process-wide lock (`photo_lock`), so a removal cannot delete a file a parallel u | `GET /admin/mail` and POSTs | admin | SMTP sender (password write-only, sealed), check connection, send test, outbox with retry | | `GET /admin/message` + POST | admin | notice mail to everyone or one person (queued) | | `GET /admin/settings` + POST | admin | policy (section 7), base URL, trusted proxies; UI > file > default | -| `GET /admin/keys` + POST rotate | admin | signing keys and their state | +| `GET /admin/keys` + POST rotate | admin | signing keys and their state; rotate is immediate and withdraws every other key (audited) | | `GET /admin/audit` | admin | filters (action, actor, target, date range), keyset paging | | `GET /admin/health` | admin | services health, outboxes, disk, DB size, last backup | | `POST /admin/health/backup` | admin | "Back up now": asks the backup worker for one run (ignored while one is pending or running); audited; 303 back with a notice | diff --git a/docs/contracts.md b/docs/contracts.md index a180cd9..8e85380 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -58,8 +58,11 @@ Clients fetch discovery once at boot and cache it. They may hard-code the paths - Signing algorithm: **EdDSA (Ed25519)**. `jwks.json` publishes every key that is active or retired within the last 7 days, as `{"kty":"OKP","crv":"Ed25519","x":...,"kid":...,"use":"sig","alg":"EdDSA"}`. -- `im` rotates the signing key every 90 days and on admin demand. A new key is published 24 hours before it - signs anything. +- `im` rotates the signing key every 90 days. A new key is published 24 hours before it signs anything. +- On admin demand (`im keys rotate`, or the admin Keys page) the rotation is immediate: the new key signs from + that moment, and every other key (pending, current or retired) is withdrawn at once. A withdrawn key is no + longer in `jwks.json`, its seed is erased, and `im` never signs or verifies with it again. This is the + emergency action after a suspected leak. - Clients cache the JWKS for 10 minutes, and refetch at most once a minute when a token names an unknown `kid`. ### 2.3 Sign-in (authorization code + PKCE)