diff --git a/docs/cli-reference.md b/docs/cli-reference.md index b1d09a7..3e008a1 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -37,7 +37,7 @@ For example, use `adapt org members ls` or `adapt sandbox ls --all`. | `execs` | `get`, `cancel`, `logs`, `attach` | | `files` | `put`, `get` | | `volumes` | `list`, `get`, `create`, `quota`, `delete` | -| `endpoints` | `list`, `get`, `create`, `access`, `bind`, `unbind`, `token`, `revoke-tokens`, `delete` | +| `endpoints` | `list`, `get`, `create`, `access`, `bind`, `unbind`, `token`, `revoke-tokens`, `request`, `delete` | | `images` | `list`, `get`, `import`, `pull`, `wait`, `delete` | | `env` | `list`, `get`, `create`, `update`, `delete` | | `registry` | `list`, `create`, `update`, `delete` | @@ -309,6 +309,37 @@ adapt endpoints token ENDPOINT_ID Use the header `X-Adapt-Authorization: Bearer TOKEN` for requests to the hosted application. Endpoint tokens cannot authenticate Platform API requests. +### Endpoint requests + +`adapt endpoints request` looks up the endpoint's URL, sends one request to the hosted application, and writes the response body to stdout as it arrives. +The path is appended to the endpoint's URL, defaults to `/`, and can include a query string. + +```sh +# Request the application +adapt endpoints request ENDPOINT_ID + +# Follow a Server-Sent Events stream +adapt endpoints request ENDPOINT_ID /events + +# Call an authenticated endpoint with a token from `adapt endpoints token` +adapt endpoints request ENDPOINT_ID --token "$ENDPOINT_TOKEN" + +# Or create a new token for this request +adapt endpoints request ENDPOINT_ID --new-token +``` + +Use `-X` for the method, `-H "Name: value"` for application headers, and `-d` for a body (inline, `@file`, or `-` for stdin). +The command sends no `Content-Type` unless you pass one with `-H`. + +The application receives only your headers and, with `--token` or `--new-token`, `X-Adapt-Authorization`. +The CLI's Platform credentials are used only to look up the endpoint and create a token, and are never sent to the application. +An `Authorization` header that you pass with `-H` goes to the application unchanged. +Redirects are not followed. + +The command waits up to `--timeout` seconds for the response headers, and then up to `--timeout` seconds between parts of the body. +If the status is not 2xx (including a redirect), the CLI prints the body and then exits with code 1. +Ctrl-C exits with code 130, including while waiting for body input from stdin, a device, or a named pipe, or while stdout is blocked. + To disconnect the endpoint from the sandbox, run: ```sh diff --git a/skills/adapt/SKILL.md b/skills/adapt/SKILL.md index 3acb4d1..a5558fb 100644 --- a/skills/adapt/SKILL.md +++ b/skills/adapt/SKILL.md @@ -90,12 +90,16 @@ adapt files get SANDBOX_ID /app/output.txt - adapt endpoints create "My app" --access authenticated adapt endpoints bind ENDPOINT_ID SANDBOX_ID --port 3000 adapt endpoints get ENDPOINT_ID +adapt endpoints request ENDPOINT_ID /path --new-token ``` File transfers are limited to 16 MiB and guest parent directories must exist. Downloads refuse to overwrite local files unless `--force` is given. Hosted apps must listen on `0.0.0.0`. Endpoint tokens authenticate the hosted app with `X-Adapt-Authorization: Bearer TOKEN`; they are not Platform API credentials. +`endpoints request` streams the app's response body to stdout (SSE included), +sends only `-H` headers plus the endpoint token from `--token`/`--new-token`, +never follows redirects, and exits 1 after printing the body of a non-2xx response. ## Connected MCP tools diff --git a/src/cli.rs b/src/cli.rs index a1c1173..26c11b7 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -486,6 +486,35 @@ pub enum EndpointCommand { Delete { id: ResourceRef, }, + /// Send an HTTP request to the hosted application and stream its response body + #[command( + after_help = "The application receives only your headers and, with --token or --new-token, X-Adapt-Authorization.\nPlatform credentials are never sent to it, and redirects are not followed.\nThe body is written to stdout as it arrives; a non-2xx status prints the body, then exits 1." + )] + Request(EndpointRequest), +} + +#[derive(Args)] +pub struct EndpointRequest { + /// Full endpoint UUID or an unambiguous ID prefix + pub id: ResourceRef, + /// Path and optional query on the endpoint, e.g. /events?since=1 + #[arg(default_value = "/")] + pub path: String, + #[arg(long, short = 'X', default_value = "GET", value_parser = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"])] + pub method: String, + /// Application header as "Name: value" (repeatable) + // Parsed by the command: clap's errors would repeat a rejected value, which may hold a credential. + #[arg(long = "header", short = 'H', value_name = "HEADER")] + pub headers: Vec, + /// Request body: literal text, @file, or - for stdin + #[arg(long, short = 'd')] + pub data: Option, + /// Endpoint access token for an authenticated endpoint + #[arg(long, conflicts_with = "new_token")] + pub token: Option, + /// Create a new endpoint access token and use it for this request + #[arg(long)] + pub new_token: bool, } #[derive(Clone, Copy, ValueEnum)] diff --git a/src/commands.rs b/src/commands.rs index d6788ef..a1b62db 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -7,13 +7,19 @@ use crate::{ }; use anyhow::{Context, Result, bail}; use clap::ValueEnum; -use reqwest::Method; +use futures_util::StreamExt; +use reqwest::{ + Method, + header::{HeaderMap, HeaderValue, LOCATION}, +}; use serde_json::{Value, json}; use std::{ io::{self, Write}, path::Path, time::Duration, }; +use tokio::io::AsyncWriteExt; +use url::Url; use uuid::Uuid; pub async fn run(cli: Cli) -> Result { @@ -168,6 +174,7 @@ pub async fn run(cli: Cli) -> Result { }, Command::Files(command) => files(&api, command).await?, Command::Volumes(command) => volumes(&api, command).await?, + Command::Endpoints(EndpointCommand::Request(args)) => return request_endpoint(&api, args).await, Command::Endpoints(command) => endpoints(&api, command).await?, Command::Images(ImageCommand::List(args)) => return list_images(&api, args, cli.json).await, Command::Images(command) => images(&api, command).await?, @@ -638,7 +645,104 @@ async fn endpoints(api: &Api, command: EndpointCommand) -> Result { EndpointCommand::RevokeTokens { id } => { delete(api, &format!("/v1/ingresses/{id}/access-tokens")).await } + EndpointCommand::Request(_) => unreachable!("Endpoint requests are dispatched separately"), + } +} + +/// Sends one request to an endpoint's hosted application and streams the body to +/// stdout. Platform credentials only look up the endpoint and create a token; the +/// application receives the caller's headers and, at most, the endpoint token. +async fn request_endpoint(api: &Api, args: EndpointRequest) -> Result { + let path = &args.path; + if !path.starts_with('/') || path.starts_with("//") || path.contains('\\') || path.contains('#') + { + bail!("Use an absolute path such as /events, without a host or fragment"); + } + let mut headers = HeaderMap::new(); + for header in &args.headers { + let (name, value) = input::header(header)?; + headers.append(name, value); + } + let endpoint = api.get(&format!("/v1/ingresses/{}", args.id)).await?; + let base = Url::parse(endpoint["url"].as_str().context("Endpoint has no URL")?) + .context("Endpoint has an invalid URL")?; + config::validate_http_url(&base)?; + if base.query().is_some() || base.fragment().is_some() { + bail!("Endpoint URL has an unexpected query or fragment"); + } + // Append like `curl "${ENDPOINT_URL}events"`, keeping any path prefix in the URL. + let url = Url::parse(&format!("{}{path}", base.as_str().trim_end_matches('/')))?; + if url.origin() != base.origin() { + bail!("Requests must stay on the endpoint's origin"); + } + let token = if args.new_token { + let id = resource_id(&endpoint)?; + let created = api + .post(&format!("/v1/ingresses/{id}/access-tokens"), &json!({})) + .await?; + let token = created["token"].as_str(); + Some( + token + .context("Token response is missing the token")? + .to_owned(), + ) + } else { + args.token + }; + if let Some(token) = token { + if token.is_empty() || token.chars().any(|c| c.is_whitespace() || c == ',') { + bail!("Invalid endpoint token"); + } + let mut value = + HeaderValue::from_str(&format!("Bearer {token}")).context("Invalid endpoint token")?; + value.set_sensitive(true); + headers.insert("X-Adapt-Authorization", value); + } + // Never api.request(): it attaches Platform credentials. This client follows no redirects. + let mut request = api + .client + .request(args.method.parse()?, url) + .headers(headers); + if let Some(source) = args.data { + // Even @file can block on a FIFO or device. Runtime shutdown does not wait + // for this worker after Ctrl-C, so neither open nor read can delay exit. + let body = tokio::task::spawn_blocking(move || input::data(&source)) + .await + .context("Request body reader failed")??; + request = request.body(body); + } + // Error URLs can carry credentials in their query, so they are removed. + let response = tokio::time::timeout(api.timeout, request.send()) + .await + .context("Timed out waiting for the endpoint to respond")? + .map_err(reqwest::Error::without_url) + .context("Endpoint request failed")?; + let status = response.status(); + let location = response.headers().get(LOCATION).cloned(); + let mut stream = response.bytes_stream(); + let mut out = tokio::io::stdout(); + while let Some(chunk) = tokio::time::timeout(api.timeout, stream.next()) + .await + .context("Endpoint response was idle for longer than --timeout")? + { + let chunk = chunk + .map_err(reqwest::Error::without_url) + .context("Endpoint response was interrupted")?; + out.write_all(&chunk).await?; + out.flush().await?; + } + if status.is_success() { + return Ok(0); + } + let mut message = format!("Endpoint returned HTTP {status}"); + if status.is_redirection() { + message += "; redirects are not followed"; + if let Some(location) = location { + let location = String::from_utf8_lossy(location.as_bytes()); + message += &format!(" (Location: {})", output::safe(&location)); + } } + bail!(message) } async fn images(api: &Api, command: ImageCommand) -> Result { diff --git a/src/input.rs b/src/input.rs index 425dc6d..0ff840d 100644 --- a/src/input.rs +++ b/src/input.rs @@ -1,4 +1,5 @@ use anyhow::{Context, Result, bail}; +use reqwest::header::{HeaderName, HeaderValue}; use serde_json::{Map, Value}; use std::{ fmt, @@ -70,19 +71,39 @@ pub fn bytes(path: &Path, max: u64) -> Result> { Ok(result) } -/// JSON is accepted inline, from @file, or from stdin with '-'. -pub fn json(source: &str) -> Result { - let bytes = if source == "-" { - bytes(Path::new("-"), MAX_FILE_BYTES)? +/// Data is accepted inline, from @file, or from stdin with '-'. +pub fn data(source: &str) -> Result> { + if source == "-" { + bytes(Path::new("-"), MAX_FILE_BYTES) } else if let Some(path) = source.strip_prefix('@') { - bytes(Path::new(path), MAX_FILE_BYTES)? + bytes(Path::new(path), MAX_FILE_BYTES) } else { - source.as_bytes().to_vec() - }; - serde_json::from_slice(&bytes) + Ok(source.as_bytes().to_vec()) + } +} + +pub fn json(source: &str) -> Result { + serde_json::from_slice(&data(source)?) .context("Expected valid JSON (inline, @file.json, or - for stdin)") } +/// An application header given as "Name: value". The endpoint token header is +/// reserved for --token and --new-token. Errors never repeat the value, which may +/// be a credential. +pub fn header(value: &str) -> Result<(HeaderName, HeaderValue)> { + let (name, value) = value.split_once(':').context("Use -H \"Name: value\"")?; + let name = HeaderName::from_bytes(name.trim().as_bytes()) + .ok() + .context("Invalid header name in -H")?; + if name == "x-adapt-authorization" { + bail!("Pass the endpoint token with --token or --new-token, not -H"); + } + let value = HeaderValue::from_str(value.trim()) + .ok() + .with_context(|| format!("Invalid value for header {name}"))?; + Ok((name, value)) +} + pub fn object(source: Option<&str>) -> Result { let value = source .map(json) diff --git a/src/main.rs b/src/main.rs index bb1b7b0..a5ec6a2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,10 +36,17 @@ async fn run(cli: Cli) -> ExitCode { // This command owns its sandbox and must finish cleanup before returning. commands::run(cli).await } else { + // Stopping an endpoint request leaves no remote work behind. + let remote_work = !matches!( + &cli.command, + cli::Command::Endpoints(cli::EndpointCommand::Request(_)) + ); tokio::select! { result = commands::run(cli) => result, _ = tokio::signal::ctrl_c() => { - eprintln!("\nCancelled. Remote executions continue; use `adapt execs cancel ID` to stop one."); + if remote_work { + eprintln!("\nCancelled. Remote executions continue; use `adapt execs cancel ID` to stop one."); + } return ExitCode::from(130); } } diff --git a/tests/cli.rs b/tests/cli.rs index 10ce12e..0a3dea6 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use std::time::Duration; use support::*; +mod endpoint_request; mod image_list; mod mcp_tools; mod resource_prefixes; diff --git a/tests/endpoint_request/mod.rs b/tests/endpoint_request/mod.rs new file mode 100644 index 0000000..049615b --- /dev/null +++ b/tests/endpoint_request/mod.rs @@ -0,0 +1,500 @@ +use crate::support::*; +use serde_json::json; +use std::{ + io::{BufRead, BufReader, Read, Write}, + process::{Child, Stdio}, + sync::mpsc, + time::Duration, +}; + +fn endpoint(app: &Server) -> serde_json::Value { + json!({"id":ID,"url":format!("{}/", app.url),"accessMode":"public"}) +} + +fn spawn(dir: &std::path::Path, platform: &Server, args: &[&str]) -> Child { + command(dir, &platform.url) + .env("ADAPT_TOKEN", "test-token") + .env("ADAPT_ORG_ID", ORG) + .args(args) + // Held open until the child is dropped, so `-d -` waits for input. + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap() +} + +/// The application must never see Platform credentials, whatever else it receives. +fn assert_no_platform_credentials(request: &Request) { + assert!(!request.headers.contains_key("x-organization-id")); + for value in request.headers.values() { + assert!(!value.contains("test-token"), "Platform token leaked"); + } +} + +#[test] +fn streams_events_as_they_arrive_without_platform_credentials() { + let (read_first, first_read) = mpsc::channel::<()>(); + let app = Server::script(vec![Box::new(move |mut socket| { + let request = read_request(&mut socket); + assert_eq!(request.method, "GET"); + assert_eq!(request.target, "/events?since=1"); + assert_eq!(request.headers["accept"], "text/event-stream"); + assert!(!request.headers.contains_key("authorization")); + assert!(!request.headers.contains_key("x-adapt-authorization")); + assert_no_platform_credentials(&request); + // No Content-Length: the body runs until the connection closes. + write!( + socket, + "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\ndata: one\n\n" + ) + .unwrap(); + socket.flush().unwrap(); + // A buffering client would wait for the end of the body, so end it and + // let the test's send fail instead of hanging. + first_read + .recv_timeout(Duration::from_secs(10)) + .expect("The CLI did not print the first event while the stream was open"); + write!(socket, "data: two\n\n").unwrap(); + request + })]); + let platform = Server::start(vec![step( + "GET", + format!("/v1/ingresses/{ID}"), + None, + endpoint(&app), + )]); + let dir = tempfile::tempdir().unwrap(); + let mut child = spawn( + dir.path(), + &platform, + &[ + "endpoints", + "request", + ID, + "/events?since=1", + "-H", + "Accept: text/event-stream", + ], + ); + let mut stdout = BufReader::new(child.stdout.take().unwrap()); + let mut first = String::new(); + stdout.read_line(&mut first).unwrap(); + stdout.read_line(&mut first).unwrap(); + // The first event reached stdout while the application held the stream open. + assert_eq!(first, "data: one\n\n"); + read_first + .send(()) + .expect("The stream ended before the first event was printed"); + let mut rest = String::new(); + stdout.read_to_string(&mut rest).unwrap(); + assert_eq!(rest, "data: two\n\n"); + let status = child.wait().unwrap(); + let mut stderr = String::new(); + child + .stderr + .take() + .unwrap() + .read_to_string(&mut stderr) + .unwrap(); + assert!(status.success(), "{stderr}"); + platform.finish(); + app.finish(); +} + +#[test] +fn authenticated_requests_send_only_the_endpoint_token() { + let app = Server::start(vec![ + Box::new(|r| { + assert_eq!(r.method, "POST"); + assert_eq!(r.target, "/api/items"); + assert_eq!(r.headers["x-adapt-authorization"], "Bearer minted-token"); + // The application's own Authorization header passes through untouched. + assert_eq!(r.headers["authorization"], "Bearer app-secret"); + assert_eq!(r.headers["content-type"], "application/json"); + assert_eq!(r.json(), json!({"name":"a"})); + assert_no_platform_credentials(r); + Reply::json(201, json!({"created":true})) + }), + Box::new(|r| { + // The path is appended to the endpoint URL, keeping its prefix. + assert_eq!(r.target, "/prefix/hello?x=1"); + assert_eq!(r.headers["x-adapt-authorization"], "Bearer given-token"); + assert!(!r.headers.contains_key("authorization")); + assert_no_platform_credentials(r); + Reply::bytes("text/plain", b"hello".to_vec()) + }), + ]); + let platform = Server::start(vec![ + step("GET", "/v1/ingresses/11111111".into(), None, endpoint(&app)), + // The token is created for the resolved ID, not the prefix. + step( + "POST", + format!("/v1/ingresses/{ID}/access-tokens"), + Some(json!({})), + json!({"token":"minted-token","expiresAt":"2030-01-01T00:00:00Z"}), + ), + step( + "GET", + format!("/v1/ingresses/{ID}"), + None, + json!({"id":ID,"url":format!("{}/prefix/", app.url)}), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let output = run( + dir.path(), + &platform.url, + &[ + "endpoints", + "request", + "11111111", + "/api/items", + "-X", + "POST", + "--new-token", + "-H", + "Authorization: Bearer app-secret", + "-H", + "Content-Type: application/json", + "-d", + r#"{"name":"a"}"#, + ], + ); + assert_eq!(success(&output), json!({"created":true})); + assert!(!String::from_utf8_lossy(&output.stderr).contains("minted-token")); + + let output = run( + dir.path(), + &platform.url, + &[ + "endpoints", + "request", + ID, + "/hello?x=1", + "--token", + "given-token", + ], + ); + assert!(output.status.success()); + assert_eq!(output.stdout, b"hello"); + platform.finish(); + app.finish(); +} + +#[test] +fn body_sources_preserve_bytes() { + const BODY: &[u8] = b"first\0\xff\nlast"; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("body.bin"); + std::fs::write(&path, BODY).unwrap(); + let mut sources = vec![ + "-".to_owned(), + "@-".to_owned(), + format!("@{}", path.display()), + ]; + if cfg!(unix) { + sources.push("@/dev/stdin".into()); + } + for source in sources { + let app = Server::start(vec![Box::new(|request| { + assert_eq!(request.method, "POST"); + assert_eq!(request.body, BODY); + assert!(!request.headers.contains_key("content-type")); + Reply::bytes("application/octet-stream", BODY.to_vec()) + })]); + let platform = Server::start(vec![step( + "GET", + format!("/v1/ingresses/{ID}"), + None, + endpoint(&app), + )]); + let mut cmd = command(dir.path(), &platform.url); + cmd.env("ADAPT_TOKEN", "test-token") + .env("ADAPT_ORG_ID", ORG) + .args(["endpoints", "request", ID, "-X", "POST", "-d", &source]); + let output = with_stdin(cmd, BODY); + assert!( + output.status.success(), + "{source}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(output.stdout, BODY, "{source}"); + platform.finish(); + app.finish(); + } +} + +#[test] +fn body_file_errors_are_reported() { + let dir = tempfile::tempdir().unwrap(); + let large = dir.path().join("large.bin"); + std::fs::File::create(&large) + .unwrap() + .set_len(16 * 1024 * 1024 + 1) + .unwrap(); + for (path, message) in [ + (dir.path().join("missing.bin"), "Cannot read"), + (large, "Input exceeds the 16777216-byte limit"), + ] { + let platform = Server::start(vec![step( + "GET", + format!("/v1/ingresses/{ID}"), + None, + json!({"id":ID,"url":"http://127.0.0.1:9/"}), + )]); + let output = run( + dir.path(), + &platform.url, + &[ + "endpoints", + "request", + ID, + "-d", + &format!("@{}", path.display()), + ], + ); + assert_eq!(output.status.code(), Some(1)); + assert!(output.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains(message), "{stderr}"); + platform.finish(); + } +} + +#[test] +fn error_statuses_print_the_body_and_redirects_are_not_followed() { + let app = Server::start(vec![ + Box::new(|_| Reply { + status: 404, + content_type: "text/plain", + headers: vec![], + body: b"no such page".to_vec(), + }), + Box::new(|_| Reply { + status: 302, + content_type: "text/plain", + headers: vec![("Location".into(), "https://other.example/login".into())], + body: vec![], + }), + ]); + let platform = Server::start(vec![ + step("GET", format!("/v1/ingresses/{ID}"), None, endpoint(&app)), + step("GET", format!("/v1/ingresses/{ID}"), None, endpoint(&app)), + ]); + let dir = tempfile::tempdir().unwrap(); + let output = run( + dir.path(), + &platform.url, + &["endpoints", "request", ID, "/missing"], + ); + assert_eq!(output.status.code(), Some(1)); + assert_eq!(output.stdout, b"no such page"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("HTTP 404"), "{stderr}"); + // An application 401/404 is not a Platform sign-in problem. + assert!(!stderr.contains("auth login"), "{stderr}"); + + let output = run(dir.path(), &platform.url, &["endpoints", "request", ID]); + assert_eq!(output.status.code(), Some(1)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("HTTP 302"), "{stderr}"); + assert!(stderr.contains("redirects are not followed"), "{stderr}"); + assert!(stderr.contains("https://other.example/login"), "{stderr}"); + platform.finish(); + app.finish(); +} + +#[test] +fn paths_and_headers_cannot_redirect_or_impersonate_credentials() { + let dir = tempfile::tempdir().unwrap(); + for path in [ + "https://other.example/x", + "//other.example/x", + "/\\other.example/x", + "relative", + "/page#fragment", + ] { + let output = run( + dir.path(), + "http://localhost:3000", + &["endpoints", "request", ID, path], + ); + assert_eq!(output.status.code(), Some(1), "{path}"); + assert!(String::from_utf8_lossy(&output.stderr).contains("absolute path")); + } + // Rejected headers may hold credentials, so errors never repeat them. + for header in [ + "X-Adapt-Authorization: Bearer header-secret", + "Authorization: Bearer header-secret\u{1}", + "header-secret", + ] { + let output = run( + dir.path(), + "http://localhost:3000", + &["endpoints", "request", ID, "-H", header], + ); + assert_eq!(output.status.code(), Some(1), "{header}"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!stderr.contains("header-secret"), "{stderr}"); + } + let output = run( + dir.path(), + "http://localhost:3000", + &["endpoints", "request", ID, "--token", "a", "--new-token"], + ); + assert_eq!(output.status.code(), Some(2)); +} + +#[test] +fn transport_errors_do_not_print_the_request_url() { + // Nothing listens on this port once the listener is dropped. + let closed = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap(); + let platform = Server::start(vec![step( + "GET", + format!("/v1/ingresses/{ID}"), + None, + json!({"id":ID,"url":format!("http://{closed}/")}), + )]); + let dir = tempfile::tempdir().unwrap(); + let output = run( + dir.path(), + &platform.url, + &["endpoints", "request", ID, "/api?token=query-secret"], + ); + assert_eq!(output.status.code(), Some(1)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("Endpoint request failed"), "{stderr}"); + assert!(!stderr.contains("query-secret"), "{stderr}"); + platform.finish(); +} + +/// A Platform endpoint lookup that reports when it arrives. +#[cfg(unix)] +fn lookup(url: String, seen: mpsc::Sender<()>) -> Handler { + let reply = step( + "GET", + format!("/v1/ingresses/{ID}"), + None, + json!({"id":ID,"url":url}), + ); + Box::new(move |request| { + let reply = reply(request); + seen.send(()).unwrap(); + reply + }) +} + +/// Sends Ctrl-C after the lookup, once the CLI has had time to block, and returns +/// the exit code. Fails instead of hanging if Ctrl-C does not stop the CLI. +#[cfg(unix)] +fn interrupt(mut child: Child, looked_up: mpsc::Receiver<()>) -> Option { + // While the lookup is pending, the CLI's Ctrl-C handler is already installed. + looked_up.recv_timeout(Duration::from_secs(10)).unwrap(); + std::thread::sleep(Duration::from_millis(500)); + assert_eq!(unsafe { libc::kill(child.id() as i32, libc::SIGINT) }, 0); + for _ in 0..100 { + if let Some(status) = child.try_wait().unwrap() { + return status.code(); + } + std::thread::sleep(Duration::from_millis(100)); + } + child.kill().unwrap(); + child.wait().unwrap(); + panic!("Ctrl-C did not stop the request"); +} + +#[cfg(unix)] +fn assert_body_read_is_interruptible(source: &str) { + let (seen, looked_up) = mpsc::channel(); + // The body never ends, so the endpoint is never contacted. + let platform = Server::start(vec![lookup("http://127.0.0.1:9/".into(), seen)]); + let dir = tempfile::tempdir().unwrap(); + let mut child = spawn( + dir.path(), + &platform, + &["endpoints", "request", ID, "-d", source], + ); + child + .stdin + .as_mut() + .unwrap() + .write_all(b"partial body") + .unwrap(); + assert_eq!(interrupt(child, looked_up), Some(130), "{source}"); + platform.finish(); +} + +#[cfg(unix)] +#[test] +fn ctrl_c_stops_a_request_waiting_for_stdin() { + assert_body_read_is_interruptible("-"); +} + +#[cfg(unix)] +#[test] +fn ctrl_c_stops_a_request_waiting_for_stdin_via_at_dash() { + assert_body_read_is_interruptible("@-"); +} + +#[cfg(unix)] +#[test] +fn ctrl_c_stops_a_request_waiting_for_stdin_device() { + assert_body_read_is_interruptible("@/dev/stdin"); +} + +#[cfg(unix)] +fn assert_fifo_read_is_interruptible(with_writer: bool) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("body.fifo"); + let name = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap(); + assert_eq!( + unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, + 0, + "{}", + std::io::Error::last_os_error() + ); + // Without a writer, open blocks; with one held open, reading waits for EOF. + let _writer = with_writer.then(|| { + std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(&path) + .unwrap() + }); + assert_body_read_is_interruptible(&format!("@{}", path.display())); +} + +#[cfg(unix)] +#[test] +fn ctrl_c_stops_a_request_opening_a_fifo() { + assert_fifo_read_is_interruptible(false); +} + +#[cfg(unix)] +#[test] +fn ctrl_c_stops_a_request_reading_a_fifo() { + assert_fifo_read_is_interruptible(true); +} + +#[cfg(unix)] +#[test] +fn ctrl_c_stops_a_request_whose_stdout_is_full() { + let app = Server::script(vec![Box::new(|mut socket| { + let request = read_request(&mut socket); + // Far more than a pipe holds: the CLI blocks writing to its unread stdout. + let _ = write!(socket, "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n"); + let _ = socket.write_all(&vec![b'x'; 8 << 20]); + request + })]); + let (seen, looked_up) = mpsc::channel(); + let platform = Server::start(vec![lookup(format!("{}/", app.url), seen)]); + let dir = tempfile::tempdir().unwrap(); + let child = spawn(dir.path(), &platform, &["endpoints", "request", ID]); + assert_eq!(interrupt(child, looked_up), Some(130)); + platform.finish(); + app.finish(); +}