Skip to main content

max / makenotwork

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