Skip to main content

rpc/natives/
ssh_key.rs

1//! SSH-key-domain natives. Wraps `server::command::{ListSshKeys, RemoveSshKey,
2//! UserHasSshKey}`. Keys are added through the `ssh-key-add`
3//! form, never a native.
4//!
5//! Every native acts on the session user only. There is deliberately no
6//! fingerprint-to-user lookup: it would map any known key to another tenant.
7
8use scripting::runtime::{
9    alloc_entity_via_export, alloc_pair_chain, alloc_string_ref, read_string_arg,
10};
11use server::command::ssh_key::{ListSshKeys, RemoveSshKey, UserHasSshKey};
12use server::command::{CmdError, CmdResult};
13use uuid::Uuid;
14use wasmtime::{AnyRef, ArrayRef, Caller, Linker, Rooted, StructRef, Val};
15
16use crate::host_failure::cmd_failure;
17use crate::natives::args::required;
18use crate::natives::native::register_native;
19use crate::session::SessionData;
20
21pub const REGISTERED_COMMANDS: &[&str] = &["list-ssh-keys", "remove-ssh-key", "user-has-ssh-key"];
22
23pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
24    register_native(linker, "ssh_key_list_ssh_keys", |caller, ()| {
25        Box::pin(async move {
26            let user_id = caller.data().ctx().user_id;
27            let result = ListSshKeys::new().user_id(user_id).run().await;
28            let entries = list_ssh_key_entries("list-ssh-keys", result)?;
29            alloc_ssh_key_chain(caller, entries).await
30        })
31    })?;
32    register_native(linker, "ssh_key_user_has_ssh_key", |caller, ()| {
33        Box::pin(async move {
34            let user_id = caller.data().ctx().user_id;
35            let result = UserHasSshKey::new().user_id(user_id).run().await;
36            bool_from_command_result("user-has-ssh-key", result)
37        })
38    })?;
39    register_native(
40        linker,
41        "ssh_key_remove_ssh_key",
42        |caller, (fp_arg,): (Option<Rooted<ArrayRef>>,)| {
43            Box::pin(async move {
44                let user_id = caller.data().ctx().user_id;
45                let fp = read_string_arg(caller, fp_arg)?;
46                run_remove_ssh_key(user_id, fp).await
47            })
48        },
49    )?;
50    Ok(())
51}
52
53/// Deletes the (user_id, fingerprint) key row; the command reports a fingerprint the user does
54/// not hold as `not-found`. If this drains the user's last key,
55/// `users.ssh_enabled` flips to false, which the next sshd-auth attempt
56/// observes. No user-visible toggle here; just the bool.
57async fn run_remove_ssh_key(user_id: Uuid, fp_arg: Option<String>) -> wasmtime::Result<i32> {
58    let fingerprint = required("remove-ssh-key", "fingerprint", fp_arg)?;
59    let result = RemoveSshKey::new()
60        .user_id(user_id)
61        .fingerprint(fingerprint)
62        .run()
63        .await;
64    bool_from_command_result("remove-ssh-key", result)
65}
66
67/// Maps the server's typestate `Bool` result (or absent row) into the i32
68/// wire form the wasm signature expects: 1 = true, 0 = false. Any other
69/// `CmdResult` variant is a contract violation and surfaces as a trap.
70fn bool_from_command_result(
71    name: &str,
72    result: Result<Option<CmdResult>, CmdError>,
73) -> wasmtime::Result<i32> {
74    match result {
75        Ok(Some(CmdResult::Bool(b))) => Ok(i32::from(b)),
76        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
77            "{name}: expected Bool, got {other:?}"
78        ))),
79        Ok(None) => Ok(0),
80        Err(err) => Err(cmd_failure(name, err)),
81    }
82}
83
84/// The six display strings that make up one `$ssh_key` wire entity, in struct
85/// slot order (id, fingerprint, name, key-type, created-at, last-used-at).
86struct SshKeyWire {
87    id: String,
88    fingerprint: String,
89    annotation: String,
90    key_type: String,
91    created_at: String,
92    last_used_at: String,
93}
94
95fn list_ssh_key_entries(
96    name: &str,
97    result: Result<Option<CmdResult>, CmdError>,
98) -> wasmtime::Result<Vec<SshKeyWire>> {
99    match result {
100        Ok(Some(CmdResult::SshKeys(keys))) => Ok(keys
101            .into_iter()
102            .map(|k| SshKeyWire {
103                id: k.id.to_string(),
104                fingerprint: k.fingerprint,
105                annotation: k.annotation,
106                key_type: k.key_type,
107                created_at: k.created_at.to_rfc3339(),
108                last_used_at: k.last_used_at.map_or_else(String::new, |t| t.to_rfc3339()),
109            })
110            .collect()),
111        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
112            "{name}: expected SshKeys, got {other:?}"
113        ))),
114        Ok(None) => Ok(Vec::new()),
115        Err(err) => Err(cmd_failure(name, err)),
116    }
117}
118
119async fn alloc_ssh_key_entity(
120    caller: &mut Caller<'_, SessionData>,
121    key: &SshKeyWire,
122) -> wasmtime::Result<Rooted<StructRef>> {
123    let id_ref = alloc_string_ref(caller, key.id.as_bytes())?;
124    let fp_ref = alloc_string_ref(caller, key.fingerprint.as_bytes())?;
125    let name_ref = alloc_string_ref(caller, key.annotation.as_bytes())?;
126    let type_ref = alloc_string_ref(caller, key.key_type.as_bytes())?;
127    let created_ref = alloc_string_ref(caller, key.created_at.as_bytes())?;
128    let last_used_ref = alloc_string_ref(caller, key.last_used_at.as_bytes())?;
129    let args = [
130        Val::AnyRef(Some(id_ref.to_anyref())),
131        Val::AnyRef(Some(fp_ref.to_anyref())),
132        Val::AnyRef(Some(name_ref.to_anyref())),
133        Val::AnyRef(Some(type_ref.to_anyref())),
134        Val::AnyRef(Some(created_ref.to_anyref())),
135        Val::AnyRef(Some(last_used_ref.to_anyref())),
136    ];
137    alloc_entity_via_export(caller, "alloc_ssh_key", &args).await
138}
139
140async fn alloc_ssh_key_chain(
141    caller: &mut Caller<'_, SessionData>,
142    entries: Vec<SshKeyWire>,
143) -> wasmtime::Result<Option<Rooted<StructRef>>> {
144    let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(entries.len());
145    for entry in &entries {
146        let entity_ref = alloc_ssh_key_entity(caller, entry).await?;
147        anyrefs.push(Some(entity_ref.to_anyref()));
148    }
149    alloc_pair_chain(caller, anyrefs).await
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155    use uuid::Uuid;
156
157    #[test]
158    fn bool_from_command_result_maps_variants() {
159        assert_eq!(
160            bool_from_command_result("x", Ok(Some(CmdResult::Bool(true)))).unwrap(),
161            1
162        );
163        assert_eq!(
164            bool_from_command_result("x", Ok(Some(CmdResult::Bool(false)))).unwrap(),
165            0
166        );
167        assert_eq!(bool_from_command_result("x", Ok(None)).unwrap(), 0);
168        assert!(bool_from_command_result("x", Err(CmdError::Args("oops".into()))).is_err());
169    }
170
171    #[tokio::test]
172    async fn run_remove_ssh_key_no_arg_emits_error() {
173        let err = run_remove_ssh_key(Uuid::nil(), None).await.unwrap_err();
174        assert!(err.to_string().contains("missing or empty"));
175    }
176
177    #[tokio::test]
178    async fn run_remove_ssh_key_empty_arg_emits_error() {
179        let err = run_remove_ssh_key(Uuid::nil(), Some(String::new()))
180            .await
181            .unwrap_err();
182        assert!(err.to_string().contains("missing or empty"));
183    }
184}