Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions skills/adapt/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
29 changes: 29 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
/// Request body: literal text, @file, or - for stdin
#[arg(long, short = 'd')]
pub data: Option<String>,
/// Endpoint access token for an authenticated endpoint
#[arg(long, conflicts_with = "new_token")]
pub token: Option<String>,
/// Create a new endpoint access token and use it for this request
#[arg(long)]
pub new_token: bool,
}

#[derive(Clone, Copy, ValueEnum)]
Expand Down
106 changes: 105 additions & 1 deletion src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8> {
Expand Down Expand Up @@ -168,6 +174,7 @@ pub async fn run(cli: Cli) -> Result<u8> {
},
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?,
Expand Down Expand Up @@ -638,7 +645,104 @@ async fn endpoints(api: &Api, command: EndpointCommand) -> Result<Value> {
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<u8> {
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")?;
Comment thread
miqui marked this conversation as resolved.
Resolved
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<Value> {
Expand Down
37 changes: 29 additions & 8 deletions src/input.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use anyhow::{Context, Result, bail};
use reqwest::header::{HeaderName, HeaderValue};
use serde_json::{Map, Value};
use std::{
fmt,
Expand Down Expand Up @@ -70,19 +71,39 @@ pub fn bytes(path: &Path, max: u64) -> Result<Vec<u8>> {
Ok(result)
}

/// JSON is accepted inline, from @file, or from stdin with '-'.
pub fn json(source: &str) -> Result<Value> {
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<Vec<u8>> {
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<Value> {
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<Value> {
let value = source
.map(json)
Expand Down
9 changes: 8 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down
1 change: 1 addition & 0 deletions tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading