C: C2 GET-only pass-through proxy with allowlist, hop guard and query filter
This commit is contained in:
1 parent
bec0ab5736
commit
bab6959a94
4 files changed
+962
-36
No files matched your search
+128
-2
@@ -4,19 +4,29 @@
|
||||
//! peers routes at all. Pass-through lives in `crate::peers::proxy` so MCP
|
||||
//! calls the same code.
|
||||
|
||||
use axum::extract::{Path, State};
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::extract::{Path, Request, State};
|
||||
use axum::http::{header, HeaderValue, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::peers::types::PeerStatus;
|
||||
use crate::peers::error::peer_error_to_app;
|
||||
use crate::peers::proxy::{self, PreparedBody};
|
||||
use crate::peers::transport::PeerResponse;
|
||||
use crate::peers::types::{PeerName, PeerStatus};
|
||||
use crate::peers::ProxyOpts;
|
||||
use crate::state::AppState;
|
||||
|
||||
pub fn routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/peers", get(list))
|
||||
.route("/peers/{peer}", get(one))
|
||||
.route("/peers/{peer}/{*path}", get(pass))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -42,6 +52,122 @@ async fn one(
|
||||
Ok(Json(registry(&st)?.status(&peer)?))
|
||||
}
|
||||
|
||||
async fn pass(
|
||||
State(st): State<AppState>,
|
||||
Path((peer, _path)): Path<(String, String)>,
|
||||
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()) {
|
||||
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();
|
||||
};
|
||||
let query = match proxy::query_from_raw(&peer, request.uri().query()) {
|
||||
Ok(query) => query,
|
||||
Err(err) => return err.into_response(),
|
||||
};
|
||||
let opts = ProxyOpts {
|
||||
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),
|
||||
Err(err) => err.into_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/...`.
|
||||
fn raw_peer_path(uri_path: &str) -> Option<&str> {
|
||||
let mut rest = uri_path;
|
||||
while let Some(stripped) = rest.strip_prefix('/') {
|
||||
if let Some(after) = stripped.strip_prefix("peers/") {
|
||||
let (_name, path) = after.split_once('/')?;
|
||||
return Some(path);
|
||||
}
|
||||
rest = &stripped[stripped.find('/')?..];
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn inbound_traceparent(headers: &axum::http::HeaderMap) -> Option<String> {
|
||||
let value = headers.get("traceparent")?.to_str().ok()?;
|
||||
if (1..=128).contains(&value.len()) && value.bytes().all(|b| b.is_ascii_graphic()) {
|
||||
Some(value.to_owned())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn accepts_event_stream(headers: &axum::http::HeaderMap) -> bool {
|
||||
headers
|
||||
.get(header::ACCEPT)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(|value| {
|
||||
value
|
||||
.split(',')
|
||||
.any(|part| part.trim().starts_with("text/event-stream"))
|
||||
})
|
||||
}
|
||||
|
||||
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