Skip to main content

max / makenotwork

23.4 KB · 581 lines History Blame Raw
1 //! The SSH-keys settings tab, described.
2 //!
3 //! The first authenticated screen through the description layer, chosen because
4 //! it isolates what the conversion is actually asking: two lists, each with a
5 //! destructive per-row action, two add forms and a picker, no bespoke markup
6 //! worth keeping, and it is where the console-theme work already landed.
7 //!
8 //! Compare `routes::pages::dashboard::tabs::user::dashboard_tab_ssh_keys`,
9 //! which answers the same address from Askama when the screen is switched off.
10 //!
11 //! # It does not render the same page, on purpose
12 //!
13 //! The Askama tab renders two empty divs that fetch their own contents on load:
14 //! `#ssh-keys-list` and `#git-tokens-list` each carry `hx-trigger="load"`, so
15 //! opening the tab costs three round trips and shows two "Loading..." lines on
16 //! the way. A description has no word for "an empty region that fetches itself",
17 //! and should not: the handler is already in the request, and a list it can read
18 //! now is a list the reader should not wait for twice.
19 //!
20 //! So this renders both lists inline, in one response. That is a better screen
21 //! and it is also why **the parity harness cannot cover this conversion** — the
22 //! two renderings differ by design rather than by accident. See the S3 notes in
23 //! wiki `mnw-server-conversion-plan`.
24 //!
25 //! It is also what makes the screen worth measuring. The Askama tab handler runs
26 //! one query; this one runs three, which is what a described dashboard screen
27 //! will typically look like, and therefore what the blocking-pool question is
28 //! actually about.
29 //!
30 //! # The vocabulary gaps this screen found
31 //!
32 //! Both filed on quasicoherent rather than worked around silently.
33 //!
34 //! 1. **A table row could not carry an action**, so both tables here had to be
35 //! lists and lost their column headers. **Closed** by quasi@`b4e3e21`: a
36 //! table cell holds controls as well as a string, and both are tables again.
37 //! 2. **No date field.** The token form's expiry was `<input type="date">` and
38 //! had to be `Text` with a format hint. **Closed** by makeover-layout 0.15.0:
39 //! `FieldKind::Date` and `FieldKind::DateTime`, admitted on the argument
40 //! `Email` was, and the format named once as `layout::DATE_FORMAT`. See
41 //! [`add_token_form`].
42
43 use makeover_layout as layout;
44 use quasi_router::screen::{Act, Cell, Cells, Choice, Column, Field};
45 use quasi_router::{Action, Method, Node, RegionKind, Request, Response, RouteError, Slot};
46 use quasi_webview::Webview;
47
48 use super::Viewer;
49 use crate::db;
50 use crate::theming::ThemeOption;
51
52 /// The conversion switch's name for this screen. `QUASI_SCREENS=user_ssh_keys`.
53 pub const SCREEN: &str = "user_ssh_keys";
54
55 /// The address this screen answers, and the one the Askama route gives up.
56 pub const PATH: &str = "/dashboard/tabs/ssh-keys";
57
58 /// The region the answer replaces: this section's own frame in the settings
59 /// strip.
60 ///
61 /// Was `settings-body`, the single pane six sections shared while the sub-nav
62 /// was hand-written. `6b24f2df` step 4 described that nav, so each section has a
63 /// frame of its own and this names the one that is ours. `quasi::settings_tabs`
64 /// draws the frame from this constant, and its tests assert the two agree.
65 pub const REGION: &str = "settings-ssh-keys";
66
67 /// The address removing a key calls, relative to this screen's own nest.
68 const REMOVE_KEY: &str = "/keys/{id}";
69
70 /// The address revoking a token calls, relative to this screen's own nest.
71 const REVOKE_TOKEN: &str = "/tokens/{id}";
72
73 /// The writes this screen serves. Registered under its nest by `super::mount`.
74 pub const WRITES: &[(Method, &str, super::Screen)] = &[
75 (Method::Delete, REMOVE_KEY, remove_key),
76 (Method::Delete, REVOKE_TOKEN, revoke_token),
77 ];
78
79 /// One registered key, as the screen needs it.
80 ///
81 /// The description is built from these rather than from `db::DbSshKey` so the
82 /// shape of a screen can be tested without a database, which is most of what
83 /// makes a described screen cheaper to hold than a template.
84 pub struct KeyView {
85 id: String,
86 fingerprint: String,
87 label: String,
88 added: String,
89 }
90
91 /// One issued token, as the screen needs it.
92 pub struct TokenView {
93 id: String,
94 name: String,
95 scope: &'static str,
96 expires: String,
97 last_used: String,
98 }
99
100 /// The tab.
101 pub fn screen(viewer: &Viewer, _request: Request) -> Result<Response, RouteError> {
102 let user_id = viewer.user.id;
103
104 // Three round trips, each holding this blocking thread. The thing S3
105 // exists to measure; see the module header on `super`.
106 let keys = viewer
107 .block_on(db::ssh_keys::list_keys_by_user(&viewer.app.db, user_id))
108 .map_err(|_| RouteError::internal("your keys could not be read"))?;
109 let tokens = viewer
110 .block_on(db::git_access_tokens::list_by_user(&viewer.app.db, user_id))
111 .map_err(|_| RouteError::internal("your tokens could not be read"))?;
112 let profile = viewer
113 .block_on(db::users::get_user_by_id(&viewer.app.db, user_id))
114 .map_err(|_| RouteError::internal("your account could not be read"))?
115 .ok_or_else(|| RouteError::not_found("that account is gone"))?;
116
117 let keys: Vec<KeyView> = keys
118 .iter()
119 .map(|k| KeyView {
120 id: k.id.to_string(),
121 fingerprint: k.fingerprint.clone(),
122 label: k.label.clone(),
123 added: k.created_at.format("%b %d, %Y").to_string(),
124 })
125 .collect();
126 let tokens: Vec<TokenView> = tokens
127 .iter()
128 .map(|t| TokenView {
129 id: t.id.to_string(),
130 name: t.name.clone(),
131 scope: if t.can_push { "Read + push" } else { "Read" },
132 expires: never_or(t.expires_at),
133 last_used: never_or(t.last_used_at),
134 })
135 .collect();
136 let themes = crate::theming::console_theme_options(profile.console_theme.as_deref());
137
138 Ok(Response::fragment(
139 REGION,
140 pane(viewer.user.username.as_ref(), &keys, &tokens, &themes),
141 ))
142 }
143
144 /// The id in the path, as the database wants it.
145 fn captured(captures: &quasi_router::Params) -> Result<uuid::Uuid, RouteError> {
146 captures
147 .get("id")
148 .and_then(|id| id.parse().ok())
149 .ok_or_else(|| RouteError::not_found("no such thing"))
150 }
151
152 /// Remove one key, and answer with the pane as it now stands.
153 ///
154 /// This screen's own route rather than `DELETE /api/users/me/ssh-keys/{id}`,
155 /// which the Askama version calls. That endpoint answers an htmx request with
156 /// the whole re-rendered Askama list and the Askama markup targeted
157 /// `#ssh-keys-list`; the described control named no target, so htmx swapped that
158 /// entire table into the button that was pressed. Found 2026-08-11 by reading
159 /// what the endpoint returns. A described write answers with the region it
160 /// changed, which is decision 7 working as designed.
161 pub fn remove_key(viewer: &Viewer, request: Request) -> Result<Response, RouteError> {
162 // Moved out because the handler signature is quasi's: the request is
163 // consumed here rather than borrowed from.
164 let captures = request.captures;
165 let id = captured(&captures)?;
166 viewer
167 .block_on(db::ssh_keys::delete_key(
168 &viewer.app.db,
169 id.into(),
170 viewer.user.id,
171 ))
172 .map_err(|_| RouteError::internal("that key could not be removed"))?;
173 screen(viewer, Request::get(PATH))
174 }
175
176 /// Revoke one token, and answer with the pane as it now stands.
177 pub fn revoke_token(viewer: &Viewer, request: Request) -> Result<Response, RouteError> {
178 let captures = request.captures;
179 let id = captured(&captures)?;
180 viewer
181 .block_on(db::git_access_tokens::revoke(
182 &viewer.app.db,
183 id.into(),
184 viewer.user.id,
185 ))
186 .map_err(|_| RouteError::internal("that token could not be revoked"))?;
187 screen(viewer, Request::get(PATH))
188 }
189
190 /// A date, or the word for not having one.
191 fn never_or(at: Option<chrono::DateTime<chrono::Utc>>) -> String {
192 at.map_or_else(|| "Never".to_owned(), |d| d.format("%b %d, %Y").to_string())
193 }
194
195 /// Everything inside the settings pane.
196 ///
197 /// Split from the handler so a test can build it without a database, which is
198 /// the same split `quasi_spike` used and the reason the description layer is
199 /// testable at all: the screen is a value.
200 fn pane(username: &str, keys: &[KeyView], tokens: &[TokenView], themes: &[ThemeOption]) -> Node {
201 Node::Region(
202 Slot::new(REGION, RegionKind::Pane)
203 .with(Node::section("SSH Keys"))
204 .with(Node::text(format!(
205 "Manage SSH keys for git clone and push access. \
206 Clone URL: git@makenot.work:{username}/{{repo}}.git"
207 )))
208 .with(keys_list(keys))
209 .with(add_key_form())
210 .with(Node::section("Console theme"))
211 .with(Node::text(
212 "Color palette for your terminal dashboard over ssh makenot.work.",
213 ))
214 .with(theme_form(themes))
215 .with(Node::section("Access Tokens (HTTPS)"))
216 .with(Node::text(format!(
217 "Personal access tokens for git over HTTPS. Use a token as the password. \
218 Clone URL: https://<token>@makenot.work/{username}/{{repo}}.git"
219 )))
220 .with(tokens_list(tokens))
221 .with(add_token_form()),
222 )
223 }
224
225 /// The registered keys, or the sentence saying there are none.
226 fn keys_list(keys: &[KeyView]) -> Node {
227 if keys.is_empty() {
228 return Node::empty("No SSH keys registered.");
229 }
230 Node::Table {
231 // The template's four columns, in its order, the last one the empty
232 // header its actions sit under.
233 columns: vec![
234 Column::new("Fingerprint")
235 .width(layout::Width::Fill)
236 .priority(layout::Priority::Essential),
237 Column::new("Label").width(layout::Width::Content),
238 Column::new("Added")
239 .width(layout::Width::Content)
240 .priority(layout::Priority::Optional),
241 Column::new("")
242 .width(layout::Width::Content)
243 .priority(layout::Priority::Essential),
244 ],
245 rows: keys
246 .iter()
247 .map(|key| {
248 Cells::new([
249 Cell::new(key.fingerprint.clone()),
250 Cell::new(key.label.clone()),
251 Cell::new(format!("Added {}", key.added)),
252 Cell::acts([Act::new(
253 "Remove",
254 // This screen's own route, under its own nest, so the
255 // answer is the pane it changed. It addressed the API
256 // route until 2026-08-11 and swapped a whole Askama
257 // table into this button; see `remove_key`.
258 // `awaiting` for the same reason the forms carry it: the
259 // answer is the whole pane rebuilt, so there is a wait
260 // with nothing on screen saying so. The confirm gates
261 // the first press, not the second one after it.
262 Action::delete(format!("{PATH}/keys/{}", key.id)).awaiting(),
263 )
264 // The template asked with hx-confirm. Said here, a terminal
265 // host asks in its own way and no host can forget to ask.
266 .confirm("Remove this SSH key?")
267 .tone(layout::Tone::Danger)]),
268 ])
269 })
270 .collect(),
271 // No paging described here: every one of these tables is a
272 // whole set the handler already counted.
273 more: None,
274 }
275 }
276
277 /// The add-a-key form.
278 ///
279 /// `awaiting` is the double-submit guard: this creates a record, so a second
280 /// submit while the first is in flight is a duplicate key. It reads as one word
281 /// here and the renderer locks the submit button from it, which is what
282 /// `frontend/src/core/loading.ts` was written to do by hand and is losing
283 /// ground against.
284 fn add_key_form() -> Node {
285 Node::Form {
286 action: Action::post("/api/users/me/ssh-keys").awaiting(),
287 submit: "Add SSH Key".into(),
288 fields: vec![
289 Field::new(layout::FieldKind::Textarea, "public_key", "Public Key")
290 .required()
291 .hint(
292 "Paste the contents of your ~/.ssh/id_ed25519.pub or similar public key file",
293 ),
294 Field::new(layout::FieldKind::Text, "label", "Label"),
295 ],
296 }
297 }
298
299 /// The console-theme picker.
300 fn theme_form(themes: &[ThemeOption]) -> Node {
301 let options: Vec<Choice> = themes
302 .iter()
303 .map(|t| Choice::new(t.id.clone(), t.name.clone()))
304 .collect();
305 let mut field = Field::select("theme_id", "Console theme", options).hint(
306 "Following the terminal picks a light or dark palette from what your terminal reports. \
307 Separate from your profile theme, which is what visitors see.",
308 );
309 if let Some(chosen) = themes.iter().find(|t| t.selected) {
310 field = field.value(chosen.id.clone());
311 }
312 Node::Form {
313 // A PUT, so a second submit overwrites rather than duplicating. Marked
314 // anyway: the wait is real and the reader has no other way to tell the
315 // save landed from the save being slow.
316 action: Action::put("/api/users/me/console-theme").awaiting(),
317 submit: "Save Theme".into(),
318 fields: vec![field],
319 }
320 }
321
322 /// The issued tokens, or the sentence saying there are none.
323 fn tokens_list(tokens: &[TokenView]) -> Node {
324 if tokens.is_empty() {
325 return Node::empty("No access tokens.");
326 }
327 Node::Table {
328 // The four independent facts the list version had to run together into
329 // one `meta` string, back in their own columns. This is the table that
330 // lost the most by being a list: name, scope, expiry and last use are
331 // read down the column, which is what a table is for.
332 columns: vec![
333 Column::new("Name")
334 .width(layout::Width::Fill)
335 .priority(layout::Priority::Essential),
336 Column::new("Scope").width(layout::Width::Content),
337 Column::new("Expires")
338 .width(layout::Width::Content)
339 .priority(layout::Priority::Optional),
340 Column::new("Last used")
341 .width(layout::Width::Content)
342 .priority(layout::Priority::Optional),
343 Column::new("")
344 .width(layout::Width::Content)
345 .priority(layout::Priority::Essential),
346 ],
347 rows: tokens
348 .iter()
349 .map(|token| {
350 Cells::new([
351 Cell::new(token.name.clone()),
352 Cell::new(token.scope),
353 Cell::new(token.expires.clone()),
354 Cell::new(token.last_used.clone()),
355 Cell::acts([Act::new(
356 "Revoke",
357 Action::delete(format!("{PATH}/tokens/{}", token.id)).awaiting(),
358 )
359 .confirm("Revoke this token?")
360 .tone(layout::Tone::Danger)]),
361 ])
362 })
363 .collect(),
364 // No paging described here: every one of these tables is a
365 // whole set the handler already counted.
366 more: None,
367 }
368 }
369
370 /// The mint-a-token form.
371 ///
372 /// `expires_on` was a `Text` field carrying a "YYYY-MM-DD" hint, against an
373 /// Askama form that spelled it `<input type="date">`: no native picker, no
374 /// platform validation, and the hint doing both jobs in prose. That was a
375 /// vocabulary gap rather than a choice, and `layout::FieldKind::Date` closed it
376 /// at makeover-layout 0.15.0. It did become one word, and the hint came out with
377 /// it: the format is the description's now, `layout::DATE_FORMAT`, so saying it
378 /// again here would be a second place for it to drift.
379 fn add_token_form() -> Node {
380 Node::Form {
381 // Creates a record, and unlike an SSH key the answer is a secret shown
382 // once. Two of these from one impatient double-press is two tokens, one
383 // of which the creator never sees and cannot recognise later.
384 action: Action::post("/api/users/me/git-tokens").awaiting(),
385 submit: "Create Token".into(),
386 fields: vec![
387 Field::new(layout::FieldKind::Text, "name", "Name").required(),
388 Field::new(layout::FieldKind::Date, "expires_on", "Expires (optional)")
389 .hint("Leave blank for a token that does not expire."),
390 Field::new(
391 layout::FieldKind::Checkbox,
392 "can_push",
393 "Allow push (write access)",
394 ),
395 ],
396 }
397 }
398
399 /// The renderer this screen is drawn with.
400 ///
401 /// Per request because `Adapter::per_viewer` builds one per request, and this
402 /// screen has nothing viewer-specific to say to it yet. It will when S2 puts the
403 /// site chrome here.
404 pub fn renderer(viewer: &Viewer) -> Webview {
405 // The fragment path never emits a document, so the shell's asset paths do
406 // not arise here. It is still the one the rest of the site uses, so a screen
407 // that later answers as a whole page cannot disagree with `crate::shell`.
408 Webview::new().with_shell(viewer.shell())
409 }
410
411 #[cfg(test)]
412 mod tests {
413 use super::*;
414 use quasi_axum::Serves;
415
416 fn key(id: &str, fingerprint: &str) -> KeyView {
417 KeyView {
418 id: id.into(),
419 fingerprint: fingerprint.into(),
420 label: "laptop".into(),
421 added: "Aug 10, 2026".into(),
422 }
423 }
424
425 fn render(node: &Node) -> String {
426 Webview::new().fragment(node)
427 }
428
429 #[test]
430 fn the_region_matches_what_the_strip_draws() {
431 // The router says what it changed, through HX-Retarget. If this and the
432 // frame the settings strip draws ever disagree the section swaps into
433 // nothing, and that failure is invisible to every other test.
434 //
435 // Read off the described strip since `6b24f2df` step 4. It was the
436 // hand-written nav's `hx-target`, which no longer exists.
437 let nav = crate::quasi::settings_tabs::html(
438 &crate::config::QuasiScreens::default(),
439 0,
440 "",
441 true,
442 true,
443 true,
444 );
445 assert!(
446 nav.contains(&format!("id=\"{REGION}\"")),
447 "the settings strip draws #{REGION}:\n{nav}"
448 );
449 assert!(nav.contains(&format!("hx-get=\"{PATH}\"")), "{nav}");
450 }
451
452 #[test]
453 fn an_empty_account_says_so_rather_than_showing_two_empty_lists() {
454 let html = render(&pane("max", &[], &[], &[]));
455 assert!(html.contains("No SSH keys registered."));
456 assert!(html.contains("No access tokens."));
457 }
458
459 #[test]
460 fn the_clone_urls_carry_the_viewers_own_name_and_cannot_smuggle_markup() {
461 let html = render(&pane("max", &[], &[], &[]));
462 assert!(html.contains("git@makenot.work:max/{repo}.git"));
463
464 // A username reaches this from the session, and the session from a
465 // signup form. The description layer escapes every string it is handed;
466 // this is the check that the format! above did not route around it.
467 let hostile = render(&pane("<script>x()</script>", &[], &[], &[]));
468 assert!(!hostile.contains("<script>x()"));
469 }
470
471 #[test]
472 fn removing_a_key_asks_first_and_every_key_asks_about_itself() {
473 let html = render(&keys_list(&[
474 key("k1", "SHA256:aaa"),
475 key("k2", "SHA256:bbb"),
476 ]));
477
478 assert!(html.contains("SHA256:aaa") && html.contains("SHA256:bbb"));
479 assert_eq!(html.matches("hx-confirm").count(), 2, "both ask: {html}");
480 // The addresses are per key rather than one shared endpoint, which is
481 // the mistake a loop over rows makes when the id is read outside it.
482 assert!(html.contains(&format!("hx-delete=\"{PATH}/keys/k1\"")));
483 assert!(html.contains(&format!("hx-delete=\"{PATH}/keys/k2\"")));
484 }
485
486 #[test]
487 fn what_destroys_something_is_marked_destructive_and_nothing_else_is() {
488 // `b279b9eb`: destructiveness is marked separately from asking first.
489 // Both acts on this screen are destructive and both ask, so the screen
490 // is the reference pair; what it also proves is the other side, that
491 // three forms which write without destroying take no tone at all.
492 let html = render(&pane(
493 "max",
494 &[key("k1", "SHA256:aaa")],
495 &[TokenView {
496 id: "t1".into(),
497 name: "laptop".into(),
498 scope: "read",
499 expires: "Never".into(),
500 last_used: "Never".into(),
501 }],
502 &[],
503 ));
504
505 assert_eq!(
506 html.matches(r#"data-tone="danger""#).count(),
507 2,
508 "removing a key and revoking a token, and nothing else: {html}"
509 );
510 // The pairing is the point rather than the count: every tone here sits
511 // on an act that also asks.
512 assert_eq!(
513 html.matches("hx-confirm").count(),
514 2,
515 "and both of them ask first: {html}"
516 );
517 assert!(html.contains("Remove this SSH key?"), "{html}");
518 assert!(html.contains("Revoke this token?"), "{html}");
519 }
520
521 #[test]
522 fn the_theme_picker_offers_every_theme_and_marks_the_chosen_one() {
523 let themes = crate::theming::console_theme_options(Some("nord"));
524 let html = render(&theme_form(&themes));
525
526 assert!(html.contains("nord"));
527 assert_eq!(
528 html.matches("selected").count(),
529 1,
530 "exactly one theme is current: {html}"
531 );
532 }
533
534 #[test]
535 fn every_write_on_this_screen_locks_itself_while_it_waits() {
536 // `0da6a218`. Both halves of the guard, because they are emitted
537 // differently and only one of them was ever right: a form names the
538 // button it has to lock (`930947c3`), an act locks itself.
539 let html = render(&pane("max", &[key("k1", "SHA256:aaa")], &[], &[]));
540
541 // Three forms, three buttons named. `find` rather than `this` is the
542 // whole of the fix, so asserting the count catches a fourth form added
543 // without the mark as well as a regression in the emitter.
544 assert_eq!(
545 html.matches(r#"hx-disable="find button[type='submit']""#)
546 .count(),
547 3,
548 "every form guards its submit: {html}"
549 );
550
551 // The delete is an act, and an act is a button already.
552 assert!(
553 html.contains(r#"hx-disable="this""#),
554 "the remove control locks itself: {html}"
555 );
556
557 // Nothing here is a measured wait. A determinate mark would mean a
558 // figure was written down, and none of these knows one.
559 assert!(!html.contains("data-awaiting-amount"), "{html}");
560 assert_eq!(
561 html.matches(r#"data-awaiting="indeterminate""#).count(),
562 4,
563 "three forms and one remove: {html}"
564 );
565 }
566
567 #[test]
568 fn the_forms_post_to_the_addresses_the_api_actually_answers() {
569 // The conversion's real risk: a described form that posts somewhere the
570 // server does not serve fails at runtime and nowhere else.
571 let html = render(&pane("max", &[], &[], &[]));
572 for address in [
573 "/api/users/me/ssh-keys",
574 "/api/users/me/console-theme",
575 "/api/users/me/git-tokens",
576 ] {
577 assert!(html.contains(address), "{address} is posted to: {html}");
578 }
579 }
580 }
581