feat(plugins): add interactive prompts and richer connection forms
This commit is contained in:
1 parent
fac270fc8a
commit
e4bda693fb
42 files changed
+3922
-200
No files matched your search
@@ -1,6 +1,9 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, BufRead, BufReader, Read, Write};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{mpsc, Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
@@ -11,6 +14,12 @@ const MAX_BINARY_BYTES: usize = 64 * 1024 * 1024;
|
||||
const FRAME_KIND_JSON: u8 = 0;
|
||||
const FRAME_KIND_BINARY: u8 = 1;
|
||||
const DEFAULT_WORK_QUEUE_CAPACITY: usize = 256;
|
||||
/// How long a plugin waits for a host answer before giving up. User prompts are
|
||||
/// bounded by their own `timeoutSecs`, so the default covers one prompt plus a
|
||||
/// little slack.
|
||||
const DEFAULT_HOST_REQUEST_TIMEOUT: Duration = Duration::from_secs(330);
|
||||
/// Host API method that relays a question to the DBX user interface.
|
||||
pub const HOST_REQUEST_USER_INPUT_METHOD: &str = "host/requestUserInput";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PluginTransport {
|
||||
@@ -124,20 +133,305 @@ impl PluginEmitter {
|
||||
if payload.len() > MAX_JSON_BYTES {
|
||||
return Err(PluginError::new(-32600, "JSON message is too large"));
|
||||
}
|
||||
let mut output = self.output.lock().map_err(|_| PluginError::new(-32000, "Plugin output lock is poisoned"))?;
|
||||
match self.transport {
|
||||
PluginTransport::JsonLines => {
|
||||
output.write_all(&payload).map_err(io_error)?;
|
||||
output.write_all(b"\n").map_err(io_error)?;
|
||||
write_json_frame(&self.output, self.transport, &payload)
|
||||
}
|
||||
}
|
||||
|
||||
fn write_json_frame(
|
||||
output: &Arc<Mutex<Box<dyn Write + Send>>>,
|
||||
transport: PluginTransport,
|
||||
payload: &[u8],
|
||||
) -> Result<(), PluginError> {
|
||||
let mut output = output.lock().map_err(|_| PluginError::new(-32000, "Plugin output lock is poisoned"))?;
|
||||
match transport {
|
||||
PluginTransport::JsonLines => {
|
||||
output.write_all(payload).map_err(io_error)?;
|
||||
output.write_all(b"\n").map_err(io_error)?;
|
||||
}
|
||||
PluginTransport::Framed => {
|
||||
output.write_all(&[FRAME_KIND_JSON]).map_err(io_error)?;
|
||||
output.write_all(&(payload.len() as u32).to_be_bytes()).map_err(io_error)?;
|
||||
output.write_all(payload).map_err(io_error)?;
|
||||
}
|
||||
}
|
||||
output.flush().map_err(io_error)
|
||||
}
|
||||
|
||||
/// A question the plugin asks the user through the host, e.g. a bastion's
|
||||
/// keyboard-interactive MFA challenge or a host-key confirmation. Serializes
|
||||
/// into the `host/requestUserInput` params of Host API 1.1.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UserInputPrompt {
|
||||
/// Text the user answers, already localized by the plugin.
|
||||
pub prompt: String,
|
||||
/// Optional heading shown above `prompt`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub title: Option<String>,
|
||||
/// Show the typed characters (defaults to masked input).
|
||||
#[serde(default)]
|
||||
pub echo: bool,
|
||||
/// Preset answer the user may keep or replace.
|
||||
#[serde(rename = "default", skip_serializing_if = "Option::is_none")]
|
||||
pub default_value: Option<String>,
|
||||
/// Fixed answers; leave empty for free-form input (at most 8).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub options: Vec<UserInputOption>,
|
||||
/// How long the user has to answer, in seconds (host clamps to 5..600).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub timeout_secs: Option<u64>,
|
||||
}
|
||||
|
||||
/// One fixed answer of a [`UserInputPrompt`].
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct UserInputOption {
|
||||
pub value: String,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
impl UserInputPrompt {
|
||||
/// A masked free-form question (verification codes, passwords, tokens).
|
||||
pub fn secret(prompt: impl Into<String>) -> Self {
|
||||
Self { prompt: prompt.into(), title: None, echo: false, default_value: None, options: Vec::new(), timeout_secs: None }
|
||||
}
|
||||
|
||||
/// A question whose answer is visible while typing (account names, paths).
|
||||
pub fn text(prompt: impl Into<String>) -> Self {
|
||||
Self { echo: true, ..Self::secret(prompt) }
|
||||
}
|
||||
|
||||
/// A multiple-choice question; the host shows the options as buttons.
|
||||
pub fn choice(prompt: impl Into<String>, options: Vec<UserInputOption>) -> Self {
|
||||
Self { options, ..Self::text(prompt) }
|
||||
}
|
||||
|
||||
pub fn with_title(mut self, title: impl Into<String>) -> Self {
|
||||
self.title = Some(title.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_default(mut self, value: impl Into<String>) -> Self {
|
||||
self.default_value = Some(value.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_timeout_secs(mut self, seconds: u64) -> Self {
|
||||
self.timeout_secs = Some(seconds);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The user's answer to a [`UserInputPrompt`].
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct UserInputAnswer {
|
||||
/// `submit`, `cancel`, or `timeout`.
|
||||
pub action: String,
|
||||
/// The typed value or chosen option value; only present on `submit`.
|
||||
#[serde(default)]
|
||||
pub value: Option<String>,
|
||||
}
|
||||
|
||||
impl UserInputAnswer {
|
||||
/// The submitted value, or `None` when the user cancelled and the host gave
|
||||
/// up waiting. Callers must fail closed on `None`.
|
||||
pub fn submitted(&self) -> Option<&str> {
|
||||
if self.action == "submit" {
|
||||
self.value.as_deref()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
self.action == "cancel"
|
||||
}
|
||||
|
||||
pub fn is_timeout(&self) -> bool {
|
||||
self.action == "timeout"
|
||||
}
|
||||
}
|
||||
|
||||
/// What the host told the plugin about itself at `plugin/initialize`.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
struct HostDescription {
|
||||
api_version: Option<String>,
|
||||
features: Vec<String>,
|
||||
}
|
||||
|
||||
/// Client for Host API methods the plugin calls back into DBX. Create it by
|
||||
/// running a [`PluginServer`]; [`host_client`] returns the running instance.
|
||||
///
|
||||
/// Calls block the calling thread until the host answers, so call them from a
|
||||
/// plugin worker (a `connection/connect` handler is already one) rather than
|
||||
/// from the thread that runs the server loop. While a user prompt is open the
|
||||
/// host pauses the deadline of the request that is waiting on it, so a human
|
||||
/// typing an MFA code is never mistaken for a connect timeout.
|
||||
#[derive(Clone)]
|
||||
pub struct HostClient {
|
||||
output: Arc<Mutex<Box<dyn Write + Send>>>,
|
||||
transport: PluginTransport,
|
||||
pending: Arc<Mutex<HashMap<String, mpsc::Sender<Result<Value, PluginError>>>>>,
|
||||
next_request_id: Arc<AtomicU64>,
|
||||
host: Arc<Mutex<HostDescription>>,
|
||||
}
|
||||
|
||||
impl HostClient {
|
||||
fn new(output: Arc<Mutex<Box<dyn Write + Send>>>, transport: PluginTransport) -> Self {
|
||||
Self {
|
||||
output,
|
||||
transport,
|
||||
pending: Arc::new(Mutex::new(HashMap::new())),
|
||||
next_request_id: Arc::new(AtomicU64::new(1)),
|
||||
host: Arc::new(Mutex::new(HostDescription::default())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Host API version DBX reported at `plugin/initialize`.
|
||||
pub fn host_api_version(&self) -> Option<String> {
|
||||
self.host.lock().ok().and_then(|host| host.api_version.clone())
|
||||
}
|
||||
|
||||
/// Whether DBX advertised `method` for this session. Gate optional calls on
|
||||
/// this (or on [`HostClient::host_api_version`]) so a plugin still works
|
||||
/// against an older host that predates the capability.
|
||||
pub fn supports(&self, method: &str) -> bool {
|
||||
self.host.lock().map(|host| host.features.iter().any(|feature| feature == method)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Calls one Host API method and waits for the answer.
|
||||
pub fn request(&self, method: &str, params: Value) -> Result<Value, PluginError> {
|
||||
self.request_with_timeout(method, params, DEFAULT_HOST_REQUEST_TIMEOUT)
|
||||
}
|
||||
|
||||
pub fn request_with_timeout(
|
||||
&self,
|
||||
method: &str,
|
||||
params: Value,
|
||||
timeout: Duration,
|
||||
) -> Result<Value, PluginError> {
|
||||
validate_protocol_name(method)?;
|
||||
let id = format!("plugin-{}", self.next_request_id.fetch_add(1, Ordering::Relaxed));
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
self.pending
|
||||
.lock()
|
||||
.map_err(|_| PluginError::new(-32000, "Host request lock is poisoned"))?
|
||||
.insert(id.clone(), sender);
|
||||
let message = serde_json::json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"method": method,
|
||||
"params": params,
|
||||
});
|
||||
if let Err(error) = self.write(&message) {
|
||||
if let Ok(mut pending) = self.pending.lock() {
|
||||
pending.remove(&id);
|
||||
}
|
||||
PluginTransport::Framed => {
|
||||
output.write_all(&[FRAME_KIND_JSON]).map_err(io_error)?;
|
||||
output.write_all(&(payload.len() as u32).to_be_bytes()).map_err(io_error)?;
|
||||
output.write_all(&payload).map_err(io_error)?;
|
||||
return Err(error);
|
||||
}
|
||||
match receiver.recv_timeout(timeout) {
|
||||
Ok(result) => result,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {
|
||||
if let Ok(mut pending) = self.pending.lock() {
|
||||
pending.remove(&id);
|
||||
}
|
||||
Err(PluginError::new(-32001, format!("Host did not answer '{method}' in time")))
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => {
|
||||
Err(PluginError::new(-32000, format!("Host dropped the answer to '{method}'")))
|
||||
}
|
||||
}
|
||||
output.flush().map_err(io_error)
|
||||
}
|
||||
|
||||
/// Asks the user a question through the DBX UI. Fails when the host has no
|
||||
/// user interface attached (headless/MCP runs), so the plugin can fall back
|
||||
/// to its own behaviour instead of waiting for an answer that cannot come.
|
||||
pub fn request_user_input(&self, prompt: &UserInputPrompt) -> Result<UserInputAnswer, PluginError> {
|
||||
let params = serde_json::to_value(prompt).map_err(|error| PluginError::new(-32603, error.to_string()))?;
|
||||
let answer = self.request(HOST_REQUEST_USER_INPUT_METHOD, params)?;
|
||||
serde_json::from_value(answer)
|
||||
.map_err(|error| PluginError::new(-32002, format!("Host returned an invalid input answer: {error}")))
|
||||
}
|
||||
|
||||
fn write(&self, value: &Value) -> Result<(), PluginError> {
|
||||
let payload = serde_json::to_vec(value).map_err(|error| PluginError::new(-32603, error.to_string()))?;
|
||||
if payload.len() > MAX_JSON_BYTES {
|
||||
return Err(PluginError::new(-32600, "JSON message is too large"));
|
||||
}
|
||||
write_json_frame(&self.output, self.transport, &payload)
|
||||
}
|
||||
|
||||
/// Remembers what the host advertised at `plugin/initialize`.
|
||||
fn note_host_description(&self, params: &Value) {
|
||||
let host = params.get("host");
|
||||
let api_version = host
|
||||
.and_then(|host| host.get("hostApiVersion"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string);
|
||||
let features = host
|
||||
.and_then(|host| host.get("features"))
|
||||
.and_then(Value::as_array)
|
||||
.map(|features| features.iter().filter_map(Value::as_str).map(str::to_string).collect())
|
||||
.unwrap_or_default();
|
||||
if let Ok(mut description) = self.host.lock() {
|
||||
*description = HostDescription { api_version, features };
|
||||
}
|
||||
}
|
||||
|
||||
/// Routes an answer from the host to the waiting caller. Returns `false`
|
||||
/// when the message is not a response to a plugin-initiated request, so the
|
||||
/// server loop can keep handling host -> plugin requests.
|
||||
fn deliver_response(&self, value: &Value) -> bool {
|
||||
if value.get("method").is_some() {
|
||||
return false;
|
||||
}
|
||||
let Some(id) = value.get("id").and_then(Value::as_str) else {
|
||||
return false;
|
||||
};
|
||||
let Some(sender) = self.pending.lock().ok().and_then(|mut pending| pending.remove(id)) else {
|
||||
return false;
|
||||
};
|
||||
let result = match value.get("error") {
|
||||
Some(error) => {
|
||||
let code = error.get("code").and_then(Value::as_i64).unwrap_or(-32603) as i32;
|
||||
let message = error
|
||||
.get("message")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| error.to_string());
|
||||
Err(PluginError::new(code, message))
|
||||
}
|
||||
None => match value.get("result") {
|
||||
Some(result) => Ok(result.clone()),
|
||||
None => Err(PluginError::new(-32603, "Host answer has neither result nor error")),
|
||||
},
|
||||
};
|
||||
let _ = sender.send(result);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
static HOST_CLIENT: Mutex<Option<HostClient>> = Mutex::new(None);
|
||||
|
||||
/// The host client of the running plugin server, if any.
|
||||
pub fn host_client() -> Option<HostClient> {
|
||||
HOST_CLIENT.lock().ok().and_then(|client| client.clone())
|
||||
}
|
||||
|
||||
/// Installs the process-wide host client. [`PluginServer::serve`] calls this;
|
||||
/// tests may replace it.
|
||||
pub fn install_host_client(client: HostClient) {
|
||||
if let Ok(mut current) = HOST_CLIENT.lock() {
|
||||
*current = Some(client);
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience wrapper for [`HostClient::request_user_input`] on the running
|
||||
/// server. Fails when the plugin server is not running.
|
||||
pub fn request_user_input(prompt: &UserInputPrompt) -> Result<UserInputAnswer, PluginError> {
|
||||
let Some(client) = host_client() else {
|
||||
return Err(PluginError::new(-32000, "Host API is unavailable: the plugin server is not running"));
|
||||
};
|
||||
client.request_user_input(prompt)
|
||||
}
|
||||
|
||||
pub struct PluginServer<H> {
|
||||
@@ -175,7 +469,11 @@ impl<H: PluginHandler> PluginServer<H> {
|
||||
}
|
||||
|
||||
pub fn serve(self) -> io::Result<()> {
|
||||
let emitter = PluginEmitter { output: Arc::new(Mutex::new(Box::new(io::stdout()))), transport: self.transport };
|
||||
let output: Arc<Mutex<Box<dyn Write + Send>>> = Arc::new(Mutex::new(Box::new(io::stdout())));
|
||||
let emitter = PluginEmitter { output: output.clone(), transport: self.transport };
|
||||
// Publish the client before serving so a handler (including the very
|
||||
// first request) can call back into the host.
|
||||
install_host_client(HostClient::new(output, self.transport));
|
||||
let workers = WorkerPool::new(self.worker_threads, self.work_queue_capacity)?;
|
||||
match self.transport {
|
||||
PluginTransport::JsonLines => self.serve_json_lines(BufReader::new(io::stdin()), emitter, &workers),
|
||||
@@ -235,13 +533,24 @@ impl<H: PluginHandler> PluginServer<H> {
|
||||
}
|
||||
|
||||
fn dispatch_json(&self, payload: &[u8], emitter: PluginEmitter, workers: &WorkerPool) -> Result<(), String> {
|
||||
let request: ProtocolRequest = serde_json::from_slice(payload).map_err(|error| error.to_string())?;
|
||||
let value: Value = serde_json::from_slice(payload).map_err(|error| error.to_string())?;
|
||||
// Answers to Host API calls the plugin made (string ids). Everything
|
||||
// else is a host -> plugin request, whose ids are numeric.
|
||||
if let Some(host) = host_client() {
|
||||
if host.deliver_response(&value) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let request: ProtocolRequest = serde_json::from_value(value).map_err(|error| error.to_string())?;
|
||||
if request.jsonrpc.as_deref() != Some("2.0") {
|
||||
return Err("request does not declare jsonrpc 2.0".to_string());
|
||||
}
|
||||
validate_protocol_name(&request.method).map_err(|error| error.message)?;
|
||||
if request.method == "plugin/initialize" {
|
||||
let id = request.id.ok_or("plugin/initialize must be a request")?;
|
||||
if let Some(host) = host_client() {
|
||||
host.note_host_description(&request.params);
|
||||
}
|
||||
let supported = request
|
||||
.params
|
||||
.get("host")
|
||||
@@ -425,6 +734,162 @@ mod tests {
|
||||
let mut reader = Cursor::new(b"12345\n".to_vec());
|
||||
assert!(read_limited_line(&mut reader, 4).unwrap_err().to_string().contains("too large"));
|
||||
}
|
||||
|
||||
use super::{
|
||||
host_client, install_host_client, request_user_input, HostClient, PluginTransport, UserInputAnswer,
|
||||
UserInputOption, UserInputPrompt, HOST_CLIENT, HOST_REQUEST_USER_INPUT_METHOD,
|
||||
};
|
||||
use std::thread;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// Output sink that records every frame the plugin writes.
|
||||
#[derive(Clone, Default)]
|
||||
struct RecordingOutput(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
impl RecordingOutput {
|
||||
fn lines(&self) -> Vec<Value> {
|
||||
let bytes = self.0.lock().unwrap().clone();
|
||||
String::from_utf8(bytes)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.filter(|line| !line.trim().is_empty())
|
||||
.map(|line| serde_json::from_str(line).unwrap())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Write for RecordingOutput {
|
||||
fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
|
||||
self.0.lock().unwrap().extend_from_slice(buffer);
|
||||
Ok(buffer.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn recording_client() -> (HostClient, RecordingOutput) {
|
||||
let output = RecordingOutput::default();
|
||||
let sink: Arc<Mutex<Box<dyn std::io::Write + Send>>> = Arc::new(Mutex::new(Box::new(output.clone())));
|
||||
let client = HostClient::new(sink, PluginTransport::JsonLines);
|
||||
install_host_client(client.clone());
|
||||
(client, output)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_client_routes_answers_and_gates_on_advertised_features() {
|
||||
let (client, output) = recording_client();
|
||||
assert!(!client.supports(HOST_REQUEST_USER_INPUT_METHOD));
|
||||
assert_eq!(client.host_api_version(), None);
|
||||
|
||||
client.note_host_description(&serde_json::json!({
|
||||
"host": { "hostApiVersion": "1.1.0", "features": [HOST_REQUEST_USER_INPUT_METHOD] }
|
||||
}));
|
||||
assert_eq!(client.host_api_version().as_deref(), Some("1.1.0"));
|
||||
assert!(client.supports(HOST_REQUEST_USER_INPUT_METHOD));
|
||||
|
||||
let prompt = UserInputPrompt::secret("Verification code")
|
||||
.with_title("Bastion MFA")
|
||||
.with_default("000000")
|
||||
.with_timeout_secs(120);
|
||||
let caller = {
|
||||
let client = client.clone();
|
||||
thread::spawn(move || client.request_user_input(&prompt))
|
||||
};
|
||||
|
||||
// Simulate the host answering the outbound request.
|
||||
let request = loop {
|
||||
if let Some(request) = output
|
||||
.lines()
|
||||
.into_iter()
|
||||
.find(|line| line["method"] == HOST_REQUEST_USER_INPUT_METHOD)
|
||||
{
|
||||
break request;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
};
|
||||
assert_eq!(request["params"]["prompt"], "Verification code");
|
||||
assert_eq!(request["params"]["title"], "Bastion MFA");
|
||||
assert_eq!(request["params"]["default"], "000000");
|
||||
assert_eq!(request["params"]["timeoutSecs"], 120);
|
||||
assert_eq!(request["params"]["echo"], false);
|
||||
assert!(request["params"].get("options").is_none());
|
||||
|
||||
assert!(client.deliver_response(&serde_json::json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": request["id"],
|
||||
"result": { "action": "submit", "value": "123456" }
|
||||
})));
|
||||
// Host -> plugin requests and unknown answers stay on the server path.
|
||||
assert!(!client.deliver_response(&serde_json::json!({ "jsonrpc": "2.0", "id": 1, "method": "connection/test" })));
|
||||
assert!(!client.deliver_response(&serde_json::json!({ "jsonrpc": "2.0", "id": "plugin-999", "result": {} })));
|
||||
|
||||
let answer = caller.join().unwrap().unwrap();
|
||||
assert_eq!(answer.submitted(), Some("123456"));
|
||||
assert!(!answer.is_cancelled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_client_surfaces_host_errors_cancels_and_timeouts() {
|
||||
let (client, output) = recording_client();
|
||||
|
||||
let error_call = {
|
||||
let client = client.clone();
|
||||
thread::spawn(move || client.request_user_input(&UserInputPrompt::text("Account")))
|
||||
};
|
||||
let request = loop {
|
||||
if let Some(request) = output.lines().into_iter().find(|line| line["method"] == HOST_REQUEST_USER_INPUT_METHOD) {
|
||||
break request;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
};
|
||||
assert!(client.deliver_response(&serde_json::json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": request["id"],
|
||||
"error": { "code": -32001, "message": "The DBX host cannot ask the user for input right now" }
|
||||
})));
|
||||
let error = error_call.join().unwrap().unwrap_err();
|
||||
assert_eq!(error.code, -32001);
|
||||
assert!(error.message.contains("cannot ask the user"));
|
||||
|
||||
// A cancel carries no value, so callers fail closed.
|
||||
let cancel = UserInputAnswer { action: "cancel".to_string(), value: None };
|
||||
assert_eq!(cancel.submitted(), None);
|
||||
assert!(cancel.is_cancelled());
|
||||
let timeout = UserInputAnswer { action: "timeout".to_string(), value: Some("ignored".to_string()) };
|
||||
assert_eq!(timeout.submitted(), None);
|
||||
assert!(timeout.is_timeout());
|
||||
|
||||
let timed_out = client
|
||||
.request_with_timeout("host/requestUserInput", serde_json::json!({ "prompt": "x" }), Duration::from_millis(30))
|
||||
.unwrap_err();
|
||||
assert!(timed_out.message.contains("did not answer"), "{}", timed_out.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_input_prompt_builders_match_the_host_contract() {
|
||||
assert_eq!(
|
||||
serde_json::to_value(UserInputPrompt::secret("Code")).unwrap(),
|
||||
serde_json::json!({ "prompt": "Code", "echo": false })
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(UserInputPrompt::choice(
|
||||
"Account",
|
||||
vec![UserInputOption { value: "deploy".to_string(), label: "deploy".to_string() }]
|
||||
))
|
||||
.unwrap(),
|
||||
serde_json::json!({
|
||||
"prompt": "Account",
|
||||
"echo": true,
|
||||
"options": [{ "value": "deploy", "label": "deploy" }]
|
||||
})
|
||||
);
|
||||
// The convenience wrapper needs a running server to talk to.
|
||||
HOST_CLIENT.lock().unwrap().take();
|
||||
assert!(request_user_input(&UserInputPrompt::secret("Code")).is_err());
|
||||
assert!(host_client().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
fn io_error(error: io::Error) -> PluginError {
|
||||
|
||||
Reference in new issue
Block a user