forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

keys.rs223 lines, 7.4 KiBHistoryRawDownload
1//! `/admin/keys`: the token-signing keys, with a rotation now and the retirement of a key that is still
2//! published.
3//!
4//! A key's state is read from the same rules the signer uses (`im_core::keys`): the current key signs, the
5//! published keys are in the JWKS, and a retired key is no longer published. The store refuses to retire the
6//! current key, so a token can always be signed.
7
8use im_core::model::AuditAction;
9use im_core::time::now_stamp;
10use serde::Deserialize;
11use serde_json::json;
12use topcoat::Result;
13use topcoat::context::{Cx, app_context};
14use topcoat::router::content::Form;
15use topcoat::router::error::{SeeOther, not_found};
16use topcoat::router::{page, route};
17use topcoat::view::{View, component, view};
18
19use crate::audit::{Actor, record};
20use crate::auth::{require_admin, require_admin_csrf};
21use crate::i18n::Lang;
22use crate::i18n::admin::{A, text};
23use crate::oidc::signing;
24use crate::pages::admin::{
25 FlashQuery, Tab, action_button, changed, done, error_text, flash_messages, frame_info,
26 notice_text, refused, tabs,
27};
28use crate::pages::path_param;
29use crate::state::AppState;
30use crate::views::{ViewerInfo, shell};
31
32/// The form of the key actions: only the CSRF token.
33#[derive(Deserialize, Default)]
34struct CsrfForm {
35 #[serde(default)]
36 csrf: String,
37}
38
39/// Where a key stands now.
40#[derive(Clone, Copy, PartialEq, Eq)]
41enum KeyState {
42 Current,
43 Published,
44 Retired,
45 Pending,
46}
47
48/// One key, with its times and its state resolved.
49struct KeyRow {
50 kid: String,
51 created: String,
52 activates: String,
53 retires: String,
54 state: KeyState,
55 /// True when the store will retire the key: not yet retired, not current, and already active.
56 retirable: bool,
57}
58
59/// `GET /admin/keys`.
60#[page("/admin/keys")]
61async fn keys_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View> {
62 let viewer = require_admin(cx).await?;
63 let state = app_context::<AppState>(cx);
64 let (lang, info) = frame_info(cx, &viewer);
65 let now = now_stamp();
66 let keys = state.store.signing_keys().await?;
67 let current = im_core::keys::current(&keys, &now).map(|key| key.kid.clone());
68 let published: Vec<String> = im_core::keys::published(&keys, &now)
69 .iter()
70 .map(|key| key.kid.clone())
71 .collect();
72 let rows: Vec<KeyRow> = keys
73 .iter()
74 .map(|key| {
75 let is_current = Some(&key.kid) == current.as_ref();
76 let state = if is_current {
77 KeyState::Current
78 } else if published.contains(&key.kid) {
79 KeyState::Published
80 } else if key.activates_at > now {
81 KeyState::Pending
82 } else {
83 KeyState::Retired
84 };
85 KeyRow {
86 kid: key.kid.clone(),
87 created: key.created_at.clone(),
88 activates: key.activates_at.clone(),
89 retires: key.retires_at.clone().unwrap_or_default(),
90 state,
91 retirable: key.retires_at.is_none() && !is_current && key.activates_at <= now,
92 }
93 })
94 .collect();
95 Ok(keys_view(
96 cx,
97 lang,
98 info,
99 viewer.session.csrf_token.clone(),
100 rows,
101 notice_text(lang, &query.notice).map(str::to_owned),
102 error_text(lang, &query.error).map(str::to_owned),
103 ))
104}
105
106/// `POST /admin/keys/rotate`: the new key signs from now on, and every other key is withdrawn at once.
107#[route(POST "/admin/keys/rotate")]
108async fn rotate_keys(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
109 let viewer = require_admin_csrf(cx, &form.csrf).await?;
110 let state = app_context::<AppState>(cx);
111 let (kid, withdrawn) = signing::rotate_now(&state.store, &state.key).await?;
112 record(
113 cx,
114 Actor::User(&viewer.user.id),
115 AuditAction::KeyRotated,
116 Some(("signing_key", &kid)),
117 json!({ "withdrawn": withdrawn }),
118 )
119 .await;
120 changed(&state.live);
121 Ok(done("/admin/keys", "key-rotated"))
122}
123
124/// `POST /admin/keys/{kid}/retire`.
125#[route(POST "/admin/keys/{kid}/retire")]
126async fn retire_key(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
127 let viewer = require_admin_csrf(cx, &form.csrf).await?;
128 let kid = key_id(cx)?;
129 let state = app_context::<AppState>(cx);
130 if state.store.retire_signing_key(&kid).await? {
131 record(
132 cx,
133 Actor::User(&viewer.user.id),
134 AuditAction::KeyRetired,
135 Some(("signing_key", &kid)),
136 json!({}),
137 )
138 .await;
139 changed(&state.live);
140 return Ok(done("/admin/keys", "key-retired"));
141 }
142 Ok(refused("/admin/keys", "key-current"))
143}
144
145/// The key id in the path. Key ids are letters, digits, `-` and `_`; anything else is a 404.
146fn key_id(cx: &Cx) -> Result<String> {
147 match path_param(cx, "kid") {
148 Some(kid)
149 if !kid.is_empty()
150 && kid.len() <= 64
151 && kid
152 .bytes()
153 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') =>
154 {
155 Ok(kid)
156 }
157 _ => Err(not_found().into()),
158 }
159}
160
161/// The text of a key state.
162fn state_text(lang: Lang, state: KeyState) -> &'static str {
163 match state {
164 KeyState::Current => text(lang, A::KeyCurrent),
165 KeyState::Published => text(lang, A::KeyPublished),
166 KeyState::Retired => text(lang, A::KeyRetired),
167 KeyState::Pending => text(lang, A::KeyPending),
168 }
169}
170
171/// The keys page: the rotation button, then one row per key.
172fn keys_view(
173 cx: &Cx,
174 lang: Lang,
175 info: ViewerInfo,
176 csrf: String,
177 rows: Vec<KeyRow>,
178 success: Option<String>,
179 problem: Option<String>,
180) -> impl View {
181 view! { cx =>
182 shell(title: text(lang, A::KeysTitle), lang: lang, viewer: Some(info),
183 tabs(lang: lang, current: Tab::Keys)
184 <section class="stack" data-live="/admin/events">
185 <h1>(text(lang, A::KeysTitle))</h1>
186 <p class="muted">(text(lang, A::KeysIntro))</p>
187 flash_messages(success: success, problem: problem)
188 action_button(action: "/admin/keys/rotate".to_owned(), csrf: csrf.clone(), label: text(lang, A::RotateNow), class: "button primary", on: "")
189 <p class="muted">(text(lang, A::RotateWarning))</p>
190 <ul class="item-list">
191 for row in rows {
192 key_item(lang: lang, csrf: csrf.clone(), row: row)
193 }
194 </ul>
195 </section>
196 )
197 }
198}
199
200/// One key: its id, its times, its state, and the retire button when the store allows it.
201#[component]
202async fn key_item(lang: Lang, csrf: String, row: KeyRow) -> Result<impl View> {
203 let state = state_text(lang, row.state);
204 let retire = format!("/admin/keys/{}/retire", row.kid);
205 Ok(view! {
206 <li class="item">
207 <div class="item-main">
208 <strong><code>(row.kid.clone())</code></strong>
209 <div class="muted">
210 <span>(text(lang, A::KeyCreated))": "(row.created.clone())</span>
211 <span>" · "(text(lang, A::KeyActivates))": "(row.activates.clone())</span>
212 if !row.retires.is_empty() {
213 <span>" · "(text(lang, A::KeyRetires))": "(row.retires.clone())</span>
214 }
215 <span>" · "(state)</span>
216 </div>
217 </div>
218 if row.retirable {
219 action_button(action: retire, csrf: csrf.clone(), label: text(lang, A::RetireKey), class: "button danger", on: "")
220 }
221 </li>
222 })
223}