fabro/lib/crates/fabro-server/tests/it/api/tcp.rs
fabro-sh-0530[bot] 7f84ac5e3f
Replace run-scoped sandbox config with named environments (#360)
## Summary

Replaces the `[run.sandbox]` configuration surface with a named,
provider-explicit environment catalog. Runs now select an environment by
slug (`[run.environment] id = "..."`) rather than configuring a sandbox
inline. Fabro resolves the catalog through normal settings precedence,
applies sparse run-level overrides, and creates a concrete sandbox from
the resolved environment.

This is a clean break — no `[run.sandbox]` compatibility layer.

### Plan Summary

- **New config shape:** Top-level `[environments.<slug>]` catalog valid
in `settings.toml`, `.fabro/project.toml`, and `workflow.toml`. Runs
reference a slug via `[run.environment] id = "..."` with optional sparse
overrides under `[run.environment.*]`.
- **Unified environment fields:** `provider`, `image` (ref +
dockerfile), `resources` (cpu/memory/disk), `network` (mode + allow
CIDRs), `lifecycle` (preserve/stop_on_terminal/auto_stop), `labels`,
`volumes`, `env` — replacing the previous split between `[run.sandbox]`,
`[run.sandbox.docker]`, `[run.sandbox.daytona]`, and
`[run.sandbox.daytona.snapshot]`.
- **OpenAPI schema update:** `RunSandboxSettings`, `DockerSettings`,
`DaytonaSettings`, and `DaytonaNetworkLayer` replaced with
`RunEnvironmentSettings`, `EnvironmentSettings`, `EnvironmentProvider`,
`EnvironmentImageSettings`, `EnvironmentResourcesSettings`,
`EnvironmentNetworkSettings`, `EnvironmentLifecycleSettings`, and
`EnvironmentVolumeSettings`.
- **CLI flag rename:** `--sandbox <provider>` → `--environment <slug>`
on `run`, `create`, `preflight`, and `server start/restart`.
- **Provider capability model:** Hard errors for security properties a
provider cannot enforce (local with blocked/CIDR networking; docker with
CIDR allow-lists). Warnings for unsupported resource limits, volumes,
labels, auto-stop, and Docker Dockerfiles.
- **Docs and internal code updated** throughout: `.fabro/project.toml`,
workflow configs, all public docs, CLI args, manifest builders, and the
runner's GitHub credentials check.

### Provider mapping

| Environment field | Local | Docker | Daytona |
|---|---|---|---|
| `image.ref` | Ignored | Docker image | Snapshot name |
| `image.dockerfile` | Ignored | Warning; ignored | Snapshot Dockerfile
(requires `image.ref`) |
| `resources.cpu/memory/disk` | Warning; ignored | cpu_quota / memory
limit / warning | Snapshot sizing |
| `network.mode = block` | **Error** | `network_mode = none` | Daytona
block |
| `network.mode = cidr_allow_list` | **Error** | **Error** | Daytona
CIDR allow-list |
| `labels` | Warning; ignored | Warning; ignored | Daytona labels |
| `volumes` | Warning; ignored | Warning; ignored | Daytona volume
mounts |
| `lifecycle.auto_stop` | Warning; ignored | Warning; ignored | Daytona
auto-stop interval |
| `env` | Process env overlay | Container env | Sandbox env |


### Fabro Details

<details>
<summary>Ran 11 stages in 217m 39s for $129.86</summary>

| Stage | Duration | Cost | Retries |
|---|---|---|---|
| start | 0s | – | 0 |
| toolchain | 1s | – | 0 |
| preflight_compile | 4m 7s | – | 0 |
| preflight_lint | 4m 9s | – | 0 |
| fix_lints | 3m 46s | $1.06 | 0 |
| implement | 76m 6s | $57.39 | 0 |
| simplify_opus | 71m 50s | $38.17 | 0 |
| simplify_gpt | 8m 27s | $2.24 | 0 |
| verify | 6m 10s | – | 0 |
| fixup | 42m 1s | $31.00 | 0 |
| fmt | 3s | – | 0 |
| **Total** | **217m 39s** | **$129.86** | **0** |

</details>

<details>
<summary>Ran <code>ImplementPlan.fabro</code> (12 nodes and 15
edges)</summary>

```dot
digraph ImplementPlan {
    graph [
        goal="Implement and simplify",
        model_stylesheet="
            * { model: claude-opus-4-7; }
        "
    ]
    rankdir=LR

    start [shape=Mdiamond, label="Start"]
    exit  [shape=Msquare, label="Exit"]

    toolchain         [label="Toolchain", shape=parallelogram, script="command -v cargo >/dev/null || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && sudo ln -sf $HOME/.cargo/bin/* /usr/local/bin/; }; cargo --version 2>&1", max_retries=0]
    preflight_compile [label="Preflight Compile", shape=parallelogram, script="cargo check -q --workspace 2>&1", max_retries=0]
    preflight_lint    [label="Preflight Lint", shape=parallelogram, script="cargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1", max_retries=0]
    fix_lints         [label="Fix Lints", prompt="The preflight lint step failed. Read the build output from context and fix all clippy lint warnings.", max_visits=3]
    implement         [label="Implement", prompt="Read the plan file referenced in the goal and implement every step. Make all the code changes described in the plan. Use red/green TDD.", model="gpt-55", reasoning_effort="xhigh"]
    simplify_opus     [label="Simplify (Opus)", prompt="@prompts/simplify.md"]
    simplify_gpt      [label="Simplify (GPT-55)", prompt="@prompts/simplify.md", model="gpt-55"]
    verify            [label="Verify", shape=parallelogram, script="cargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1 && cargo nextest run --cargo-quiet --workspace --status-level fail 2>&1 && cargo dev docs refresh 2>&1 && cargo dev docs check 2>&1", goal_gate=true, retry_target="fixup"]
    fixup             [label="Fixup", prompt="The verify step failed. Read the build output from context and fix all clippy lint warnings, test failures, and generated docs errors.", max_visits=3]
    fmt               [label="Format", shape=parallelogram, script="cargo +nightly-2026-04-14 fmt --all 2>&1", max_retries=0]

    start -> toolchain
    toolchain -> preflight_compile [condition="outcome=succeeded"]
    toolchain -> exit
    preflight_compile -> preflight_lint [condition="outcome=succeeded"]
    preflight_compile -> exit
    preflight_lint -> implement [condition="outcome=succeeded"]
    preflight_lint -> fix_lints
    fix_lints -> preflight_lint
    implement -> simplify_opus -> simplify_gpt -> verify
    verify -> fmt   [condition="outcome=succeeded"]
    verify -> fixup
    fixup -> verify
    fmt -> exit
}

```

</details>

⚒️ Generated with [Fabro](https://fabro.sh)

---------

Co-authored-by: Fabro <noreply@fabro.sh>
Co-authored-by: Bryan Helmkamp <bryan@brynary.com>
Co-authored-by: Bryan Helmkamp <bhelmkamp@users.noreply.github.com>
2026-05-23 13:03:21 -04:00

252 lines
7.6 KiB
Rust

#![expect(
clippy::disallowed_methods,
reason = "integration tests stage fixtures with sync std::fs; test infrastructure, not Tokio-hot path"
)]
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use axum::http::StatusCode;
use fabro_config::bind::Bind;
use fabro_config::{RuntimeDirectory, ServerSettingsBuilder};
use fabro_server::ip_allowlist::{IpAllowlist, IpAllowlistConfig};
use fabro_server::jwt_auth::{AuthMode, resolve_auth_mode_with_lookup};
use fabro_server::serve::{ServeArgs, serve_command};
use fabro_server::server::{RouterOptions, build_router_with_options};
use fabro_server::test_support::{TEST_DEV_TOKEN, TEST_SESSION_SECRET, test_app_state};
use fabro_util::terminal::Styles;
use tempfile::TempDir;
use tokio::net::TcpListener;
use tokio::task::JoinHandle;
use tokio::time::sleep;
use crate::helpers::{api, reqwest_status};
async fn start_tcp_server(auth_mode: AuthMode, ip_allowlist: Arc<IpAllowlistConfig>) -> SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("test TCP listener should bind");
let addr = listener
.local_addr()
.expect("test TCP listener should have a local address");
let state = test_app_state();
let router =
build_router_with_options(state, &auth_mode, ip_allowlist, RouterOptions::default());
tokio::spawn(async move {
let _ = axum::serve(
listener,
router.into_make_service_with_connect_info::<SocketAddr>(),
)
.await;
});
addr
}
#[cfg(unix)]
fn build_unix_client(path: &Path) -> fabro_http::HttpClient {
fabro_http::HttpClientBuilder::new()
.unix_socket(path)
.no_proxy()
.build()
.expect("Unix test client should build")
}
fn write_test_config(tempdir: &TempDir, settings: &str) -> PathBuf {
let config_path = tempdir.path().join("settings.toml");
std::fs::write(&config_path, settings).expect("test settings should write");
std::fs::write(
RuntimeDirectory::new(tempdir.path()).env_path(),
format!("FABRO_DEV_TOKEN={TEST_DEV_TOKEN}\nSESSION_SECRET={TEST_SESSION_SECRET}\n"),
)
.expect("test env file should write");
config_path
}
async fn spawn_served_listener(
settings: impl AsRef<str>,
) -> (JoinHandle<anyhow::Result<()>>, Bind, TempDir) {
let tempdir = tempfile::tempdir().expect("temporary server directory should create");
let config_path = write_test_config(&tempdir, settings.as_ref());
let styles: &'static Styles = Box::leak(Box::new(Styles::new(false)));
let (tx, rx) = tokio::sync::oneshot::channel();
let mut tx = Some(tx);
let storage_dir = tempdir.path().to_path_buf();
let handle = tokio::spawn(async move {
Box::pin(serve_command(
ServeArgs {
bind: None,
web: false,
no_web: true,
model: None,
provider: None,
environment: None,
max_concurrent_runs: None,
config: Some(config_path),
#[cfg(debug_assertions)]
watch_web: false,
},
styles,
Some(storage_dir),
None,
move |bind| {
let sender = tx.take().expect("server should only report readiness once");
sender.send(bind.clone()).ok();
Ok(())
},
))
.await
});
let Ok(bind) = rx.await else {
let result = handle
.await
.expect("server task should not panic before reporting readiness");
panic!("server should report its bind address: {result:?}");
};
(handle, bind, tempdir)
}
async fn wait_for_health(client: &fabro_http::HttpClient, url: &str) {
for _ in 0..50 {
if let Ok(response) = client.get(url).send().await {
let status = response.status();
if status == 200 {
return;
}
}
sleep(Duration::from_millis(10)).await;
}
panic!("timed out waiting for health endpoint at {url}");
}
#[tokio::test]
async fn tcp_accepts_plain_http_requests() {
let (handle, bind, _tempdir) = spawn_served_listener(
r#"
_version = 1
[server.listen]
type = "tcp"
address = "127.0.0.1:0"
[server.auth]
methods = ["dev-token"]
"#,
)
.await;
let addr = match bind {
Bind::Tcp(addr) => addr,
Bind::Unix(path) => panic!("expected TCP bind, got unix socket at {}", path.display()),
};
let client = fabro_http::test_http_client().unwrap();
wait_for_health(&client, &format!("http://127.0.0.1:{}/health", addr.port())).await;
let response = client
.get(format!("http://127.0.0.1:{}{}", addr.port(), api("/runs")))
.bearer_auth(TEST_DEV_TOKEN)
.send()
.await
.expect("plain HTTP request should succeed");
reqwest_status(response, StatusCode::OK, "GET /api/v1/runs").await;
handle.abort();
}
#[tokio::test]
async fn tcp_dev_token_auth_uses_bearer_auth() {
let resolved = ServerSettingsBuilder::from_toml(
r#"
_version = 1
[server.auth]
methods = ["dev-token"]
"#,
)
.expect("test settings should resolve")
.server;
let auth_mode = resolve_auth_mode_with_lookup(&resolved, |name| match name {
"SESSION_SECRET" => Some(TEST_SESSION_SECRET.to_string()),
"FABRO_DEV_TOKEN" => Some(TEST_DEV_TOKEN.to_string()),
_ => None,
})
.expect("auth mode should resolve");
let addr = start_tcp_server(auth_mode, Arc::new(IpAllowlistConfig::default())).await;
let client = fabro_http::test_http_client().unwrap();
let url = format!("http://127.0.0.1:{}{}", addr.port(), api("/runs"));
let unauthorized = client.get(&url).send().await.unwrap();
reqwest_status(unauthorized, StatusCode::UNAUTHORIZED, "GET /api/v1/runs").await;
let authorized = client
.get(url)
.bearer_auth(TEST_DEV_TOKEN)
.send()
.await
.unwrap();
reqwest_status(authorized, StatusCode::OK, "GET /api/v1/runs").await;
}
#[cfg(unix)]
#[tokio::test]
async fn unix_socket_accepts_plain_http_requests() {
let socket_dir = tempfile::tempdir().unwrap();
let socket_path = socket_dir.path().join("fabro.sock");
let (handle, bind, _tempdir) = spawn_served_listener(format!(
r#"
_version = 1
[server.listen]
type = "unix"
path = "{}"
[server.auth]
methods = ["dev-token"]
"#,
socket_path.display()
))
.await;
let path = match bind {
Bind::Unix(path) => path,
Bind::Tcp(addr) => panic!("expected Unix bind, got TCP address {addr}"),
};
let client = build_unix_client(&path);
wait_for_health(&client, "http://fabro/health").await;
let response = client
.get(format!("http://fabro{}", api("/runs")))
.bearer_auth(TEST_DEV_TOKEN)
.send()
.await
.expect("Unix-socket HTTP request should succeed");
reqwest_status(response, StatusCode::OK, "GET /api/v1/runs").await;
handle.abort();
}
#[tokio::test]
async fn tcp_ip_allowlist_uses_connect_info() {
let addr = start_tcp_server(
fabro_server::test_support::test_auth_mode(),
Arc::new(IpAllowlistConfig {
allowlist: IpAllowlist::new(vec!["10.0.0.0/8".parse().unwrap()]),
trusted_proxy_count: 0,
}),
)
.await;
let client = fabro_http::test_http_client().unwrap();
let response = client
.get(format!("http://127.0.0.1:{}{}", addr.port(), api("/runs")))
.send()
.await
.unwrap();
reqwest_status(response, StatusCode::FORBIDDEN, "GET /api/v1/runs").await;
}