Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

4.2 KB
Raw Blame
//! Platform requests preserve response bytes and scope credentials to the selected organization.
use assert_cmd::Command;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use tempfile::tempdir;

fn cli() -> Command {
    Command::new(assert_cmd::cargo::cargo_bin!("boxlite"))
}

#[test]
fn api_streams_preview_bytes_for_the_selected_environment() {
    let dir = tempdir().unwrap();
    let server = TcpListener::bind("127.0.0.1:0").unwrap();
    let api = format!("http://{}/api/v1/org", server.local_addr().unwrap());
    let jpeg = [0xff, 0xd8, 0x00, 0x83, 0xff, 0xd9];
    let request = std::thread::spawn(move || {
        let (mut stream, _) = server.accept().unwrap();
        let mut request_line = String::new();
        BufReader::new(&stream)
            .read_line(&mut request_line)
            .unwrap();
        write!(
            stream,
            "HTTP/1.1 200 OK\r\nContent-Type: image/jpeg\r\nContent-Length: {}\r\n\r\n",
            jpeg.len()
        )
        .unwrap();
        stream.write_all(&jpeg).unwrap();
        request_line
    });
    cli()
        .current_dir(dir.path())
        .env_clear()
        .env("PATH", std::env::var_os("PATH").unwrap())
        .env("HOME", dir.path())
        .env("BOXLITE_API_URL", api)
        .env("BOXLITE_API_KEY", "test-key")
        .args([
            "api",
            "GET",
            "/apps/shop/preview?env=staging",
            "--accept",
            "image/jpeg",
        ])
        .assert()
        .success()
        .stdout(jpeg.to_vec())
        .stderr("");
    assert_eq!(
        request.join().unwrap(),
        "GET /api/v1/org/apps/shop/preview?env=staging HTTP/1.1\r\n"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn raw_requests_and_domain_binding_use_the_selected_platform_context() {
    use axum::{
        Json, Router,
        extract::Request,
        http::{Method, header},
    };
    use serde_json::{Value, json};
    let router = Router::new().fallback(|request:Request| async move {
        let (head, body) = request.into_parts();
        assert_eq!(head.headers[header::AUTHORIZATION], "Bearer test-key");
        let body = axum::body::to_bytes(body, 2048).await.unwrap();
        let doc: Value = serde_json::from_slice(&body).unwrap();
        match (head.method,head.uri.path()) {
            (Method::POST, "/v1/team/apps/store/actions") => {
                assert_eq!(head.uri.query(),Some("env=staging"));
                assert_eq!(head.headers["idempotency-key"],"run-42");
                assert_eq!(doc,json!({"type":"publish"}));
                Json(json!({"ok":true}))
            }
            (Method::PUT, "/v1/team/domains/shop.example.test/target") => {
                assert_eq!(doc,json!({"type":"app","app":"shop","environment":"qa"}));
                Json(json!({"hostname":"shop.example.test","url":"https://shop.example.test","target":doc}))
            }
            _ => panic!("unexpected route {}",head.uri),
        }
    });
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = format!("http://{}", listener.local_addr().unwrap());
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
    let dir = tempdir().unwrap();
    let call = |args: &[&str]| {
        let mut command = cli();
        command
            .env_clear()
            .env("BOXLITE_HOME", dir.path())
            .env("BOXLITE_API_KEY", "test-key")
            .args(["--url", &address, "--path-prefix", "team"])
            .args(args);
        command
    };
    call(&[
        "api",
        "POST",
        "/apps/store/actions?env=staging",
        "-i",
        "-",
        "-H",
        "Idempotency-Key: run-42",
    ])
    .write_stdin(r#"{"type":"publish"}"#)
    .assert()
    .success()
    .stdout(r#"{"ok":true}"#);
    call(&[
        "domain",
        "bind",
        "shop.example.test",
        "--type",
        "app",
        "--app",
        "shop",
        "--env",
        "qa",
    ])
    .assert()
    .success()
    .stdout("shop.example.test → shop/qa\nhttps://shop.example.test\n");
    for path in [
        "https://example.test",
        "//example.test/steal",
        "/%2e%2e/other",
    ] {
        call(&["api", "GET", path]).assert().failure().stdout("");
    }
}