Lines
92.44 %
Functions
64.1 %
Branches
100 %
//! SSH-key-domain natives. Wraps `server::command::{ListSshKeys, RemoveSshKey,
//! UserHasSshKey}`. Keys are added through the `ssh-key-add`
//! form, never a native.
//!
//! Every native acts on the session user only. There is deliberately no
//! fingerprint-to-user lookup: it would map any known key to another tenant.
use scripting::runtime::{
alloc_entity_via_export, alloc_pair_chain, alloc_string_ref, read_string_arg,
};
use server::command::ssh_key::{ListSshKeys, RemoveSshKey, UserHasSshKey};
use server::command::{CmdError, CmdResult};
use uuid::Uuid;
use wasmtime::{AnyRef, ArrayRef, Caller, Linker, Rooted, StructRef, Val};
use crate::host_failure::cmd_failure;
use crate::natives::args::required;
use crate::natives::native::register_native;
use crate::session::SessionData;
pub const REGISTERED_COMMANDS: &[&str] = &["list-ssh-keys", "remove-ssh-key", "user-has-ssh-key"];
pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
register_native(linker, "ssh_key_list_ssh_keys", |caller, ()| {
Box::pin(async move {
let user_id = caller.data().ctx().user_id;
let result = ListSshKeys::new().user_id(user_id).run().await;
let entries = list_ssh_key_entries("list-ssh-keys", result)?;
alloc_ssh_key_chain(caller, entries).await
})
})?;
register_native(linker, "ssh_key_user_has_ssh_key", |caller, ()| {
let result = UserHasSshKey::new().user_id(user_id).run().await;
bool_from_command_result("user-has-ssh-key", result)
register_native(
linker,
"ssh_key_remove_ssh_key",
|caller, (fp_arg,): (Option<Rooted<ArrayRef>>,)| {
let fp = read_string_arg(caller, fp_arg)?;
run_remove_ssh_key(user_id, fp).await
},
)?;
Ok(())
}
/// Deletes the (user_id, fingerprint) key row; the command reports a fingerprint the user does
/// not hold as `not-found`. If this drains the user's last key,
/// `users.ssh_enabled` flips to false, which the next sshd-auth attempt
/// observes. No user-visible toggle here; just the bool.
async fn run_remove_ssh_key(user_id: Uuid, fp_arg: Option<String>) -> wasmtime::Result<i32> {
let fingerprint = required("remove-ssh-key", "fingerprint", fp_arg)?;
let result = RemoveSshKey::new()
.user_id(user_id)
.fingerprint(fingerprint)
.run()
.await;
bool_from_command_result("remove-ssh-key", result)
/// Maps the server's typestate `Bool` result (or absent row) into the i32
/// wire form the wasm signature expects: 1 = true, 0 = false. Any other
/// `CmdResult` variant is a contract violation and surfaces as a trap.
fn bool_from_command_result(
name: &str,
result: Result<Option<CmdResult>, CmdError>,
) -> wasmtime::Result<i32> {
match result {
Ok(Some(CmdResult::Bool(b))) => Ok(i32::from(b)),
Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
"{name}: expected Bool, got {other:?}"
))),
Ok(None) => Ok(0),
Err(err) => Err(cmd_failure(name, err)),
/// The six display strings that make up one `$ssh_key` wire entity, in struct
/// slot order (id, fingerprint, name, key-type, created-at, last-used-at).
struct SshKeyWire {
id: String,
fingerprint: String,
annotation: String,
key_type: String,
created_at: String,
last_used_at: String,
fn list_ssh_key_entries(
) -> wasmtime::Result<Vec<SshKeyWire>> {
Ok(Some(CmdResult::SshKeys(keys))) => Ok(keys
.into_iter()
.map(|k| SshKeyWire {
id: k.id.to_string(),
fingerprint: k.fingerprint,
annotation: k.annotation,
key_type: k.key_type,
created_at: k.created_at.to_rfc3339(),
last_used_at: k.last_used_at.map_or_else(String::new, |t| t.to_rfc3339()),
.collect()),
"{name}: expected SshKeys, got {other:?}"
Ok(None) => Ok(Vec::new()),
async fn alloc_ssh_key_entity(
caller: &mut Caller<'_, SessionData>,
key: &SshKeyWire,
) -> wasmtime::Result<Rooted<StructRef>> {
let id_ref = alloc_string_ref(caller, key.id.as_bytes())?;
let fp_ref = alloc_string_ref(caller, key.fingerprint.as_bytes())?;
let name_ref = alloc_string_ref(caller, key.annotation.as_bytes())?;
let type_ref = alloc_string_ref(caller, key.key_type.as_bytes())?;
let created_ref = alloc_string_ref(caller, key.created_at.as_bytes())?;
let last_used_ref = alloc_string_ref(caller, key.last_used_at.as_bytes())?;
let args = [
Val::AnyRef(Some(id_ref.to_anyref())),
Val::AnyRef(Some(fp_ref.to_anyref())),
Val::AnyRef(Some(name_ref.to_anyref())),
Val::AnyRef(Some(type_ref.to_anyref())),
Val::AnyRef(Some(created_ref.to_anyref())),
Val::AnyRef(Some(last_used_ref.to_anyref())),
];
alloc_entity_via_export(caller, "alloc_ssh_key", &args).await
async fn alloc_ssh_key_chain(
entries: Vec<SshKeyWire>,
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(entries.len());
for entry in &entries {
let entity_ref = alloc_ssh_key_entity(caller, entry).await?;
anyrefs.push(Some(entity_ref.to_anyref()));
alloc_pair_chain(caller, anyrefs).await
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bool_from_command_result_maps_variants() {
assert_eq!(
bool_from_command_result("x", Ok(Some(CmdResult::Bool(true)))).unwrap(),
1
);
bool_from_command_result("x", Ok(Some(CmdResult::Bool(false)))).unwrap(),
0
assert_eq!(bool_from_command_result("x", Ok(None)).unwrap(), 0);
assert!(bool_from_command_result("x", Err(CmdError::Args("oops".into()))).is_err());
#[tokio::test]
async fn run_remove_ssh_key_no_arg_emits_error() {
let err = run_remove_ssh_key(Uuid::nil(), None).await.unwrap_err();
assert!(err.to_string().contains("missing or empty"));
async fn run_remove_ssh_key_empty_arg_emits_error() {
let err = run_remove_ssh_key(Uuid::nil(), Some(String::new()))
.await
.unwrap_err();