The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
//! Hosted workload requests cross the control-plane and App origins with different credentials.
use axum::{
Router,
body::{Body, to_bytes},
extract::Request,
http::{Response, StatusCode, header},
response::IntoResponse,
};
use serde_json::{Value, json};
use std::{
fs,
net::SocketAddr,
sync::{Arc, Mutex},
};
use tokio::net::TcpListener;
#[derive(Debug)]
struct Received {
path: String,
bearer: Option<String>,
cookie: Option<String>,
body: Vec<u8>,
}
type Log = Arc<Mutex<Vec<Received>>>;
async fn server(
handle: impl Fn(&Received) -> Response<Body> + Send + Sync + 'static,
) -> (SocketAddr, Log) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let log = Log::default();
let recorded = log.clone();
let handle = Arc::new(handle);
let app = Router::new().fallback(move |request: Request| {
let recorded = recorded.clone();
let handle = handle.clone();
async move {
let (head, body) = request.into_parts();
let get = |name| {
head.headers
.get(name)
.and_then(|h| h.to_str().ok())
.map(str::to_owned)
};
let observed = Received {
path: head.uri.to_string(),
bearer: get(header::AUTHORIZATION),
cookie: get(header::COOKIE),
body: to_bytes(body, 65536).await.unwrap().to_vec(),
};
let result = handle(&observed);
recorded.lock().unwrap().push(observed);
result
}
});
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
(address, log)
}
async fn run(home: &std::path::Path, args: &[&str], success: bool) -> Value {
let result = tokio::process::Command::new(assert_cmd::cargo::cargo_bin!("boxlite"))
.env_clear()
.env("HOME", home)
.env("PATH", "")
.current_dir(home)
.arg("--home")
.arg(home)
.args(["--context", "team", "app", "--app", "shop", "--json"])
.args(args)
.output()
.await
.unwrap();
assert_eq!(
result.status.success(),
success,
"{args:?}: {}",
String::from_utf8_lossy(&result.stderr)
);
serde_json::from_slice(if success {
&result.stdout
} else {
&result.stderr
})
.unwrap()
}
#[tokio::test]
async fn app_workload_exchanges_oidc_ticket_and_keeps_redirects_and_credentials_on_their_origin() {
let (app, site) = server(|r| {
if r.path.starts_with("/.boxlite/open?") {
Response::builder()
.status(302)
.header(header::LOCATION, "/")
.header(
header::SET_COOKIE,
"__Host-bxl_access=one-use; Path=/; HttpOnly",
)
.body(Body::empty())
.unwrap()
} else {
Response::builder()
.status(307)
.header(header::LOCATION, "https://example.invalid/next")
.header(header::SET_COOKIE, "user=private; HttpOnly")
.body(Body::from("redirect"))
.unwrap()
}
})
.await;
let (control,requests)=server(move|r|{
let body=match r.path.as_str(){
"/v1/org/apps/shop/envs/main"=>json!({"url":format!("http://{app}")}),
"/v1/org/apps/shop/envs/main/auth/test-sessions"=>json!({"cookie":"end_user=test","user":{"email":"[email protected]"}}),
"/v1/org/apps/shop/envs/main/open-ticket"=>json!({"url":format!("http://{app}/.boxlite/open?t=one"),"expires_at":"2040-01-01T00:00:00Z"}),
_=>return axum::http::StatusCode::NOT_FOUND.into_response(),
};
axum::Json(body).into_response()
}).await;
let home = tempfile::tempdir().unwrap();
fs::write(home.path().join("credentials.toml"),format!("[profiles.team]\nurl='http://{control}'\npath_prefix='org'\nauth_method='oidc'\naccess_token='platform-token'\nexpires_at='2040-01-01T00:00:00Z'\n")).unwrap();
let result = run(
home.path(),
&[
"request",
"/submit",
"--data",
"hello",
"--as",
"[email protected]",
"--role",
"owner",
"--expect",
"307",
],
true,
)
.await;
assert_eq!(result["status"], 307);
assert_eq!(result["redirect"], "https://example.invalid/next");
assert_eq!(
result["headers"]["set-cookie"][0],
"user=<redacted>; HttpOnly"
);
{
let site = site.lock().unwrap();
assert_eq!(site.len(), 2);
assert!(site.iter().all(|r| r.bearer.is_none()));
assert_eq!(
site[1].cookie.as_deref(),
Some("end_user=test; __Host-bxl_access=one-use")
);
assert_eq!(site[1].body, b"hello");
}
let ticket = run(
home.path(),
&[
"status",
"--open",
"--print-url",
"--as",
"[email protected]",
"--role",
"owner",
"--path",
"/admin",
],
true,
)
.await;
assert_eq!(ticket["opened"], false);
let requests = requests.lock().unwrap();
assert!(
requests
.iter()
.all(|r| r.bearer.as_deref() == Some("Bearer platform-token"))
);
assert_eq!(
serde_json::from_slice::<Value>(&requests.last().unwrap().body).unwrap(),
json!({"next":"/admin","as":"[email protected]","role":"owner"})
);
}
#[tokio::test]
async fn app_workload_requests_check_the_destination_and_never_replay_a_redirect_with_the_organization_key()
{
let (other, other_requests) = server(|_| axum::Json(json!({})).into_response()).await;
let (site, app_requests) = server(move |r| {
if r.path == "/shop/health" {
Response::builder()
.status(302)
.header(header::LOCATION, format!("http://{other}/next"))
.body(Body::empty())
.unwrap()
} else if r.path == "/shop/unavailable" {
StatusCode::SERVICE_UNAVAILABLE.into_response()
} else {
axum::Json(json!({"healthy":true})).into_response()
}
})
.await;
let (control, control_requests) =
server(move |_| axum::Json(json!({"url":format!("http://{site}/shop")})).into_response())
.await;
let home = tempfile::tempdir().unwrap();
fs::create_dir(home.path().join(".boxlite")).unwrap();
fs::write(
home.path().join("credentials.toml"),
format!("[profiles.team]\nurl='http://{control}'\npath_prefix='org'\napi_key='org-key'\n"),
)
.unwrap();
let direct = run(home.path(), &["curl", "/read", "--body"], true).await;
assert_eq!(direct, json!({"healthy":true}));
let cached = run(home.path(), &["request", "/read"], true).await;
assert_eq!(cached["timing"]["cached"]["url"], true);
let failure = run(home.path(), &["request", "/unavailable", "--fail"], false).await;
assert_eq!(failure["error"]["code"], "http_error");
assert_eq!(failure["error"]["status"], 503);
let wrong = run(
home.path(),
&["request", "/health", "--expect", "200"],
false,
)
.await;
assert_eq!(wrong["error"]["code"], "http_unexpected");
run(
home.path(),
&["request", &format!("http://{other}/foreign")],
false,
)
.await;
assert!(other_requests.lock().unwrap().is_empty());
assert_eq!(control_requests.lock().unwrap().len(), 1);
let app = app_requests.lock().unwrap();
assert_eq!(app.len(), 4);
assert!(
app.iter()
.all(|r| r.bearer.as_deref() == Some("Bearer org-key"))
);
}