Skip to main content

max / makenotwork

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