Require relay signatures by default (fixes GHSA-rrhv-24wq-6q5j) (#3510)

* Require relay signatures on every /api route by default

Relayed requests were only signature-checked inside one route group, so
the relay-auth and host-relay routes merged outside it accepted unsigned
relayed requests (GHSA-rrhv-24wq-6q5j): anyone reaching a host through
the relay could list and remove its paired devices.

Replace the per-group layers with one guard over /api. A pure
relay_route_policy() decides per route: the three pairing routes stay
unsigned, device management, the enrollment code and the /host proxy are
refused over relay, and everything else needs a valid signature and gets
a signed response. Local requests are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Refuse local-only routes to WebRTC peers too

Requests over a WebRTC data channel reached the local backend with the
relay header stripped, so the guard treated them as coming from this
machine and a paired device could still fetch an enrollment code, remove
paired devices or proxy on to other hosts. The peer now marks every
proxied HTTP and WebSocket request with x-vk-webrtc-peer, and the guard
refuses local-only routes for it. The data channel itself is the
authentication (only a paired device can open it), so these requests
still need no signature.

Also make /open-remote-editor/* and /relay-auth/client/* local-only:
both contact or pair other hosts with this host's keys, and the frontend
already never sends them to another host. Local-only routes now answer
404 instead of 403, because relay clients treat 401/403 as an expired
signing session and re-handshake.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Anastasiia Solop
2026-11-27 09:17:15 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent d49b13ee8e
commit 7fbde10fc4
10 changed files with 727 additions and 57 deletions
Generated
+1
View File
@@ -9109,6 +9109,7 @@ dependencies = [
"tokio",
"tokio-tungstenite 0.26.2",
"tokio-util",
"tower",
"tower-http 0.5.2",
"tracing",
"tracing-subscriber",
+5
View File
@@ -15,6 +15,11 @@ pub use proxy::{
};
pub use signaling::{IceCandidate, SdpAnswer, SdpOffer};
/// Set on every request the host proxies from a WebRTC data channel to its
/// local backend, so the backend can tell it came from a paired device rather
/// than from this machine. Any copy the peer sends is dropped first.
pub const WEBRTC_PEER_HEADER: &str = "x-vk-webrtc-peer";
/// Build a webrtc API restricted to UDP4 (IPv4 only).
///
/// Without this, the ICE agent tries IPv6 STUN which times out on most
+85 -5
View File
@@ -15,10 +15,10 @@ use webrtc::{
sdp::session_description::RTCSessionDescription,
},
};
use ws_bridge::{bridge_tungstenite_ws, connect_upstream_ws};
use ws_bridge::{bridge_tungstenite_ws, connect_upstream_ws_with_headers};
use crate::{
WebRtcError, fragment,
WEBRTC_PEER_HEADER, WebRtcError, fragment,
proxy::{
DataChannelMessage, DataChannelRequest, DataChannelResponse, DataChannelWsStream, WsError,
WsFrame, WsOpen, WsOpened,
@@ -321,13 +321,14 @@ async fn proxy_request(
for (key, values) in &request.headers {
let k = key.to_ascii_lowercase();
if k == "origin" || k == "host" || k == "x-vk-relayed" {
if k == "origin" || k == "host" || k == "x-vk-relayed" || k == WEBRTC_PEER_HEADER {
continue;
}
for value in values {
req_builder = req_builder.header(key.as_str(), value.as_str());
}
}
req_builder = req_builder.header(WEBRTC_PEER_HEADER, "1");
if let Some(body_b64) = &request.body_b64 {
use base64::Engine as _;
@@ -436,8 +437,12 @@ async fn run_ws_bridge(
) -> Result<(), WebRtcError> {
let conn_id = ws_open.conn_id;
let url = format!("ws://{}{}", local_backend_addr, ws_open.path);
let (ws_stream, selected_protocol) =
connect_upstream_ws(url, ws_open.protocols.as_deref()).await?;
let (ws_stream, selected_protocol) = connect_upstream_ws_with_headers(
url,
ws_open.protocols.as_deref(),
&[(WEBRTC_PEER_HEADER, "1")],
)
.await?;
let opened_msg = DataChannelMessage::WsOpened(WsOpened {
conn_id,
@@ -459,3 +464,78 @@ async fn run_ws_bridge(
.await
.map_err(WebRtcError::from)
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use base64::Engine as _;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
};
use uuid::Uuid;
use super::proxy_request;
use crate::{WEBRTC_PEER_HEADER, proxy::DataChannelRequest};
/// Accepts one HTTP request and answers with its lowercased header block.
async fn echo_headers_server() -> (std::net::SocketAddr, tokio::task::JoinHandle<()>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let task = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut head = Vec::new();
let mut chunk = [0u8; 1024];
while !head.windows(4).any(|w| w == b"\r\n\r\n") {
let n = stream.read(&mut chunk).await.unwrap();
if n == 0 {
break;
}
head.extend_from_slice(&chunk[..n]);
}
let head = String::from_utf8_lossy(&head).to_lowercase();
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{head}",
head.len()
);
stream.write_all(response.as_bytes()).await.unwrap();
});
(addr, task)
}
#[tokio::test]
async fn proxied_requests_are_marked_as_coming_from_a_peer() {
let (addr, server) = echo_headers_server().await;
let headers = HashMap::from([
("X-VK-WebRTC-Peer".to_string(), vec!["0".to_string()]),
("x-vk-relayed".to_string(), vec!["1".to_string()]),
("x-test".to_string(), vec!["kept".to_string()]),
]);
let client = reqwest::Client::builder().no_proxy().build().unwrap();
let response = proxy_request(
&client,
addr,
DataChannelRequest {
id: Uuid::new_v4(),
method: "GET".to_string(),
path: "/api/health".to_string(),
headers,
body_b64: None,
},
)
.await;
server.await.unwrap();
assert_eq!(response.status, 200);
let body = base64::engine::general_purpose::STANDARD
.decode(response.body_b64.unwrap())
.unwrap();
let head = String::from_utf8(body).unwrap();
assert_eq!(head.matches(&format!("{WEBRTC_PEER_HEADER}:")).count(), 1);
assert!(head.contains(&format!("{WEBRTC_PEER_HEADER}: 1\r\n")));
assert!(!head.contains("x-vk-relayed"));
assert!(head.contains("x-test: kept\r\n"));
}
}
+1
View File
@@ -72,6 +72,7 @@ dotenv = "0.15"
[dev-dependencies]
tempfile = "3"
tower = { version = "0.5", features = ["util"] }
[features]
default = []
@@ -1,21 +1,24 @@
use std::time::{SystemTime, UNIX_EPOCH};
use axum::{
Json,
body::{Body, to_bytes},
extract::{OriginalUri, Request, State},
http::HeaderValue,
http::{HeaderValue, Method, StatusCode},
middleware::Next,
response::Response,
response::{IntoResponse, Response},
};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
use deployment::Deployment;
use relay_client::RELAY_HEADER;
use relay_control::signing::{
NONCE_HEADER, REQUEST_SIGNATURE_HEADER, RESPONSE_NONCE_HEADER, RESPONSE_SIGNATURE_HEADER,
RESPONSE_TIMESTAMP_HEADER, RequestSignature, SIGNING_SESSION_HEADER, TIMESTAMP_HEADER,
build_response_signing_message,
RESPONSE_TIMESTAMP_HEADER, RelaySigningService, RequestSignature, SIGNING_SESSION_HEADER,
TIMESTAMP_HEADER, build_response_signing_message,
};
use relay_webrtc::WEBRTC_PEER_HEADER;
use url::form_urlencoded;
use utils::response::ApiResponse;
use uuid::Uuid;
use crate::{DeploymentImpl, error::ApiError};
@@ -27,15 +30,129 @@ pub type RelayRequestSignatureContext = RequestSignature;
/// into memory. This cap prevents a large payload from causing OOM.
const RELAY_SIGNED_BODY_MAX_BYTES: usize = 50 * 1024 * 1024;
pub async fn require_relay_request_signature(
/// How a relayed request to an `/api` route is handled. Paths are the ones the
/// `/api` router matches on, so without the `/api` prefix.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelayRoutePolicy {
/// Must work before a device is paired. Passed through without a
/// signature, and the response is not signed.
Unsigned,
/// Requires a valid signature from a paired device; the response is signed.
Signed,
/// Requires a valid signature, then is refused with 404: only the local
/// machine may use it. Also refused for requests from a WebRTC peer.
LocalOnly,
}
/// Routes a relayed request may reach without a signature. Each one does its
/// own authentication: the SPAKE2 steps need the one-time enrollment code, and
/// the refresh verifies an Ed25519 signature from a trusted client.
///
/// Matching is exact on the raw path. A trailing slash, a doubled slash or a
/// percent-encoded variant is not on this list, so it falls back to `Signed`.
const UNSIGNED_RELAY_ROUTES: &[(Method, &str)] = &[
(Method::POST, "/relay-auth/server/spake2/start"),
(Method::POST, "/relay-auth/server/spake2/finish"),
(Method::POST, "/relay-auth/server/signing-session/refresh"),
];
/// Decide how a relayed request is handled. Anything not listed is `Signed`.
pub fn relay_route_policy(method: &Method, path: &str) -> RelayRoutePolicy {
if UNSIGNED_RELAY_ROUTES
.iter()
.any(|(allowed_method, allowed_path)| allowed_method == method && *allowed_path == path)
{
return RelayRoutePolicy::Unsigned;
}
if is_local_only_path(path) {
return RelayRoutePolicy::LocalOnly;
}
RelayRoutePolicy::Signed
}
/// Routes only this machine may use: managing this host's paired devices and
/// the enrollment code, pairing this machine with other hosts, and anything
/// that contacts another host with this host's keys (`/host/*`,
/// `/open-remote-editor/*`, which also opens an editor here).
///
/// The frontend's `LOCAL_ONLY_API_PREFIXES` (`localApiTransport.ts`) lists the
/// routes it never sends to another host. Every route there is either listed
/// here or is one of the pairing routes in `UNSIGNED_RELAY_ROUTES`; keep the
/// two in step.
fn is_local_only_path(path: &str) -> bool {
path == "/relay-auth/server/enrollment-code"
|| path == "/relay-auth/server/clients"
|| path.starts_with("/relay-auth/server/clients/")
|| path.starts_with("/relay-auth/client/")
|| path.starts_with("/host/")
|| path.starts_with("/open-remote-editor/")
}
/// Guard for every `/api` route. Relayed requests are handled by
/// [`relay_route_policy`], so a new route requires a signature by default.
/// Requests from a WebRTC peer are refused on local-only routes. All other
/// requests pass through untouched.
pub async fn relay_request_guard(
State(deployment): State<DeploymentImpl>,
request: Request,
next: Next,
) -> Result<Response, ApiError> {
if !is_relay_request(&request) {
return Ok(next.run(request).await);
guard_relay_request(deployment.relay_signing(), request, next).await
}
pub(crate) async fn guard_relay_request(
signing: &RelaySigningService,
request: Request,
next: Next,
) -> Result<Response, ApiError> {
let policy = relay_route_policy(request.method(), request.uri().path());
if is_relay_request(&request) {
if policy == RelayRoutePolicy::Unsigned {
return Ok(next.run(request).await);
}
let (request, request_signature, path_and_query) =
verify_relay_request(signing, request).await?;
let response = if policy == RelayRoutePolicy::LocalOnly {
local_only_response()
} else {
next.run(request).await
};
return sign_response(signing, response, &request_signature, &path_and_query).await;
}
// A WebRTC data channel can only be opened by a paired device (the offer
// goes through `/webrtc/offer`, which needs a signature), so requests over
// it carry no signature of their own. They still come from another device.
if is_webrtc_peer_request(&request) && policy == RelayRoutePolicy::LocalOnly {
return Ok(local_only_response());
}
Ok(next.run(request).await)
}
/// 404 rather than 401/403: relay clients read those as an expired signing
/// session and re-handshake, and the remote web app's settings still request
/// `/relay-auth/client/hosts` from the host it is viewing.
fn local_only_response() -> Response {
(
StatusCode::NOT_FOUND,
Json(ApiResponse::<()>::error(
"This route is only available on the host machine.",
)),
)
.into_response()
}
async fn verify_relay_request(
signing: &RelaySigningService,
request: Request,
) -> Result<(Request, RequestSignature, String), ApiError> {
let (request_signature, path_and_query) = extract_request_signature(&request)?;
let (parts, body) = request.into_parts();
@@ -43,8 +160,7 @@ pub async fn require_relay_request_signature(
.await
.map_err(|_| ApiError::PayloadTooLarge)?;
if let Err(error) = deployment
.relay_signing()
if let Err(error) = signing
.verify_request(
&request_signature,
parts.method.as_str(),
@@ -63,23 +179,17 @@ pub async fn require_relay_request_signature(
}
let mut request = Request::from_parts(parts, Body::from(body_bytes));
request.extensions_mut().insert(request_signature);
request.extensions_mut().insert(request_signature.clone());
Ok(next.run(request).await)
Ok((request, request_signature, path_and_query))
}
pub async fn sign_relay_response(
State(deployment): State<DeploymentImpl>,
request: Request,
next: Next,
async fn sign_response(
signing: &RelaySigningService,
response: Response,
request_signature: &RequestSignature,
path_and_query: &str,
) -> Result<Response, ApiError> {
if !is_relay_request(&request) {
return Ok(next.run(request).await);
}
let (request_signature, path_and_query) = extract_request_signature(&request)?;
let response = next.run(request).await;
let (mut parts, body) = response.into_parts();
let body_bytes = to_bytes(body, RELAY_SIGNED_BODY_MAX_BYTES)
.await
@@ -91,14 +201,14 @@ pub async fn sign_relay_response(
let message = build_response_signing_message(
response_timestamp,
status,
&path_and_query,
path_and_query,
request_signature.signing_session_id,
request_signature.nonce,
response_nonce,
&body_bytes,
);
let signature = deployment.relay_signing().sign_bytes(message.as_bytes());
let signature = signing.sign_bytes(message.as_bytes());
let response_signature = BASE64_STANDARD.encode(signature.to_bytes());
insert_header(
@@ -291,6 +401,10 @@ fn unix_timestamp_now() -> Result<i64, ()> {
i64::try_from(duration.as_secs()).map_err(|_| ())
}
fn is_webrtc_peer_request(request: &Request) -> bool {
request.headers().contains_key(WEBRTC_PEER_HEADER)
}
fn is_relay_request(request: &Request) -> bool {
request
.headers()
@@ -298,3 +412,424 @@ fn is_relay_request(request: &Request) -> bool {
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value.trim() == "1")
}
#[cfg(test)]
mod tests {
use axum::{
Router,
body::{Body, to_bytes},
extract::{Request, State},
http::{Method, StatusCode},
middleware::{Next, from_fn_with_state},
response::Response,
routing::{get, post},
};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
use ed25519_dalek::{Signature, SigningKey, Verifier};
use relay_client::RELAY_HEADER;
use relay_control::signing::{
NONCE_HEADER, REQUEST_SIGNATURE_HEADER, RESPONSE_NONCE_HEADER, RESPONSE_SIGNATURE_HEADER,
RESPONSE_TIMESTAMP_HEADER, RelaySigningService, SIGNING_SESSION_HEADER, TIMESTAMP_HEADER,
build_response_signing_message,
};
use relay_webrtc::WEBRTC_PEER_HEADER;
use tower::ServiceExt;
use uuid::Uuid;
use super::{RelayRoutePolicy, guard_relay_request, relay_route_policy};
use crate::error::ApiError;
const HOST_ID: &str = "3f2b8c1e-7d4a-4f6b-9a1e-2c5d8e9f0a1b";
#[test]
fn pairing_routes_are_unsigned() {
for path in [
"/relay-auth/server/spake2/start",
"/relay-auth/server/spake2/finish",
"/relay-auth/server/signing-session/refresh",
] {
assert_eq!(
relay_route_policy(&Method::POST, path),
RelayRoutePolicy::Unsigned,
"{path}"
);
}
}
#[test]
fn other_routes_are_signed() {
for (method, path) in [
(Method::GET, "/health"),
(Method::GET, "/terminal/ws"),
(Method::POST, "/webrtc/offer"),
(Method::GET, "/does-not-exist"),
(Method::GET, "/"),
(Method::GET, ""),
] {
assert_eq!(
relay_route_policy(&method, path),
RelayRoutePolicy::Signed,
"{method} {path}"
);
}
}
#[test]
fn device_management_and_onward_proxying_are_local_only() {
let host_path = format!("/host/{HOST_ID}/api/health");
for (method, path) in [
(Method::GET, "/relay-auth/server/clients"),
(Method::DELETE, "/relay-auth/server/clients/abc"),
(Method::POST, "/relay-auth/server/enrollment-code"),
(Method::POST, "/relay-auth/client/pair"),
(Method::GET, "/relay-auth/client/hosts"),
(Method::DELETE, "/relay-auth/client/hosts/abc"),
(Method::POST, "/open-remote-editor/workspace"),
(Method::GET, host_path.as_str()),
(Method::POST, host_path.as_str()),
] {
assert_eq!(
relay_route_policy(&method, path),
RelayRoutePolicy::LocalOnly,
"{method} {path}"
);
}
}
#[test]
fn variants_of_pairing_routes_are_not_unsigned() {
for path in [
"/relay-auth/server/spake2/start/",
"//relay-auth/server/spake2/start",
"/relay-auth/server//spake2/start",
"/relay-auth/server/spake2%2Fstart",
"/relay-auth/server/spake2/%73tart",
"/relay-auth/server/SPAKE2/start",
"/relay-auth/server/spake2/start/../../clients",
"/api/relay-auth/server/spake2/start",
] {
assert_ne!(
relay_route_policy(&Method::POST, path),
RelayRoutePolicy::Unsigned,
"{path}"
);
}
}
#[test]
fn wrong_method_on_pairing_route_is_signed() {
for method in [Method::GET, Method::PUT, Method::DELETE, Method::HEAD] {
assert_eq!(
relay_route_policy(&method, "/relay-auth/server/spake2/start"),
RelayRoutePolicy::Signed,
"{method}"
);
}
}
struct TestPeer {
server: RelaySigningService,
client: RelaySigningService,
session_id: Uuid,
}
async fn paired_peer() -> TestPeer {
let server = RelaySigningService::new(SigningKey::from_bytes(&[1; 32]));
let client_key = SigningKey::from_bytes(&[2; 32]);
let session_id = server.create_session(client_key.verifying_key()).await;
TestPeer {
server,
client: RelaySigningService::new(client_key),
session_id,
}
}
async fn test_guard(
State(signing): State<RelaySigningService>,
request: Request,
next: Next,
) -> Result<Response, ApiError> {
guard_relay_request(&signing, request, next).await
}
fn app(signing: RelaySigningService) -> Router {
let api = Router::new()
.route("/health", get(|| async { "ok" }))
.route(
"/relay-auth/server/spake2/start",
post(|| async { "start" }),
)
.route("/relay-auth/server/clients", get(|| async { "clients" }))
.route("/relay-auth/client/hosts", get(|| async { "hosts" }))
.route("/host/{host_id}/{*tail}", get(|| async { "proxied" }))
.layer(from_fn_with_state(signing, test_guard));
Router::new().nest("/api", api)
}
fn request(method: Method, uri: &str, relayed: bool) -> Request {
let mut builder = Request::builder().method(method).uri(uri);
if relayed {
builder = builder.header(RELAY_HEADER, "1");
}
builder.body(Body::empty()).unwrap()
}
fn signed_request(peer: &TestPeer, method: Method, uri: &str) -> Request {
let signature = peer
.client
.sign_request(peer.session_id, method.as_str(), uri, &[]);
Request::builder()
.method(method)
.uri(uri)
.header(RELAY_HEADER, "1")
.header(
SIGNING_SESSION_HEADER,
signature.signing_session_id.to_string(),
)
.header(TIMESTAMP_HEADER, signature.timestamp.to_string())
.header(NONCE_HEADER, signature.nonce.to_string())
.header(REQUEST_SIGNATURE_HEADER, signature.signature_b64)
.body(Body::empty())
.unwrap()
}
async fn status(app: &Router, request: Request) -> StatusCode {
app.clone().oneshot(request).await.unwrap().status()
}
#[tokio::test]
async fn local_requests_pass_through_unchanged() {
let peer = paired_peer().await;
let app = app(peer.server.clone());
for uri in [
"/api/health",
"/api/relay-auth/server/clients",
"/api/relay-auth/client/hosts",
&format!("/api/host/{HOST_ID}/api/health"),
] {
let response = app
.clone()
.oneshot(request(Method::GET, uri, false))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK, "{uri}");
assert!(response.headers().get(RESPONSE_SIGNATURE_HEADER).is_none());
}
}
#[tokio::test]
async fn unsigned_relayed_requests_are_rejected() {
let peer = paired_peer().await;
let app = app(peer.server.clone());
for (method, uri) in [
(Method::GET, "/api/health".to_string()),
(Method::GET, "/api/relay-auth/server/clients".to_string()),
(Method::GET, format!("/api/host/{HOST_ID}/api/health")),
] {
assert_eq!(
status(&app, request(method.clone(), &uri, true)).await,
StatusCode::UNAUTHORIZED,
"{method} {uri}"
);
}
}
#[tokio::test]
async fn unmatched_relayed_paths_reach_no_handler() {
// axum answers unmatched paths with its own 404 before any layer runs.
let peer = paired_peer().await;
let app = app(peer.server.clone());
for uri in [
"/api/does-not-exist",
"/api/relay-auth/server/spake2/start/",
"/api/relay-auth/server/spake2%2Fstart",
"/api//relay-auth/server/spake2/start",
] {
assert_eq!(
status(&app, request(Method::POST, uri, true)).await,
StatusCode::NOT_FOUND,
"{uri}"
);
}
}
#[tokio::test]
async fn pairing_route_works_unsigned_over_relay() {
let peer = paired_peer().await;
let app = app(peer.server.clone());
let response = app
.oneshot(request(
Method::POST,
"/api/relay-auth/server/spake2/start",
true,
))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert!(response.headers().get(RESPONSE_SIGNATURE_HEADER).is_none());
}
#[tokio::test]
async fn signed_relayed_request_passes_and_response_is_signed() {
let peer = paired_peer().await;
let app = app(peer.server.clone());
let request = signed_request(&peer, Method::GET, "/api/health");
let request_nonce: Uuid = request.headers()[NONCE_HEADER]
.to_str()
.unwrap()
.parse()
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let header = |name: &str| response.headers()[name].to_str().unwrap().to_string();
let timestamp: i64 = header(RESPONSE_TIMESTAMP_HEADER).parse().unwrap();
let response_nonce: Uuid = header(RESPONSE_NONCE_HEADER).parse().unwrap();
let signature_bytes: [u8; 64] = BASE64_STANDARD
.decode(header(RESPONSE_SIGNATURE_HEADER))
.unwrap()
.try_into()
.unwrap();
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
assert_eq!(&body[..], b"ok");
let message = build_response_signing_message(
timestamp,
200,
"/api/health",
peer.session_id,
request_nonce,
response_nonce,
&body,
);
peer.server
.server_public_key()
.verify(message.as_bytes(), &Signature::from_bytes(&signature_bytes))
.expect("response signature verifies");
}
#[tokio::test]
async fn signature_in_query_is_accepted() {
// WebSocket upgrades carry the signature in the query string.
let peer = paired_peer().await;
let app = app(peer.server.clone());
let signature = peer
.client
.sign_request(peer.session_id, "GET", "/api/health?x=1", &[]);
let uri = format!(
"/api/health?x=1&{SIGNING_SESSION_HEADER}={}&{TIMESTAMP_HEADER}={}&{NONCE_HEADER}={}&{REQUEST_SIGNATURE_HEADER}={}",
signature.signing_session_id,
signature.timestamp,
signature.nonce,
url::form_urlencoded::byte_serialize(signature.signature_b64.as_bytes())
.collect::<String>(),
);
assert_eq!(
status(&app, request(Method::GET, &uri, true)).await,
StatusCode::OK
);
}
#[tokio::test]
async fn invalid_or_replayed_signatures_are_rejected() {
let peer = paired_peer().await;
let app = app(peer.server.clone());
// Signed for a different path.
let mut wrong_path = signed_request(&peer, Method::GET, "/api/other");
*wrong_path.uri_mut() = "/api/health".parse().unwrap();
assert_eq!(status(&app, wrong_path).await, StatusCode::UNAUTHORIZED);
// Unknown signing session.
let stranger = RelaySigningService::new(SigningKey::from_bytes(&[3; 32]));
let unknown = TestPeer {
server: peer.server.clone(),
client: stranger,
session_id: Uuid::new_v4(),
};
assert_eq!(
status(&app, signed_request(&unknown, Method::GET, "/api/health")).await,
StatusCode::UNAUTHORIZED
);
// Replay of a request that was accepted once.
let first = signed_request(&peer, Method::GET, "/api/health");
let mut replay = request(Method::GET, "/api/health", false);
*replay.headers_mut() = first.headers().clone();
assert_eq!(status(&app, first).await, StatusCode::OK);
assert_eq!(status(&app, replay).await, StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn local_only_routes_are_refused_even_when_signed() {
let peer = paired_peer().await;
let app = app(peer.server.clone());
for uri in [
"/api/relay-auth/server/clients".to_string(),
"/api/relay-auth/client/hosts".to_string(),
format!("/api/host/{HOST_ID}/api/health"),
] {
let response = app
.clone()
.oneshot(signed_request(&peer, Method::GET, &uri))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND, "{uri}");
assert!(response.headers().get(RESPONSE_SIGNATURE_HEADER).is_some());
}
}
fn webrtc_peer_request(uri: &str) -> Request {
Request::builder()
.method(Method::GET)
.uri(uri)
.header(WEBRTC_PEER_HEADER, "1")
.body(Body::empty())
.unwrap()
}
#[tokio::test]
async fn webrtc_peer_requests_skip_signatures_but_not_local_only_routes() {
let peer = paired_peer().await;
let app = app(peer.server.clone());
let response = app
.clone()
.oneshot(webrtc_peer_request("/api/health"))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert!(response.headers().get(RESPONSE_SIGNATURE_HEADER).is_none());
for uri in [
"/api/relay-auth/server/clients".to_string(),
"/api/relay-auth/client/hosts".to_string(),
format!("/api/host/{HOST_ID}/api/health"),
] {
assert_eq!(
status(&app, webrtc_peer_request(&uri)).await,
StatusCode::NOT_FOUND,
"{uri}"
);
}
}
#[tokio::test]
async fn relayed_and_webrtc_markers_together_still_need_a_signature() {
let peer = paired_peer().await;
let app = app(peer.server.clone());
let mut request = request(Method::GET, "/api/health", true);
request
.headers_mut()
.insert(WEBRTC_PEER_HEADER, "1".parse().unwrap());
assert_eq!(status(&app, request).await, StatusCode::UNAUTHORIZED);
}
}
+5 -13
View File
@@ -1,22 +1,14 @@
use axum::Router;
use crate::{DeploymentImpl, middleware};
use crate::DeploymentImpl;
mod open_remote_editor;
mod proxy;
pub use open_remote_editor::OpenRemoteWorkspaceInEditorRequest;
pub fn router(deployment: &DeploymentImpl) -> Router<DeploymentImpl> {
Router::new().merge(proxy::router()).merge(
open_remote_editor::router()
.layer(axum::middleware::from_fn_with_state(
deployment.clone(),
middleware::sign_relay_response,
))
.layer(axum::middleware::from_fn_with_state(
deployment.clone(),
middleware::require_relay_request_signature,
)),
)
pub fn router() -> Router<DeploymentImpl> {
Router::new()
.merge(proxy::router())
.merge(open_remote_editor::router())
}
+9 -14
View File
@@ -35,7 +35,7 @@ pub mod webrtc;
pub mod workspaces;
pub fn router(deployment: DeploymentImpl) -> IntoMakeService<Router> {
let relay_signed_routes = Router::new()
let api_routes = Router::new()
.route("/health", get(health::health_check))
.merge(config::router())
.merge(acp_registry::router())
@@ -59,20 +59,15 @@ pub fn router(deployment: DeploymentImpl) -> IntoMakeService<Router> {
.nest("/remote", remote::router())
.merge(webrtc::router())
.nest("/attachments", attachments::routes())
.layer(axum::middleware::from_fn_with_state(
deployment.clone(),
middleware::sign_relay_response,
))
.layer(axum::middleware::from_fn_with_state(
deployment.clone(),
middleware::require_relay_request_signature,
))
.with_state(deployment.clone());
let api_routes = Router::new()
.merge(relay_auth::router())
.merge(host_relay::router(&deployment))
.merge(relay_signed_routes)
.merge(host_relay::router())
// Relayed requests need a valid signature on every `/api` route,
// except the few that pairing needs (see
// `middleware::relay_route_policy`).
.layer(axum::middleware::from_fn_with_state(
deployment.clone(),
middleware::relay_request_guard,
))
.layer(ValidateRequestHeaderLayer::custom(
middleware::validate_origin,
))
+57
View File
@@ -40,9 +40,26 @@ type UpstreamWebSocket =
pub async fn connect_upstream_ws(
ws_url: String,
protocols: Option<&str>,
) -> Result<(UpstreamWebSocket, Option<String>), UpstreamWsConnectError> {
connect_upstream_ws_with_headers(ws_url, protocols, &[]).await
}
/// Like [`connect_upstream_ws`], adding `headers` to the upgrade request.
/// Header names must be lowercase.
pub async fn connect_upstream_ws_with_headers(
ws_url: String,
protocols: Option<&str>,
headers: &[(&'static str, &'static str)],
) -> Result<(UpstreamWebSocket, Option<String>), UpstreamWsConnectError> {
let mut ws_request = ws_url.into_client_request()?;
for (name, value) in headers {
ws_request.headers_mut().insert(
http::HeaderName::from_static(name),
http::HeaderValue::from_static(value),
);
}
if let Some(protocols) = protocols
&& !protocols.trim().is_empty()
{
@@ -145,3 +162,43 @@ where
{
ws_copy_bidirectional(a, b, std::convert::identity, std::convert::identity).await
}
#[cfg(test)]
mod tests {
use tokio::net::TcpListener;
use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
use super::connect_upstream_ws_with_headers;
#[tokio::test]
#[allow(clippy::result_large_err)] // tungstenite's handshake callback signature
async fn extra_headers_reach_the_upstream_handshake() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let mut seen = None;
let _ws =
tokio_tungstenite::accept_hdr_async(stream, |req: &Request, res: Response| {
seen = req
.headers()
.get("x-test-marker")
.map(|v| v.to_str().unwrap().to_string());
Ok(res)
})
.await
.unwrap();
seen
});
let _upstream = connect_upstream_ws_with_headers(
format!("ws://{addr}/socket"),
None,
&[("x-test-marker", "1")],
)
.await
.unwrap();
assert_eq!(server.await.unwrap().as_deref(), Some("1"));
}
}
+1 -1
View File
@@ -3,7 +3,7 @@ mod ws_io;
pub use bridge::{
UpstreamWsConnectError, WsBridgeError, bridge_axum_ws, bridge_tungstenite_ws,
connect_upstream_ws,
connect_upstream_ws, connect_upstream_ws_with_headers,
};
pub use ws_io::{
AxumWsStreamIo, TungsteniteWsStreamIo, axum_ws_stream_io, tungstenite_ws_stream_io,
@@ -25,6 +25,10 @@ export interface LocalApiTransport {
) => Promise<WebSocket> | WebSocket;
}
// Routes that are never sent to another host. The server refuses these over
// relay and WebRTC (`is_local_only_path` in
// crates/server/src/middleware/relay_request_signature.rs), apart from the
// pairing routes under /api/relay-auth/server/; keep the two in step.
const LOCAL_ONLY_API_PREFIXES = [
'/api/open-remote-editor/',
'/api/relay-auth/server/',