C: review round 1 proxy fixes
Unit names go through the local route's validation, so escaped and dash-rooted units work through the proxy; backslashes stay legal only there. Response preparation (status classification, content-type check, size/stream bounds) moves into proxy.rs for REST and MCP to share. x-slinuxm-peer is only set for configured peers, proxied SSE is no-cache, and the unreachable handler fallbacks are gone.
This commit is contained in:
1 parent
9be74b9dd8
commit
7a4d64c051
3 files changed
+405
-153
No files matched your search
+75
-80
@@ -8,18 +8,16 @@ use std::time::Duration;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::extract::{Path, Request, State};
|
||||
use axum::http::{header, HeaderName, HeaderValue, StatusCode};
|
||||
use axum::http::{header, HeaderName, HeaderValue};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::peers::error::peer_error_to_app;
|
||||
use crate::peers::proxy::{self, PreparedBody};
|
||||
use crate::peers::transport::PeerResponse;
|
||||
use crate::peers::proxy::{self, PreparedBody, PreparedResponse};
|
||||
use crate::peers::types::{PeerName, PeerStatus};
|
||||
use crate::peers::ProxyOpts;
|
||||
use crate::peers::{PeerRegistry, ProxyOpts};
|
||||
use crate::state::AppState;
|
||||
|
||||
pub fn routes() -> Router<AppState> {
|
||||
@@ -34,22 +32,25 @@ struct PeerList {
|
||||
peers: Vec<PeerStatus>,
|
||||
}
|
||||
|
||||
fn registry(st: &AppState) -> Result<&crate::peers::PeerRegistry, AppError> {
|
||||
/// Only reachable with a registry: `api::router` merges these routes on
|
||||
/// `state.peers.is_some()` and the field is fixed for the process lifetime.
|
||||
fn registry(st: &AppState) -> &PeerRegistry {
|
||||
st.peers
|
||||
.as_deref()
|
||||
.ok_or_else(|| AppError::NotFound("no such route".into()))
|
||||
.expect("peer routes are mounted only with a peer registry")
|
||||
}
|
||||
|
||||
async fn list(State(st): State<AppState>) -> Result<Json<PeerList>, AppError> {
|
||||
let peers = registry(&st)?.snapshot();
|
||||
Ok(Json(PeerList { peers }))
|
||||
async fn list(State(st): State<AppState>) -> Json<PeerList> {
|
||||
Json(PeerList {
|
||||
peers: registry(&st).snapshot(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn one(
|
||||
State(st): State<AppState>,
|
||||
Path(peer): Path<String>,
|
||||
) -> Result<Json<PeerStatus>, AppError> {
|
||||
Ok(Json(registry(&st)?.status(&peer)?))
|
||||
Ok(Json(registry(&st).status(&peer)?))
|
||||
}
|
||||
|
||||
async fn pass(
|
||||
@@ -57,31 +58,40 @@ async fn pass(
|
||||
Path((peer, _path)): Path<(String, String)>,
|
||||
request: Request,
|
||||
) -> Response {
|
||||
with_peer_header(&peer, pass_through(&st, &peer, request).await)
|
||||
let reg = registry(&st);
|
||||
// The registry parses and looks the name up in one call, so an unknown or
|
||||
// malformed name gets the contract's 404 and no peer header: the response
|
||||
// does not come from a peer.
|
||||
let name = match reg.status(&peer) {
|
||||
Ok(status) => status.name,
|
||||
Err(err) => return err.into_response(),
|
||||
};
|
||||
with_peer_header(&name, pass_through(reg, &name, &st, request).await)
|
||||
}
|
||||
|
||||
/// Every outcome for a proxy call names the peer, including consolidator-side
|
||||
/// errors (bad path, dead peer), so a client can tell which peer failed.
|
||||
fn with_peer_header(peer: &str, mut response: Response) -> Response {
|
||||
if let Ok(value) = HeaderValue::from_str(peer) {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(HeaderName::from_static(proxy::PEER_HEADER), value);
|
||||
}
|
||||
fn with_peer_header(name: &PeerName, mut response: Response) -> Response {
|
||||
let value = HeaderValue::from_str(name.as_str()).expect("validated peer name");
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(HeaderName::from_static(proxy::PEER_HEADER), value);
|
||||
response
|
||||
}
|
||||
|
||||
async fn pass_through(st: &AppState, peer: &str, request: Request) -> Response {
|
||||
let Some(reg) = st.peers.clone() else {
|
||||
return AppError::NotFound("no such route".into()).into_response();
|
||||
};
|
||||
if let Err(err) = proxy::reject_inbound_hop(peer, request.headers()) {
|
||||
async fn pass_through(
|
||||
reg: &PeerRegistry,
|
||||
name: &PeerName,
|
||||
st: &AppState,
|
||||
request: Request,
|
||||
) -> Response {
|
||||
if let Err(err) = proxy::reject_inbound_hop(name.as_str(), request.headers()) {
|
||||
return err.into_response();
|
||||
}
|
||||
let Some(raw_path) = raw_peer_path(request.uri().path()) else {
|
||||
return AppError::BadRequest(format!("peer {peer}: path not allowed")).into_response();
|
||||
return AppError::BadRequest(format!("peer {name}: path not allowed")).into_response();
|
||||
};
|
||||
let query = match proxy::query_from_raw(peer, request.uri().query()) {
|
||||
let query = match proxy::query_from_raw(name.as_str(), request.uri().query()) {
|
||||
Ok(query) => query,
|
||||
Err(err) => return err.into_response(),
|
||||
};
|
||||
@@ -89,12 +99,50 @@ async fn pass_through(st: &AppState, peer: &str, request: Request) -> Response {
|
||||
traceparent: inbound_traceparent(request.headers()),
|
||||
accept_sse: accepts_event_stream(request.headers()),
|
||||
};
|
||||
match reg.get(peer, raw_path, &query, opts).await {
|
||||
Ok(resp) => proxy_response(st, peer, resp),
|
||||
let resp = match reg.get(name.as_str(), raw_path, &query, opts).await {
|
||||
Ok(resp) => resp,
|
||||
Err(err) => return err.into_response(),
|
||||
};
|
||||
let deadline =
|
||||
tokio::time::Instant::now() + Duration::from_secs(st.config.limits.max_follow_secs);
|
||||
match proxy::prepare_response(
|
||||
name,
|
||||
resp,
|
||||
reg.config().max_response_bytes,
|
||||
deadline,
|
||||
st.shutdown.clone(),
|
||||
) {
|
||||
Ok(prepared) => prepared_response(prepared),
|
||||
Err(err) => err.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
fn prepared_response(prepared: PreparedResponse) -> Response {
|
||||
let sse = prepared
|
||||
.content_type
|
||||
.as_ref()
|
||||
.is_some_and(|value| value.as_bytes() == b"text/event-stream");
|
||||
let body = match prepared.body {
|
||||
PreparedBody::Bytes(bytes) => Body::from(bytes),
|
||||
PreparedBody::Stream(stream) => Body::from_stream(stream),
|
||||
};
|
||||
let mut response = Response::new(body);
|
||||
*response.status_mut() = prepared.status;
|
||||
if let Some(content_type) = prepared.content_type {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::CONTENT_TYPE, content_type);
|
||||
}
|
||||
// A follow must not be buffered or cached by an intermediary; the local
|
||||
// routes get this from axum's `Sse`.
|
||||
if sse {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// Path after `/peers/{name}/`, still percent-encoded. Nesting strips
|
||||
/// `/api/v1` before this runs, so both the mounted server and the bare API
|
||||
/// router yield `/peers/...`.
|
||||
@@ -130,59 +178,6 @@ fn accepts_event_stream(headers: &axum::http::HeaderMap) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
fn proxy_response(st: &AppState, peer: &str, resp: PeerResponse) -> Response {
|
||||
let name = match PeerName::parse(peer) {
|
||||
Ok(name) => name,
|
||||
Err(_) => {
|
||||
return AppError::NotFound(format!("peer {peer}: unknown peer")).into_response();
|
||||
}
|
||||
};
|
||||
let max_bytes = st
|
||||
.peers
|
||||
.as_ref()
|
||||
.map(|reg| reg.config().max_response_bytes)
|
||||
.unwrap_or(0);
|
||||
let deadline =
|
||||
tokio::time::Instant::now() + Duration::from_secs(st.config.limits.max_follow_secs);
|
||||
let status = match StatusCode::from_u16(resp.status) {
|
||||
Ok(status) => status,
|
||||
Err(_) => {
|
||||
return peer_error_to_app(&name, &crate::peers::PeerError::Http(resp.status))
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
let content_type = match content_type_header(&name, resp.content_type.as_deref()) {
|
||||
Ok(value) => value,
|
||||
Err(err) => return err.into_response(),
|
||||
};
|
||||
let body = match proxy::prepare_body(&name, resp.body, max_bytes, deadline, st.shutdown.clone())
|
||||
{
|
||||
Ok(PreparedBody::Bytes(bytes)) => Body::from(bytes),
|
||||
Ok(PreparedBody::Stream(stream)) => Body::from_stream(stream),
|
||||
Err(err) => return err.into_response(),
|
||||
};
|
||||
let mut response = Response::new(body);
|
||||
*response.status_mut() = status;
|
||||
if let Some(content_type) = content_type {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::CONTENT_TYPE, content_type);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
fn content_type_header(
|
||||
peer: &PeerName,
|
||||
value: Option<&str>,
|
||||
) -> Result<Option<HeaderValue>, AppError> {
|
||||
match value {
|
||||
None => Ok(None),
|
||||
Some(value) => HeaderValue::from_str(value).map(Some).map_err(|_| {
|
||||
peer_error_to_app(peer, &crate::peers::PeerError::Malformed(String::new()))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use axum::http::StatusCode;
|
||||
|
||||
Reference in new issue
Block a user