1
//! Self-service SSH key management.
2
//!
3
//! - GET `/account/ssh-key`
4
//!   Renders the list of registered keys plus the `ssh-key-add` form.
5
//!   If the request carries `?added=<fp>`, also renders a
6
//!   ready-to-paste `~/.ssh/config` snippet - the same one
7
//!   `nomisync-sshd` writes back after a successful `ssh-copy-id`
8
//!   bootstrap.
9
//! - POST `/api/account/ssh-key/add`
10
//!   Submits the form and sends the browser to the manage page with
11
//!   `?added=<fingerprint>` so the snippet panel appears.
12
//! - POST `/api/account/ssh-key/remove` (`Form<RemoveKeyForm>`)
13
//!   Calls [`RemoveSshKey`] and redirects back without the panel.
14

            
15
use askama::Template;
16
use axum::{
17
    Extension, Form,
18
    extract::{Query, State},
19
    http::{StatusCode, header},
20
    response::{IntoResponse, Response},
21
};
22
use forms::SSH_KEY_ADD;
23
use rpc::forms::user_zone;
24
use serde::Deserialize;
25
use server::command::{
26
    CmdResult,
27
    ssh_key::{ListSshKeys, RemoveSshKey, SshKeyRecord},
28
};
29
use server::timezone::{Tz, display};
30
use std::sync::Arc;
31
use uuid::Uuid;
32

            
33
use crate::pages::forms::{
34
    create::{Create, Created},
35
    failure_error,
36
};
37
use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
38

            
39
pub const SUBMIT_PATH: &str = "/api/account/ssh-key/add";
40

            
41
const CREATE: Create = Create {
42
    form: &SSH_KEY_ADD,
43
    action: SUBMIT_PATH,
44
};
45

            
46
struct 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")]
55
struct SshKeyPage {
56
    form: String,
57
    keys: Vec<KeyRow>,
58
    config_snippet: Option<String>,
59
}
60

            
61
#[derive(Deserialize)]
62
pub struct PageQuery {
63
    added: Option<String>,
64
}
65

            
66
7
fn key_row(row: SshKeyRecord, zone: Tz) -> KeyRow {
67
    KeyRow {
68
7
        fingerprint: row.fingerprint,
69
7
        key_type: row.key_type,
70
7
        annotation: row.annotation,
71
7
        last_used: row.last_used_at.map(|at| display(at, zone)),
72
    }
73
7
}
74

            
75
5
async fn user_keys(user_id: Uuid) -> Result<Vec<SshKeyRecord>, WebError> {
76
5
    Ok(match ListSshKeys::new().user_id(user_id).run().await? {
77
5
        Some(CmdResult::SshKeys(rows)) => rows,
78
        _ => Vec::new(),
79
    })
80
5
}
81

            
82
2
pub async fn ssh_key_page(
83
2
    State(data): State<Arc<AppState>>,
84
2
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
85
2
    Query(q): Query<PageQuery>,
86
2
) -> Result<impl IntoResponse, WebError> {
87
2
    let user = &jwt_auth.user;
88
2
    let zone = user_zone(user.id)
89
2
        .await
90
        .map_err(|failure| failure_error("SSH key page failed", failure))?;
91
2
    let keys = user_keys(user.id)
92
2
        .await?
93
        .into_iter()
94
1
        .map(|row| key_row(row, zone))
95
        .collect();
96
2
    let config_snippet = q
97
2
        .added
98
2
        .as_deref()
99
1
        .map(|fp| build_config_snippet(&data.conf.ssh, &user.name, fp));
100
2
    let form = CREATE.blank(user.id).await?;
101

            
102
2
    Ok(HtmlTemplate(SshKeyPage {
103
2
        form,
104
2
        keys,
105
2
        config_snippet,
106
2
    }))
107
2
}
108

            
109
5
pub async fn ssh_key_add(
110
5
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
111
5
    Form(pairs): Form<Vec<(String, String)>>,
112
5
) -> Result<Response, WebError> {
113
5
    let user_id = jwt_auth.user.id;
114
5
    Ok(match CREATE.submit(user_id, pairs).await? {
115
3
        Created::Saved { id, .. } => added(user_id, id).await?,
116
2
        Created::Invalid(response) => response,
117
    })
118
5
}
119

            
120
/// Sends the htmx form to the manage page showing the snippet of key `id`.
121
3
async fn added(user_id: Uuid, id: Uuid) -> Result<Response, WebError> {
122
3
    let fingerprint = user_keys(user_id)
123
3
        .await?
124
        .into_iter()
125
3
        .find(|key| key.id == id)
126
3
        .map(|key| format!("?added={}", encode_query(&key.fingerprint)))
127
        .unwrap_or_default();
128
3
    let location = format!("/account/ssh-key{fingerprint}");
129
3
    Ok((StatusCode::OK, [("HX-Redirect", location)], "").into_response())
130
3
}
131

            
132
#[derive(Deserialize)]
133
pub struct RemoveKeyForm {
134
    fingerprint: String,
135
}
136

            
137
2
pub async fn ssh_key_remove(
138
2
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
139
2
    Form(form): Form<RemoveKeyForm>,
140
2
) -> Result<Response, WebError> {
141
2
    RemoveSshKey::new()
142
2
        .user_id(jwt_auth.user.id)
143
2
        .fingerprint(form.fingerprint)
144
2
        .run()
145
2
        .await?;
146
1
    Ok((
147
1
        StatusCode::SEE_OTHER,
148
1
        [(header::LOCATION, "/account/ssh-key")],
149
1
        "",
150
1
    )
151
1
        .into_response())
152
2
}
153

            
154
/// Minimal percent-encoder for the `?added=` query value.
155
/// Encodes everything outside the unreserved RFC-3986 set so an SSH
156
/// key fingerprint (`SHA256:` plus base64) round-trips cleanly. Tiny
157
/// enough to keep inline; adding `percent-encoding` as a direct dep
158
/// for one call site is overkill.
159
5
fn encode_query(raw: &str) -> String {
160
5
    let mut out = String::with_capacity(raw.len() * 3);
161
5
    for byte in raw.as_bytes() {
162
176
        let unreserved = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~');
163
176
        if unreserved {
164
163
            out.push(*byte as char);
165
        } else {
166
13
            out.push_str(&format!("%{byte:02X}"));
167
        }
168
    }
169
5
    out
170
5
}
171

            
172
1
fn build_config_snippet(
173
1
    ssh: &crate::config::SshConnectInfo,
174
1
    user_name: &str,
175
1
    fingerprint: &str,
176
1
) -> String {
177
1
    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
1
        hostname = ssh.hostname,
192
1
        port = ssh.port,
193
1
        user = user_name,
194
1
        host_fp = ssh.host_fingerprint,
195
1
        key_fp = fingerprint,
196
    )
197
1
}
198

            
199
#[cfg(test)]
200
#[path = "ssh_key_tests.rs"]
201
mod tests;