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

            
8
use scripting::runtime::{
9
    alloc_entity_via_export, alloc_pair_chain, alloc_string_ref, read_string_arg,
10
};
11
use server::command::ssh_key::{ListSshKeys, RemoveSshKey, UserHasSshKey};
12
use server::command::{CmdError, CmdResult};
13
use uuid::Uuid;
14
use wasmtime::{AnyRef, ArrayRef, Caller, Linker, Rooted, StructRef, Val};
15

            
16
use crate::host_failure::cmd_failure;
17
use crate::natives::args::required;
18
use crate::natives::native::register_native;
19
use crate::session::SessionData;
20

            
21
pub const REGISTERED_COMMANDS: &[&str] = &["list-ssh-keys", "remove-ssh-key", "user-has-ssh-key"];
22

            
23
230200
pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
24
230200
    register_native(linker, "ssh_key_list_ssh_keys", |caller, ()| {
25
1120
        Box::pin(async move {
26
1120
            let user_id = caller.data().ctx().user_id;
27
1120
            let result = ListSshKeys::new().user_id(user_id).run().await;
28
1120
            let entries = list_ssh_key_entries("list-ssh-keys", result)?;
29
1120
            alloc_ssh_key_chain(caller, entries).await
30
1120
        })
31
1120
    })?;
32
230200
    register_native(linker, "ssh_key_user_has_ssh_key", |caller, ()| {
33
2240
        Box::pin(async move {
34
2240
            let user_id = caller.data().ctx().user_id;
35
2240
            let result = UserHasSshKey::new().user_id(user_id).run().await;
36
2240
            bool_from_command_result("user-has-ssh-key", result)
37
2240
        })
38
2240
    })?;
39
230200
    register_native(
40
230200
        linker,
41
230200
        "ssh_key_remove_ssh_key",
42
800
        |caller, (fp_arg,): (Option<Rooted<ArrayRef>>,)| {
43
800
            Box::pin(async move {
44
800
                let user_id = caller.data().ctx().user_id;
45
800
                let fp = read_string_arg(caller, fp_arg)?;
46
800
                run_remove_ssh_key(user_id, fp).await
47
800
            })
48
800
        },
49
    )?;
50
230200
    Ok(())
51
230200
}
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.
57
802
async fn run_remove_ssh_key(user_id: Uuid, fp_arg: Option<String>) -> wasmtime::Result<i32> {
58
802
    let fingerprint = required("remove-ssh-key", "fingerprint", fp_arg)?;
59
800
    let result = RemoveSshKey::new()
60
800
        .user_id(user_id)
61
800
        .fingerprint(fingerprint)
62
800
        .run()
63
800
        .await;
64
800
    bool_from_command_result("remove-ssh-key", result)
65
802
}
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.
70
3044
fn bool_from_command_result(
71
3044
    name: &str,
72
3044
    result: Result<Option<CmdResult>, CmdError>,
73
3044
) -> wasmtime::Result<i32> {
74
3044
    match result {
75
2562
        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
1
        Ok(None) => Ok(0),
80
481
        Err(err) => Err(cmd_failure(name, err)),
81
    }
82
3044
}
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).
86
struct 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

            
95
1120
fn list_ssh_key_entries(
96
1120
    name: &str,
97
1120
    result: Result<Option<CmdResult>, CmdError>,
98
1120
) -> wasmtime::Result<Vec<SshKeyWire>> {
99
1120
    match result {
100
1120
        Ok(Some(CmdResult::SshKeys(keys))) => Ok(keys
101
1120
            .into_iter()
102
            .map(|k| SshKeyWire {
103
320
                id: k.id.to_string(),
104
320
                fingerprint: k.fingerprint,
105
320
                annotation: k.annotation,
106
320
                key_type: k.key_type,
107
320
                created_at: k.created_at.to_rfc3339(),
108
320
                last_used_at: k.last_used_at.map_or_else(String::new, |t| t.to_rfc3339()),
109
320
            })
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
1120
}
118

            
119
320
async fn alloc_ssh_key_entity(
120
320
    caller: &mut Caller<'_, SessionData>,
121
320
    key: &SshKeyWire,
122
320
) -> wasmtime::Result<Rooted<StructRef>> {
123
320
    let id_ref = alloc_string_ref(caller, key.id.as_bytes())?;
124
320
    let fp_ref = alloc_string_ref(caller, key.fingerprint.as_bytes())?;
125
320
    let name_ref = alloc_string_ref(caller, key.annotation.as_bytes())?;
126
320
    let type_ref = alloc_string_ref(caller, key.key_type.as_bytes())?;
127
320
    let created_ref = alloc_string_ref(caller, key.created_at.as_bytes())?;
128
320
    let last_used_ref = alloc_string_ref(caller, key.last_used_at.as_bytes())?;
129
320
    let args = [
130
320
        Val::AnyRef(Some(id_ref.to_anyref())),
131
320
        Val::AnyRef(Some(fp_ref.to_anyref())),
132
320
        Val::AnyRef(Some(name_ref.to_anyref())),
133
320
        Val::AnyRef(Some(type_ref.to_anyref())),
134
320
        Val::AnyRef(Some(created_ref.to_anyref())),
135
320
        Val::AnyRef(Some(last_used_ref.to_anyref())),
136
320
    ];
137
320
    alloc_entity_via_export(caller, "alloc_ssh_key", &args).await
138
320
}
139

            
140
1120
async fn alloc_ssh_key_chain(
141
1120
    caller: &mut Caller<'_, SessionData>,
142
1120
    entries: Vec<SshKeyWire>,
143
1120
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
144
1120
    let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(entries.len());
145
1120
    for entry in &entries {
146
320
        let entity_ref = alloc_ssh_key_entity(caller, entry).await?;
147
320
        anyrefs.push(Some(entity_ref.to_anyref()));
148
    }
149
1120
    alloc_pair_chain(caller, anyrefs).await
150
1120
}
151

            
152
#[cfg(test)]
153
mod tests {
154
    use super::*;
155
    use uuid::Uuid;
156

            
157
    #[test]
158
1
    fn bool_from_command_result_maps_variants() {
159
1
        assert_eq!(
160
1
            bool_from_command_result("x", Ok(Some(CmdResult::Bool(true)))).unwrap(),
161
1
            1
162
        );
163
1
        assert_eq!(
164
1
            bool_from_command_result("x", Ok(Some(CmdResult::Bool(false)))).unwrap(),
165
1
            0
166
        );
167
1
        assert_eq!(bool_from_command_result("x", Ok(None)).unwrap(), 0);
168
1
        assert!(bool_from_command_result("x", Err(CmdError::Args("oops".into()))).is_err());
169
1
    }
170

            
171
    #[tokio::test]
172
1
    async fn run_remove_ssh_key_no_arg_emits_error() {
173
1
        let err = run_remove_ssh_key(Uuid::nil(), None).await.unwrap_err();
174
1
        assert!(err.to_string().contains("missing or empty"));
175
1
    }
176

            
177
    #[tokio::test]
178
1
    async fn run_remove_ssh_key_empty_arg_emits_error() {
179
1
        let err = run_remove_ssh_key(Uuid::nil(), Some(String::new()))
180
1
            .await
181
            .unwrap_err();
182
1
        assert!(err.to_string().contains("missing or empty"));
183
1
    }
184
}