use std::{net::IpAddr, num::NonZeroU16, sync::Arc, time::Instant};
use axum::{
Json, Router,
body::{Body, Bytes, HttpBody},
extract::{
DefaultBodyLimit, FromRequest, Path, Request, State,
rejection::{JsonRejection, PathRejection},
},
http::{HeaderMap, HeaderValue, Method, StatusCode, Uri, header},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::{delete, get, patch, post},
};
use clap::ValueEnum;
use serde::{Deserialize, Deserializer, Serialize};
use time::{OffsetDateTime, SignedDuration};
use tokio::task::spawn_blocking;
use troll_core::{Role, Zone, ZoneChanges, parse_duration};
use crate::{
cli::{
AppAllocationArgs, ClaimArgs, EditArgs, KindArg, LeaseArgs, RoleArg, WebArgs, WebScheme,
},
commands::{
Context, app, edit, history, inspect, list, registry,
timestamp::{deserialize_leased_at, deserialize_required_leased_at, parse_leased_at},
zone,
},
error::{CliError, ErrorOutput},
json_object::JsonObject,
output::SCHEMA,
};
use super::{SessionToken, log::Logger, web};
const TOKEN_HEADER: &str = "x-troll-token";
const JSON_TYPE: &str = "application/json";
const MAX_BODY_BYTES: usize = 64 * 1024;
const DEFAULT_HTTP_PORT: u16 = 80;
const LOOPBACK_HOSTS: [&str; 2] = ["127.0.0.1", "localhost"];
pub(super) fn router(context: Arc<Context>, port: u16, token: SessionToken, log: Logger) -> Router {
Router::new()
.merge(web::routes(port, &token))
.route("/healthz", get(health))
.route("/api/v1/ports", get(ports))
.route("/api/v1/ports/{port}", get(check))
.route("/api/v1/drift", get(drift))
.route("/api/v1/snapshot", get(snapshot))
.route(
"/api/v1/claims",
post(claim).route_layer(middleware::from_fn(require_json)),
)
.route(
"/api/v1/claims/{port}",
delete(release_claim)
.merge(patch(edit_claim).route_layer(middleware::from_fn(require_json))),
)
.route(
"/api/v1/leases",
post(lease).route_layer(middleware::from_fn(require_json)),
)
.route(
"/api/v1/leases/{port}/renew",
post(renew).route_layer(middleware::from_fn(require_json)),
)
.route(
"/api/v1/leases/{port}",
delete(release).merge(patch(edit_lease).route_layer(middleware::from_fn(require_json))),
)
.route(
"/api/v1/lease-groups/{group}/renew",
post(renew_group).route_layer(middleware::from_fn(require_json)),
)
.route("/api/v1/lease-groups/{group}", delete(release_group))
.route(
"/api/v1/zones",
get(zones).merge(post(add_zone).route_layer(middleware::from_fn(require_json))),
)
.route(
"/api/v1/zones/{label}",
delete(remove_zone)
.merge(patch(edit_zone).route_layer(middleware::from_fn(require_json))),
)
.route(
"/api/v1/apps",
get(apps).merge(post(reserve_app).route_layer(middleware::from_fn(require_json))),
)
.route("/api/v1/apps/{app}", get(show_app).delete(release_app))
.route(
"/api/v1/apps/{app}/components",
post(add_components).route_layer(middleware::from_fn(require_json)),
)
.route(
"/api/v1/apps/{app}/components/{component}",
delete(remove_component),
)
.route(
"/api/v1/sweep",
post(sweep).route_layer(middleware::from_fn(require_json)),
)
.route("/api/v1/history", get(history_list))
.route(
"/api/v1/history/{id}/restore",
post(history_restore).route_layer(middleware::from_fn(require_json)),
)
.fallback(not_found)
.method_not_allowed_fallback(not_found)
.layer(middleware::from_fn_with_state(
Arc::new((Access::new(port, token), log)),
guard_request,
))
.with_state(context)
}
struct Access {
hosts: Vec<String>,
token: SessionToken,
}
impl Access {
fn new(port: u16, token: SessionToken) -> Self {
let mut hosts = Vec::from(LOOPBACK_HOSTS.map(|host| format!("{host}:{port}")));
if port == DEFAULT_HTTP_PORT {
hosts.extend(LOOPBACK_HOSTS.map(str::to_owned));
}
Self { hosts, token }
}
fn allows_host(&self, host: &[u8]) -> bool {
self.hosts.iter().any(|allowed| host == allowed.as_bytes())
}
fn check(&self, request: &Request) -> Result<(), ApiError> {
let headers = request.headers();
let Some(host) = single_header(headers, header::HOST)
.map(HeaderValue::as_bytes)
.filter(|host| self.allows_host(host))
else {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"Forbidden",
"Host is not allowed",
3,
));
};
if request
.uri()
.authority()
.is_some_and(|authority| !self.allows_host(authority.as_str().as_bytes()))
{
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"Forbidden",
"request target authority is not allowed",
3,
));
}
if matches!(
*request.method(),
Method::POST | Method::PATCH | Method::DELETE
) {
if !self.is_same_origin(headers, host) {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"Forbidden",
"Origin is not allowed",
3,
));
}
if !single_header(headers, TOKEN_HEADER)
.is_some_and(|token| self.token.matches(token.as_bytes()))
{
return Err(ApiError::new(
StatusCode::UNAUTHORIZED,
"Unauthorized",
"a valid X-Troll-Token is required",
3,
));
}
}
Ok(())
}
fn is_same_origin(&self, headers: &HeaderMap, host: &[u8]) -> bool {
let authority = single_header(headers, header::ORIGIN)
.and_then(|origin| origin.as_bytes().strip_prefix(b"http://"));
authority.is_some_and(|authority| {
self.allows_host(authority)
&& (authority == host
|| authority.strip_suffix(b":80") == Some(host)
|| host.strip_suffix(b":80") == Some(authority))
})
}
}
fn single_header(
headers: &HeaderMap,
name: impl axum::http::header::AsHeaderName,
) -> Option<&HeaderValue> {
let values = headers.get_all(name);
let mut values = values.iter();
let value = values.next()?;
values.next().is_none().then_some(value)
}
async fn guard_request(
State(service): State<Arc<(Access, Logger)>>,
request: Request,
next: Next,
) -> Response {
let (access, log) = service.as_ref();
let started = Instant::now();
let method = request.method().clone();
let path = request.uri().path().to_owned();
let mut response = match access.check(&request) {
Err(error) => error.into_response(),
Ok(()) if method == Method::OPTIONS => ApiError::new(
StatusCode::METHOD_NOT_ALLOWED,
"MethodNotAllowed",
"OPTIONS is not supported",
2,
)
.into_response(),
Ok(()) if method == Method::HEAD => not_found().await.into_response(),
Ok(()) => match buffer_request(request).await {
Ok(request) => next.run(request).await,
Err(error) => error.into_response(),
},
};
web::apply_browser_headers(response.headers_mut());
log.line(format_args!(
"troll serve {} {} {} {}ms",
access.token.redact(method.as_str()),
access.token.redact(&path),
response.status().as_u16(),
started.elapsed().as_millis(),
));
response
}
async fn buffer_request(request: Request) -> Result<Request, ApiError> {
if request.body().is_end_stream() {
return Ok(request);
}
let (parts, body) = request.into_parts();
let mut body_request = Request::new(body);
DefaultBodyLimit::max(MAX_BODY_BYTES).apply(&mut body_request);
let bytes = Bytes::from_request(body_request, &())
.await
.map_err(|error| {
if error.status() == StatusCode::PAYLOAD_TOO_LARGE {
ApiError::new(
StatusCode::PAYLOAD_TOO_LARGE,
"PayloadTooLarge",
"request body exceeds 64 KiB",
2,
)
} else {
ApiError::bad_request("could not read request body")
}
})?;
Ok(Request::from_parts(parts, Body::from(bytes)))
}
async fn require_json(request: Request, next: Next) -> Response {
let valid_type = single_header(request.headers(), header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| {
let media_type = value.split(';').next().unwrap_or_default();
media_type.trim().eq_ignore_ascii_case(JSON_TYPE)
});
if valid_type {
next.run(request).await
} else {
ApiError::unsupported_media_type().into_response()
}
}
async fn not_found() -> ApiError {
ApiError::new(StatusCode::NOT_FOUND, "NotFound", "route not found", 3)
}
async fn health() -> Json<HealthOutput> {
Json(HealthOutput {
schema: SCHEMA,
status: "ok",
})
}
#[derive(Serialize)]
struct HealthOutput {
schema: u32,
status: &'static str,
}
async fn ports(State(context): State<Arc<Context>>, uri: Uri) -> Result<Response, ApiError> {
let (kind, role) = list_filters(uri.query())?;
let result = blocking(context, move |context| {
inspect::build_list(context, kind.map(Into::into), role.map(Into::into))
})
.await?;
reply(StatusCode::OK, result)
}
async fn check(
State(context): State<Arc<Context>>,
port: Result<Path<u16>, PathRejection>,
) -> Result<Response, ApiError> {
let port = path_port(port)?;
let result = blocking(context, move |context| {
inspect::build_tagged_check(context, port)
})
.await?;
reply(StatusCode::OK, result)
}
async fn drift(State(context): State<Arc<Context>>) -> Result<Response, ApiError> {
let result = blocking(context, |context| list::build_drift(context, None, None)).await?;
reply(StatusCode::OK, result)
}
async fn snapshot(State(context): State<Arc<Context>>) -> Result<Response, ApiError> {
let result = blocking(context, inspect::build_snapshot).await?;
reply(StatusCode::OK, result)
}
async fn history_list(State(context): State<Arc<Context>>) -> Result<Response, ApiError> {
let result = blocking(context, history::build_history_list).await?;
reply(StatusCode::OK, result)
}
async fn history_restore(
State(context): State<Arc<Context>>,
id: Result<Path<String>, PathRejection>,
) -> Result<Response, ApiError> {
let id = path_value(id)?;
let result = blocking(context, move |context| {
history::build_history_restore(context, &id)
})
.await?;
reply(StatusCode::OK, result)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ClaimBody {
port: NonZeroU16,
project: String,
service: String,
bind: Option<IpAddr>,
#[serde(default)]
role: Role,
container: Option<String>,
used_by: Option<Vec<String>>,
web: Option<String>,
web_scheme: Option<WebScheme>,
component: Option<String>,
}
async fn claim(
State(context): State<Arc<Context>>,
body: Result<Json<JsonObject<ClaimBody>>, JsonRejection>,
) -> Result<Response, ApiError> {
let body = json_body(body)?;
let args = ClaimArgs {
port: body.port.get(),
project: body.project,
service: body.service,
bind: body.bind,
role: role_arg(body.role),
container: body.container,
used_by: body.used_by,
web: WebArgs {
web: body.web,
web_scheme: body.web_scheme,
},
component: body.component,
};
let result = blocking(context, move |context| registry::build_claim(context, args)).await?;
reply(StatusCode::CREATED, result)
}
fn role_arg(role: Role) -> RoleArg {
match role {
Role::App => RoleArg::App,
Role::Service => RoleArg::Service,
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ClaimEditBody {
service: Option<String>,
role: Option<Role>,
bind: Option<IpAddr>,
used_by: Option<Vec<String>>,
#[serde(default)]
clear_used_by: bool,
#[serde(default, deserialize_with = "edit::deserialize_nullable_string")]
container: Option<Option<String>>,
web: Option<String>,
web_scheme: Option<WebScheme>,
#[serde(default)]
no_web: bool,
component: Option<String>,
#[serde(default)]
no_component: bool,
}
async fn edit_claim(
State(context): State<Arc<Context>>,
port: Result<Path<u16>, PathRejection>,
headers: HeaderMap,
body: Result<Json<JsonObject<ClaimEditBody>>, JsonRejection>,
) -> Result<Response, ApiError> {
let tag = if_match(&headers)?;
let port = path_port(port)?;
let body = json_body(body)?;
let args = EditArgs {
tag: None,
service: body.service,
role: body.role.map(role_arg),
bind: body.bind,
used_by: body.used_by,
clear_used_by: body.clear_used_by,
clear_container: body.container == Some(None),
container: body.container.flatten(),
web: WebArgs {
web: body.web,
web_scheme: body.web_scheme,
},
no_web: body.no_web,
component: body.component,
no_component: body.no_component,
};
let result = blocking(context, move |context| {
edit::build_edit(context, port, Some(&tag), args.try_into()?)
})
.await?;
reply(StatusCode::OK, result)
}
async fn release_claim(
State(context): State<Arc<Context>>,
port: Result<Path<u16>, PathRejection>,
uri: Uri,
headers: HeaderMap,
) -> Result<Response, ApiError> {
let tag = optional_if_match(&headers)?;
let port = path_port(port)?;
let force_shared = force_shared(uri.query())?;
let result = blocking(context, move |context| {
registry::build_release_claim(context, port, force_shared, tag.as_deref())
})
.await?;
reply(StatusCode::OK, result)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct LeaseBody {
project: String,
purpose: String,
duration: Option<String>,
pid: Option<u32>,
bind: Option<IpAddr>,
group: Option<Vec<String>>,
pool: Option<String>,
}
async fn lease(
State(context): State<Arc<Context>>,
body: Result<Json<JsonObject<LeaseBody>>, JsonRejection>,
) -> Result<Response, ApiError> {
let body = json_body(body)?;
let args = LeaseArgs {
project: body.project,
purpose: body.purpose,
duration: duration(body.duration.as_deref())?,
pid: body.pid,
bind: body.bind,
pool: body.pool,
};
if let Some(components) = body.group {
let result = blocking(context, move |context| {
registry::build_lease_group(context, args, components)
})
.await?;
return reply(StatusCode::CREATED, result);
}
let result = blocking(context, move |context| registry::build_lease(context, args)).await?;
reply(StatusCode::CREATED, result)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct LeaseEditBody {
purpose: Option<String>,
duration: Option<String>,
}
async fn edit_lease(
State(context): State<Arc<Context>>,
port: Result<Path<u16>, PathRejection>,
headers: HeaderMap,
body: Result<Json<JsonObject<LeaseEditBody>>, JsonRejection>,
) -> Result<Response, ApiError> {
let tag = if_match(&headers)?;
let port = path_port(port)?;
let body = json_body(body)?;
let duration = duration(body.duration.as_deref())?;
let result = blocking(context, move |context| {
edit::build_lease_edit(context, port, Some(&tag), body.purpose, duration)
})
.await?;
reply(StatusCode::OK, result)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RenewBody {
duration: Option<String>,
#[serde(default, deserialize_with = "deserialize_leased_at")]
leased_at: Option<OffsetDateTime>,
}
async fn renew(
State(context): State<Arc<Context>>,
port: Result<Path<u16>, PathRejection>,
body: Result<Json<JsonObject<RenewBody>>, JsonRejection>,
) -> Result<Response, ApiError> {
let port = path_port(port)?;
let body = json_body(body)?;
let duration = duration(body.duration.as_deref())?;
let result = blocking(context, move |context| {
registry::build_renew(context, port, duration, body.leased_at)
})
.await?;
reply(StatusCode::OK, result)
}
async fn release(
State(context): State<Arc<Context>>,
port: Result<Path<u16>, PathRejection>,
uri: Uri,
headers: HeaderMap,
) -> Result<Response, ApiError> {
let tag = optional_if_match(&headers)?;
let port = path_port(port)?;
let leased_at = release_leased_at(uri.query())?;
let result = blocking(context, move |context| {
registry::build_release_lease(context, port, leased_at, tag.as_deref())
})
.await?;
reply(StatusCode::OK, result)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct GroupRenewBody {
duration: Option<String>,
}
async fn renew_group(
State(context): State<Arc<Context>>,
group: Result<Path<String>, PathRejection>,
body: Result<Json<JsonObject<GroupRenewBody>>, JsonRejection>,
) -> Result<Response, ApiError> {
let group = path_value(group)?;
let duration = duration(json_body(body)?.duration.as_deref())?;
let result = blocking(context, move |context| {
registry::build_renew_group(context, group, duration)
})
.await?;
reply(StatusCode::OK, result)
}
async fn release_group(
State(context): State<Arc<Context>>,
group: Result<Path<String>, PathRejection>,
headers: HeaderMap,
) -> Result<Response, ApiError> {
let tag = optional_if_match(&headers)?;
let group = path_value(group)?;
let result = blocking(context, move |context| {
registry::build_release_group(context, group, tag.as_deref())
})
.await?;
reply(StatusCode::OK, result)
}
fn release_leased_at(query: Option<&str>) -> Result<Option<OffsetDateTime>, ApiError> {
release_query(query, "leased_at")?
.as_deref()
.map(parse_leased_at)
.transpose()
.map_err(ApiError::bad_request)
}
fn release_query(query: Option<&str>, expected: &str) -> Result<Option<String>, ApiError> {
let mut fields = query
.unwrap_or_default()
.split('&')
.filter(|field| !field.is_empty());
let Some(field) = fields.next() else {
return Ok(None);
};
let (name, value) = field.split_once('=').unwrap_or((field, ""));
if decode_query(name)? != expected || fields.next().is_some() {
return Err(ApiError::bad_request(
"unknown or repeated release query field",
));
}
decode_query(value).map(Some)
}
async fn zones(State(context): State<Arc<Context>>) -> Result<Response, ApiError> {
let result = blocking(context, zone::build_zone_list).await?;
reply(StatusCode::OK, result)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ZoneBody {
label: String,
reason: Option<String>,
ports: Vec<String>,
enabled: Option<bool>,
}
async fn add_zone(
State(context): State<Arc<Context>>,
body: Result<Json<JsonObject<ZoneBody>>, JsonRejection>,
) -> Result<Response, ApiError> {
let body = json_body(body)?;
let zone = Zone {
label: body.label,
reason: body.reason,
ports: body.ports,
enabled: body.enabled.unwrap_or(true),
};
let result = blocking(context, move |context| zone::build_zone_add(context, zone)).await?;
reply(StatusCode::CREATED, result)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ZoneEditBody {
#[serde(default, deserialize_with = "edit::deserialize_nullable_string")]
reason: Option<Option<String>>,
ports: Option<Vec<String>>,
enabled: Option<bool>,
}
async fn edit_zone(
State(context): State<Arc<Context>>,
label: Result<Path<String>, PathRejection>,
headers: HeaderMap,
body: Result<Json<JsonObject<ZoneEditBody>>, JsonRejection>,
) -> Result<Response, ApiError> {
let tag = if_match(&headers)?;
let label = path_value(label)?;
let body = json_body(body)?;
let changes = ZoneChanges {
reason: body.reason,
ports: body.ports,
};
let result = blocking(context, move |context| {
zone::build_zone_edit_if_match(context, &label, &tag, changes, body.enabled)
})
.await?;
reply(StatusCode::OK, result)
}
async fn remove_zone(
State(context): State<Arc<Context>>,
label: Result<Path<String>, PathRejection>,
headers: HeaderMap,
) -> Result<Response, ApiError> {
let tag = optional_if_match(&headers)?;
let label = path_value(label)?;
let result = blocking(context, move |context| {
zone::build_zone_remove(context, &label, tag.as_deref())
})
.await?;
reply(StatusCode::OK, result)
}
async fn apps(State(context): State<Arc<Context>>) -> Result<Response, ApiError> {
let result = blocking(context, app::build_app_list).await?;
reply(StatusCode::OK, result)
}
async fn show_app(
State(context): State<Arc<Context>>,
name: Result<Path<String>, PathRejection>,
) -> Result<Response, ApiError> {
let name = path_value(name)?;
let result = blocking(context, move |context| app::build_app_show(context, &name)).await?;
reply(StatusCode::OK, result)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct AppBody {
app: String,
components: Vec<String>,
#[serde(default)]
pins: Vec<String>,
bind: Option<IpAddr>,
}
async fn reserve_app(
State(context): State<Arc<Context>>,
body: Result<Json<JsonObject<AppBody>>, JsonRejection>,
) -> Result<Response, ApiError> {
let body = json_body(body)?;
let args = AppAllocationArgs {
app: body.app,
components: body.components,
pins: body.pins,
bind: body.bind,
};
let result = blocking(context, move |context| {
app::build_app_reserve(context, args)
})
.await?;
reply(StatusCode::CREATED, result)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ComponentsBody {
components: Vec<String>,
#[serde(default)]
pins: Vec<String>,
bind: Option<IpAddr>,
}
async fn add_components(
State(context): State<Arc<Context>>,
name: Result<Path<String>, PathRejection>,
body: Result<Json<JsonObject<ComponentsBody>>, JsonRejection>,
) -> Result<Response, ApiError> {
let name = path_value(name)?;
let body = json_body(body)?;
let args = AppAllocationArgs {
app: name,
components: body.components,
pins: body.pins,
bind: body.bind,
};
let result = blocking(context, move |context| app::build_app_add(context, args)).await?;
reply(StatusCode::CREATED, result)
}
async fn remove_component(
State(context): State<Arc<Context>>,
path: Result<Path<(String, String)>, PathRejection>,
uri: Uri,
headers: HeaderMap,
) -> Result<Response, ApiError> {
let tag = optional_if_match(&headers)?;
let (name, component) = path_value(path)?;
let force_shared = force_shared(uri.query())?;
let result = blocking(context, move |context| {
app::build_app_remove(context, &name, &component, force_shared, tag.as_deref())
})
.await?;
reply(StatusCode::OK, result)
}
fn force_shared(query: Option<&str>) -> Result<bool, ApiError> {
release_query(query, "force_shared")?
.map(|value| {
value
.parse()
.map_err(|_| ApiError::bad_request("force_shared must be true or false"))
})
.transpose()
.map(Option::unwrap_or_default)
}
async fn release_app(
State(context): State<Arc<Context>>,
name: Result<Path<String>, PathRejection>,
uri: Uri,
headers: HeaderMap,
) -> Result<Response, ApiError> {
let tag = optional_if_match(&headers)?;
let name = path_value(name)?;
let confirm = release_query(uri.query(), "confirm")?
.ok_or_else(|| ApiError::bad_request("confirm query field is required"))?;
let result = blocking(context, move |context| {
app::build_app_release(context, &name, &confirm, tag.as_deref())
})
.await?;
reply(StatusCode::OK, result)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SweepBody {
#[serde(default)]
dry_run: bool,
#[serde(default, deserialize_with = "deserialize_sweep_leases")]
leases: Option<Vec<JsonObject<SweepLeaseBody>>>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SweepLeaseBody {
port: NonZeroU16,
bind: IpAddr,
#[serde(deserialize_with = "deserialize_required_leased_at")]
leased_at: OffsetDateTime,
}
fn deserialize_sweep_leases<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Option<Vec<JsonObject<SweepLeaseBody>>>, D::Error> {
Vec::deserialize(deserializer).map(Some)
}
async fn sweep(
State(context): State<Arc<Context>>,
body: Result<Json<JsonObject<SweepBody>>, JsonRejection>,
) -> Result<Response, ApiError> {
let body = json_body(body)?;
if body.dry_run && body.leases.is_some() {
return Err(ApiError::bad_request(
"leases is only accepted when dry_run is false",
));
}
let approved = body.leases.map(|leases| {
leases
.into_iter()
.map(|JsonObject(lease)| (lease.port.get(), lease.bind, lease.leased_at))
.collect::<Vec<_>>()
});
let result = blocking(context, move |context| {
registry::build_sweep(context, body.dry_run, approved.as_deref())
})
.await?;
reply(StatusCode::OK, result)
}
async fn blocking<T: Send + 'static>(
context: Arc<Context>,
build: impl FnOnce(&Context) -> Result<T, CliError> + Send + 'static,
) -> Result<T, ApiError> {
let result = spawn_blocking(move || build(&context)).await.map_err(|_| {
ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"Serve",
"request worker failed",
1,
)
})?;
Ok(result?)
}
fn reply(status: StatusCode, value: impl Serialize) -> Result<Response, ApiError> {
let body = serde_json::to_vec(&value).map_err(CliError::Json)?;
Ok((status, [(header::CONTENT_TYPE, JSON_TYPE)], body).into_response())
}
fn path_port(port: Result<Path<u16>, PathRejection>) -> Result<u16, ApiError> {
match port {
Ok(Path(port)) if port != 0 => Ok(port),
_ => Err(ApiError::bad_request(
"port must be an integer between 1 and 65535",
)),
}
}
fn path_value<T>(path: Result<Path<T>, PathRejection>) -> Result<T, ApiError> {
path.map(|Path(value)| value)
.map_err(|_| ApiError::bad_request("invalid path parameter"))
}
fn if_match(headers: &HeaderMap) -> Result<String, ApiError> {
optional_if_match(headers)?.ok_or_else(|| {
ApiError::new(
StatusCode::PRECONDITION_REQUIRED,
"PreconditionRequired",
"If-Match is required",
2,
)
})
}
fn optional_if_match(headers: &HeaderMap) -> Result<Option<String>, ApiError> {
if !headers.contains_key(header::IF_MATCH) {
return Ok(None);
}
let invalid_tag = || ApiError::bad_request("If-Match must contain one strong entry tag");
let value = single_header(headers, header::IF_MATCH)
.and_then(|value| value.to_str().ok())
.ok_or_else(invalid_tag)?;
let tag = if let Some(quoted) = value.strip_prefix('"') {
quoted.strip_suffix('"').ok_or_else(invalid_tag)?
} else {
value
};
if tag.is_empty()
|| tag == "*"
|| tag.starts_with("W/")
|| !tag
.bytes()
.all(|byte| byte.is_ascii_graphic() && !matches!(byte, b'"' | b','))
{
return Err(invalid_tag());
}
Ok(Some(tag.to_owned()))
}
fn json_body<T>(body: Result<Json<JsonObject<T>>, JsonRejection>) -> Result<T, ApiError> {
match body {
Ok(Json(JsonObject(body))) => Ok(body),
Err(JsonRejection::MissingJsonContentType(_)) => Err(ApiError::unsupported_media_type()),
Err(_) => Err(ApiError::bad_request("invalid JSON request body")),
}
}
fn duration(input: Option<&str>) -> Result<Option<SignedDuration>, ApiError> {
input
.map(parse_duration)
.transpose()
.map_err(|error| ApiError::bad_request(format!("invalid duration: {error}")))
}
fn list_filters(query: Option<&str>) -> Result<(Option<KindArg>, Option<RoleArg>), ApiError> {
let mut kind = None;
let mut role = None;
for field in query
.unwrap_or_default()
.split('&')
.filter(|field| !field.is_empty())
{
let (name, value) = field.split_once('=').unwrap_or((field, ""));
match decode_query(name)?.as_str() {
"kind" if kind.is_none() => {
kind = Some(
KindArg::from_str(&decode_query(value)?, false).map_err(|_| {
ApiError::bad_request("kind must be ours, system or third-party")
})?,
);
}
"role" if role.is_none() => {
role = Some(
RoleArg::from_str(&decode_query(value)?, false)
.map_err(|_| ApiError::bad_request("role must be app or service"))?,
);
}
_ => {
return Err(ApiError::bad_request(
"unknown or repeated list query field",
));
}
}
}
Ok((kind, role))
}
fn decode_query(input: &str) -> Result<String, ApiError> {
let invalid = || ApiError::bad_request("invalid query encoding");
let mut decoded = Vec::with_capacity(input.len());
let mut bytes = input.bytes();
while let Some(byte) = bytes.next() {
let byte = match byte {
b'%' => {
let high = bytes.next().and_then(|byte| char::from(byte).to_digit(16));
let low = bytes.next().and_then(|byte| char::from(byte).to_digit(16));
match (high, low) {
(Some(high), Some(low)) => (high * 16 + low) as u8,
_ => return Err(invalid()),
}
}
b'+' => b' ',
byte => byte,
};
decoded.push(byte);
}
String::from_utf8(decoded).map_err(|_| invalid())
}
#[derive(Debug)]
struct ApiError {
status: StatusCode,
kind: &'static str,
message: String,
exit_code: u8,
}
impl ApiError {
fn new(
status: StatusCode,
kind: &'static str,
message: impl Into<String>,
exit_code: u8,
) -> Self {
Self {
status,
kind,
message: message.into(),
exit_code,
}
}
fn bad_request(message: impl Into<String>) -> Self {
Self::new(StatusCode::BAD_REQUEST, "InvalidRequest", message, 2)
}
fn unsupported_media_type() -> Self {
Self::new(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"UnsupportedMediaType",
"Content-Type must be application/json",
2,
)
}
}
impl From<CliError> for ApiError {
fn from(error: CliError) -> Self {
let (kind, code) = error.kind_and_code();
let status = match (kind, code) {
(
"NotFound" | "AppNotFound" | "ComponentNotFound" | "ZoneNotFound" | "GroupNotFound"
| "HistoryNotFound" | "PoolNotFound",
_,
) => StatusCode::NOT_FOUND,
("Stale", _) => StatusCode::PRECONDITION_FAILED,
(_, 2) => StatusCode::BAD_REQUEST,
(_, 3) => StatusCode::CONFLICT,
(_, 4) => StatusCode::SERVICE_UNAVAILABLE,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
Self::new(status, kind, error.to_string(), code)
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let body = ErrorOutput::new(self.kind, self.message.trim_end(), self.exit_code);
let mut response = (self.status, Json(body)).into_response();
if self.status == StatusCode::SERVICE_UNAVAILABLE {
response
.headers_mut()
.insert(header::RETRY_AFTER, HeaderValue::from_static("1"));
}
response
}
}
#[cfg(test)]
mod tests {
use std::{io, time::Duration};
use axum::body::to_bytes;
use clap::error::ErrorKind;
use serde_json::{Value, json};
use time::format_description::well_known::Rfc3339;
use troll_core::{OperationError, ProbeError, Refused, StoreError};
use super::*;
#[test]
fn host_is_exact_and_required_on_all_requests() {
let access = Access::new(8123, SessionToken::generate().unwrap());
let mut request = Request::new(Body::empty());
assert_eq!(
access.check(&request).unwrap_err().status,
StatusCode::FORBIDDEN
);
for host in ["127.0.0.1:8123", "localhost:8123"] {
request
.headers_mut()
.insert(header::HOST, HeaderValue::from_static(host));
assert!(access.check(&request).is_ok());
}
for host in [
"localhost",
"127.0.0.1:8124",
"LOCALHOST:8123",
"localhost.:8123",
"127.0.0.1:08123",
"localhost:8123.evil.invalid",
] {
request
.headers_mut()
.insert(header::HOST, HeaderValue::from_static(host));
assert_eq!(
access.check(&request).unwrap_err().status,
StatusCode::FORBIDDEN
);
}
request.headers_mut().remove(header::HOST);
for host in ["localhost:8123", "127.0.0.1:8123"] {
request
.headers_mut()
.append(header::HOST, HeaderValue::from_static(host));
}
assert_eq!(
access.check(&request).unwrap_err().status,
StatusCode::FORBIDDEN
);
}
#[test]
fn port_80_accepts_loopback_hosts_without_a_port() {
let access = Access::new(80, SessionToken::generate().unwrap());
for host in ["127.0.0.1", "localhost", "127.0.0.1:80", "localhost:80"] {
let request = Request::builder()
.header(header::HOST, host)
.body(Body::empty())
.unwrap();
assert!(access.check(&request).is_ok(), "{host}");
}
}
#[test]
fn absolute_form_request_authority_must_be_an_allowed_host() {
let access = Access::new(8123, SessionToken::generate().unwrap());
for (target, allowed) in [
("http://127.0.0.1:8123/healthz", true),
("http://localhost:8123/healthz", true),
("http://localhost:8124/healthz", false),
("http://localhost/healthz", false),
("http://unlisted.invalid:8123/healthz", false),
] {
let request = Request::builder()
.uri(target)
.header(header::HOST, "localhost:8123")
.body(Body::empty())
.unwrap();
let status = access
.check(&request)
.map_or_else(|error| error.status, |_| StatusCode::OK);
assert_eq!(
status,
if allowed {
StatusCode::OK
} else {
StatusCode::FORBIDDEN
},
"{target}"
);
}
}
#[test]
fn maps_cli_errors_to_http_status_and_preserves_the_envelope() {
let refusal = |reason| CliError::Operation(OperationError::Refused(reason));
let cases = [
(
CliError::Usage(clap::Error::raw(ErrorKind::InvalidValue, "test")),
StatusCode::BAD_REQUEST,
),
(
CliError::Operation(OperationError::InvalidRequest("test".into())),
StatusCode::BAD_REQUEST,
),
(
refusal(Refused::NotFound { port: 8123 }),
StatusCode::NOT_FOUND,
),
(
refusal(Refused::PortTaken {
port: 8123,
by: "project".into(),
}),
StatusCode::CONFLICT,
),
(
refusal(Refused::RangeExhausted {
range: 20000..=24999,
}),
StatusCode::CONFLICT,
),
(
refusal(Refused::NotHolder {
port: 8123,
holder: "owner".into(),
}),
StatusCode::CONFLICT,
),
(
refusal(Refused::Ambiguous { port: 8123 }),
StatusCode::CONFLICT,
),
(
refusal(Refused::Changed { port: 8123 }),
StatusCode::CONFLICT,
),
(
refusal(Refused::DurationTooLong {
max: SignedDuration::hours(1),
}),
StatusCode::CONFLICT,
),
(
CliError::Store(StoreError::Locked {
path: "registry.lock".into(),
timeout: Duration::ZERO,
}),
StatusCode::SERVICE_UNAVAILABLE,
),
(
CliError::Probe(ProbeError::new("test")),
StatusCode::INTERNAL_SERVER_ERROR,
),
(
CliError::EphemeralRange(ProbeError::new("test")),
StatusCode::INTERNAL_SERVER_ERROR,
),
(
CliError::Output(io::Error::other("test")),
StatusCode::INTERNAL_SERVER_ERROR,
),
];
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
for (error, expected_status) in cases {
let (kind, exit_code) = error.kind_and_code();
let message = error.to_string();
let response = ApiError::from(error).into_response();
assert_eq!(response.status(), expected_status);
assert_eq!(
response
.headers()
.get(header::RETRY_AFTER)
.map(|value| value.to_str().unwrap()),
(expected_status == StatusCode::SERVICE_UNAVAILABLE).then_some("1")
);
let body = runtime
.block_on(to_bytes(response.into_body(), 4096))
.unwrap();
let body: Value = serde_json::from_slice(&body).unwrap();
assert_eq!(
body,
json!({
"schema": 1,
"error": {"kind": kind, "message": message.trim_end(), "exit_code": exit_code}
})
);
}
}
#[test]
fn bodies_require_json_objects_with_known_fields() {
for body in [
b"{".as_slice(),
br#"{"other":true}"#,
br#"{"dry_run":null}"#,
br#"{"dry_run":true,"dry_run":false}"#,
br#"[true]"#,
br#"{} {}"#,
] {
let result = json_body(Json::<JsonObject<SweepBody>>::from_bytes(body));
assert_eq!(result.err().unwrap().status, StatusCode::BAD_REQUEST);
}
assert!(
!json_body(Json::<JsonObject<SweepBody>>::from_bytes(b"{}"))
.unwrap()
.dry_run
);
assert!(
json_body(Json::<JsonObject<SweepBody>>::from_bytes(
br#"{"dry_run":true}"#
))
.unwrap()
.dry_run
);
}
#[test]
fn lease_identity_is_optional_but_each_supplied_value_must_be_rfc3339() {
let expected = OffsetDateTime::parse("2026-11-30T02:00:00Z", &Rfc3339).unwrap();
assert_eq!(release_leased_at(None).unwrap(), None);
assert_eq!(
release_leased_at(Some("leased_at=2026-11-30T03%3A00%3A00%2B01%3A00")).unwrap(),
Some(expected)
);
for query in [
"leased_at=wrong",
"leased_at",
"leased_at=%",
"leased_at=2026-11-30T02:00:00Z&leased_at=2026-11-30T02:00:00Z",
"lease_at=2026-11-30T02:00:00Z",
] {
assert_eq!(
release_leased_at(Some(query)).unwrap_err().status,
StatusCode::BAD_REQUEST
);
}
for (body, leased_at) in [
(r#"{}"#, None),
(r#"{"leased_at":"2026-11-30T02:00:00Z"}"#, Some(expected)),
(r#"{"leased_at":"2026-11-30t02:00:00z"}"#, Some(expected)),
] {
let parsed = json_body(Json::<JsonObject<RenewBody>>::from_bytes(body.as_bytes()));
assert_eq!(parsed.unwrap().leased_at, leased_at);
}
for body in [
r#"{"leased_at":""}"#,
r#"{"leased_at":null}"#,
r#"{"leased_at":1}"#,
r#"{"leased_at":"2026-11-30T02:00:00Z","leased_at":"2026-11-30T02:00:00Z"}"#,
] {
let parsed = json_body(Json::<JsonObject<RenewBody>>::from_bytes(body.as_bytes()));
assert_eq!(parsed.err().unwrap().status, StatusCode::BAD_REQUEST);
}
}
#[test]
fn renew_and_delete_reject_malformed_or_lossy_lease_timestamps() {
for timestamp in [
"2026-11-30X02:00:00.123456789Z",
"2026-11-30T02:00:00.1234567891Z",
"2016-12-31T23:59:60Z",
"2026-11-30T02:00:00.123456789",
"2026-11-30T02:00:00.Z",
"2026-11-30T02:00:00+0200",
"2026-02-30T02:00:00Z",
] {
let body = json!({"leased_at": timestamp}).to_string();
let result = json_body(Json::<JsonObject<RenewBody>>::from_bytes(body.as_bytes()));
let error = result
.err()
.unwrap_or_else(|| panic!("renew accepted {timestamp}"));
assert_eq!(error.status, StatusCode::BAD_REQUEST);
assert_eq!(error.message, "invalid JSON request body");
let query = format!("leased_at={}", timestamp.replace('+', "%2B"));
let error = release_leased_at(Some(&query)).unwrap_err();
assert_eq!(error.status, StatusCode::BAD_REQUEST);
assert_eq!(error.message, "leased_at must be an RFC 3339 timestamp");
}
}
#[cfg(target_os = "linux")]
async fn dispatch_response<S>(mut service: S, request: Request) -> Response
where
S: axum::ServiceExt<Request, Response = Response, Error = std::convert::Infallible>,
{
service.call(request).await.unwrap()
}
#[cfg(target_os = "linux")]
async fn dispatch<S>(service: S, request: Request) -> (StatusCode, Value)
where
S: axum::ServiceExt<Request, Response = Response, Error = std::convert::Infallible>,
{
let response = dispatch_response(service, request).await;
let status = response.status();
let body = to_bytes(response.into_body(), 4096).await.unwrap();
(status, serde_json::from_slice(&body).unwrap())
}
#[cfg(target_os = "linux")]
fn fixture_router(fixture: &crate::test_support::TempDir) -> (Router, String) {
let (log, _logs) = Logger::start(io::sink()).unwrap();
fixture_router_with_log(fixture, log)
}
#[cfg(target_os = "linux")]
fn fixture_router_with_log(
fixture: &crate::test_support::TempDir,
log: Logger,
) -> (Router, String) {
use std::fs;
use troll_probe::LinuxProbe;
let proc_root = fixture.path().join("proc");
fs::create_dir_all(proc_root.join("sys/net/ipv4")).unwrap();
fs::write(
proc_root.join("sys/net/ipv4/ip_local_port_range"),
"32768 60999",
)
.unwrap();
fs::create_dir(proc_root.join("net")).unwrap();
fs::write(
proc_root.join("net/tcp"),
" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n",
).unwrap();
let context =
Context::load_from(fixture.path(), LinuxProbe::with_proc_root(proc_root)).unwrap();
let token = SessionToken::generate().unwrap();
let credential = token.as_str().to_owned();
(router(Arc::new(context), 8123, token, log), credential)
}
#[cfg(target_os = "linux")]
struct Console {
router: Router,
token: String,
}
#[cfg(target_os = "linux")]
impl Console {
fn new(fixture: &crate::test_support::TempDir) -> Self {
let (router, token) = fixture_router(fixture);
Self { router, token }
}
async fn call(
&self,
method: Method,
path: &str,
body: Option<Value>,
tag: Option<&str>,
expected: StatusCode,
) -> Value {
let mut request = Request::builder()
.method(method.clone())
.uri(format!("/api/v1{path}"))
.header(header::HOST, "localhost:8123")
.header(header::ORIGIN, "http://localhost:8123")
.header(TOKEN_HEADER, &self.token);
if let Some(tag) = tag {
request = request.header(header::IF_MATCH, tag);
}
let body = if let Some(body) = body {
request = request.header(header::CONTENT_TYPE, JSON_TYPE);
Body::from(body.to_string())
} else {
Body::empty()
};
let (status, body) = dispatch(self.router.clone(), request.body(body).unwrap()).await;
assert_eq!(status, expected, "{method} {path}: {body}");
assert_eq!(body["schema"], SCHEMA);
body
}
async fn stale_delete(
&self,
fixture: &crate::test_support::TempDir,
path: &str,
tag: &str,
) {
let before = registry_files(fixture);
let reply = self
.call(
Method::DELETE,
path,
None,
Some(tag),
StatusCode::PRECONDITION_FAILED,
)
.await;
assert_eq!(reply["error"]["kind"], "Stale");
assert_eq!(registry_files(fixture), before);
}
}
#[cfg(target_os = "linux")]
fn registry_files(fixture: &crate::test_support::TempDir) -> [Vec<u8>; 2] {
["registry.toml", "registry.toml.bak"]
.map(|name| std::fs::read(fixture.path().join(name)).unwrap())
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn mutations_require_token_and_reject_missing_foreign_null_and_repeated_origins() {
let fixture = crate::test_support::TempDir::new();
let Console { router, token } = Console::new(&fixture);
for (method, path) in [
(Method::POST, "/api/v1/claims"),
(Method::PATCH, "/api/v1/claims/8123"),
(Method::DELETE, "/api/v1/claims/8123"),
(Method::DELETE, "/api/v1/zones/guarded"),
] {
let request = || {
Request::builder()
.method(method.clone())
.uri(path)
.header(header::HOST, "localhost:8123")
};
let with_origin = request().header(header::ORIGIN, "http://localhost:8123");
let (status, _) =
dispatch(router.clone(), with_origin.body(Body::empty()).unwrap()).await;
assert_eq!(status, StatusCode::UNAUTHORIZED, "{method}");
for origins in [
&[][..],
&["https://foreign.invalid"],
&["null"],
&["http://127.0.0.1:8123"],
&["http://localhost:8124"],
&["http://localhost:8123/"],
&["http://localhost:8123", "http://localhost:8123"],
] {
let mut request = request().header(TOKEN_HEADER, &token);
for origin in origins {
request = request.header(header::ORIGIN, *origin);
}
let (status, body) =
dispatch(router.clone(), request.body(Body::empty()).unwrap()).await;
assert_eq!(status, StatusCode::FORBIDDEN, "{method} {origins:?}");
assert_eq!(body["error"]["message"], "Origin is not allowed");
}
}
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn patch_requires_one_strong_tag() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
for path in ["/claims/8123", "/leases/20000", "/zones/reserved"] {
let body = console
.call(
Method::PATCH,
path,
Some(json!({})),
None,
StatusCode::PRECONDITION_REQUIRED,
)
.await;
assert_eq!(body["error"]["kind"], "PreconditionRequired");
for tag in [
"*",
"\"*\"",
"W/\"abc\"",
"\"abc\", \"def\"",
"\"abc",
"\"\"",
] {
console
.call(
Method::PATCH,
path,
Some(json!({})),
Some(tag),
StatusCode::BAD_REQUEST,
)
.await;
}
}
for path in [
"/claims/8123",
"/apps/demo/components/api",
"/apps/demo?confirm=demo",
"/zones/reserved",
] {
console
.call(
Method::DELETE,
path,
None,
Some("W/\"abc\""),
StatusCode::BAD_REQUEST,
)
.await;
}
let mut headers = HeaderMap::new();
headers.append(header::IF_MATCH, HeaderValue::from_static("abc"));
headers.append(header::IF_MATCH, HeaderValue::from_static("def"));
assert_eq!(
if_match(&headers).unwrap_err().status,
StatusCode::BAD_REQUEST
);
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn body_limit_covers_json_and_routes_that_ignore_bodies() {
let fixture = crate::test_support::TempDir::new();
let Console { router, token } = Console::new(&fixture);
for (method, path, length, expected) in [
(
Method::POST,
"/api/v1/sweep",
MAX_BODY_BYTES,
StatusCode::OK,
),
(
Method::POST,
"/api/v1/sweep",
MAX_BODY_BYTES + 1,
StatusCode::PAYLOAD_TOO_LARGE,
),
(
Method::GET,
"/healthz",
MAX_BODY_BYTES + 1,
StatusCode::PAYLOAD_TOO_LARGE,
),
(
Method::DELETE,
"/api/v1/zones/reserved",
MAX_BODY_BYTES + 1,
StatusCode::PAYLOAD_TOO_LARGE,
),
(
Method::PATCH,
"/api/v1/leases/20000",
MAX_BODY_BYTES + 1,
StatusCode::PAYLOAD_TOO_LARGE,
),
] {
let mut body = b"{}".to_vec();
body.resize(length, b' ');
let request = Request::builder()
.method(method.clone())
.uri(path)
.header(header::HOST, "localhost:8123")
.header(header::ORIGIN, "http://localhost:8123")
.header(TOKEN_HEADER, &token)
.header(header::CONTENT_TYPE, JSON_TYPE)
.body(Body::from(body))
.unwrap();
let (status, body) = dispatch(router.clone(), request).await;
assert_eq!(status, expected, "{method} {path}: {body}");
if expected == StatusCode::PAYLOAD_TOO_LARGE {
assert_eq!(body["error"]["kind"], "PayloadTooLarge");
}
}
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn claim_create_and_edit_publish_current_tags_and_safe_links() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
let claim = console
.call(
Method::POST,
"/claims",
Some(json!({
"port": 8123, "project": "demo", "service": "Frontend", "web": "//admin",
"bind": "::", "web_scheme": "https"
})),
None,
StatusCode::CREATED,
)
.await;
assert_eq!(claim["port"], 8123);
assert_eq!(claim["role"], "app");
let list = console
.call(Method::GET, "/ports", None, None, StatusCode::OK)
.await;
let check = console
.call(Method::GET, "/ports/8123", None, None, StatusCode::OK)
.await;
let tag = check["permanent"][0]["tag"].as_str().unwrap();
assert_eq!(list["apps"][0]["tag"], tag);
assert_eq!(check["permanent"][0]["link"], "https://[::1]:8123//admin");
assert_eq!(list["apps"][0]["link"], check["permanent"][0]["link"]);
let edit = console
.call(
Method::PATCH,
"/claims/8123",
Some(json!({
"service": "Updated frontend", "bind": "0.0.0.0", "web": "/new"
})),
Some(&format!("\"{tag}\"")),
StatusCode::OK,
)
.await;
assert_eq!(edit["service"], "Updated frontend");
assert_eq!(edit["link"], "https://127.0.0.1:8123/new");
assert_ne!(edit["tag"], tag);
let stale = console
.call(
Method::PATCH,
"/claims/8123",
Some(json!({
"service": " Stale attempted edit "
})),
Some(tag),
StatusCode::PRECONDITION_FAILED,
)
.await;
assert_eq!(
stale["error"]["message"],
"entry tag for port 8123 is stale"
);
let check = console
.call(Method::GET, "/ports/8123", None, None, StatusCode::OK)
.await;
assert_eq!(check["permanent"][0]["service"], "Updated frontend");
assert_eq!(check["permanent"][0]["tag"], edit["tag"]);
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn claim_delete_refuses_a_new_dependent_even_with_force_shared() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
let claim = console
.call(
Method::POST,
"/claims",
Some(
json!({"port": 8123, "project": "demo", "service": "Redis", "role": "service"}),
),
None,
StatusCode::CREATED,
)
.await;
let tag = claim["tag"].as_str().unwrap();
let edited = console
.call(
Method::PATCH,
"/claims/8123",
Some(json!({"used_by": ["new-consumer"]})),
Some(tag),
StatusCode::OK,
)
.await;
for path in ["/claims/8123", "/claims/8123?force_shared=true"] {
console
.stale_delete(&fixture, path, &format!("\"{tag}\""))
.await;
}
console
.call(
Method::DELETE,
"/claims/8123?force_shared=true",
None,
edited["tag"].as_str(),
StatusCode::OK,
)
.await;
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn claim_patch_distinguishes_omitted_container_from_null() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
let claimed = console.call(
Method::POST, "/claims",
Some(json!({"port": 8123, "project": "demo", "service": "web", "container": "demo-web"})),
None, StatusCode::CREATED,
).await;
let unchanged = console
.call(
Method::PATCH,
"/claims/8123",
Some(json!({"service": "new name"})),
claimed["tag"].as_str(),
StatusCode::OK,
)
.await;
assert_eq!(unchanged["container"], "demo-web");
let cleared = console
.call(
Method::PATCH,
"/claims/8123",
Some(json!({"container": null})),
unchanged["tag"].as_str(),
StatusCode::OK,
)
.await;
assert!(cleared.get("container").is_none());
assert_ne!(cleared["tag"], unchanged["tag"]);
let checked = console
.call(Method::GET, "/ports/8123", None, None, StatusCode::OK)
.await;
assert!(checked["permanent"][0].get("container").is_none());
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn delete_claim_releases_the_claim_and_returns_its_entry() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
console
.call(
Method::POST,
"/claims",
Some(json!({"port": 8123, "project": "demo", "service": "Frontend"})),
None,
StatusCode::CREATED,
)
.await;
let released = console
.call(Method::DELETE, "/claims/8123", None, None, StatusCode::OK)
.await;
assert_eq!(released["tier"], "permanent");
assert_eq!(released["port"], 8123);
assert_eq!(released["project"], "demo");
assert_eq!(released["service"], "Frontend");
let checked = console
.call(Method::GET, "/ports/8123", None, None, StatusCode::OK)
.await;
assert_eq!(checked["permanent"], json!([]));
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn delete_claim_requires_force_for_a_shared_service() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
console
.call(
Method::POST,
"/claims",
Some(json!({
"port": 8123, "project": "cache", "service": "Redis",
"role": "service", "used_by": ["consumer"]
})),
None,
StatusCode::CREATED,
)
.await;
let refused = console
.call(
Method::DELETE,
"/claims/8123",
None,
None,
StatusCode::CONFLICT,
)
.await;
assert_eq!(refused["error"]["kind"], "SharedService");
let released = console
.call(
Method::DELETE,
"/claims/8123?force_shared=true",
None,
None,
StatusCode::OK,
)
.await;
assert_eq!(released["role"], "service");
assert_eq!(released["used_by"], json!(["consumer"]));
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn delete_claim_refuses_a_lease_only_port_and_preserves_the_lease() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
let lease = console
.call(
Method::POST,
"/leases",
Some(json!({"project": "demo", "purpose": "Preview"})),
None,
StatusCode::CREATED,
)
.await;
let port = lease["port"].as_u64().unwrap();
let check_path = format!("/ports/{port}");
let before = console
.call(Method::GET, &check_path, None, None, StatusCode::OK)
.await;
assert_eq!(before["lease"].as_array().unwrap().len(), 1);
let refused = console
.call(
Method::DELETE,
&format!("/claims/{port}"),
None,
None,
StatusCode::NOT_FOUND,
)
.await;
assert_eq!(refused["error"]["kind"], "NotFound");
let after = console
.call(Method::GET, &check_path, None, None, StatusCode::OK)
.await;
assert_eq!(after["lease"], before["lease"]);
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn invalid_proposed_edits_and_invalid_registry_reads_have_distinct_statuses() {
use std::fs;
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
for (port, component) in [(8123, "web"), (8124, "api")] {
console.call(Method::POST, "/claims", Some(json!({
"port": port, "project": "demo", "service": component, "component": component
})), None, StatusCode::CREATED).await;
}
let check = console
.call(Method::GET, "/ports/8124", None, None, StatusCode::OK)
.await;
let tag = check["permanent"][0]["tag"].as_str().unwrap();
let registry = fixture.path().join("registry.toml");
let backup = fixture.path().join("registry.toml.bak");
let saved = fs::read_to_string(®istry).unwrap();
let previous = fs::read(&backup).unwrap();
for change in [
json!({"component": "web"}),
json!({"web": "/invalid?query"}),
] {
let error = console
.call(
Method::PATCH,
"/claims/8124",
Some(change),
Some(tag),
StatusCode::BAD_REQUEST,
)
.await;
assert_eq!(error["error"]["kind"], "InvalidRequest");
assert_eq!(error["error"]["exit_code"], 2);
assert_eq!(fs::read_to_string(®istry).unwrap(), saved);
assert_eq!(fs::read(&backup).unwrap(), previous);
}
for (text, kind) in [
(saved.replace("port = 8124", "port = 0"), "InvalidRegistry"),
("not TOML = [".to_owned(), "RegistryParse"),
] {
fs::write(®istry, text).unwrap();
let error = console
.call(
Method::PATCH,
"/claims/8124",
Some(json!({
"service": "still valid input"
})),
Some(tag),
StatusCode::INTERNAL_SERVER_ERROR,
)
.await;
assert_eq!(error["error"]["kind"], kind);
assert_eq!(error["error"]["exit_code"], 1);
}
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn zones_edit_fields_and_enabled_state_with_current_tag() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
console
.call(
Method::POST,
"/claims",
Some(json!({
"port": 8123, "project": "demo", "service": "Frontend"
})),
None,
StatusCode::CREATED,
)
.await;
let created = console
.call(
Method::POST,
"/zones",
Some(json!({
"label": "reserved", "reason": "Old reason", "ports": ["8080"], "enabled": false
})),
None,
StatusCode::CREATED,
)
.await;
assert_eq!(created["zone"]["enabled"], false);
assert_eq!(created["conflicts"], json!([]));
let zones = console
.call(Method::GET, "/zones", None, None, StatusCode::OK)
.await;
assert_eq!(zones["zones"][0], created["zone"]);
let first_tag = zones["zones"][0]["tag"].as_str().unwrap();
let edited = console
.call(
Method::PATCH,
"/zones/reserved",
Some(json!({
"reason": "Development ports", "ports": ["8120-8130"]
})),
Some(first_tag),
StatusCode::OK,
)
.await;
assert_eq!(edited["zone"]["reason"], "Development ports");
assert_eq!(edited["zone"]["ports"], json!(["8120-8130"]));
assert_eq!(edited["zone"]["enabled"], false);
let edited_tag = edited["zone"]["tag"].as_str().unwrap();
assert_ne!(first_tag, edited_tag);
let stale = console
.call(
Method::PATCH,
"/zones/reserved",
Some(json!({"enabled": true})),
Some(first_tag),
StatusCode::PRECONDITION_FAILED,
)
.await;
assert_eq!(
stale["error"]["message"],
"entry tag for zone \"reserved\" is stale"
);
let enabled = console
.call(
Method::PATCH,
"/zones/reserved",
Some(json!({"enabled": true})),
Some(&format!("\"{edited_tag}\"")),
StatusCode::OK,
)
.await;
assert_eq!(enabled["zone"]["enabled"], true);
assert_eq!(enabled["conflicts"][0]["port"], 8123);
let enabled_tag = enabled["zone"]["tag"].as_str().unwrap();
assert_ne!(enabled_tag, edited_tag);
let disabled = console
.call(
Method::PATCH,
"/zones/reserved",
Some(json!({
"enabled": false, "reason": null
})),
Some(enabled_tag),
StatusCode::OK,
)
.await;
assert_eq!(disabled["zone"]["enabled"], false);
assert!(disabled["zone"].get("reason").is_none());
assert_eq!(disabled["conflicts"], json!([]));
let deleted = console
.call(
Method::DELETE,
"/zones/reserved",
None,
None,
StatusCode::OK,
)
.await;
assert_eq!(deleted["zone"], disabled["zone"]);
let zones = console
.call(Method::GET, "/zones", None, None, StatusCode::OK)
.await;
assert_eq!(zones["zones"], json!([]));
let missing = console
.call(
Method::DELETE,
"/zones/reserved",
None,
None,
StatusCode::NOT_FOUND,
)
.await;
assert_eq!(missing["error"]["kind"], "ZoneNotFound");
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn zone_delete_refuses_a_widened_range() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
let created = console
.call(
Method::POST,
"/zones",
Some(json!({"label": "reserved", "ports": ["8123"]})),
None,
StatusCode::CREATED,
)
.await;
let tag = created["zone"]["tag"].as_str().unwrap();
let widened = console
.call(
Method::PATCH,
"/zones/reserved",
Some(json!({"ports": ["8123-8150"]})),
Some(tag),
StatusCode::OK,
)
.await;
console.stale_delete(&fixture, "/zones/reserved", tag).await;
let removed = console
.call(
Method::DELETE,
"/zones/reserved",
None,
widened["zone"]["tag"].as_str(),
StatusCode::OK,
)
.await;
assert_eq!(removed["zone"]["ports"], json!(["8123-8150"]));
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn zone_list_reports_overlapping_conflicts() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
console
.call(
Method::POST,
"/claims",
Some(json!({"port": 8123, "project": "demo", "service": "web"})),
None,
StatusCode::CREATED,
)
.await;
let mut conflicts = Vec::new();
for (label, ports) in [("development", "8120-8130"), ("restricted", "8123")] {
let created = console
.call(
Method::POST,
"/zones",
Some(json!({"label": label, "ports": [ports]})),
None,
StatusCode::CREATED,
)
.await;
assert_eq!(created["conflicts"][0]["port"], 8123);
conflicts.push(created["conflicts"][0].clone());
}
let zones = console
.call(Method::GET, "/zones", None, None, StatusCode::OK)
.await;
assert_eq!(zones["conflicts"], json!(conflicts));
assert_eq!(zones["conflict_count"], 1);
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn zone_add_rejects_dot_segment_labels() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
for label in [".", ".."] {
let error = console
.call(
Method::POST,
"/zones",
Some(json!({"label": label, "ports": ["8123"]})),
None,
StatusCode::BAD_REQUEST,
)
.await;
assert_eq!(error["error"]["kind"], "InvalidRequest");
assert_eq!(error["error"]["exit_code"], 2);
}
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn app_routes_require_confirmation_and_preserve_shared_services_until_forced() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
let reserved = console
.call(
Method::POST,
"/apps",
Some(json!({
"app": "demo", "components": ["web", "db:service"], "pins": ["db=8123"]
})),
None,
StatusCode::CREATED,
)
.await;
assert_eq!(reserved["app"], "demo");
assert_eq!(reserved["contiguous"], true);
let db = &reserved["entries"][1];
assert_eq!(db["port"], 8123);
assert_eq!(db["role"], "service");
let shared = console
.call(
Method::PATCH,
"/claims/8123",
Some(json!({
"used_by": ["consumer"]
})),
db["tag"].as_str(),
StatusCode::OK,
)
.await;
assert_eq!(shared["used_by"], json!(["consumer"]));
let added = console
.call(
Method::POST,
"/apps/demo/components",
Some(json!({
"components": ["metrics"], "pins": ["metrics=8124"]
})),
None,
StatusCode::CREATED,
)
.await;
assert_eq!(added["entries"][0]["component"], "metrics");
let shown = console
.call(Method::GET, "/apps/demo", None, None, StatusCode::OK)
.await;
assert_eq!(shown["entries"].as_array().unwrap().len(), 3);
let listed = console
.call(Method::GET, "/apps", None, None, StatusCode::OK)
.await;
assert_eq!(listed["apps"][0]["entries"], shown["entries"]);
console
.call(
Method::DELETE,
"/apps/demo",
None,
None,
StatusCode::BAD_REQUEST,
)
.await;
let mismatch = console
.call(
Method::DELETE,
"/apps/demo?confirm=other",
None,
None,
StatusCode::CONFLICT,
)
.await;
assert_eq!(mismatch["error"]["kind"], "ConfirmationMismatch");
let held = console
.call(
Method::DELETE,
"/apps/demo?confirm=demo",
None,
None,
StatusCode::CONFLICT,
)
.await;
assert_eq!(held["error"]["kind"], "AppHasDependents");
let remove = "/apps/demo/components/db";
for query in ["", "?force_shared=false"] {
let refusal = console
.call(
Method::DELETE,
&format!("{remove}{query}"),
None,
None,
StatusCode::CONFLICT,
)
.await;
assert_eq!(refusal["error"]["kind"], "SharedService");
assert!(
refusal["error"]["message"]
.as_str()
.unwrap()
.contains("consumer")
);
}
console
.call(
Method::DELETE,
&format!("{remove}?force_shared=true&force_shared=false"),
None,
None,
StatusCode::BAD_REQUEST,
)
.await;
let removed = console
.call(
Method::DELETE,
&format!("{remove}?force_shared=true"),
None,
None,
StatusCode::OK,
)
.await;
assert_eq!(removed["entries"][0]["port"], 8123);
let missing = console
.call(Method::DELETE, remove, None, None, StatusCode::NOT_FOUND)
.await;
assert_eq!(missing["error"]["kind"], "ComponentNotFound");
let released = console
.call(
Method::DELETE,
"/apps/demo?confirm=demo",
None,
None,
StatusCode::OK,
)
.await;
assert_eq!(released["entries"].as_array().unwrap().len(), 2);
let missing = console
.call(Method::GET, "/apps/demo", None, None, StatusCode::NOT_FOUND)
.await;
assert_eq!(missing["error"]["kind"], "AppNotFound");
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn component_delete_refuses_a_replacement_at_the_same_key() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
let made = console
.call(
Method::POST,
"/apps",
Some(json!({"app": "demo", "components": ["web", "db"], "pins": ["db=8123"]})),
None,
StatusCode::CREATED,
)
.await;
let tag = made["entries"][1]["tag"].as_str().unwrap();
let path = "/apps/demo/components/db";
console
.call(Method::DELETE, path, None, Some(tag), StatusCode::OK)
.await;
let replacement = console
.call(
Method::POST,
"/apps/demo/components",
Some(json!({"components": ["db"], "pins": ["db=8124"]})),
None,
StatusCode::CREATED,
)
.await;
console.stale_delete(&fixture, path, tag).await;
console
.call(
Method::DELETE,
path,
None,
replacement["entries"][0]["tag"].as_str(),
StatusCode::OK,
)
.await;
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn app_delete_refuses_a_component_added_since_the_confirmation_read() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
console
.call(
Method::POST,
"/apps",
Some(json!({"app": "demo", "components": ["web"], "pins": ["web=8123"]})),
None,
StatusCode::CREATED,
)
.await;
let shown = console
.call(Method::GET, "/apps/demo", None, None, StatusCode::OK)
.await;
let listed = console
.call(Method::GET, "/apps", None, None, StatusCode::OK)
.await;
let tag = shown["tag"].as_str().unwrap();
assert_eq!(listed["apps"][0]["tag"], tag);
console
.call(
Method::POST,
"/apps/demo/components",
Some(json!({"components": ["db"], "pins": ["db=8124"]})),
None,
StatusCode::CREATED,
)
.await;
let path = "/apps/demo?confirm=demo";
console.stale_delete(&fixture, path, tag).await;
let shown = console
.call(Method::GET, "/apps/demo", None, None, StatusCode::OK)
.await;
assert_ne!(shown["tag"], tag);
let removed = console
.call(
Method::DELETE,
path,
None,
shown["tag"].as_str(),
StatusCode::OK,
)
.await;
assert_eq!(removed["entries"], shown["entries"]);
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn sweep_acts_only_on_the_approved_lease_list_and_reports_skipped_identities() {
use std::convert::Infallible;
use troll_core::Lease;
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
let store = crate::platform::open_store(fixture.path());
let lease = |port| Lease {
port,
bind: troll_core::DEFAULT_BIND,
project: "demo".into(),
purpose: "preview".into(),
holder: "test".into(),
holder_pid: None,
component: None,
group: None,
leased_at: parse_leased_at("2000-01-01T00:00:00Z").unwrap(),
expires_at: parse_leased_at("2000-01-02T00:00:00Z").unwrap(),
};
store
.update(|registry| {
registry.lease.extend([lease(20000), lease(20001)]);
Ok::<_, Infallible>(())
})
.unwrap();
let preview = console
.call(
Method::POST,
"/sweep",
Some(json!({"dry_run": true})),
None,
StatusCode::OK,
)
.await;
let approved: Vec<_> = preview["removed"]
.as_array()
.unwrap()
.iter()
.map(|lease| json!({"port": lease["port"], "bind": lease["bind"], "leased_at": lease["leased_at"]}))
.collect();
assert_eq!(approved.len(), 2);
store
.update(|registry| {
registry.lease[1].expires_at = parse_leased_at("2099-01-01T00:00:00Z").unwrap();
registry.lease.push(lease(20002));
Ok::<_, Infallible>(())
})
.unwrap();
let before = registry_files(&fixture);
for body in [
json!({"leases": null}),
json!({"leases": [[20000, "2000-01-01T00:00:00Z"]]}),
json!({"leases": [{"port": 20000, "leased_at": "2000-01-01T00:00:00Z"}]}),
json!({"leases": [{"port": 20000, "bind": "loopback", "leased_at": "2000-01-01T00:00:00Z"}]}),
] {
console
.call(
Method::POST,
"/sweep",
Some(body),
None,
StatusCode::BAD_REQUEST,
)
.await;
assert_eq!(registry_files(&fixture), before);
}
let empty = console
.call(
Method::POST,
"/sweep",
Some(json!({"leases": []})),
None,
StatusCode::OK,
)
.await;
assert_eq!(empty["removed"], json!([]));
assert_eq!(registry_files(&fixture), before);
let result = console
.call(
Method::POST,
"/sweep",
Some(json!({"dry_run": false, "leases": approved})),
None,
StatusCode::OK,
)
.await;
assert_eq!(result["removed"], json!([preview["removed"][0]]));
assert_eq!(result["kept"], json!([approved[1]]));
let result = console
.call(
Method::POST,
"/sweep",
Some(json!({})),
None,
StatusCode::OK,
)
.await;
assert_eq!(result["removed"][0]["port"], 20002);
assert_eq!(result["removed"].as_array().unwrap().len(), 1);
assert_eq!(store.load().unwrap().lease[0].port, 20001);
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn filtered_port_listing_keeps_full_stack_group_tag() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
let created = console
.call(
Method::POST,
"/leases",
Some(json!({"project": "demo", "purpose": "Stack preview", "group": ["web", "api"], "duration": "5m"})),
None,
StatusCode::CREATED,
)
.await;
let port = created["leases"][0]["port"].as_u64().unwrap();
std::fs::create_dir(fixture.path().join("proc/self")).unwrap();
std::fs::write(
fixture.path().join("proc/net/tcp"),
format!(
" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n0: 0100007F:{port:04X} 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 12345\n"
),
)
.unwrap();
let all = console
.call(Method::GET, "/ports", None, None, StatusCode::OK)
.await;
let all_leases = all["leases"].as_array().unwrap();
assert_eq!(all_leases.len(), 2);
let visible = all_leases
.iter()
.find(|lease| lease["port"] == port)
.unwrap();
let filtered = console
.call(
Method::GET,
"/ports?kind=system",
None,
None,
StatusCode::OK,
)
.await;
let filtered_leases = filtered["leases"].as_array().unwrap();
assert_eq!(filtered_leases.len(), 1);
assert_eq!(filtered_leases[0]["port"], port);
assert!(visible["group_tag"].is_string());
assert_eq!(filtered_leases[0]["group_tag"], visible["group_tag"]);
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn stack_leases_edit_one_member_and_renew_and_release_as_a_group() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
let created = console.call(Method::POST, "/leases", Some(json!({
"project": "demo", "purpose": "Stack preview", "group": ["web", "api"], "duration": "5m"
})), None, StatusCode::CREATED).await;
let group = created["group"].as_str().unwrap();
let group_path = format!("/lease-groups/{group}");
let renew_path = format!("{group_path}/renew");
let leases = created["leases"].as_array().unwrap();
assert_eq!(leases.len(), 2);
let port = leases[0]["port"].as_u64().unwrap();
let other_port = leases[1]["port"].as_u64().unwrap();
assert_ne!(port, other_port);
let lease_path = format!("/leases/{port}");
let tag = leases[0]["tag"].as_str().unwrap();
let checked = console
.call(
Method::GET,
&format!("/ports/{port}"),
None,
None,
StatusCode::OK,
)
.await;
assert_eq!(checked["lease"], json!([leases[0]]));
let list = console
.call(Method::GET, "/ports", None, None, StatusCode::OK)
.await;
assert_eq!(list["leases"][0]["tag"], tag);
let group_tag = list["leases"][0]["group_tag"].as_str().unwrap();
assert_eq!(list["leases"][1]["group_tag"], group_tag);
assert_eq!(created["group_tag"], group_tag);
let edited = console
.call(
Method::PATCH,
&lease_path,
Some(json!({
"purpose": "New purpose", "duration": "15m"
})),
Some(tag),
StatusCode::OK,
)
.await;
assert_eq!(edited["purpose"], "New purpose");
assert_ne!(edited["tag"], tag);
assert_ne!(edited["expires_at"], leases[0]["expires_at"]);
assert_eq!(edited["leased_at"], leases[0]["leased_at"]);
let stale = console
.call(
Method::PATCH,
&lease_path,
Some(json!({"purpose": "old draft"})),
Some(tag),
StatusCode::PRECONDITION_FAILED,
)
.await;
assert_eq!(
stale["error"]["message"],
format!("entry tag for port {port} is stale")
);
let leased_at = edited["leased_at"].as_str().unwrap();
console
.stale_delete(
&fixture,
&format!("{lease_path}?leased_at={leased_at}"),
tag,
)
.await;
console.stale_delete(&fixture, &group_path, group_tag).await;
console
.call(
Method::PATCH,
&group_path,
Some(json!({})),
Some(tag),
StatusCode::NOT_FOUND,
)
.await;
console
.call(
Method::POST,
&renew_path,
Some(json!({})),
None,
StatusCode::OK,
)
.await;
let lower_bound = OffsetDateTime::now_utc() + troll_core::DEFAULT_LEASE_MAX;
let mut renewed = console
.call(
Method::POST,
&renew_path,
Some(json!({"duration": "999d"})),
None,
StatusCode::OK,
)
.await;
let upper_bound = OffsetDateTime::now_utc() + troll_core::DEFAULT_LEASE_MAX;
assert_eq!(renewed["group"], group);
assert_ne!(renewed["group_tag"], group_tag);
let list = console
.call(Method::GET, "/ports", None, None, StatusCode::OK)
.await;
assert_eq!(list["leases"][0]["group_tag"], renewed["group_tag"]);
assert_eq!(list["leases"][1]["group_tag"], renewed["group_tag"]);
assert_eq!(renewed["leases"][0]["purpose"], "New purpose");
assert_eq!(renewed["leases"][1]["purpose"], "Stack preview");
assert_eq!(
renewed["leases"][0]["expires_at"],
renewed["leases"][1]["expires_at"]
);
let expiry = OffsetDateTime::parse(
renewed["leases"][0]["expires_at"].as_str().unwrap(),
&Rfc3339,
)
.unwrap();
assert!((lower_bound..=upper_bound).contains(&expiry));
let released = console
.call(
Method::DELETE,
&group_path,
None,
Some(renewed["group_tag"].as_str().unwrap()),
StatusCode::OK,
)
.await;
for lease in renewed["leases"].as_array_mut().unwrap() {
let tag = lease.as_object_mut().unwrap().remove("tag").unwrap();
let entry: troll_core::Lease = serde_json::from_value(lease.clone()).unwrap();
assert_eq!(tag, entry.entry_tag());
}
assert_eq!(released["leases"], renewed["leases"]);
let missing = console
.call(
Method::DELETE,
&group_path,
None,
None,
StatusCode::NOT_FOUND,
)
.await;
assert_eq!(missing["error"]["kind"], "GroupNotFound");
let list = console
.call(Method::GET, "/ports", None, None, StatusCode::OK)
.await;
assert_eq!(list["leases"], json!([]));
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn request_logs_omit_credentials_from_headers_query_and_body() {
use std::fs;
let fixture = crate::test_support::TempDir::new();
let path = fixture.path().join("request.log");
let (logger, drain) = Logger::start(fs::File::create(&path).unwrap()).unwrap();
let (router, token) = fixture_router_with_log(&fixture, logger);
let tag = "private-tag-marker";
let request = Request::builder()
.method(Method::PATCH)
.uri(format!("/api/v1/claims/8123?token={token}"))
.header(header::HOST, "localhost:8123")
.header(header::ORIGIN, "http://localhost:8123")
.header(TOKEN_HEADER, &token)
.header(header::IF_MATCH, tag)
.header(header::CONTENT_TYPE, JSON_TYPE)
.body(Body::from(json!({"service": &token}).to_string()))
.unwrap();
let (status, _) = dispatch(router, request).await;
assert_eq!(status, StatusCode::NOT_FOUND);
drain.wait();
let logs = fs::read_to_string(path).unwrap();
assert!(
logs.lines()
.any(|line| line.starts_with("troll serve PATCH /api/v1/claims/8123 404 "))
);
assert!(
!logs.contains(&token),
"request log leaked the session token"
);
assert!(!logs.contains(tag), "request log leaked the If-Match value");
assert!(
!logs.contains("?token="),
"request log included the query string"
);
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn page_routes_are_host_guarded_and_send_browser_headers() {
const EXPECTED_CSP: &str = concat!(
"default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; ",
"img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
);
let fixture = crate::test_support::TempDir::new();
let (app, credential) = fixture_router(&fixture);
for (path, content_type) in [
("/", "text/html; charset=utf-8"),
("/app.js", "text/javascript; charset=utf-8"),
("/style.css", "text/css; charset=utf-8"),
] {
let request = |host| {
Request::builder()
.uri(path)
.header(header::HOST, host)
.body(Body::empty())
.unwrap()
};
let response = dispatch_response(app.clone(), request("localhost:8123")).await;
assert_eq!(response.status(), StatusCode::OK, "{path}");
let headers = response.headers();
for (name, value) in [
(header::CONTENT_TYPE, content_type),
(header::CONTENT_SECURITY_POLICY, EXPECTED_CSP),
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
(header::REFERRER_POLICY, "no-referrer"),
(header::X_FRAME_OPTIONS, "DENY"),
] {
assert_eq!(headers[&name], value, "{path} {name}");
}
assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN));
if path == "/" {
assert_eq!(headers[header::CACHE_CONTROL], "no-store");
}
let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();
let body = std::str::from_utf8(&body).unwrap();
if path == "/" {
assert!(body.contains(&format!(
r#"<meta name="troll-token" content="{credential}">"#
)));
} else {
assert!(!body.is_empty());
assert!(!body.contains(&credential));
}
let response = dispatch_response(app.clone(), request("unlisted.invalid:8123")).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN, "{path}");
for (name, value) in [
(header::CONTENT_SECURITY_POLICY, EXPECTED_CSP),
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
(header::REFERRER_POLICY, "no-referrer"),
(header::X_FRAME_OPTIONS, "DENY"),
] {
assert_eq!(response.headers()[&name], value, "{path} {name}");
}
let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();
let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(body["error"]["kind"], "Forbidden");
}
}
#[cfg(target_os = "linux")]
#[test]
fn renew_and_delete_accept_a_numeric_offset_matching_the_stored_instant() {
let fixture = crate::test_support::TempDir::new();
let (app, credential) = fixture_router(&fixture);
let stored = "2026-11-30T02:00:00.123456789Z";
std::fs::write(
fixture.path().join("registry.toml"),
format!(
"schema = 1\n[[lease]]\nport = 20000\nbind = '127.0.0.1'\nproject = 'test'\n\
purpose = 'preview'\nholder = 'test'\nleased_at = '{stored}'\n\
expires_at = '2026-11-30T03:00:00Z'\n"
),
)
.unwrap();
let offset = "2026-11-30t04:00:00.123456789+02:00";
let request = || {
Request::builder()
.header(header::HOST, "localhost:8123")
.header(header::ORIGIN, "http://localhost:8123")
.header(TOKEN_HEADER, &credential)
};
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
let (status, body) = runtime.block_on(dispatch(
app.clone(),
request()
.method(Method::POST)
.uri("/api/v1/leases/20000/renew")
.header(header::CONTENT_TYPE, JSON_TYPE)
.body(Body::from(json!({"leased_at": offset}).to_string()))
.unwrap(),
));
assert_eq!(status, StatusCode::OK, "{body}");
assert_eq!(body["leased_at"], stored);
let (status, body) = runtime.block_on(dispatch(
app,
request()
.method(Method::DELETE)
.uri(format!(
"/api/v1/leases/20000?leased_at={}",
offset.replace('+', "%2B")
))
.header(header::IF_MATCH, body["tag"].as_str().unwrap())
.body(Body::empty())
.unwrap(),
));
assert_eq!(status, StatusCode::OK, "{body}");
assert_eq!(body["leased_at"], stored);
}
#[cfg(target_os = "linux")]
#[test]
fn router_applies_guards_to_handlers_and_fallbacks_without_sockets() {
let fixture = crate::test_support::TempDir::new();
let (app, credential) = fixture_router(&fixture);
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
let (status, body) = runtime.block_on(dispatch(
app.clone(),
Request::builder()
.uri("/missing")
.body(Body::empty())
.unwrap(),
));
assert_eq!(status, StatusCode::FORBIDDEN);
assert_eq!(body["error"]["kind"], "Forbidden");
let body = r#"{"project":"demo","purpose":"fixture"}"#;
let post = || {
Request::builder()
.method(Method::POST)
.uri("/api/v1/leases")
.header(header::HOST, "localhost:8123")
.header(header::ORIGIN, "http://localhost:8123")
};
let (status, _) = runtime.block_on(dispatch(
app.clone(),
post().body(Body::from(body)).unwrap(),
));
assert_eq!(status, StatusCode::UNAUTHORIZED);
let (status, rejection) = runtime.block_on(dispatch(
app.clone(),
post()
.header(TOKEN_HEADER, &credential)
.header(TOKEN_HEADER, &credential)
.header(header::CONTENT_TYPE, JSON_TYPE)
.body(Body::from(body))
.unwrap(),
));
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(rejection["error"]["kind"], "Unauthorized");
let (status, _) = runtime.block_on(dispatch(
app.clone(),
post()
.header(TOKEN_HEADER, &credential)
.body(Body::from(body))
.unwrap(),
));
assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE);
let (status, rejection) = runtime.block_on(dispatch(
app.clone(),
post()
.header(TOKEN_HEADER, &credential)
.header(header::CONTENT_TYPE, "application/problem+json")
.body(Body::from(body))
.unwrap(),
));
assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE);
assert_eq!(rejection["error"]["kind"], "UnsupportedMediaType");
let (status, body) = runtime.block_on(dispatch(
app.clone(),
post()
.header(TOKEN_HEADER, &credential)
.header(header::CONTENT_TYPE, "application/json; charset=utf-8")
.body(Body::from(body))
.unwrap(),
));
assert_eq!(status, StatusCode::CREATED);
let port = body["port"].as_u64().unwrap();
let (status, body) = runtime.block_on(dispatch(
app,
Request::builder()
.method(Method::DELETE)
.uri(format!("/api/v1/leases/{port}"))
.header(header::HOST, "127.0.0.1:8123")
.header(header::ORIGIN, "http://127.0.0.1:8123")
.header(TOKEN_HEADER, &credential)
.body(Body::empty())
.unwrap(),
));
assert_eq!(status, StatusCode::OK);
assert_eq!(body["tier"], "lease");
assert_eq!(body["port"], port);
}
#[test]
fn list_query_uses_cli_filter_values() {
let (kind, role) = list_filters(Some("kind=third%2Dparty&role=%73ervice")).unwrap();
assert!(matches!(kind, Some(KindArg::ThirdParty)));
assert!(matches!(role, Some(RoleArg::Service)));
for query in [
"kind=unknown",
"role=invalid",
"kind=ours&kind=system",
"role=%",
"%ff=x",
"other=1",
] {
let result = list_filters(Some(query));
assert_eq!(result.err().unwrap().status, StatusCode::BAD_REQUEST);
}
}
#[cfg(target_os = "linux")]
#[test]
fn history_routes_list_and_restore_released_claims() {
let fixture = crate::test_support::TempDir::new();
let (app, token) = fixture_router(&fixture);
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let (status, _) = runtime.block_on(dispatch(
app.clone(),
Request::builder()
.method(Method::POST)
.uri("/api/v1/claims")
.header(header::HOST, "127.0.0.1:8123")
.header(header::ORIGIN, "http://127.0.0.1:8123")
.header(TOKEN_HEADER, &token)
.header(header::CONTENT_TYPE, JSON_TYPE)
.body(Body::from(
r#"{"port":8199,"project":"hist-app","service":"Web UI","web":"/"}"#,
))
.unwrap(),
));
assert_eq!(status, StatusCode::CREATED);
let (status, _) = runtime.block_on(dispatch(
app.clone(),
Request::builder()
.method(Method::DELETE)
.uri("/api/v1/claims/8199")
.header(header::HOST, "127.0.0.1:8123")
.header(header::ORIGIN, "http://127.0.0.1:8123")
.header(TOKEN_HEADER, &token)
.body(Body::empty())
.unwrap(),
));
assert_eq!(status, StatusCode::OK);
let (status, body) = runtime.block_on(dispatch(
app.clone(),
Request::builder()
.method(Method::GET)
.uri("/api/v1/history")
.header(header::HOST, "127.0.0.1:8123")
.body(Body::empty())
.unwrap(),
));
assert_eq!(status, StatusCode::OK);
assert_eq!(body["retention_days"], 30);
let id = body["entries"][0]["id"].as_str().unwrap().to_owned();
let (status, _) = runtime.block_on(dispatch(
app.clone(),
Request::builder()
.method(Method::POST)
.uri(format!("/api/v1/history/{id}/restore"))
.header(header::HOST, "127.0.0.1:8123")
.header(header::ORIGIN, "http://127.0.0.1:8123")
.header(header::CONTENT_TYPE, JSON_TYPE)
.body(Body::from("{}"))
.unwrap(),
));
assert_eq!(status, StatusCode::UNAUTHORIZED);
let (status, restored) = runtime.block_on(dispatch(
app.clone(),
Request::builder()
.method(Method::POST)
.uri(format!("/api/v1/history/{id}/restore"))
.header(header::HOST, "127.0.0.1:8123")
.header(header::ORIGIN, "http://127.0.0.1:8123")
.header(TOKEN_HEADER, &token)
.header(header::CONTENT_TYPE, JSON_TYPE)
.body(Body::from("{}"))
.unwrap(),
));
assert_eq!(status, StatusCode::OK);
assert_eq!(restored["project"], "hist-app");
assert_eq!(restored["entries"][0]["port"], 8199);
let (status, _) = runtime.block_on(dispatch(
app,
Request::builder()
.method(Method::POST)
.uri(format!("/api/v1/history/{id}/restore"))
.header(header::HOST, "127.0.0.1:8123")
.header(header::ORIGIN, "http://127.0.0.1:8123")
.header(TOKEN_HEADER, &token)
.header(header::CONTENT_TYPE, JSON_TYPE)
.body(Body::from("{}"))
.unwrap(),
));
assert_eq!(status, StatusCode::NOT_FOUND);
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn snapshot_returns_ports_drift_apps_and_zones_in_one_reply() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
console
.call(
Method::POST,
"/claims",
Some(json!({"port": 8220, "project": "snap-app", "service": "Web", "component": "web"})),
None,
StatusCode::CREATED,
)
.await;
console
.call(
Method::POST,
"/zones",
Some(json!({"label": "snap-zone", "ports": ["8220"]})),
None,
StatusCode::CREATED,
)
.await;
let snap = console
.call(Method::GET, "/snapshot", None, None, StatusCode::OK)
.await;
assert_eq!(snap["schema"], SCHEMA);
assert_eq!(snap["ports"]["apps"][0]["port"], 8220);
assert_eq!(snap["apps"]["apps"][0]["app"], "snap-app");
assert_eq!(snap["zones"]["zones"][0]["label"], "snap-zone");
assert_eq!(snap["drift"]["counts"]["zone_conflicts"], 1);
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn lease_endpoint_honors_named_pool_and_rejects_unknown_pool() {
let fixture = crate::test_support::TempDir::new();
std::fs::write(
fixture.path().join("config.toml"),
"lease_range = [20000, 20999]\n[pools]\npreview = [20600, 20605]\n",
)
.unwrap();
let console = Console::new(&fixture);
let leased = console
.call(
Method::POST,
"/leases",
Some(json!({"project": "demo", "purpose": "web", "pool": "preview"})),
None,
StatusCode::CREATED,
)
.await;
assert_eq!(leased["port"], 20600);
let missing = console
.call(
Method::POST,
"/leases",
Some(json!({"project": "demo", "purpose": "web", "pool": "missing"})),
None,
StatusCode::NOT_FOUND,
)
.await;
assert_eq!(missing["error"]["kind"], "PoolNotFound");
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn zone_endpoints_preserve_label_case_and_match_case_insensitively() {
let fixture = crate::test_support::TempDir::new();
let console = Console::new(&fixture);
let created = console
.call(
Method::POST,
"/zones",
Some(json!({"label": "Prod-Web", "ports": ["8300-8310"]})),
None,
StatusCode::CREATED,
)
.await;
assert_eq!(created["zone"]["label"], "Prod-Web");
let dup = console
.call(
Method::POST,
"/zones",
Some(json!({"label": "prod-web", "ports": ["8320"]})),
None,
StatusCode::CONFLICT,
)
.await;
assert_eq!(dup["error"]["kind"], "ZoneExists");
let tag = created["zone"]["tag"].as_str().unwrap();
let updated = console
.call(
Method::PATCH,
"/zones/prod-web",
Some(json!({"enabled": false})),
Some(tag),
StatusCode::OK,
)
.await;
assert_eq!(updated["zone"]["label"], "Prod-Web");
assert_eq!(updated["zone"]["enabled"], false);
let removed = console
.call(
Method::DELETE,
"/zones/PROD-WEB",
None,
updated["zone"]["tag"].as_str(),
StatusCode::OK,
)
.await;
assert_eq!(removed["zone"]["label"], "Prod-Web");
}
}