web/pages/account/
ssh_key.rs1use askama::Template;
16use axum::{
17 Extension, Form,
18 extract::{Query, State},
19 http::{StatusCode, header},
20 response::{IntoResponse, Response},
21};
22use forms::SSH_KEY_ADD;
23use rpc::forms::user_zone;
24use serde::Deserialize;
25use server::command::{
26 CmdResult,
27 ssh_key::{ListSshKeys, RemoveSshKey, SshKeyRecord},
28};
29use server::timezone::{Tz, display};
30use std::sync::Arc;
31use uuid::Uuid;
32
33use crate::pages::forms::{
34 create::{Create, Created},
35 failure_error,
36};
37use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
38
39pub const SUBMIT_PATH: &str = "/api/account/ssh-key/add";
40
41const CREATE: Create = Create {
42 form: &SSH_KEY_ADD,
43 action: SUBMIT_PATH,
44};
45
46struct KeyRow {
47 fingerprint: String,
48 key_type: String,
49 annotation: String,
50 last_used: Option<String>,
51}
52
53#[derive(Template)]
54#[template(path = "pages/account/ssh_key.html")]
55struct SshKeyPage {
56 form: String,
57 keys: Vec<KeyRow>,
58 config_snippet: Option<String>,
59}
60
61#[derive(Deserialize)]
62pub struct PageQuery {
63 added: Option<String>,
64}
65
66fn key_row(row: SshKeyRecord, zone: Tz) -> KeyRow {
67 KeyRow {
68 fingerprint: row.fingerprint,
69 key_type: row.key_type,
70 annotation: row.annotation,
71 last_used: row.last_used_at.map(|at| display(at, zone)),
72 }
73}
74
75async fn user_keys(user_id: Uuid) -> Result<Vec<SshKeyRecord>, WebError> {
76 Ok(match ListSshKeys::new().user_id(user_id).run().await? {
77 Some(CmdResult::SshKeys(rows)) => rows,
78 _ => Vec::new(),
79 })
80}
81
82pub async fn ssh_key_page(
83 State(data): State<Arc<AppState>>,
84 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
85 Query(q): Query<PageQuery>,
86) -> Result<impl IntoResponse, WebError> {
87 let user = &jwt_auth.user;
88 let zone = user_zone(user.id)
89 .await
90 .map_err(|failure| failure_error("SSH key page failed", failure))?;
91 let keys = user_keys(user.id)
92 .await?
93 .into_iter()
94 .map(|row| key_row(row, zone))
95 .collect();
96 let config_snippet = q
97 .added
98 .as_deref()
99 .map(|fp| build_config_snippet(&data.conf.ssh, &user.name, fp));
100 let form = CREATE.blank(user.id).await?;
101
102 Ok(HtmlTemplate(SshKeyPage {
103 form,
104 keys,
105 config_snippet,
106 }))
107}
108
109pub async fn ssh_key_add(
110 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
111 Form(pairs): Form<Vec<(String, String)>>,
112) -> Result<Response, WebError> {
113 let user_id = jwt_auth.user.id;
114 Ok(match CREATE.submit(user_id, pairs).await? {
115 Created::Saved { id, .. } => added(user_id, id).await?,
116 Created::Invalid(response) => response,
117 })
118}
119
120async fn added(user_id: Uuid, id: Uuid) -> Result<Response, WebError> {
122 let fingerprint = user_keys(user_id)
123 .await?
124 .into_iter()
125 .find(|key| key.id == id)
126 .map(|key| format!("?added={}", encode_query(&key.fingerprint)))
127 .unwrap_or_default();
128 let location = format!("/account/ssh-key{fingerprint}");
129 Ok((StatusCode::OK, [("HX-Redirect", location)], "").into_response())
130}
131
132#[derive(Deserialize)]
133pub struct RemoveKeyForm {
134 fingerprint: String,
135}
136
137pub async fn ssh_key_remove(
138 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
139 Form(form): Form<RemoveKeyForm>,
140) -> Result<Response, WebError> {
141 RemoveSshKey::new()
142 .user_id(jwt_auth.user.id)
143 .fingerprint(form.fingerprint)
144 .run()
145 .await?;
146 Ok((
147 StatusCode::SEE_OTHER,
148 [(header::LOCATION, "/account/ssh-key")],
149 "",
150 )
151 .into_response())
152}
153
154fn encode_query(raw: &str) -> String {
160 let mut out = String::with_capacity(raw.len() * 3);
161 for byte in raw.as_bytes() {
162 let unreserved = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~');
163 if unreserved {
164 out.push(*byte as char);
165 } else {
166 out.push_str(&format!("%{byte:02X}"));
167 }
168 }
169 out
170}
171
172fn build_config_snippet(
173 ssh: &crate::config::SshConnectInfo,
174 user_name: &str,
175 fingerprint: &str,
176) -> String {
177 format!(
178 "Host nomisync\n\
179 \x20 HostName {hostname}\n\
180 \x20 Port {port}\n\
181 \x20 User {user}\n\
182 \x20 IdentitiesOnly yes\n\
183 \x20 # IdentityAgent ${{SSH_AUTH_SOCK}} # uncomment if using gpg-agent\n\
184 \x20 # IdentityFile ~/.ssh/id_ed25519 # or point at your private key\n\
185 \n\
186 # Host key fingerprint (verify on first connect):\n\
187 # {host_fp}\n\
188 \n\
189 # This key's fingerprint:\n\
190 # {key_fp}\n",
191 hostname = ssh.hostname,
192 port = ssh.port,
193 user = user_name,
194 host_fp = ssh.host_fingerprint,
195 key_fp = fingerprint,
196 )
197}
198
199#[cfg(test)]
200#[path = "ssh_key_tests.rs"]
201mod tests;