Lines
97.73 %
Functions
30.26 %
Branches
100 %
//! Self-service SSH key management.
//!
//! - GET `/account/ssh-key`
//! Renders the list of registered keys plus the `ssh-key-add` form.
//! If the request carries `?added=<fp>`, also renders a
//! ready-to-paste `~/.ssh/config` snippet - the same one
//! `nomisync-sshd` writes back after a successful `ssh-copy-id`
//! bootstrap.
//! - POST `/api/account/ssh-key/add`
//! Submits the form and sends the browser to the manage page with
//! `?added=<fingerprint>` so the snippet panel appears.
//! - POST `/api/account/ssh-key/remove` (`Form<RemoveKeyForm>`)
//! Calls [`RemoveSshKey`] and redirects back without the panel.
use askama::Template;
use axum::{
Extension, Form,
extract::{Query, State},
http::{StatusCode, header},
response::{IntoResponse, Response},
};
use forms::SSH_KEY_ADD;
use rpc::forms::user_zone;
use serde::Deserialize;
use server::command::{
CmdResult,
ssh_key::{ListSshKeys, RemoveSshKey, SshKeyRecord},
use server::timezone::{Tz, display};
use std::sync::Arc;
use uuid::Uuid;
use crate::pages::forms::{
create::{Create, Created},
failure_error,
use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
pub const SUBMIT_PATH: &str = "/api/account/ssh-key/add";
const CREATE: Create = Create {
form: &SSH_KEY_ADD,
action: SUBMIT_PATH,
struct KeyRow {
fingerprint: String,
key_type: String,
annotation: String,
last_used: Option<String>,
}
#[derive(Template)]
#[template(path = "pages/account/ssh_key.html")]
struct SshKeyPage {
form: String,
keys: Vec<KeyRow>,
config_snippet: Option<String>,
#[derive(Deserialize)]
pub struct PageQuery {
added: Option<String>,
fn key_row(row: SshKeyRecord, zone: Tz) -> KeyRow {
KeyRow {
fingerprint: row.fingerprint,
key_type: row.key_type,
annotation: row.annotation,
last_used: row.last_used_at.map(|at| display(at, zone)),
async fn user_keys(user_id: Uuid) -> Result<Vec<SshKeyRecord>, WebError> {
Ok(match ListSshKeys::new().user_id(user_id).run().await? {
Some(CmdResult::SshKeys(rows)) => rows,
_ => Vec::new(),
})
pub async fn ssh_key_page(
State(data): State<Arc<AppState>>,
Extension(jwt_auth): Extension<JWTAuthMiddleware>,
Query(q): Query<PageQuery>,
) -> Result<impl IntoResponse, WebError> {
let user = &jwt_auth.user;
let zone = user_zone(user.id)
.await
.map_err(|failure| failure_error("SSH key page failed", failure))?;
let keys = user_keys(user.id)
.await?
.into_iter()
.map(|row| key_row(row, zone))
.collect();
let config_snippet = q
.added
.as_deref()
.map(|fp| build_config_snippet(&data.conf.ssh, &user.name, fp));
let form = CREATE.blank(user.id).await?;
Ok(HtmlTemplate(SshKeyPage {
form,
keys,
config_snippet,
}))
pub async fn ssh_key_add(
Form(pairs): Form<Vec<(String, String)>>,
) -> Result<Response, WebError> {
let user_id = jwt_auth.user.id;
Ok(match CREATE.submit(user_id, pairs).await? {
Created::Saved { id, .. } => added(user_id, id).await?,
Created::Invalid(response) => response,
/// Sends the htmx form to the manage page showing the snippet of key `id`.
async fn added(user_id: Uuid, id: Uuid) -> Result<Response, WebError> {
let fingerprint = user_keys(user_id)
.find(|key| key.id == id)
.map(|key| format!("?added={}", encode_query(&key.fingerprint)))
.unwrap_or_default();
let location = format!("/account/ssh-key{fingerprint}");
Ok((StatusCode::OK, [("HX-Redirect", location)], "").into_response())
pub struct RemoveKeyForm {
pub async fn ssh_key_remove(
Form(form): Form<RemoveKeyForm>,
RemoveSshKey::new()
.user_id(jwt_auth.user.id)
.fingerprint(form.fingerprint)
.run()
.await?;
Ok((
StatusCode::SEE_OTHER,
[(header::LOCATION, "/account/ssh-key")],
"",
)
.into_response())
/// Minimal percent-encoder for the `?added=` query value.
/// Encodes everything outside the unreserved RFC-3986 set so an SSH
/// key fingerprint (`SHA256:` plus base64) round-trips cleanly. Tiny
/// enough to keep inline; adding `percent-encoding` as a direct dep
/// for one call site is overkill.
fn encode_query(raw: &str) -> String {
let mut out = String::with_capacity(raw.len() * 3);
for byte in raw.as_bytes() {
let unreserved = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~');
if unreserved {
out.push(*byte as char);
} else {
out.push_str(&format!("%{byte:02X}"));
out
fn build_config_snippet(
ssh: &crate::config::SshConnectInfo,
user_name: &str,
fingerprint: &str,
) -> String {
format!(
"Host nomisync\n\
\x20 HostName {hostname}\n\
\x20 Port {port}\n\
\x20 User {user}\n\
\x20 IdentitiesOnly yes\n\
\x20 # IdentityAgent ${{SSH_AUTH_SOCK}} # uncomment if using gpg-agent\n\
\x20 # IdentityFile ~/.ssh/id_ed25519 # or point at your private key\n\
\n\
# Host key fingerprint (verify on first connect):\n\
# {host_fp}\n\
# This key's fingerprint:\n\
# {key_fp}\n",
hostname = ssh.hostname,
port = ssh.port,
user = user_name,
host_fp = ssh.host_fingerprint,
key_fp = fingerprint,
#[cfg(test)]
#[path = "ssh_key_tests.rs"]
mod tests;