This commit is contained in:
Mateusz Gruszczyński committed 2026-10-04 11:15:58 +02:00
1 parent 87e571c170
commit fa7abc9e53
308 files changed
+49746 -50237

No files matched your search

+405
View File
@@ -0,0 +1,405 @@
async fn transform_status(State(state): State<Arc<App>>) -> Json<Value> {
let snapshot = state.config.load_full();
let global = &snapshot.envelope.config.transform;
let vhosts: Vec<_> = snapshot
.envelope
.config
.vhosts
.iter()
.map(|vhost| {
json!({
"id": vhost.id,
"hosts": vhost.frontend.hosts,
"settings": vhost.transform.resolve(global).ok()
})
})
.collect();
Json(json!({
"settings": global,
"resources": crate::transform::resource_usage(global),
"metrics": state.transform_metrics.view(),
"vhosts": vhosts
}))
}
#[derive(Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct PurgeScope {
vhost: Option<String>,
}
async fn cache_purge(
State(state): State<Arc<App>>,
Extension(session): Extension<Session>,
Query(scope): Query<PurgeScope>,
) -> Result<Json<Value>, ApiError> {
if let Some(id) = &scope.vhost {
if !state
.config
.load()
.envelope
.config
.vhosts
.iter()
.any(|host| &host.id == id)
{
return Err(ApiError(
StatusCode::NOT_FOUND,
"unknown vhost cache scope".into(),
));
}
}
let detail = format!(
"scope={}; in-flight fills invalidated",
scope.vhost.as_deref().unwrap_or("all")
);
state
.store
.audit(&session.username, "cache.purge", &detail)
.await
.map_err(auth::internal)?;
let purged = match &scope.vhost {
Some(id) => state.cache.purge_scope(id),
None => state.cache.purge(None),
};
Ok(Json(
json!({"purged_entries":purged, "vhost":scope.vhost, "metrics":state.cache.view()}),
))
}
async fn cache_invalidate(
State(state): State<Arc<App>>,
Extension(session): Extension<Session>,
input: Result<Json<crate::cache::InvalidationRequest>, axum::extract::rejection::JsonRejection>,
) -> Result<Json<Value>, ApiError> {
let Json(request) = input.map_err(public::invalid_json)?;
if let Some(id) = &request.vhost {
if !state
.config
.load()
.envelope
.config
.vhosts
.iter()
.any(|host| &host.id == id)
{
return Err(ApiError(
StatusCode::NOT_FOUND,
"unknown vhost cache scope".into(),
));
}
}
let detail = format!(
"operation={:?}; selector={:?}; vhost={}; host={}; value={:?}",
request.operation,
request.selector,
request.vhost.as_deref().unwrap_or("all"),
request.host.as_deref().unwrap_or("any"),
request.value
);
state
.store
.audit(&session.username, "cache.invalidate", &detail)
.await
.map_err(auth::internal)?;
let result = state
.cache
.invalidate(request)
.map_err(|error| ApiError(StatusCode::UNPROCESSABLE_ENTITY, error.to_string()))?;
Ok(Json(json!({
"result": result,
"metrics": state.cache.view(),
"bans": state.cache.bans()
})))
}
async fn cache_bans(State(state): State<Arc<App>>) -> Json<Value> {
Json(json!({"bans": state.cache.bans()}))
}
async fn cache_ban_delete(
State(state): State<Arc<App>>,
Extension(session): Extension<Session>,
Path(id): Path<u64>,
) -> Result<Json<Value>, ApiError> {
if !state.cache.remove_ban(id) {
return Err(ApiError(StatusCode::NOT_FOUND, "unknown cache BAN rule".into()));
}
state
.store
.audit(&session.username, "cache.ban.remove", &format!("ban_id={id}"))
.await
.map_err(auth::internal)?;
Ok(Json(json!({"removed": id, "bans": state.cache.bans()})))
}
async fn active_tunnels(State(state): State<Arc<App>>) -> Json<Value> {
Json(json!({"tunnels": state.tunnel_registry.list()}))
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct KillTunnelRequest {
#[serde(default)]
reason: Option<String>,
}
async fn kill_tunnel(
State(state): State<Arc<App>>,
Extension(session): Extension<Session>,
Path(id): Path<u64>,
input: Result<Json<KillTunnelRequest>, axum::extract::rejection::JsonRejection>,
) -> Result<Json<Value>, ApiError> {
let Json(input) = input.map_err(public::invalid_json)?;
let reason = input
.reason
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.unwrap_or("administrator request");
if reason.len() > 256 || reason.chars().any(char::is_control) {
return Err(ApiError(
StatusCode::UNPROCESSABLE_ENTITY,
"invalid tunnel close reason".into(),
));
}
let Some(tunnel) = state.tunnel_registry.kill(id) else {
return Err(ApiError(StatusCode::NOT_FOUND, "unknown active tunnel".into()));
};
state
.store
.audit(
&session.username,
"tunnel.kill",
&format!(
"tunnel_id={}; client={}; host={}; upstream={}; protocol={}; reason={}",
tunnel.id, tunnel.client, tunnel.host, tunnel.upstream, tunnel.protocol, reason
),
)
.await
.map_err(auth::internal)?;
Ok(Json(json!({"closed": tunnel, "reason": reason})))
}
async fn cache_cold_cleanup(
State(state): State<Arc<App>>,
Extension(session): Extension<Session>,
input: Result<Json<crate::cache::ColdCleanupRequest>, axum::extract::rejection::JsonRejection>,
) -> Result<(StatusCode, Json<Value>), ApiError> {
let Json(request) = input.map_err(public::invalid_json)?;
let detail = format!(
"unused_for_seconds={:?}; oldest={:?}; hits_zero={}",
request.unused_for_seconds, request.oldest, request.hits_zero
);
let job = state
.cache
.start_cold_cleanup(request)
.map_err(|error| ApiError(StatusCode::UNPROCESSABLE_ENTITY, error.to_string()))?;
state
.store
.audit(&session.username, "cache.cold_cleanup", &detail)
.await
.map_err(auth::internal)?;
Ok((StatusCode::ACCEPTED, Json(json!({"job": job}))))
}
async fn cache_cold_cleanup_job(
State(state): State<Arc<App>>,
Path(id): Path<u64>,
) -> Result<Json<Value>, ApiError> {
let job = state
.cache
.cold_cleanup_job(id)
.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "unknown cold-cache cleanup job".into()))?;
Ok(Json(json!({"job": job})))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CertificateUpload {
cert_pem: String,
key_pem: String,
hosts: Vec<String>,
}
async fn certificate_upload(
State(state): State<Arc<App>>,
Extension(session): Extension<Session>,
Json(input): Json<CertificateUpload>,
) -> Result<Json<Value>, ApiError> {
let key = zeroize::Zeroizing::new(input.key_pem);
let directory = state.policy.cert_dir.clone().ok_or_else(|| {
ApiError(
StatusCode::CONFLICT,
"certificate storage is unavailable; configure the certificate directory".into(),
)
})?;
let permit = state
.certificate_slots
.clone()
.try_acquire_owned()
.map_err(|_| {
ApiError(
StatusCode::TOO_MANY_REQUESTS,
"certificate upload queue is full".into(),
)
})?;
let certificate = tokio::task::spawn_blocking(move || {
let _permit = permit;
crate::tls::upload(
&directory,
input.cert_pem.as_bytes(),
key.as_bytes(),
input.hosts,
)
})
.await
.map_err(|_| {
ApiError(
StatusCode::INTERNAL_SERVER_ERROR,
"certificate upload task failed".into(),
)
})?
.map_err(|e| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("{e:#}")))?;
state
.store
.audit(&session.username, "certificate.upload", &certificate.id)
.await
.map_err(auth::internal)?;
// Never serialize the PEM request or any key material, including on success.
Ok(Json(json!({"certificate":certificate, "staged":true})))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CertificateApiRotate {
#[serde(default)]
key_id: Option<String>,
#[serde(default)]
token: Option<String>,
#[serde(default)]
comment: Option<String>,
}
fn valid_certificate_api_comment(value: &str) -> bool {
value.len() <= 256 && !value.chars().any(char::is_control)
}
fn certificate_api_status_value(values: Vec<crate::db::CertificateApiCredential>) -> Value {
let legacy = values.first();
json!({
"configured": !values.is_empty(),
"key_id": legacy.map(|value| value.key_id.clone()),
"created_at": legacy.map(|value| value.created_at),
"last_used_at": legacy.and_then(|value| value.last_used_at),
"credentials": values,
"max_credentials": crate::db::CERTIFICATE_API_CREDENTIAL_CAPACITY,
"scopes": ["certificates:deploy", "certificates:reload"],
})
}
async fn certificate_api_status(State(state): State<Arc<App>>) -> Result<Json<Value>, ApiError> {
let values = state
.store
.certificate_api_credentials()
.await
.map_err(auth::internal)?;
Ok(Json(certificate_api_status_value(values)))
}
async fn certificate_api_rotate(
State(state): State<Arc<App>>,
Extension(session): Extension<Session>,
Json(input): Json<CertificateApiRotate>,
) -> Result<Json<Value>, ApiError> {
let generated = input.token.is_none();
let token = input.token.unwrap_or_else(auth::random_secret);
if !valid_certificate_api_token(&token) {
return Err(ApiError(
StatusCode::UNPROCESSABLE_ENTITY,
"certificate_api.invalid_token_format".into(),
));
}
let key_id = input.key_id.unwrap_or_else(|| {
let random = auth::random_secret();
format!("certapi-{}", &random[..12])
});
if !valid_certificate_api_key_id(&key_id) {
return Err(ApiError(
StatusCode::UNPROCESSABLE_ENTITY,
"certificate_api.invalid_key_id".into(),
));
}
let comment = input.comment.unwrap_or_default().trim().to_owned();
if !valid_certificate_api_comment(&comment) {
return Err(ApiError(
StatusCode::UNPROCESSABLE_ENTITY,
"certificate_api.invalid_comment".into(),
));
}
let token_hash = auth::secret_hash(&token);
let credential = state
.store
.upsert_certificate_api_credential(
&key_id,
&token_hash,
&comment,
&session.username,
)
.await
.map_err(|error| {
if error.to_string().contains("credential limit reached") {
ApiError(StatusCode::CONFLICT, "certificate_api.limit_reached".into())
} else {
auth::internal(error)
}
})?;
let values = state
.store
.certificate_api_credentials()
.await
.map_err(auth::internal)?;
let mut value = certificate_api_status_value(values);
value["credential"] = serde_json::to_value(&credential).map_err(auth::internal)?;
value["token"] = Value::String(token);
value["generated"] = Value::Bool(generated);
Ok(Json(value))
}
async fn certificate_api_revoke(
State(state): State<Arc<App>>,
Extension(session): Extension<Session>,
Path(key_id): Path<String>,
) -> Result<Json<Value>, ApiError> {
if !valid_certificate_api_key_id(&key_id) {
return Err(ApiError(StatusCode::NOT_FOUND, "certificate_api.not_found".into()));
}
let revoked = state
.store
.revoke_certificate_api_credential(&key_id, &session.username)
.await
.map_err(auth::internal)?;
if !revoked {
return Err(ApiError(StatusCode::NOT_FOUND, "certificate_api.not_found".into()));
}
Ok(Json(json!({"revoked": true, "key_id": key_id})))
}
async fn certificate_api_revoke_all(
State(state): State<Arc<App>>,
Extension(session): Extension<Session>,
) -> Result<Json<Value>, ApiError> {
let revoked = state
.store
.revoke_all_certificate_api_credentials(&session.username)
.await
.map_err(auth::internal)?;
Ok(Json(json!({"configured": false, "revoked": revoked})))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CertificateDeploy {
certificate_id: String,
cert_pem: String,
key_pem: String,
}