From 9bb9590be22e5667573faf5073a029eb29a2e12b Mon Sep 17 00:00:00 2001 From: "blu@blu.cx" <38222767+thebrandonlucas@users.noreply.github.com> Date: Wed, 7 Oct 2026 07:53:29 -0500 Subject: [PATCH] feat(cli): add noninteractive controls and interrupt-safe progress Add global --no-input and -q/--quiet, route stderr diagnostics through a Terminal helper that separates optional progress and notices from confirmation and recovery information, and show cancellable status on interactive stderr only. Terminal::during ties a status line to the one future it describes, so it clears on completion, error, or cancellation and cannot leak into a result. Ctrl-C exits 130 and wins at prompts. The interrupt handler is installed before the command runs, and terminal prompts, stdin, and --data or credential file reads run on a detached thread so a blocked read cannot hold the process. A hidden prompt saves the terminal attributes and restores them when cancelled, and a Ctrl-C typed at it, which rpassword raises as SIGINT itself, is reported as an interruption rather than an I/O failure. Every write is recorded immediately before it is sent, and an in-flight login change (token refresh, device login, or logout revoke) is recorded until its local side is saved. An interruption reports that no resource change was submitted, how to recover a login change, or an unknown outcome with the original ID; it never claims a write was cancelled. A fresh saved login is used without the credential lock, which is now taken only to refresh, so parallel commands no longer run one at a time. A const assertion keeps LOCK_TIMEOUT at least twice AUTH_TIMEOUT. Logout keeps the lock across revoke so a concurrent refresh cannot leave the new session live. TerminalModes' unsafe calls are an approved exception in the style guide. --- Cargo.toml | 2 +- README.md | 6 +- docs/quality.md | 4 + src/api.rs | 343 +++++++++++++++--- src/auth.rs | 167 ++++++--- src/cli.rs | 13 +- src/config.rs | 28 +- src/input.rs | 54 ++- src/lib.rs | 1 + src/startup.rs | 80 +++-- src/terminal.rs | 152 ++++++++ tests/cli_integration.rs | 751 ++++++++++++++++++++++++++++++++++++++- 12 files changed, 1439 insertions(+), 162 deletions(-) create mode 100644 src/terminal.rs diff --git a/Cargo.toml b/Cargo.toml index 9812217..1ec5aba 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,7 @@ clap_complete = "=4.6.11" serde = { version = "=1.0.229", features = ["derive"] } serde_json = { version = "=1.0.151", features = ["arbitrary_precision"] } toml = "=1.1.6" -tokio = { version = "=1.53.1", features = ["macros", "rt-multi-thread", "time", "signal"] } +tokio = { version = "=1.53.1", features = ["macros", "rt-multi-thread", "time", "signal", "sync"] } reqwest = { version = "=0.13.5", default-features = false, features = ["rustls-no-provider", "json", "form", "query", "stream"] } # The TLS provider is ring, installed at startup; aws-lc-rs would need a C toolchain on every platform. rustls = { version = "=0.23.45", default-features = false, features = ["ring", "std", "tls12"] } diff --git a/README.md b/README.md index ba33f6f..cca1fef 100644 --- a/README.md +++ b/README.md @@ -170,9 +170,9 @@ voltage payments get PAYMENT_ID --profile prod --wait completed --timeout 120 For a BOLT11 receive, `--qr` prints the invoice as a terminal QR code and `--copy` puts it on the clipboard as soon as it is ready. Either flag implies `--wait ready`; with `--wait completed` the invoice is shown first and polling continues to settlement. -Sends, treasury movements, deletes, webhook key rotation, and disabling a credit line ask for confirmation after printing the resolved scope and request to stderr. Non-interactive use needs `--yes`. +Sends, treasury movements, deletes, webhook key rotation, and disabling a credit line ask for confirmation after printing the resolved scope and request to stderr. Non-interactive use needs `--yes`. `--no-input` forbids prompts even on a terminal: use `--yes --no-input` to approve a consequential action, and supply credentials via environment, private file, or `--stdin` (for `auth import-key`). `--yes` never supplies a secret. -Payments and treasury movements carry an ID, generated for you unless you pass `--id`. Before sending, the CLI records the ID, operation, scope, and request hash (never the body) in a private journal under `requests/`, and it refuses to reuse an ID with a different request. If the connection drops after a submission, the CLI makes one short read of the ID: if the payment is visible, it reports acceptance; otherwise it exits with code 4 and the ID, without resubmitting. Check the ID before deciding to retry. Ctrl-C exits with code 130 and never cancels a submitted payment. +Payments and treasury movements carry an ID, generated for you unless you pass `--id`. Before sending, the CLI records the ID, operation, scope, and request hash (never the body) in a private journal under `requests/`, and it refuses to reuse an ID with a different request. If the connection drops after a submission, the CLI makes one short read of the ID: if the payment is visible, it reports acceptance; otherwise it exits with code 4 and the ID, without resubmitting. Check the ID before deciding to retry. Ctrl-C exits with code 130, including at a confirmation prompt: before a write is sent it reports that no resource change was submitted, or, if a login was being refreshed, created, or logged out, how to recover it; once a write may have been sent it reports the outcome as unknown, with the original ID and reconciliation instructions for a payment. It never cancels a submitted request. ## Output @@ -182,7 +182,7 @@ On a terminal, results are readable tables; when piped, they are JSON. `--json` {"http_status":202,"data":null,"resource_id":"PAYMENT_ID","outcome":"accepted"} ``` -API fields stay inside `data`. With `--all`, JSON output collects the pages into `data.pages`, and NDJSON writes one envelope per page as it arrives. Diagnostics, prompts, and progress go to stderr. Human errors start with `error:` and may include a safe `hint:`; `--json` makes command-line parse errors machine-readable as well as runtime errors. A downstream consumer that closes stdout early is treated as successful pipeline completion. +API fields stay inside `data`. With `--all`, JSON output collects the pages into `data.pages`, and NDJSON writes one envelope per page as it arrives. Diagnostics, prompts, and progress go to stderr. Interactive stderr shows immediate, cancellable status for network requests and waits; redirected stderr gets no spinner/control codes. `-q, --quiet` suppresses optional status and notices, never requested results, errors, confirmation details, warnings, or recovery IDs. Human errors start with `error:` and may include a safe `hint:`; `--json` makes command-line parse errors machine-readable as well as runtime errors. A downstream consumer that closes stdout early is treated as successful pipeline completion. Known secret fields and the credentials the CLI presented are redacted from normal output and from error details. Operations that return a one-time secret (webhook creation and key rotation, checkout sessions, stream tokens) refuse to run unless you pass `--output-file PATH`, which writes the complete response to a new owner-only file, or `--show-secrets`. Treat your own metadata as potentially sensitive; redaction cannot recognise it. diff --git a/docs/quality.md b/docs/quality.md index 8e852f7..5341d40 100644 --- a/docs/quality.md +++ b/docs/quality.md @@ -201,6 +201,10 @@ an existing simpler pattern cannot satisfy it. - `check_owner` in `config.rs` calls `libc::geteuid` in an `unsafe` block because std has no safe effective-UID accessor; the block is one call with a `SAFETY:` comment. +- `TerminalModes` in `terminal.rs` calls `libc::tcgetattr` and `libc::tcsetattr` + in `unsafe` blocks because std cannot save or restore terminal attributes. It + restores echo when Ctrl-C cancels a hidden prompt whose read cannot return; + each block is one call with a `SAFETY:` comment. - `config`, `registry`, and `secret` are public modules. The integration suite seeds saved credentials through the real persistence boundary and walks the operation contract to exercise every route; no other item is diff --git a/src/api.rs b/src/api.rs index d97f07a..d778fe5 100644 --- a/src/api.rs +++ b/src/api.rs @@ -17,13 +17,15 @@ use crate::{ payment::{PaymentDirection, PaymentView, ReceiveKind, StatusText, WaitProgress, WaitTarget}, registry::{AuthScheme, Method, Operation, OperationId}, secret::Secret, + terminal::Terminal, }; use futures_util::StreamExt; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::Value; use std::{ collections::BTreeSet, - io::{IsTerminal, Write}, + io::Write, + sync::{Mutex, OnceLock, PoisonError}, time::Duration, }; use tokio::time::Instant; @@ -62,27 +64,18 @@ impl Authorization { global: &GlobalFlags, settings: &Settings, scope: &Scope, + submission: &SubmissionState, ) -> Result { let scheme = invocation.operation.auth; - let checkout_token = |variable: &str| -> Result { - if let Some(source) = &invocation.token_file { - return read_secret(source); - } - std::env::var(variable) - .ok() - .map(Secret::new) - .filter(|secret| !secret.expose().trim().is_empty()) - .ok_or_else(|| Error::auth(format!("Supply --token-file or {variable}"))) - }; Ok(match scheme { - AuthScheme::Account => { - Self::Account(auth::resolve_organization(settings, scope, global).await?) - } + AuthScheme::Account => Self::Account( + auth::resolve_organization(settings, scope, global, submission).await?, + ), AuthScheme::CheckoutSession => { - Self::CheckoutSession(checkout_token("VOLTAGE_CHECKOUT_TOKEN")?) + Self::CheckoutSession(checkout_token(invocation, "VOLTAGE_CHECKOUT_TOKEN").await?) } AuthScheme::CheckoutStream => { - Self::CheckoutStream(checkout_token("VOLTAGE_STREAM_TOKEN")?) + Self::CheckoutStream(checkout_token(invocation, "VOLTAGE_STREAM_TOKEN").await?) } AuthScheme::None => Self::None, }) @@ -100,6 +93,18 @@ impl Authorization { } } +/// A checkout credential from `--token-file`, else from `variable`. +async fn checkout_token(invocation: &ApiInvocation, variable: &str) -> Result { + if let Some(source) = &invocation.token_file { + return read_secret(source).await; + } + std::env::var(variable) + .ok() + .map(Secret::new) + .filter(|secret| !secret.expose().trim().is_empty()) + .ok_or_else(|| Error::auth(format!("Supply --token-file or {variable}"))) +} + struct Response { status: u16, body: Value, @@ -112,6 +117,7 @@ struct Api { base: String, authorization: Authorization, origin: Option, + terminal: Terminal, } impl Api { @@ -125,6 +131,7 @@ impl Api { base: auth::base_url(global.api_url.as_deref().unwrap_or(API_URL))?, authorization, origin: invocation.origin.clone(), + terminal: global.terminal(), }) } @@ -173,6 +180,11 @@ impl Api { body: Option<&Value>, ) -> Result { let read_only = method.is_read_only(); + let _progress = self.terminal.progress(if read_only { + "Waiting for API response..." + } else { + "Submitting request..." + }); let response = self .request(method.into(), path, query, body) .send() @@ -234,8 +246,12 @@ impl Api { /// Follow a checkout event stream, writing one envelope per event until it closes. async fn stream(&self, request: &Request, out: &mut Output) -> Result<()> { let response = self - .request(reqwest::Method::GET, &request.path, &request.query, None) - .send() + .terminal + .during( + "Opening checkout event stream...", + self.request(reqwest::Method::GET, &request.path, &request.query, None) + .send(), + ) .await .map_err(|_| Error::transport("Could not open checkout event stream"))?; let status = response.status().as_u16(); @@ -256,7 +272,12 @@ impl Api { let mut stream = response.bytes_stream(); let mut pending = Vec::new(); let mut assembler = EventAssembler::default(); - while let Some(chunk) = stream.next().await { + loop { + let chunk = self + .terminal + .during("Waiting for checkout event...", stream.next()) + .await; + let Some(chunk) = chunk else { break }; let chunk = chunk.map_err(|_| Error::transport("Checkout stream disconnected"))?; pending.extend_from_slice(&chunk); if pending.len() > MAX_EVENT_BYTES { @@ -431,20 +452,27 @@ pub async fn execute( settings: &Settings, scope: &Scope, out: &mut Output, + submission: &SubmissionState, ) -> Result<()> { let operation = invocation.operation; - let mut request = Request::build(invocation, scope)?; + let mut request = Request::read(invocation, scope).await?; check_invoice_flags(invocation, &request)?; if operation.id.returns_one_time_secret() && !out.secure_destination() { return Err(Error::usage( "This operation returns a one-time secret; supply --output-file PATH or --show-secrets before executing", )); } - let authorization = Authorization::resolve(invocation, global, settings, scope).await?; + // Decline a noninteractive confirmation before refreshing credentials or making + // a wallet preflight request. The summary is still mandatory even in quiet mode. + if request.is_consequential(operation) && !global.yes && !global.terminal().can_prompt() { + return confirm(operation, scope, &request, global).await; + } + let authorization = + Authorization::resolve(invocation, global, settings, scope, submission).await?; let api = Api::new(global, invocation, authorization)?; let deadline = Instant::now() + global.timeout; if request.pagination_mode() == PaginationMode::Offset && operation.has_parameter("cursor") { - eprintln!( + api.terminal.important( "Offset pagination is deprecated by the API; omit --offset and --pagination to page by cursor." ); } @@ -455,7 +483,7 @@ pub async fn execute( let Submission { mut response, reconciled, - } = submit(&api, invocation, &request, scope).await?; + } = submit(&api, invocation, &request, scope, submission).await?; check_response(invocation, &response, scope)?; if let Some(until) = wait_target(invocation) { return wait_for_payment( @@ -494,12 +522,12 @@ async fn guard_submission( verify_wallet_environment(api, scope, invocation.resource_id).await?; } if request.is_consequential(operation) { - confirm(operation, scope, request, global.yes)?; + confirm(operation, scope, request, global).await?; } if operation.method != Method::Get && let (Some(body), Some(id)) = (&request.body, request.body_id) { - journal(settings, operation, scope, body, id)?; + journal(settings, operation, scope, body, id, api.terminal)?; } Ok(()) } @@ -582,7 +610,13 @@ struct ConfirmationSummary<'a> { } /// Show the resolved scope and request on stderr, then require `--yes` or a terminal answer. -fn confirm(operation: &Operation, scope: &Scope, request: &Request, yes: bool) -> Result<()> { +async fn confirm( + operation: &Operation, + scope: &Scope, + request: &Request, + global: &GlobalFlags, +) -> Result<()> { + let terminal = global.terminal(); let mut summary = serde_json::to_value(ConfirmationSummary { action: operation.command.join(" "), organization: scope.org, @@ -591,25 +625,21 @@ fn confirm(operation: &Operation, scope: &Scope, request: &Request, yes: bool) - request: request.body.as_ref(), })?; redact(&mut summary, &[]); - eprintln!("{}", serde_json::to_string_pretty(&summary)?); + terminal.important(serde_json::to_string_pretty(&summary)?); if operation.id == OperationId::CreatePayment { - eprintln!( + terminal.important( "Network/provider fee limits exclude additional processing fees. The wallet determines the network." ); } - if yes { + if global.yes { return Ok(()); } - if !std::io::stdin().is_terminal() { + if !terminal.can_prompt() { return Err(Error::usage( - "This operation requires --yes in noninteractive use", + "This operation requires --yes when input is disabled or noninteractive", )); } - eprint!("Proceed? [y/N] "); - std::io::stderr().flush()?; - let mut reply = String::new(); - std::io::stdin().read_line(&mut reply)?; - if !matches!(reply.trim(), "y" | "Y" | "yes") { + if !terminal.confirm("Proceed?").await? { return Err(Error::usage("Operation cancelled before submission")); } Ok(()) @@ -643,6 +673,7 @@ fn journal( scope: &Scope, body: &Value, id: Uuid, + terminal: Terminal, ) -> Result<()> { use sha2::{Digest, Sha256}; private_dir(&settings.dir)?; @@ -669,10 +700,102 @@ fn journal( let mut file = new_private(&path)?; file.write_all(&serde_json::to_vec(&record)?)?; file.sync_all()?; - eprintln!("Resource ID: {id}. Recovery record: {}", path.display()); + terminal.important(format!( + "Resource ID: {id}. Recovery record: {}", + path.display() + )); Ok(()) } +/// What this command may have changed, for reporting an interruption. A write is recorded +/// immediately before the request leaves the process, never during validation, confirmation, +/// or wallet preflight: once sending starts, a cancelled future cannot tell whether the +/// service received the request. +#[derive(Default)] +pub struct SubmissionState { + write: OnceLock, + /// A change to a saved login whose server side may be done but whose local side is not. + /// Cleared only once the local side is done, never on drop: Ctrl-C drops the command + /// before the interruption is reported. + session: Mutex>, +} + +/// A login change that the server and the saved credentials can disagree about. +pub(crate) enum SessionChange { + /// The single-use refresh token may be spent, but its replacement is not yet saved. + Refresh { account: String }, + /// The server may have issued a session that is not yet saved. + Login, + /// The server may have revoked the session, but the saved login is not yet removed. + Logout { account: String }, +} + +struct SubmittedWrite { + operation: OperationId, + resource_id: Option, + organization_id: Option, + environment_ids: Vec, +} + +impl SubmissionState { + /// A command sends at most one mutation, so the first record is the only one. + fn record(&self, operation: OperationId, resource_id: Option, scope: &Scope) { + let _ = self.write.set(SubmittedWrite { + operation, + resource_id, + organization_id: scope.org, + environment_ids: scope.envs.clone(), + }); + } + + pub(crate) fn session_changing(&self, change: SessionChange) { + *self.session.lock().unwrap_or_else(PoisonError::into_inner) = Some(change); + } + + pub(crate) fn session_settled(&self) { + *self.session.lock().unwrap_or_else(PoisonError::into_inner) = None; + } + + /// The error for Ctrl-C. It claims a write may continue only when one may have been sent, + /// and never claims that the write was cancelled. A sent write outranks a session change, + /// which always comes first. + pub fn interrupted(&self) -> Error { + let Some(write) = self.write.get() else { + let session = self.session.lock().unwrap_or_else(PoisonError::into_inner); + return match &*session { + Some(SessionChange::Refresh { account }) => Error::interrupted(format!( + "Interrupted while refreshing the saved login for {account}" + )) + .with_hint( + "If the next command reports an expired session, run voltage login again.", + ), + Some(SessionChange::Login) => Error::interrupted( + "Interrupted after sign-in may have created a session that was not saved", + ) + .with_hint( + "Run voltage login again; account global signout ends an unsaved session.", + ), + Some(SessionChange::Logout { account }) => Error::interrupted(format!( + "Interrupted while logging out {account}; its session may already be revoked" + )) + .with_hint("Rerun the logout with --local to remove the saved login."), + None => Error::interrupted("Interrupted before any resource change was submitted"), + }; + }; + let message = match write.resource_id { + Some(id) if write.operation.submits_payment() => format!( + "Interrupted after payment {id} may have been submitted; query its original ID before resubmitting. The payment was not cancelled." + ), + _ => "Interrupted after the request may have been submitted; check its result before retrying. The request was not cancelled.".to_owned(), + }; + Error::interrupted(message).with_detail(ErrorDetail::uncertain_submission( + write.resource_id, + write.organization_id, + write.environment_ids.clone(), + )) + } +} + struct Submission { response: Response, /// The mutation's transport failed, but reading the original ID proved acceptance. @@ -686,8 +809,12 @@ async fn submit( invocation: &ApiInvocation, request: &Request, scope: &Scope, + submission: &SubmissionState, ) -> Result { let operation = invocation.operation; + if operation.method != Method::Get { + submission.record(operation.id, request.resource_id, scope); + } let result = api .send( operation.method, @@ -754,9 +881,9 @@ async fn reconcile_payment(api: &Api, request: &Request, scope: &Scope) -> Optio if PaymentView::from_body(&found.body).id != Some(id) { return None; } - eprintln!( + api.terminal.important(format!( "Payment {id} is visible after the interrupted submission; reconciled by reading its original ID." - ); + )); Some(found) } @@ -785,7 +912,8 @@ async fn wait_for_payment( ); let target = until.as_str(); if invocation.operation.method != Method::Get { - eprintln!("Payment {id} accepted; waiting for {target}."); + api.terminal + .important(format!("Payment {id} accepted; waiting for {target}.")); } let mut backoff = Backoff::new( match until { @@ -804,10 +932,10 @@ async fn wait_for_payment( && (Some(status) != last_status.as_ref() || last_notice.elapsed() >= STATUS_NOTICE_INTERVAL) { - eprintln!( + api.terminal.notice(format!( "Payment {id} status: {}; waiting for {target}.", status.as_str() - ); + )); last_status = Some(status.clone()); last_notice = Instant::now(); } @@ -815,10 +943,11 @@ async fn wait_for_payment( && !invoice_presented && let Some(invoice) = view.invoice() { - present_invoice(invoice, invocation)?; + present_invoice(invoice, invocation, api.terminal)?; invoice_presented = true; if until == WaitTarget::Completed { - eprintln!("Invoice is ready; continuing to poll for settlement."); + api.terminal + .notice("Invoice is ready; continuing to poll for settlement."); } } match view.progress(until) { @@ -834,6 +963,7 @@ async fn wait_for_payment( Error::usage("The ready payment does not contain a BOLT11 invoice") })?, invocation, + api.terminal, )?; } return out.write( @@ -866,12 +996,12 @@ async fn wait_for_payment( } /// Copy and render a ready BOLT11 invoice as requested; both go to stderr. -fn present_invoice(invoice: &str, invocation: &ApiInvocation) -> Result<()> { +fn present_invoice(invoice: &str, invocation: &ApiInvocation, terminal: Terminal) -> Result<()> { if invocation.copy { match arboard::Clipboard::new().and_then(|mut clipboard| clipboard.set_text(invoice)) { - Ok(()) => eprintln!("Invoice copied to the clipboard."), - Err(_) => eprintln!( - "Warning: the invoice is ready, but it could not be copied to the clipboard." + Ok(()) => terminal.notice("Invoice copied to the clipboard."), + Err(_) => terminal.important( + "Warning: the invoice is ready, but it could not be copied to the clipboard.", ), } } @@ -892,7 +1022,7 @@ fn present_invoice(invoice: &str, invocation: &ApiInvocation) -> Result<()> { .map(|line| format!(" {line} ")) .collect::>() .join("\n"); - eprintln!("\nScan to pay:\n\n{image}\n"); + terminal.important(format!("\nScan to pay:\n\n{image}\n")); } Ok(()) } @@ -910,7 +1040,12 @@ async fn await_session_projection( if Instant::now() + pause >= deadline { return Err(Error::timeout("Checkout session projection is not ready")); } - tokio::time::sleep(pause).await; + api.terminal + .during( + "Waiting for checkout session projection...", + tokio::time::sleep(pause), + ) + .await; response = tokio::time::timeout_at( deadline, api.send(Method::Get, &request.path, &request.query, None), @@ -1089,7 +1224,7 @@ mod tests { } fn list_request(args: &[&str]) -> Request { - Request::build(&invocation(args), &scope()).unwrap() + Request::build(&invocation(args), &scope(), None).unwrap() } fn api(authorization: Authorization) -> Api { @@ -1098,6 +1233,7 @@ mod tests { base: "https://api.example.test/v1".into(), authorization, origin: None, + terminal: Terminal::new(false, false), } } @@ -1279,6 +1415,97 @@ mod tests { assert_eq!(error.message, "Event exceeds 1 MiB"); } + #[test] + fn interruption_claims_a_possible_submission_only_after_a_write_starts() { + let submission = SubmissionState::default(); + let before = submission.interrupted(); + assert_eq!(before.kind, ErrorKind::Interrupted); + assert_eq!( + before.message, + "Interrupted before any resource change was submitted" + ); + assert!(before.detail.is_none()); + + let id = Uuid::nil(); + submission.record(OperationId::CreatePayment, Some(id), &scope()); + // Only the first write is the command's submission. + submission.record(OperationId::DeleteWallet, None, &scope()); + let after = submission.interrupted(); + assert!( + after + .message + .contains(&format!("payment {id} may have been submitted")) + ); + assert!(after.message.contains("was not cancelled")); + let detail = serde_json::to_value(after.detail.unwrap()).unwrap(); + assert_eq!(detail["resource_id"], json!(id)); + assert_eq!(detail["organization_id"], json!(ORG)); + assert_eq!(detail["outcome"], "unknown"); + } + + #[test] + fn interruption_during_a_session_change_says_how_to_recover_until_it_settles() { + let submission = SubmissionState::default(); + for (change, message, hint) in [ + ( + SessionChange::Refresh { + account: "person".into(), + }, + "Interrupted while refreshing the saved login for person", + "voltage login", + ), + ( + SessionChange::Login, + "Interrupted after sign-in may have created a session that was not saved", + "voltage login", + ), + ( + SessionChange::Logout { + account: "person".into(), + }, + "Interrupted while logging out person; its session may already be revoked", + "--local", + ), + ] { + submission.session_changing(change); + let during = submission.interrupted(); + assert_eq!(during.message, message); + assert!(during.hint.unwrap().contains(hint)); + assert!(during.detail.is_none()); + + submission.session_settled(); + let after = submission.interrupted(); + assert_eq!( + after.message, + "Interrupted before any resource change was submitted" + ); + } + + // A sent write outranks a session change that has not settled. + submission.session_changing(SessionChange::Refresh { + account: "person".into(), + }); + submission.record(OperationId::DeleteWallet, None, &scope()); + assert!( + submission + .interrupted() + .message + .contains("may have been submitted") + ); + } + + #[test] + fn interruption_after_another_write_is_uncertain_without_naming_a_payment() { + let submission = SubmissionState::default(); + submission.record(OperationId::DeleteWallet, None, &scope()); + let error = submission.interrupted(); + assert!(!error.message.contains("payment")); + assert!(error.message.contains("may have been submitted")); + let detail = serde_json::to_value(error.detail.unwrap()).unwrap(); + assert!(detail["resource_id"].is_null()); + assert_eq!(detail["outcome"], "unknown"); + } + #[test] fn journal_rejects_the_same_id_for_a_different_request() { let dir = tempfile::tempdir().unwrap(); @@ -1294,16 +1521,18 @@ mod tests { let create_payment = operation(OperationId::CreatePayment); let id = Uuid::nil(); let body = json!({"id": id, "wallet_id": WALLET}); - journal(&settings, create_payment, &scope(), &body, id).unwrap(); - journal(&settings, create_payment, &scope(), &body, id).unwrap(); + let terminal = Terminal::new(false, false); + journal(&settings, create_payment, &scope(), &body, id, terminal).unwrap(); + journal(&settings, create_payment, &scope(), &body, id, terminal).unwrap(); let changed = json!({"id": id, "wallet_id": ORG}); - let error = journal(&settings, create_payment, &scope(), &changed, id).unwrap_err(); + let error = + journal(&settings, create_payment, &scope(), &changed, id, terminal).unwrap_err(); assert_eq!(error.kind, ErrorKind::Usage); let other_scope = Scope { envs: Vec::new(), ..scope() }; - assert!(journal(&settings, create_payment, &other_scope, &body, id).is_err()); + assert!(journal(&settings, create_payment, &other_scope, &body, id, terminal).is_err()); let record: JournalRecord = serde_json::from_str( &std::fs::read_to_string(dir.path().join(JOURNAL_DIR).join(format!("{id}.json"))) .unwrap(), @@ -1328,7 +1557,7 @@ mod tests { "bolt11", "--qr", ]); - let request = Request::build(&receive, &scope()).unwrap(); + let request = Request::build(&receive, &scope(), None).unwrap(); assert!(check_invoice_flags(&receive, &request).is_ok()); let onchain = invocation(&[ "payments", @@ -1339,7 +1568,7 @@ mod tests { "onchain", "--copy", ]); - let request = Request::build(&onchain, &scope()).unwrap(); + let request = Request::build(&onchain, &scope(), None).unwrap(); assert_eq!( check_invoice_flags(&onchain, &request).unwrap_err().message, "--qr and --copy require a BOLT11 receive (--kind bolt11)" diff --git a/src/auth.rs b/src/auth.rs index 44b86f4..20f8591 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -6,19 +6,18 @@ use crate::{ Error, Result, + api::{SessionChange, SubmissionState}, cli::{GlobalFlags, ImportKeyFlags, LoginFlags}, config::{ - AUTH_URL, Account, AccountKind, Credential, InputSource, Login, Scope, Settings, - read_secret, + AUTH_URL, Account, AccountKind, Credential, InputSource, LOCK_TIMEOUT, Login, Scope, + Settings, read_secret, }, secret::Secret, + terminal::Terminal, }; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use serde_json::Value; -use std::{ - io::IsTerminal, - time::{Duration, SystemTime, UNIX_EPOCH}, -}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; use zeroize::{Zeroize, Zeroizing}; const CLIENT_ID: &str = "voltage-cli"; @@ -26,6 +25,8 @@ const DEVICE_CODE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code"; const TOKEN_EXCHANGE_GRANT: &str = "urn:ietf:params:oauth:grant-type:token-exchange"; const ACCESS_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:access_token"; const AUTH_TIMEOUT: Duration = Duration::from_secs(30); +// A credential lock holder makes at most one auth request, so a waiter must outlast it. +const _: () = assert!(LOCK_TIMEOUT.as_secs() >= 2 * AUTH_TIMEOUT.as_secs()); /// Access tokens this close to expiry are refreshed before use. const REFRESH_MARGIN: u64 = 30; /// Device approval waits are bounded regardless of the server's `expires_in`. @@ -164,7 +165,11 @@ async fn bounded_body(mut response: reqwest::Response, limit: usize) -> Result Result { +async fn auth_request( + request: reqwest::RequestBuilder, + terminal: Terminal, +) -> Result { + let _progress = terminal.progress("Waiting for auth service..."); let response = request.send().await.map_err(|_| { Error::transport( "Authentication request failed; no token request was automatically retried", @@ -356,6 +361,7 @@ pub async fn login( settings: &mut Settings, flags: &LoginFlags, global: &GlobalFlags, + submission: &SubmissionState, ) -> Result { let url = base_url(global.auth_url.as_deref().unwrap_or(AUTH_URL))?; if let Some(name) = &global.account @@ -366,34 +372,37 @@ pub async fn login( )); } let client = client(AUTH_TIMEOUT)?; + let terminal = global.terminal(); let response = auth_request( client .post(format!("{url}/oauth/device_authorization")) .form(&[("client_id", CLIENT_ID)]), + terminal, ) .await?; response.require_success()?; let device: DeviceAuthorization = response.json("Invalid device authorization response")?; let verification = device.verification_url()?; - eprintln!( + terminal.important(format!( "Open {verification}\nConfirm this code: {}", device.user_code - ); + )); if !flags.no_browser && webbrowser::open(verification).is_err() { - eprintln!("Could not open a browser; open the URL above manually."); + terminal.important("Could not open a browser; open the URL above manually."); } - let token = poll_device_grant(&client, &url, &device).await?; + let token = poll_device_grant(&client, &url, &device, terminal, submission).await?; let login = token.into_login(None, None)?; let session = Secret::new(login.refresh_token.expose().to_owned()); let saved = save_login(settings, login, flags, global, &client, &url).await; if saved.is_err() { // A local storage/discovery failure must not silently orphan a remote session. - if revoke(&client, &url, &session).await.is_err() { - eprintln!( + if revoke(&client, &url, &session, terminal).await.is_err() { + terminal.important( "Could not revoke the new CLI session after login failed. Use account global signout to invalidate its refresh session." ); } } + submission.session_settled(); saved } @@ -402,6 +411,8 @@ async fn poll_device_grant( client: &reqwest::Client, url: &str, device: &DeviceAuthorization, + terminal: Terminal, + submission: &SubmissionState, ) -> Result { let expires = device.expires_in.min(MAX_LOGIN_WAIT); let deadline = tokio::time::Instant::now() + Duration::from_secs(expires); @@ -413,20 +424,32 @@ async fn poll_device_grant( if tokio::time::Instant::now() + Duration::from_secs(interval) >= deadline { return Err(Error::timeout("Login expired; run voltage login again")); } - tokio::time::sleep(Duration::from_secs(interval)).await; + terminal + .during( + "Waiting for device approval...", + tokio::time::sleep(Duration::from_secs(interval)), + ) + .await; + // Any poll can be the one that issues the session, which stays unsaved until login + // finishes; between polls, nothing has been issued. + submission.session_changing(SessionChange::Login); let response = tokio::time::timeout_at( deadline, - auth_request(client.post(format!("{url}/oauth/token")).form(&[ - ("client_id", CLIENT_ID), - ("grant_type", DEVICE_CODE_GRANT), - ("device_code", device.device_code.expose()), - ])), + auth_request( + client.post(format!("{url}/oauth/token")).form(&[ + ("client_id", CLIENT_ID), + ("grant_type", DEVICE_CODE_GRANT), + ("device_code", device.device_code.expose()), + ]), + terminal, + ), ) .await .map_err(|_| Error::timeout("Login expired"))??; if response.is_success() { return response.json("Invalid token response"); } + submission.session_settled(); let error = response .json::("Invalid authentication response") .ok() @@ -456,6 +479,7 @@ async fn save_login( client .get(format!("{url}/users/current")) .bearer_auth(login.access_token.expose()), + global.terminal(), ) .await?; response.require_success()?; @@ -468,7 +492,7 @@ async fn save_login( .or_else(|| login.email.clone()) .or_else(|| login.user_id.clone()) .ok_or_else(|| Error::auth("User response has no account identity"))?; - let _lock = settings.lock().await?; + let _lock = settings.lock(global.terminal()).await?; settings.reload()?; if settings.config.accounts.contains_key(&name) { return Err(Error::usage(format!( @@ -504,12 +528,20 @@ async fn save_login( } /// Revoke a session whose refresh token the CLI holds. -async fn revoke(client: &reqwest::Client, url: &str, refresh_token: &Secret) -> Result<()> { - auth_request(client.post(format!("{url}/oauth/revoke")).form(&[ - ("client_id", CLIENT_ID), - ("token_type_hint", "refresh_token"), - ("token", refresh_token.expose()), - ])) +async fn revoke( + client: &reqwest::Client, + url: &str, + refresh_token: &Secret, + terminal: Terminal, +) -> Result<()> { + auth_request( + client.post(format!("{url}/oauth/revoke")).form(&[ + ("client_id", CLIENT_ID), + ("token_type_hint", "refresh_token"), + ("token", refresh_token.expose()), + ]), + terminal, + ) .await? .require_success() } @@ -519,6 +551,7 @@ pub async fn resolve( settings: &Settings, scope: &Scope, flags: &GlobalFlags, + submission: &SubmissionState, ) -> Result { if let Some(key) = ambient_api_key(flags) { if key.expose().trim().is_empty() { @@ -551,23 +584,40 @@ pub async fn resolve( "Saved credentials cannot be refreshed at a different auth URL", )); } - let _lock = settings.lock().await?; - let Credential::Login(login) = settings.read_credential(&name)? else { - return Err(Error::auth("Invalid saved credential")); - }; + // Credential writes replace the whole value atomically, so a fresh login is used + // without the lock. Only a refresh, which spends the single-use refresh token, is + // serialized. + let login = saved_login(settings, &name)?; + if login.expires_at > now() + REFRESH_MARGIN { + return Ok(Credential::Login(login)); + } + let _lock = settings.lock(flags.terminal()).await?; + // Another process may have refreshed while this one waited. + let login = saved_login(settings, &name)?; if login.expires_at > now() + REFRESH_MARGIN { return Ok(Credential::Login(login)); } - let refreshed = Credential::Login(refresh(&url, login).await?); + submission.session_changing(SessionChange::Refresh { + account: name.clone(), + }); + let refreshed = Credential::Login(refresh(&url, login, flags.terminal()).await?); settings.write_credential(&name, account.store, &refreshed)?; + submission.session_settled(); Ok(refreshed) } } } +fn saved_login(settings: &Settings, name: &str) -> Result { + match settings.read_credential(name)? { + Credential::Login(login) => Ok(login), + Credential::ApiKey(_) => Err(Error::auth("Invalid saved credential")), + } +} + /// Rotate an expiring login; the refresh token is single use, so the result is saved /// before any caller sees it. -async fn refresh(url: &str, login: Login) -> Result { +async fn refresh(url: &str, login: Login, terminal: Terminal) -> Result { let response = auth_request( client(AUTH_TIMEOUT)? .post(format!("{url}/oauth/token")) @@ -576,6 +626,7 @@ async fn refresh(url: &str, login: Login) -> Result { ("grant_type", "refresh_token"), ("refresh_token", login.refresh_token.expose()), ]), + terminal, ) .await?; response.require_success()?; @@ -589,8 +640,9 @@ pub async fn resolve_organization( settings: &Settings, scope: &Scope, flags: &GlobalFlags, + submission: &SubmissionState, ) -> Result { - let login = match resolve(settings, scope, flags).await? { + let login = match resolve(settings, scope, flags, submission).await? { Credential::ApiKey(key) => return Ok(ApiCredential::ApiKey(key)), Credential::Login(login) => login, }; @@ -606,6 +658,7 @@ pub async fn resolve_organization( ("subject_token_type", ACCESS_TOKEN_TYPE), ("audience", &organization.to_string()), ]), + flags.terminal(), ) .await?; response.require_success()?; @@ -620,8 +673,18 @@ pub async fn resolve_organization( Ok(ApiCredential::OrganizationToken(token.access_token)) } -pub async fn logout(settings: &mut Settings, scope: &Scope, local: bool) -> Result { - let _lock = settings.lock().await?; +pub async fn logout( + settings: &mut Settings, + scope: &Scope, + local: bool, + terminal: Terminal, + submission: &SubmissionState, +) -> Result { + // The lock spans the revoke on purpose. Released, a concurrent refresh could rotate the + // token in between, and logout would revoke the spent token while the new session stays + // live. Logout is rare, and a fresh login is used without the lock, so only refreshes and + // configuration writes wait behind it, for at most AUTH_TIMEOUT. + let _lock = settings.lock(terminal).await?; settings.reload()?; let name = settings.account_name(scope)?; let account = settings.account(&name)?; @@ -632,11 +695,15 @@ pub async fn logout(settings: &mut Settings, scope: &Scope, local: bool) -> Resu )); }; let url = base_url(&account.auth_url)?; - revoke(&client(AUTH_TIMEOUT)?, &url, &login.refresh_token).await?; + submission.session_changing(SessionChange::Logout { + account: name.clone(), + }); + revoke(&client(AUTH_TIMEOUT)?, &url, &login.refresh_token, terminal).await?; } settings.delete_credential(&name)?; settings.config.accounts.remove(&name); settings.save()?; + submission.session_settled(); Ok(LogoutOutcome { account: name, removed: true, @@ -661,22 +728,20 @@ pub async fn import_key( _ => return Err(Error::usage("Exactly one --env is required")), }; let key = if flags.stdin { - read_secret(&InputSource::Stdin)? + read_secret(&InputSource::Stdin).await? } else { - if !std::io::stdin().is_terminal() { + let terminal = global.terminal(); + if !terminal.can_prompt() { return Err(Error::usage( - "Use --stdin to import an API key noninteractively", + "Use --stdin to import an API key when input is disabled or noninteractive (--yes does not supply a key)", )); } - Secret::new( - rpassword::prompt_password("Environment API key: ") - .map_err(|error| Error::transport(error.to_string()))?, - ) + terminal.read_hidden("Environment API key: ").await? }; if key.expose().trim().is_empty() { return Err(Error::usage("API key cannot be empty")); } - let _lock = settings.lock().await?; + let _lock = settings.lock(global.terminal()).await?; settings.reload()?; if settings.config.accounts.contains_key(&name) { return Err(Error::usage("Credential already exists")); @@ -706,17 +771,20 @@ pub async fn discover( scope: &Scope, flags: &GlobalFlags, what: Discovery, + submission: &SubmissionState, ) -> Result { let requires_login = || Error::auth("Organization/environment discovery requires a user login"); let token = match what { - Discovery::Organizations => match resolve(settings, scope, flags).await? { + Discovery::Organizations => match resolve(settings, scope, flags, submission).await? { Credential::Login(login) => login.access_token, Credential::ApiKey(_) => return Err(requires_login()), }, - Discovery::Environments => match resolve_organization(settings, scope, flags).await? { - ApiCredential::OrganizationToken(token) => token, - ApiCredential::ApiKey(_) => return Err(requires_login()), - }, + Discovery::Environments => { + match resolve_organization(settings, scope, flags, submission).await? { + ApiCredential::OrganizationToken(token) => token, + ApiCredential::ApiKey(_) => return Err(requires_login()), + } + } }; let name = settings.account_name(scope)?; let url = base_url(&settings.account(&name)?.auth_url)?; @@ -730,6 +798,7 @@ pub async fn discover( client(AUTH_TIMEOUT)? .get(format!("{url}{path}")) .bearer_auth(token.expose()), + flags.terminal(), ) .await?; response.require_success()?; diff --git a/src/cli.rs b/src/cli.rs index bc67d1b..87c4f78 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -13,6 +13,7 @@ use crate::{ payment::{AmountUnit, Currency, Network, PaymentDirection, ReceiveKind, WaitTarget}, price::ConversionRequest, registry::{OPERATIONS, Operation, OperationId, Parameter, operation}, + terminal::Terminal, }; use clap::{ Arg, ArgAction, ArgMatches, Args, Command as ClapCommand, FromArgMatches, Subcommand, @@ -62,9 +63,15 @@ pub struct GlobalFlags { /// Explicitly allow secrets in result output #[arg(long, global = true, help_heading = "Output")] pub show_secrets: bool, - /// Approve consequential actions without prompting + /// Approve consequential actions without prompting (never supplies a credential) #[arg(short = 'y', long, global = true, help_heading = "Safety")] pub yes: bool, + /// Never prompt for approval or a secret; supply --yes or --stdin as needed + #[arg(long, global = true, help_heading = "Safety")] + pub no_input: bool, + /// Hide optional progress and notices, not errors, results, or recovery IDs + #[arg(short = 'q', long, global = true, help_heading = "Output")] + pub quiet: bool, /// HTTP or wait deadline in seconds #[arg(long, global = true, value_name = "SECONDS", default_value = "60", value_parser = parse_timeout, help_heading = "Request")] pub timeout: Duration, @@ -107,6 +114,10 @@ impl GlobalFlags { OutputFormat::select(self.json, self.output) } + pub fn terminal(&self) -> Terminal { + Terminal::new(self.quiet, self.no_input) + } + pub fn scope_selection(&self) -> ScopeSelection { ScopeSelection { profile: self.profile.clone(), diff --git a/src/config.rs b/src/config.rs index 99bc99f..4a36a43 100644 --- a/src/config.rs +++ b/src/config.rs @@ -4,7 +4,11 @@ //! to the operating system store; file storage is an explicit choice with the same //! ownership and permission checks on every read. -use crate::{Error, Result, secret::Secret}; +use crate::{ + Error, Result, + secret::Secret, + terminal::{Terminal, read_detached}, +}; use clap::ValueEnum; use serde::{Deserialize, Serialize}; use std::{ @@ -24,7 +28,7 @@ const CONFIG_FILE: &str = "config.toml"; const CREDENTIALS_DIR: &str = "credentials"; const LOCK_FILE: &str = "credentials.lock"; const KEYRING_SERVICE: &str = "voltage-cli"; -const LOCK_TIMEOUT: Duration = Duration::from_secs(60); +pub(crate) const LOCK_TIMEOUT: Duration = Duration::from_secs(60); const LOCK_RETRY: Duration = Duration::from_millis(100); #[derive(Clone, Default, Serialize, Deserialize)] @@ -388,7 +392,7 @@ impl Settings { } /// Exclusive process lock for credential and configuration writes. - pub async fn lock(&self) -> Result { + pub async fn lock(&self, terminal: Terminal) -> Result { private_dir(&self.dir)?; let path = self.dir.join(LOCK_FILE); if path.exists() { @@ -405,10 +409,13 @@ impl Settings { let file = options.open(path)?; check_owner(&file.metadata()?)?; let deadline = tokio::time::Instant::now() + LOCK_TIMEOUT; + let mut progress = None; loop { match file.try_lock() { Ok(()) => return Ok(file), Err(TryLockError::WouldBlock) => { + progress + .get_or_insert_with(|| terminal.progress("Waiting for credential lock...")); if tokio::time::Instant::now() >= deadline { return Err(Error::transport("Timed out waiting for credential lock")); } @@ -586,12 +593,15 @@ pub enum InputSource { File(PathBuf), } -/// A credential from stdin or a private file, trimmed and never empty. -pub fn read_secret(source: &InputSource) -> Result { - let raw = match source { - InputSource::Stdin => read_bounded(std::io::stdin(), MAX_PRIVATE_FILE_BYTES)?, - InputSource::File(path) => read_private(path)?, - }; +/// A credential from stdin or a private file, trimmed and never empty. Stdin or a FIFO can +/// block indefinitely, so the read is detached and Ctrl-C still ends the command. +pub async fn read_secret(source: &InputSource) -> Result { + let source = source.clone(); + let raw = read_detached(move || match &source { + InputSource::Stdin => read_bounded(std::io::stdin(), MAX_PRIVATE_FILE_BYTES), + InputSource::File(path) => read_private(path), + }) + .await??; let value = raw.trim(); if value.is_empty() { return Err(Error::usage("Credential is empty")); diff --git a/src/input.rs b/src/input.rs index 0a16310..01d9c73 100644 --- a/src/input.rs +++ b/src/input.rs @@ -13,6 +13,7 @@ use crate::{ config::{InputSource, Scope}, payment::{Amount, AmountUnit, Currency, Network, PaymentDirection, ReceiveKind}, registry::{Method, Operation, OperationId, Parameter, ParameterLocation, ScopeParameter}, + terminal::read_detached, }; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; @@ -54,9 +55,19 @@ pub struct Request { } impl Request { - pub fn build(invocation: &ApiInvocation, scope: &Scope) -> Result { + /// Read a raw `--data` body, then build the request. + pub async fn read(invocation: &ApiInvocation, scope: &Scope) -> Result { + let raw = match &invocation.body { + Some(BodySource::Raw(source)) => Some(raw_body(source).await?), + _ => None, + }; + Self::build(invocation, scope, raw) + } + + /// `raw` is the body `--data` supplied, already read; `read` supplies it. + pub fn build(invocation: &ApiInvocation, scope: &Scope, raw: Option) -> Result { let operation = invocation.operation; - let body = body(invocation, scope)?; + let body = body(invocation, scope, raw)?; let body_id = body.as_ref().and_then(|body| RawPayload(body).id()); Ok(Self { path: path(operation, invocation.resource_id, scope)?, @@ -497,14 +508,20 @@ fn friendly_body( }) } -/// A complete JSON object from stdin or a file, bounded and otherwise untouched. -fn raw_body(source: &InputSource) -> Result { - let reader: Box = match source { - InputSource::Stdin => Box::new(std::io::stdin()), - InputSource::File(path) => Box::new(std::fs::File::open(path)?), - }; - let mut bytes = Vec::new(); - reader.take(MAX_BODY_BYTES + 1).read_to_end(&mut bytes)?; +/// A complete JSON object from stdin or a file, bounded and otherwise untouched. Stdin or a +/// FIFO can block indefinitely, so the read is detached and Ctrl-C still ends the command. +async fn raw_body(source: &InputSource) -> Result { + let source = source.clone(); + let bytes = read_detached(move || -> Result> { + let reader: Box = match &source { + InputSource::Stdin => Box::new(std::io::stdin()), + InputSource::File(path) => Box::new(std::fs::File::open(path)?), + }; + let mut bytes = Vec::new(); + reader.take(MAX_BODY_BYTES + 1).read_to_end(&mut bytes)?; + Ok(bytes) + }) + .await??; if bytes.len() as u64 > MAX_BODY_BYTES { return Err(Error::usage("Request body exceeds 16 MiB")); } @@ -515,17 +532,20 @@ fn raw_body(source: &InputSource) -> Result { Ok(body) } -fn body(invocation: &ApiInvocation, scope: &Scope) -> Result> { +fn body(invocation: &ApiInvocation, scope: &Scope, raw: Option) -> Result> { let operation = invocation.operation; - let body = match &invocation.body { - None if operation.body => { + let body = match (&invocation.body, raw) { + (None, _) if operation.body => { return Err(Error::usage( "This operation requires --data @file or --data -", )); } - None => return Ok(None), - Some(BodySource::Raw(source)) => raw_body(source)?, - Some(BodySource::Friendly(flags)) => friendly_body(flags, invocation.alias, scope)?, + (None, _) => return Ok(None), + (Some(BodySource::Raw(_)), Some(raw)) => raw, + (Some(BodySource::Raw(_)), None) => { + return Err(Error::usage("The --data body was not read")); + } + (Some(BodySource::Friendly(flags)), _) => friendly_body(flags, invocation.alias, scope)?, }; check_payload(operation, invocation.alias, RawPayload(&body), scope)?; Ok(Some(body)) @@ -757,7 +777,7 @@ mod tests { let Command::Api(api) = invocation.command else { panic!("expected an API command"); }; - Request::build(&api, &scope()) + Request::build(&api, &scope(), None) } #[test] diff --git a/src/lib.rs b/src/lib.rs index 163d2ff..8686925 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,6 +16,7 @@ mod price; pub mod registry; pub mod secret; mod startup; +mod terminal; pub(crate) use error::{Error, Result}; pub use startup::run; diff --git a/src/startup.rs b/src/startup.rs index 9223b8b..0c091dc 100644 --- a/src/startup.rs +++ b/src/startup.rs @@ -1,7 +1,8 @@ //! Process composition: parse the command line, run one command, report, and exit. use crate::{ - Error, Result, api, + Error, Result, + api::{self, SubmissionState}, auth::{self, Discovery}, cli::{ self, AuthCommand, Command, GlobalFlags, Invocation, LocalCommand, ParseFailure, @@ -10,6 +11,7 @@ use crate::{ config::{self, Profile, Scope, Settings}, output::{Envelope, Output, OutputFormat, report_error, write_stdout}, price::{PRICE_URL, PriceService}, + terminal::Terminal, }; use serde::Serialize; use std::process::ExitCode; @@ -23,11 +25,25 @@ pub async fn run() -> ExitCode { Err(failure) => return fail_parse(failure, json_errors), }; let format = invocation.global.output_format(); + let submission = SubmissionState::default(); + // Biased, with the interrupt first: tokio installs the SIGINT handler when `ctrl_c` is + // first polled. Polled second, a command that reaches a prompt without awaiting would leave + // an early Ctrl-C to the default handler, which kills the process without a report. let result = tokio::select! { - result = execute(invocation) => result, - _ = tokio::signal::ctrl_c() => Err(Error::interrupted( - "Interrupted; any submitted payment continues independently. Use its original ID to check status.", - )), + biased; + _ = tokio::signal::ctrl_c() => { + // The next interrupt must not wait for synchronous cleanup or stderr I/O. The + // listener is detached on purpose: runtime shutdown after the report ends it. + // process::exit skips destructors; by then the first interrupt has already + // dropped `execute`, which restores terminal echo after a hidden prompt. + tokio::spawn(async { + if tokio::signal::ctrl_c().await.is_ok() { + std::process::exit(130); + } + }); + Err(submission.interrupted()) + }, + result = execute(invocation, &submission) => result, }; match result { Ok(()) => ExitCode::SUCCESS, @@ -67,7 +83,7 @@ fn process_exit(code: i32) -> ExitCode { .unwrap_or(ExitCode::FAILURE) } -async fn execute(invocation: Invocation) -> Result<()> { +async fn execute(invocation: Invocation, submission: &SubmissionState) -> Result<()> { let Invocation { global, command } = invocation; if let Command::Local(LocalCommand::Completions { shell }) = command { // The generator panics on a write error, so render to memory and use the normal @@ -76,6 +92,7 @@ async fn execute(invocation: Invocation) -> Result<()> { clap_complete::generate(shell, &mut cli::command(), BINARY_NAME, &mut script); return write_stdout(&script); } + let terminal = global.terminal(); let mut out = Output::new( global.output_format(), global.show_secrets, @@ -87,13 +104,19 @@ async fn execute(invocation: Invocation) -> Result<()> { global.price_url.as_deref().unwrap_or(PRICE_URL), global.timeout, )?; + const WAITING: &str = "Waiting for price service..."; let envelope = match command { - Command::Local(LocalCommand::Price(flags)) => { - Envelope::local(service.report(flags.at.as_deref()).await?)? - } + Command::Local(LocalCommand::Price(flags)) => Envelope::local( + terminal + .during(WAITING, service.report(flags.at.as_deref())) + .await?, + )?, Command::Local(LocalCommand::Convert(flags)) => Envelope::local( - service - .convert(&flags.request(), flags.at.as_deref()) + terminal + .during( + WAITING, + service.convert(&flags.request(), flags.at.as_deref()), + ) .await?, )?, _ => unreachable!("matched above"), @@ -103,9 +126,11 @@ async fn execute(invocation: Invocation) -> Result<()> { let mut settings = Settings::open(config::directory(global.config_dir.clone())?)?; let scope = settings.scope(global.scope_selection())?; match command { - Command::Api(api) => api::execute(&api, &global, &settings, &scope, &mut out).await, + Command::Api(api) => { + api::execute(&api, &global, &settings, &scope, &mut out, submission).await + } Command::Local(local) => { - let envelope = local_command(local, &global, &mut settings, &scope).await?; + let envelope = local_command(local, &global, &mut settings, &scope, submission).await?; out.write(envelope, &[]) } } @@ -116,12 +141,15 @@ async fn local_command( global: &GlobalFlags, settings: &mut Settings, scope: &Scope, + submission: &SubmissionState, ) -> Result { match command { - LocalCommand::Login(flags) => Envelope::local(auth::login(settings, &flags, global).await?), - LocalCommand::Logout(flags) => { - Envelope::local(auth::logout(settings, scope, flags.local).await?) + LocalCommand::Login(flags) => { + Envelope::local(auth::login(settings, &flags, global, submission).await?) } + LocalCommand::Logout(flags) => Envelope::local( + auth::logout(settings, scope, flags.local, global.terminal(), submission).await?, + ), LocalCommand::Auth { command: AuthCommand::Status, } => Envelope::local(auth::status(settings, scope, global)?), @@ -129,12 +157,21 @@ async fn local_command( command: AuthCommand::ImportKey(flags), } => Envelope::local(auth::import_key(settings, scope, &flags, global).await?), LocalCommand::Organizations { .. } => Envelope::local( - auth::discover(settings, scope, global, Discovery::Organizations).await?, + auth::discover( + settings, + scope, + global, + Discovery::Organizations, + submission, + ) + .await?, + ), + LocalCommand::Environments { .. } => Envelope::local( + auth::discover(settings, scope, global, Discovery::Environments, submission).await?, ), - LocalCommand::Environments { .. } => { - Envelope::local(auth::discover(settings, scope, global, Discovery::Environments).await?) + LocalCommand::Profiles { command } => { + profiles(command, settings, scope, global.terminal()).await } - LocalCommand::Profiles { command } => profiles(command, settings, scope).await, LocalCommand::Completions { .. } | LocalCommand::Price(_) | LocalCommand::Convert(_) => { Err(Error::usage("This command needs no configuration")) } @@ -159,8 +196,9 @@ async fn profiles( command: ProfileCommand, settings: &mut Settings, scope: &Scope, + terminal: Terminal, ) -> Result { - let _lock = settings.lock().await?; + let _lock = settings.lock(terminal).await?; settings.reload()?; let unknown = || Error::usage("Unknown profile"); match command { diff --git a/src/terminal.rs b/src/terminal.rs new file mode 100644 index 0000000..1f77579 --- /dev/null +++ b/src/terminal.rs @@ -0,0 +1,152 @@ +//! Terminal interaction policy: prompts, progress, and diagnostics on stderr. Results and +//! errors are written by `output`. + +use crate::{Error, Result, secret::Secret}; +use std::{ + fmt::Display, + io::{ErrorKind, IsTerminal, Write}, +}; +use tokio::sync::oneshot; + +/// What the process may show to and ask of the person at the terminal, from `--quiet` and +/// `--no-input`. +#[derive(Clone, Copy)] +pub struct Terminal { + quiet: bool, + no_input: bool, +} + +impl Terminal { + pub fn new(quiet: bool, no_input: bool) -> Self { + Self { quiet, no_input } + } + + /// A prompt needs an interactive stdin and must not be disabled by `--no-input`. + pub fn can_prompt(self) -> bool { + !self.no_input && std::io::stdin().is_terminal() + } + + /// Optional status for a human, cleared when the guard drops; no control codes on + /// redirected stderr. + pub fn progress(self, label: &'static str) -> Progress { + let active = !self.quiet && std::io::stderr().is_terminal(); + if active { + eprint!("{label}"); + let _ = std::io::stderr().flush(); + } + Progress { active } + } + + /// Show `label` while `work` runs. The status cannot outlive the work: it clears on + /// completion, error, or cancellation. + pub async fn during(self, label: &'static str, work: impl Future) -> T { + let _progress = self.progress(label); + work.await + } + + /// Optional information that `--quiet` suppresses. + pub fn notice(self, message: impl Display) { + if !self.quiet { + eprintln!("{message}"); + } + } + + /// Information needed to confirm or recover an operation; `--quiet` never hides it. + pub fn important(self, message: impl Display) { + eprintln!("{message}"); + } + + /// Ask a yes/no question on stderr. Anything but an explicit yes declines. + pub async fn confirm(self, question: &str) -> Result { + eprint!("{question} [y/N] "); + std::io::stderr().flush()?; + let reply = read_detached(|| { + let mut reply = String::new(); + std::io::stdin().read_line(&mut reply).map(|_| reply) + }) + .await??; + Ok(matches!(reply.trim(), "y" | "Y" | "yes")) + } + + /// Read a secret without echo. + pub async fn read_hidden(self, prompt: &'static str) -> Result { + // The detached read restores echo only when it returns, and Ctrl-C does not wait for + // it. This guard restores the terminal when the read completes or is cancelled. + #[cfg(unix)] + let _modes = TerminalModes::save(); + match read_detached(move || rpassword::prompt_password(prompt).map(Secret::new)).await? { + // rpassword turns off terminal signals, so a typed Ctrl-C reaches it as a + // character. It raises SIGINT itself and then returns this error; waiting here + // lets the interrupt handler report the interruption instead of an I/O failure. + Err(error) if error.kind() == ErrorKind::Interrupted => std::future::pending().await, + read => Ok(read?), + } + } +} + +/// A blocked read of a terminal, stdin, or FIFO cannot be cancelled, and a runtime waits for +/// its blocking pool at shutdown. The read therefore runs on a detached thread whose only +/// completion signal is the channel: Ctrl-C ends the process without waiting for the input, +/// and process exit discards the unfinished read. +pub async fn read_detached( + read: impl FnOnce() -> T + Send + 'static, +) -> Result { + let (sender, receiver) = oneshot::channel(); + std::thread::spawn(move || { + let _ = sender.send(read()); + }); + receiver + .await + .map_err(|_| Error::transport("Terminal input ended unexpectedly")) +} + +/// The controlling terminal's attributes, put back when dropped. `rpassword` turns off echo +/// on `/dev/tty` and turns it back on only when its read returns. +#[cfg(unix)] +struct TerminalModes { + tty: std::fs::File, + saved: libc::termios, +} + +#[cfg(unix)] +impl TerminalModes { + /// `None` without a controlling terminal, where there is nothing to restore. + fn save() -> Option { + use std::os::fd::AsRawFd; + let tty = std::fs::File::open("/dev/tty").ok()?; + let mut saved = std::mem::MaybeUninit::::uninit(); + // SAFETY: the descriptor is open for the duration of the call, and tcgetattr fully + // initializes `saved` when it returns 0. + if unsafe { libc::tcgetattr(tty.as_raw_fd(), saved.as_mut_ptr()) } != 0 { + return None; + } + // SAFETY: tcgetattr returned 0 above. + let saved = unsafe { saved.assume_init() }; + Some(Self { tty, saved }) + } +} + +#[cfg(unix)] +impl Drop for TerminalModes { + fn drop(&mut self) { + use std::os::fd::AsRawFd; + // SAFETY: the descriptor is still owned by `tty`, and `saved` holds attributes read + // from the same terminal. + unsafe { libc::tcsetattr(self.tty.as_raw_fd(), libc::TCSANOW, &self.saved) }; + } +} + +/// Clears its status line when dropped, including when Ctrl-C cancels the owning future. +#[must_use = "progress is cleared as soon as the guard is dropped"] +pub struct Progress { + active: bool, +} + +impl Drop for Progress { + fn drop(&mut self) { + if self.active { + eprint!("\r\x1b[2K"); + let _ = std::io::stderr().flush(); + } + } +} diff --git a/tests/cli_integration.rs b/tests/cli_integration.rs index 8ff337c..ff6049e 100644 --- a/tests/cli_integration.rs +++ b/tests/cli_integration.rs @@ -16,6 +16,8 @@ use std::{ time::Duration, }; use tempfile::TempDir; +#[cfg(unix)] +use tokio::sync::Notify; use voltage_cli::{ config::{ self, Account, AccountKind, Config, Credential, CredentialStore, Login, Profile, Settings, @@ -24,7 +26,7 @@ use voltage_cli::{ secret::Secret, }; use wiremock::{ - Mock, MockBuilder, MockServer, Request, ResponseTemplate, + Mock, MockBuilder, MockServer, Request, Respond, ResponseTemplate, matchers::{ body_json, body_string_contains, header, method, path, query_param, query_param_is_missing, }, @@ -174,7 +176,12 @@ fn cli(dir: &Path, server: &MockServer) -> Command { } fn cli_at(dir: &Path, api_url: &str) -> Command { - let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("voltage")); + Command::from_std(process_at(dir, api_url)) +} + +/// `cli_at` as a plain process, for tests that attach a terminal or deliver a signal. +fn process_at(dir: &Path, api_url: &str) -> std::process::Command { + let mut cmd = std::process::Command::new(assert_cmd::cargo::cargo_bin!("voltage")); for name in [ "VOLTAGE_ORGANIZATION_ID", "VOLTAGE_ENVIRONMENT_ID", @@ -246,7 +253,7 @@ fn accepted() -> ResponseTemplate { async fn respond( server: &MockServer, request: MockBuilder, - response: ResponseTemplate, + response: impl Respond + 'static, times: u64, ) { request @@ -256,7 +263,7 @@ async fn respond( .await; } -async fn respond_once(server: &MockServer, request: MockBuilder, response: ResponseTemplate) { +async fn respond_once(server: &MockServer, request: MockBuilder, response: impl Respond + 'static) { respond(server, request, response, 1).await; } @@ -1152,6 +1159,38 @@ async fn concurrent_processes_refresh_once_and_save_the_rotated_token() { ); } +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_fresh_login_does_not_wait_for_the_credential_lock() { + use std::os::unix::fs::OpenOptionsExt; + let (server, dir) = fixture().await; + seeded_login(dir.path(), &server, false); + organization_exchange(&server, LOGIN_ACCESS, ORG, "org-access", 1).await; + respond_once( + &server, + route("GET", wallets_path(ORG)).and(header("authorization", "Bearer org-access")), + ok(json!([])), + ) + .await; + // Another process holds the lock, as it would during a slow refresh. + let held = std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .open(dir.path().join("credentials.lock")) + .unwrap(); + held.lock().unwrap(); + let mut command = cli(dir.path(), &server); + command + .args(["wallets", "list", "--account", LOGIN_NAME, "--org", ORG]) + .timeout(Duration::from_secs(10)); + tokio::task::spawn_blocking(move || command.assert().success()) + .await + .unwrap(); + drop(held); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn organization_exchange_uses_the_saved_auth_origin_and_keeps_discovery_on_login() { let auth = MockServer::start().await; @@ -1278,6 +1317,710 @@ async fn logout_retains_credentials_on_revocation_failure_and_local_is_explicit( // Payments: submission, confirmation, waits, and reconciliation // --------------------------------------------------------------------------------------- +/// A pseudo-terminal pair: the controller end reads what the child writes, and the terminal +/// end is handed to the child as stdin or stderr. +#[cfg(unix)] +fn open_pty() -> (std::fs::File, std::fs::File) { + use std::os::fd::FromRawFd; + let mut controller = 0; + let mut terminal = 0; + // SAFETY: openpty only writes the two descriptors on success; the name, termios, and + // window-size pointers are optional and may be null. + let opened = unsafe { + libc::openpty( + &mut controller, + &mut terminal, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }; + assert_eq!(opened, 0, "{}", std::io::Error::last_os_error()); + // openpty has no close-on-exec option. Without it, a child that another test spawns + // concurrently inherits both ends and keeps the controller's drain open after this test's + // child exits. The descriptor a child receives as stdio is a dup2 copy, which does not + // keep the flag. Only a spawn between openpty and these calls can still inherit them. + for descriptor in [controller, terminal] { + // SAFETY: the descriptor was just opened, and F_SETFD only changes its flags. + let set = unsafe { libc::fcntl(descriptor, libc::F_SETFD, libc::FD_CLOEXEC) }; + assert_eq!(set, 0, "{}", std::io::Error::last_os_error()); + } + // SAFETY: both descriptors were just opened, nothing else owns them, and each is wrapped + // exactly once, so each `File` closes its descriptor once. + unsafe { + ( + std::fs::File::from_raw_fd(controller), + std::fs::File::from_raw_fd(terminal), + ) + } +} + +/// Deliver SIGINT, as Ctrl-C does on a terminal. +#[cfg(unix)] +fn interrupt(child: &std::process::Child) { + let status = std::process::Command::new("kill") + .args(["-INT", &child.id().to_string()]) + .status() + .unwrap(); + assert!(status.success()); +} + +/// Answer with `response` and announce each arrival, so a test acts only once the request +/// is in flight. +#[cfg(unix)] +fn announced(response: ResponseTemplate) -> (impl Respond, Arc) { + let arrived = Arc::new(Notify::new()); + let announce = Arc::clone(&arrived); + let responder = move |_: &Request| { + announce.notify_one(); + response.clone() + }; + (responder, arrived) +} + +/// Start the binary with `args`, interrupt it once its request reaches the server, and +/// return its output after it exits with 130. +#[cfg(unix)] +async fn interrupt_in_flight( + dir: &Path, + server: &MockServer, + arrived: &Notify, + args: &[&str], +) -> std::process::Output { + use std::process::Stdio; + let child = process_at(dir, &server.uri()) + .args(args) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + // Generous: a device login waits out its first poll interval before any request. + tokio::time::timeout(Duration::from_secs(15), arrived.notified()) + .await + .unwrap(); + interrupt(&child); + let output = tokio::time::timeout( + Duration::from_secs(5), + tokio::task::spawn_blocking(move || child.wait_with_output().unwrap()), + ) + .await + .unwrap() + .unwrap(); + assert_eq!( + output.status.code(), + Some(130), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + output +} + +/// The JSON error report: the last line of stderr, after any recovery notice. +#[cfg(unix)] +fn error_report(stderr: &[u8]) -> Value { + serde_json::from_str(String::from_utf8_lossy(stderr).lines().last().unwrap()).unwrap() +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn progress_is_terminal_only_and_cleared_on_completion() { + use std::io::Read; + use std::process::Stdio; + let (server, dir) = fixture().await; + route("GET", wallets_path(ORG)) + .respond_with(ok(json!({"items":[]})).set_delay(Duration::from_millis(400))) + .expect(2) + .mount(&server) + .await; + let args = ["wallets", "list", "--org", ORG]; + let redirected = process_at(dir.path(), &server.uri()) + .args(args) + .output() + .unwrap(); + assert!(redirected.status.success()); + assert!(redirected.stderr.is_empty()); + + let (mut controller, terminal) = open_pty(); + let child = process_at(dir.path(), &server.uri()) + .args(args) + .stdin(Stdio::null()) + .stderr(Stdio::from(terminal)) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let reader = tokio::task::spawn_blocking(move || { + let mut shown = Vec::new(); + // Linux PTYs return EIO rather than EOF when the terminal end closes. + let _ = controller.read_to_end(&mut shown); + shown + }); + let output = tokio::task::spawn_blocking(move || child.wait_with_output().unwrap()) + .await + .unwrap(); + assert!(output.status.success()); + let shown = reader.await.unwrap(); + let shown = String::from_utf8_lossy(&shown); + assert!(shown.contains("Waiting for API response..."), "{shown}"); + assert!(shown.ends_with("\r\u{1b}[2K"), "{shown}"); + server.verify().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn no_input_requires_explicit_approval_and_secret_source() { + let (server, dir) = fixture().await; + let body = json!({"id":RESOURCE,"wallet_id":WALLET,"currency":"btc","type":"bolt11","data":{"payment_request":"invoice"}}); + let rejected = cli(dir.path(), &server) + .args([ + "--no-input", + "payments", + "create", + "--org", + ORG, + "--env", + ENV, + "--data", + "-", + ]) + .write_stdin(body.to_string()) + .assert() + .code(2); + assert!(stderr(&rejected).contains("requires --yes")); + let missing_secret = cli(dir.path(), &server) + .args([ + "--no-input", + "--yes", + "auth", + "import-key", + "--account", + "other", + "--org", + ORG, + "--env", + ENV, + ]) + .assert() + .code(2); + assert!(stderr(&missing_secret).contains("--stdin")); + assert!(server.received_requests().await.unwrap().is_empty()); + assert!(!dir.path().join("requests").exists()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn quiet_keeps_results_errors_and_payment_recovery_id() { + let (server, dir) = fixture().await; + respond_once(&server, route("POST", payments_path()), accepted()).await; + let body = json!({"id":RESOURCE,"wallet_id":WALLET,"currency":"btc","type":"bolt11","data":{"payment_request":"invoice"}}); + let result = cli(dir.path(), &server) + .args([ + "-q", + "--yes", + "--no-input", + "payments", + "create", + "--org", + ORG, + "--env", + ENV, + "--data", + "-", + ]) + .write_stdin(body.to_string()) + .assert() + .success(); + assert_eq!(json_stdout(&result)["resource_id"], RESOURCE); + assert!(stderr(&result).contains("Recovery record:")); + assert!(!stderr(&result).contains("\u{1b}[")); + let error = cli(dir.path(), &server) + .args([ + "--quiet", + "--no-input", + "payments", + "create", + "--org", + ORG, + "--env", + ENV, + "--data", + "-", + ]) + .write_stdin(body.to_string()) + .assert() + .code(2); + assert!(stderr(&error).contains("requires --yes")); + server.verify().await; +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn interrupt_at_the_confirmation_prompt_exits_130_without_submitting() { + use std::io::Read; + use std::process::Stdio; + let (server, dir) = fixture().await; + let body = json!({"id":RESOURCE,"wallet_id":WALLET,"currency":"btc","type":"bolt11","data":{"payment_request":"invoice"}}); + let data = dir.path().join("request.json"); + std::fs::write(&data, body.to_string()).unwrap(); + let (mut controller, terminal) = open_pty(); + let child = process_at(dir.path(), &server.uri()) + .args(["payments", "create", "--org", ORG, "--env", ENV, "--data"]) + .arg(format!("@{}", data.display())) + .stdin(Stdio::from(terminal.try_clone().unwrap())) + .stderr(Stdio::from(terminal)) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + // The controller stays open until the child exits so its stderr writes never fail. + let controller = tokio::time::timeout( + Duration::from_secs(10), + tokio::task::spawn_blocking(move || { + let mut shown = Vec::new(); + let mut chunk = [0; 4096]; + while !String::from_utf8_lossy(&shown).contains("Proceed? [y/N]") { + let read = controller.read(&mut chunk).unwrap(); + assert_ne!(read, 0, "{}", String::from_utf8_lossy(&shown)); + shown.extend_from_slice(&chunk[..read]); + } + controller + }), + ) + .await + .unwrap() + .unwrap(); + interrupt(&child); + let pid = child.id().to_string(); + let exited = tokio::time::timeout( + Duration::from_secs(5), + tokio::task::spawn_blocking(move || child.wait_with_output().unwrap()), + ) + .await; + let Ok(output) = exited else { + // Unblock the waiter so the runtime can shut down, then fail. + std::process::Command::new("kill") + .args(["-KILL", &pid]) + .status() + .unwrap(); + panic!("Ctrl-C at the confirmation prompt did not end the process"); + }; + let output = output.unwrap(); + drop(controller); + assert_eq!(output.status.code(), Some(130)); + assert!(output.stdout.is_empty()); + assert!(server.received_requests().await.unwrap().is_empty()); + assert!(!dir.path().join("requests").exists()); +} + +/// Local modes of a pseudo-terminal, as the child sees them through `/dev/tty`. +#[cfg(unix)] +fn local_modes(pty: &std::fs::File) -> libc::tcflag_t { + use std::os::fd::AsRawFd; + let mut modes = std::mem::MaybeUninit::::uninit(); + // SAFETY: the descriptor is open, and tcgetattr fully initializes `modes` on success. + assert_eq!( + unsafe { libc::tcgetattr(pty.as_raw_fd(), modes.as_mut_ptr()) }, + 0 + ); + // SAFETY: tcgetattr returned 0 above. + unsafe { modes.assume_init() }.c_lflag +} + +/// How a test delivers Ctrl-C to a child on a pseudo-terminal. +#[cfg(unix)] +#[derive(Clone, Copy)] +enum CtrlC { + /// SIGINT from outside, as the terminal sends it to the foreground process. + Signal, + /// The character a person types, which a prompt with terminal signals off reads itself. + Typed, +} + +/// Interrupt `auth import-key` once its hidden prompt has turned off echo. Returns the exit +/// code, whether echo is on afterward, and everything the child wrote to the terminal. +#[cfg(unix)] +async fn interrupt_the_hidden_key_prompt(ctrl_c: CtrlC) -> (Option, bool, String) { + use std::io::{Read, Write}; + use std::os::unix::process::CommandExt; + use std::process::Stdio; + let (server, dir) = fixture().await; + let (mut controller, terminal) = open_pty(); + // The terminal end is revoked when the session leader exits; the controller end keeps + // reporting the shared attributes. + let observer = controller.try_clone().unwrap(); + let mut command = process_at(dir.path(), &server.uri()); + command + .args([ + "auth", + "import-key", + "--account", + "k", + "--org", + ORG, + "--env", + ENV, + ]) + .stdin(Stdio::from(terminal.try_clone().unwrap())) + .stderr(Stdio::from(terminal)) + .stdout(Stdio::piped()); + // SAFETY: setsid and ioctl are async-signal-safe, and the closure allocates nothing. + // The new session takes the PTY on stdin as its controlling terminal, so `/dev/tty` + // names it. + unsafe { + command.pre_exec(|| { + if libc::setsid() == -1 || libc::ioctl(0, libc::TIOCSCTTY as _, 0) == -1 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let child = command.spawn().unwrap(); + // A session leader's exit waits for its terminal output to drain, so the controller is + // read until the child closes the terminal, not only until the prompt appears. + let (prompted, prompt) = tokio::sync::oneshot::channel(); + let drain = tokio::task::spawn_blocking(move || { + let mut prompted = Some(prompted); + let mut shown = Vec::new(); + let mut chunk = [0; 4096]; + while let Ok(read @ 1..) = controller.read(&mut chunk) { + shown.extend_from_slice(&chunk[..read]); + if String::from_utf8_lossy(&shown).contains("Environment API key:") { + prompted.take().map(|prompted| prompted.send(())); + } + } + String::from_utf8_lossy(&shown).into_owned() + }); + tokio::time::timeout(Duration::from_secs(10), prompt) + .await + .unwrap() + .unwrap(); + // The prompt is written before echo is turned off; interrupt only once the read is + // hidden, or the test would pass without restoring anything. + tokio::time::timeout(Duration::from_secs(10), async { + while local_modes(&observer) & libc::ECHO != 0 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + match ctrl_c { + CtrlC::Signal => interrupt(&child), + CtrlC::Typed => (&observer).write_all(b"\x03").unwrap(), + } + let pid = child.id().to_string(); + let exited = tokio::time::timeout( + Duration::from_secs(5), + tokio::task::spawn_blocking(move || child.wait_with_output().unwrap()), + ) + .await; + let Ok(output) = exited else { + std::process::Command::new("kill") + .args(["-KILL", &pid]) + .status() + .unwrap(); + panic!("Ctrl-C at the hidden key prompt did not end the process"); + }; + let code = output.unwrap().status.code(); + let echo = local_modes(&observer) & libc::ECHO != 0; + // The controller reports end of input once the last terminal descriptor closes. + drop(command); + let shown = tokio::time::timeout(Duration::from_secs(5), drain) + .await + .unwrap() + .unwrap(); + (code, echo, shown) +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn interrupt_at_the_hidden_key_prompt_restores_terminal_echo() { + let (code, echo, shown) = interrupt_the_hidden_key_prompt(CtrlC::Signal).await; + assert_eq!(code, Some(130), "{shown}"); + assert!(echo); +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn typed_ctrl_c_at_the_hidden_key_prompt_reports_an_interruption() { + let (code, echo, shown) = interrupt_the_hidden_key_prompt(CtrlC::Typed).await; + assert_eq!(code, Some(130), "{shown}"); + assert!(shown.contains("Interrupted before any resource change was submitted")); + assert!(echo); +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn interrupt_during_a_refresh_says_the_login_may_need_renewal() { + let (server, dir) = fixture().await; + seeded_login(dir.path(), &server, true); + let (responder, arrived) = announced( + ok(json!({ + "access_token":"new-access","refresh_token":"new-refresh", + "token_type":"Bearer","expires_in":600 + })) + .set_delay(Duration::from_secs(10)), + ); + respond_once( + &server, + route("POST", "/oauth/token").and(body_string_contains("grant_type=refresh_token")), + responder, + ) + .await; + let output = interrupt_in_flight( + dir.path(), + &server, + &arrived, + &["wallets", "list", "--account", LOGIN_NAME, "--org", ORG], + ) + .await; + let report = error_report(&output.stderr); + assert_eq!( + report["error"]["message"], + format!("Interrupted while refreshing the saved login for {LOGIN_NAME}") + ); + assert!( + report["error"]["hint"] + .as_str() + .unwrap() + .contains("voltage login") + ); + server.verify().await; +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn interrupt_during_a_logout_revoke_points_to_a_local_logout() { + let (server, dir) = fixture().await; + let settings = seeded_login(dir.path(), &server, false); + let (responder, arrived) = announced(ok(json!({})).set_delay(Duration::from_secs(10))); + respond_once(&server, route("POST", "/oauth/revoke"), responder).await; + let output = interrupt_in_flight( + dir.path(), + &server, + &arrived, + &["logout", "--account", LOGIN_NAME], + ) + .await; + let report = error_report(&output.stderr); + assert_eq!( + report["error"]["message"], + format!("Interrupted while logging out {LOGIN_NAME}; its session may already be revoked") + ); + assert!( + report["error"]["hint"] + .as_str() + .unwrap() + .contains("--local") + ); + // The saved login is still there for the local logout the hint suggests. + assert!(settings.read_credential(LOGIN_NAME).is_ok()); + server.verify().await; +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn interrupt_before_a_new_login_is_saved_says_a_session_may_exist() { + let (server, dir) = fixture().await; + respond_once( + &server, + route("POST", "/oauth/device_authorization"), + ok(json!({ + "device_code":"device-secret","user_code":"ABCD-EFGH", + "verification_uri":"https://app.voltage.cloud/cli/authorize","expires_in":60,"interval":5 + })), + ) + .await; + respond_once( + &server, + route("POST", "/oauth/token"), + ok(json!({ + "access_token":"login-access","refresh_token":"login-refresh", + "token_type":"Bearer","expires_in":600 + })), + ) + .await; + // The session exists once tokens are issued; saving it waits on the identity lookup. + let (responder, arrived) = announced( + ok(json!({"id":RESOURCE,"email":LOGIN_EMAIL})).set_delay(Duration::from_secs(10)), + ); + respond_once(&server, route("GET", "/users/current"), responder).await; + let output = interrupt_in_flight( + dir.path(), + &server, + &arrived, + &[ + "login", + "--auth-url", + &server.uri(), + "--no-browser", + "--account", + LOGIN_NAME, + "--credential-store", + "file", + ], + ) + .await; + let report = error_report(&output.stderr); + assert_eq!( + report["error"]["message"], + "Interrupted after sign-in may have created a session that was not saved" + ); + assert!( + report["error"]["hint"] + .as_str() + .unwrap() + .contains("voltage login") + ); + assert!( + !settings_at(dir.path()) + .config + .accounts + .contains_key(LOGIN_NAME) + ); + server.verify().await; +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn interrupt_during_a_read_does_not_claim_a_change_was_submitted() { + let (server, dir) = fixture().await; + let (responder, arrived) = + announced(ok(json!({"items":[]})).set_delay(Duration::from_secs(10))); + respond_once(&server, route("GET", wallets_path(ORG)), responder).await; + let output = interrupt_in_flight( + dir.path(), + &server, + &arrived, + &["wallets", "list", "--org", ORG], + ) + .await; + let report = error_report(&output.stderr); + assert_eq!( + report["error"]["message"], + "Interrupted before any resource change was submitted" + ); + assert!(report["error"]["detail"].is_null()); + assert!(!dir.path().join("requests").exists()); + server.verify().await; +} + +/// A `--data` read that is still waiting for input must not keep Ctrl-C from ending the +/// command. A FIFO blocks like an idle stdin, and opening its write end waits for the CLI to +/// open the read end, so the test knows the read has started. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn interrupt_while_a_request_body_is_still_being_read() { + use std::process::Stdio; + let (server, dir) = fixture().await; + let fifo = dir.path().join("body.json"); + let made = std::process::Command::new("mkfifo") + .arg(&fifo) + .status() + .unwrap(); + assert!(made.success()); + let child = process_at(dir.path(), &server.uri()) + .args(["payments", "create", "--data"]) + .arg(format!("@{}", fifo.display())) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + // Held open and never written, so the CLI's read blocks until the process ends. + let _writer = tokio::time::timeout( + Duration::from_secs(15), + tokio::task::spawn_blocking(move || { + std::fs::OpenOptions::new().write(true).open(fifo).unwrap() + }), + ) + .await + .unwrap() + .unwrap(); + interrupt(&child); + let pid = child.id().to_string(); + let Ok(output) = tokio::time::timeout( + Duration::from_secs(5), + tokio::task::spawn_blocking(move || child.wait_with_output().unwrap()), + ) + .await + else { + std::process::Command::new("kill") + .args(["-KILL", &pid]) + .status() + .unwrap(); + panic!("Ctrl-C during a blocked --data read did not end the process"); + }; + let output = output.unwrap(); + assert_eq!( + output.status.code(), + Some(130), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + error_report(&output.stderr)["error"]["message"], + "Interrupted before any resource change was submitted" + ); + assert!(server.received_requests().await.unwrap().is_empty()); +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn interrupt_during_payment_submission_reports_original_id_without_retry() { + let (server, dir) = fixture().await; + let (responder, arrived) = announced(accepted().set_delay(Duration::from_secs(10))); + respond_once(&server, route("POST", payments_path()), responder).await; + let body = json!({"id":RESOURCE,"wallet_id":WALLET,"currency":"btc","type":"bolt11","data":{"payment_request":"invoice"}}); + let data = dir.path().join("request.json"); + std::fs::write(&data, body.to_string()).unwrap(); + let data = format!("@{}", data.display()); + let output = interrupt_in_flight( + dir.path(), + &server, + &arrived, + &[ + "--yes", "payments", "create", "--org", ORG, "--env", ENV, "--data", &data, + ], + ) + .await; + assert!(output.stdout.is_empty()); + let report = error_report(&output.stderr); + assert_eq!(report["error"]["detail"]["resource_id"], RESOURCE); + assert_eq!(report["error"]["detail"]["outcome"], "unknown"); + let message = report["error"]["message"].as_str().unwrap(); + assert!(message.contains(&format!("payment {RESOURCE} may have been submitted"))); + assert!(message.contains("was not cancelled")); + assert!( + dir.path() + .join(format!("requests/{RESOURCE}.json")) + .exists() + ); + server.verify().await; +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn interrupt_during_another_write_reports_an_uncertain_submission() { + let (server, dir) = fixture().await; + let (responder, arrived) = + announced(ResponseTemplate::new(204).set_delay(Duration::from_secs(10))); + respond_once( + &server, + route("DELETE", format!("{}/{WALLET}", wallets_path(ORG))), + responder, + ) + .await; + let output = interrupt_in_flight( + dir.path(), + &server, + &arrived, + &["--yes", "wallets", "delete", WALLET, "--org", ORG], + ) + .await; + let report = error_report(&output.stderr); + let message = report["error"]["message"].as_str().unwrap(); + assert!(message.contains("may have been submitted"), "{message}"); + assert!(!message.contains("payment"), "{message}"); + assert_eq!(report["error"]["detail"]["organization_id"], ORG); + assert_eq!(report["error"]["detail"]["outcome"], "unknown"); + server.verify().await; +} + #[tokio::test(flavor = "multi_thread")] async fn raw_send_without_yes_never_submits() { let (server, dir) = fixture().await;