1
//! SSH key management commands.
2
//!
3
//! The SSH daemon uses these to look up and authorise incoming
4
//! connections; the automation CLI uses them to add / list / remove
5
//! keys for a user. Keeping them all server-side means both surfaces
6
//! share one source of truth and one set of SQL queries.
7

            
8
use crate::command::admin_connection;
9
use chrono::{DateTime, Utc};
10
use serde::Serialize;
11
use sqlx::Connection;
12
use sqlx::types::Uuid;
13
use std::fmt::Debug;
14
use supp_macro::command;
15

            
16
use super::{CmdError, CmdResult};
17

            
18
// Adding a key flips `ssh_enabled` back to TRUE, so a switched-off account must
19
// not reach this write. Gating at the write rather than in the daemon covers
20
// ssh-copy-id, the TUI's `CliSshKeyAdd`/`CliSshKeyRemove` and the web page
21
// alike. Locks the row, so it must run inside the writing transaction.
22
8838
async fn require_verified(conn: &mut sqlx::PgConnection, user_id: Uuid) -> Result<(), CmdError> {
23
6904
    match sqlx::query_file_scalar!("sql/select/users/verified.sql", user_id)
24
6904
        .fetch_optional(conn)
25
6904
        .await?
26
    {
27
6902
        Some(true) => Ok(()),
28
2
        _ => Err(CmdError::Disabled),
29
    }
30
6904
}
31

            
32
/// Wire-format record of an SSH public key. Lives in
33
/// `server::command` so consumers don't reach into the DB layer
34
/// directly.
35
#[derive(Debug, Clone, Serialize)]
36
pub struct SshKeyRecord {
37
    pub id: Uuid,
38
    pub user_id: Uuid,
39
    pub key_type: String,
40
    pub key_blob: Vec<u8>,
41
    pub fingerprint: String,
42
    pub annotation: String,
43
    pub created_at: DateTime<Utc>,
44
    pub last_used_at: Option<DateTime<Utc>>,
45
}
46

            
47
// Add a key for `user_id`. Idempotent on `(user_id, fingerprint)`:
48
// re-adding the same key updates its annotation and leaves the
49
// original creation timestamp intact. Flips `users.ssh_enabled` to
50
// `TRUE` as a side effect so a fresh key immediately permits SSH
51
// login.
52
command! {
53
    AddSshKey {
54
        #[required]
55
        user_id: Uuid,
56
        #[required]
57
        key_type: String,
58
        #[required]
59
        key_blob: Vec<u8>,
60
        #[required]
61
        fingerprint: String,
62
        #[optional]
63
        annotation: String,
64
    } => {
65
        let mut conn = admin_connection().await?;
66
        let mut tx = conn.begin().await?;
67
        require_verified(&mut tx, user_id).await?;
68
        let annotation = annotation.unwrap_or_default();
69
        let row = sqlx::query_file!(
70
            "sql/insert/ssh_keys/add.sql",
71
            user_id,
72
            key_type,
73
            key_blob,
74
            fingerprint,
75
            annotation,
76
        )
77
        .fetch_one(&mut *tx)
78
        .await
79
        .map_err(refuse_a_key_held_elsewhere)?;
80
        sqlx::query_file!("sql/update/users/set_ssh_enabled.sql", user_id, true)
81
            .execute(&mut *tx)
82
            .await?;
83
        tx.commit().await?;
84
        Ok(Some(CmdResult::Uuid(row.id)))
85
    }
86
47255
}
87

            
88
// List all keys for `user_id`, sorted by creation time (oldest
89
// first).
90
/// A public key names exactly one account, so adding one that another account
91
/// already holds is the caller's mistake, not a database fault.
92
541
fn refuse_a_key_held_elsewhere(error: sqlx::Error) -> CmdError {
93
541
    if let sqlx::Error::Database(db) = &error
94
541
        && db.is_unique_violation()
95
541
        && db.constraint() == Some("user_ssh_keys_fingerprint_key")
96
    {
97
541
        return CmdError::Args(
98
541
            t!("this SSH key is already registered to another account").to_string(),
99
541
        );
100
    }
101
    CmdError::DB(error)
102
541
}
103

            
104
command! {
105
    ListSshKeys {
106
        #[required]
107
        user_id: Uuid,
108
    } => {
109
        let mut conn = admin_connection().await?;
110
        let rows = sqlx::query_file!(
111
            "sql/select/ssh_keys/list_for_user.sql",
112
            user_id
113
        )
114
        .fetch_all(&mut *conn)
115
        .await?;
116
        let keys = rows
117
            .into_iter()
118
            .map(|r| SshKeyRecord {
119
2088
                id: r.id,
120
2088
                user_id: r.user_id,
121
2088
                key_type: r.key_type,
122
2088
                key_blob: r.key_blob,
123
2088
                fingerprint: r.fingerprint,
124
2088
                annotation: r.annotation,
125
2088
                created_at: r.created_at,
126
2088
                last_used_at: r.last_used_at,
127
2088
            })
128
            .collect();
129
        Ok(Some(CmdResult::SshKeys(keys)))
130
    }
131
22382
}
132

            
133
// Remove a key by `(user_id, fingerprint)`. When the user has no
134
// remaining keys, flips `ssh_enabled` back to `FALSE` so the account
135
// doesn't retain the password-auth bypass left over from adding a
136
// key.
137
command! {
138
    RemoveSshKey {
139
        #[required]
140
        user_id: Uuid,
141
        #[required]
142
        fingerprint: String,
143
    } => {
144
        let mut conn = admin_connection().await?;
145
        let mut tx = conn.begin().await?;
146
        require_verified(&mut tx, user_id).await?;
147
        let deleted = sqlx::query_file!(
148
            "sql/delete/ssh_keys/by_fingerprint.sql",
149
            user_id,
150
            fingerprint
151
        )
152
        .execute(&mut *tx)
153
        .await?
154
        .rows_affected();
155
        if deleted == 0 {
156
            return Err(CmdError::NotFound(format!("no SSH key {fingerprint}")));
157
        }
158
        let remaining = sqlx::query_file!(
159
            "sql/select/ssh_keys/count_for_user.sql",
160
            user_id
161
        )
162
        .fetch_one(&mut *tx)
163
        .await?
164
        .count
165
        .unwrap_or(0);
166
        if remaining == 0 {
167
            sqlx::query_file!("sql/update/users/set_ssh_enabled.sql", user_id, false)
168
                .execute(&mut *tx)
169
                .await?;
170
        }
171
        tx.commit().await?;
172
        Ok(Some(CmdResult::Bool(true)))
173
    }
174
4916
}
175

            
176
// Returns `Bool(true)` when `user_id` has at least one registered
177
// public key. Drives the password-once gate at the SSH daemon: once
178
// any key is on file, password auth for that user is permanently
179
// rejected.
180
command! {
181
    UserHasSshKey {
182
        #[required]
183
        user_id: Uuid,
184
    } => {
185
        let mut conn = admin_connection().await?;
186
        let count = sqlx::query_file!(
187
            "sql/select/ssh_keys/count_for_user.sql",
188
            user_id
189
        )
190
        .fetch_one(&mut *conn)
191
        .await?
192
        .count
193
        .unwrap_or(0);
194
        Ok(Some(CmdResult::Bool(count > 0)))
195
    }
196
10400
}
197

            
198
// Resolve a fingerprint to a user id. Returns `None` when the
199
// fingerprint is unknown or the user has `ssh_enabled = FALSE`.
200
// Used by the SSH daemon's publickey auth callback. Stamps
201
// `last_used_at` on success so operators can spot unused keys.
202
command! {
203
    LookupUserBySshKey {
204
        #[required]
205
        fingerprint: String,
206
    } => {
207
        let mut conn = admin_connection().await?;
208
        // The fingerprint is unique (migration 0007), so this is at most one row.
209
        let Some(row) = sqlx::query_file!(
210
            "sql/select/ssh_keys/lookup_user.sql",
211
            fingerprint
212
        )
213
        .fetch_optional(&mut *conn)
214
        .await?
215
        else {
216
            return Ok(None);
217
        };
218
        if !row.ssh_enabled || !row.verified {
219
            return Ok(None);
220
        }
221
        sqlx::query_file!(
222
            "sql/update/ssh_keys/touch_last_used.sql",
223
            fingerprint,
224
            row.user_id
225
        )
226
            .execute(&mut *conn)
227
            .await?;
228
        Ok(Some(CmdResult::Uuid(row.user_id)))
229
    }
230
7605
}
231

            
232
#[cfg(test)]
233
mod command_tests;