Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/bin/relay/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ relay.with_web(web).run().await?;
- `run` consumes the relay, so clone the handles your tasks need first.
- Build on `web().routes()`: `with_web` replaces the router, so `Router::new()`
drops the built-in routes.
- A route reads the connection's peer address with axum's
`ConnectInfo<SocketAddr>` extractor. It is the accepted socket, never a
forwarding header, so behind a proxy it is the proxy.
- `run` drains on SIGTERM or SIGINT from the moment it serves. Before that they
keep their default action, and still do after a startup error. With ACME, they
are caught from the first issuance on instead, which they end, so a container
Expand Down
8 changes: 4 additions & 4 deletions rs/moq-relay/src/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,11 @@ impl Address for Peer {
type Listener = Listener;
}

/// Lets a handler extract the peer address as `ConnectInfo<Peer>`, so the auth
/// request can report where a WebSocket or HTTP session came from.
impl axum::extract::connect_info::Connected<Peer> for Peer {
/// Expose the accepted socket through Axum's standard extractor, including to
/// routes supplied by an embedder.
impl axum::extract::connect_info::Connected<Peer> for SocketAddr {
fn connect_info(target: Peer) -> Self {
target
target.0
}
}

Expand Down
61 changes: 50 additions & 11 deletions rs/moq-relay/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,7 @@ impl Web {
/// reload. The caller builds `app` from [`routes`](Self::routes) plus any
/// extra routes it merged in. An embedder driving a [`crate::Relay`]
/// passes that router to [`crate::Relay::with_web`] instead of calling this.
/// Every route can extract the accepted peer as `ConnectInfo<SocketAddr>`.
Comment thread
kixelated marked this conversation as resolved.
Resolved
pub async fn serve(self, app: Router) -> anyhow::Result<()> {
let Web {
state,
Expand All @@ -422,7 +423,7 @@ impl Web {
let app = app
.fallback(serve_landing)
.layer(axum::middleware::from_fn(get_cors))
.into_make_service_with_connect_info::<crate::listener::Peer>();
.into_make_service_with_connect_info::<net::SocketAddr>();
let ws = config.resolved_ws();

let http = if let Some(listener) = http_listener {
Expand Down Expand Up @@ -970,7 +971,7 @@ async fn admit_http(
query: AuthQuery,
uri: &http::Uri,
headers: &http::HeaderMap,
remote: crate::listener::Peer,
remote: net::SocketAddr,
mtls: Option<Extension<MtlsPeer>>,
) -> axum::response::Result<(auth::Lease, moq_net::origin::Consumer)> {
// The public request API represents a missing or root path as empty; the
Expand All @@ -983,7 +984,7 @@ async fn admit_http(
.map(str::to_owned)
.or_else(|| query.jwt.map(|jwt| format!("jwt={jwt}")));
request.server_name = request_host(uri, headers);
request.remote = Some(remote.0);
request.remote = Some(remote);
request.tls = mtls.and_then(|Extension(MtlsPeer(identity))| auth::peer(&identity));
// The listener's timeout bounds admission as it bounds the request headers. An
// HTTP read has no handshake deadline to inherit, so the bound starts here.
Expand Down Expand Up @@ -1012,7 +1013,7 @@ async fn serve_announced(
path: Option<Path<String>>,
Query(query): Query<AuthQuery>,
mtls: Option<Extension<MtlsPeer>>,
ConnectInfo(remote): ConnectInfo<crate::listener::Peer>,
ConnectInfo(remote): ConnectInfo<net::SocketAddr>,
uri: http::Uri,
headers: http::HeaderMap,
State(state): State<Arc<WebState>>,
Expand Down Expand Up @@ -1050,7 +1051,7 @@ async fn serve_fetch(
Path(path): Path<String>,
Query(params): Query<FetchParams>,
mtls: Option<Extension<MtlsPeer>>,
ConnectInfo(remote): ConnectInfo<crate::listener::Peer>,
ConnectInfo(remote): ConnectInfo<net::SocketAddr>,
uri: http::Uri,
headers: http::HeaderMap,
State(state): State<Arc<WebState>>,
Expand Down Expand Up @@ -1206,7 +1207,7 @@ mod tests {
let cluster = cluster::Cluster::new(crate::cluster::Options::default()).unwrap();
let web = Web::new(auth, cluster, certificates.clone(), Config::default());
let state = web.state;
let remote = ConnectInfo(crate::listener::Peer("127.0.0.1:1234".parse().unwrap()));
let remote = ConnectInfo("127.0.0.1:1234".parse().unwrap());
let status = if fetch {
serve_fetch(
Path("room/video".to_owned()),
Expand Down Expand Up @@ -1281,7 +1282,7 @@ mod tests {
group: FetchGroup::Latest,
}),
None,
ConnectInfo(crate::listener::Peer("127.0.0.1:1234".parse().unwrap())),
ConnectInfo("127.0.0.1:1234".parse().unwrap()),
"/fetch/room/video".parse().unwrap(),
http::HeaderMap::new(),
State(state.clone()),
Expand All @@ -1292,7 +1293,7 @@ mod tests {
Some(Path("room".to_owned())),
Query(AuthQuery { jwt: None }),
None,
ConnectInfo(crate::listener::Peer("127.0.0.1:1234".parse().unwrap())),
ConnectInfo("127.0.0.1:1234".parse().unwrap()),
"/announced/room".parse().unwrap(),
http::HeaderMap::new(),
State(state.clone()),
Expand Down Expand Up @@ -1363,7 +1364,7 @@ mod tests {
group: selector,
}),
None,
ConnectInfo(crate::listener::Peer("127.0.0.1:1234".parse().unwrap())),
ConnectInfo("127.0.0.1:1234".parse().unwrap()),
format!("/fetch/room/video?tier={tier}").parse().unwrap(),
http::HeaderMap::new(),
State(state.clone()),
Expand All @@ -1379,7 +1380,7 @@ mod tests {
Some(Path("room".into())),
Query(AuthQuery { jwt: None }),
None,
ConnectInfo(crate::listener::Peer("127.0.0.1:1234".parse().unwrap())),
ConnectInfo("127.0.0.1:1234".parse().unwrap()),
format!("/announced/room?tier={tier}").parse().unwrap(),
http::HeaderMap::new(),
State(state.clone()),
Expand Down Expand Up @@ -1452,7 +1453,7 @@ mod tests {
let mut cluster = cluster::Cluster::new(crate::cluster::Options::default()).unwrap();
cluster.stats = moq_net::stats::Registry::new(Default::default());
let state = Web::new(auth, cluster, certificates, Config::default()).state;
let peer = || ConnectInfo(crate::listener::Peer("127.0.0.1:1234".parse().unwrap()));
let peer = || ConnectInfo("127.0.0.1:1234".parse().unwrap());
let fetched = serve_fetch(
Path("room/video".into()),
Query(FetchParams {
Expand Down Expand Up @@ -1857,6 +1858,44 @@ mod tests {
serving.abort();
}

/// An embedded route can read the accepted address with Axum's standard
/// extractor, regardless of client-supplied proxy headers.
#[tokio::test]
async fn embedded_routes_receive_the_socket_address() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let dir = TempDir::new().unwrap();
let (_, cert, _) = make_certs(&dir);
let mut config = Config::default();
config.http.listen = Some("127.0.0.1:0".parse().unwrap());
let auth = crate::auth::Config {
public_subscribe: vec![moq_auth::Pattern::all()],
..Default::default()
}
.init("test", &moq_tokio::tls::Connect::default(), false)
.unwrap();
let cluster = cluster::Cluster::new(crate::cluster::Options::default()).unwrap();
let certificates = moq_tokio::tls::Certificates::from_pem(&std::fs::read(&cert).unwrap()).unwrap();
let web = Web::new(auth, cluster, certificates, config).bind().unwrap();
let http = web.addrs().http.unwrap();
let app = Router::new().route(
"/remote",
get(|ConnectInfo(remote): ConnectInfo<net::SocketAddr>| async move { remote.to_string() }),
);
let serving = tokio::spawn(web.serve(app));
let mut tcp = tokio::net::TcpStream::connect(http).await.unwrap();
let expected = tcp.local_addr().unwrap().to_string();
tcp.write_all(
b"GET /remote HTTP/1.1\r\nHost: localhost\r\nX-Forwarded-For: 192.0.2.1\r\nConnection: close\r\n\r\n",
)
.await
.unwrap();
let mut response = String::new();
tcp.read_to_string(&mut response).await.unwrap();
assert_eq!(response.split("\r\n\r\n").nth(1), Some(expected.as_str()), "{response}");
serving.abort();
let _ = serving.await;
}

/// HTTPS settings without the HTTPS listener that would read them are refused,
/// not ignored.
#[tokio::test]
Expand Down
4 changes: 2 additions & 2 deletions rs/moq-relay/src/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub(crate) async fn serve_ws(
OriginalUri(uri): OriginalUri,
headers: HeaderMap,
mtls: Option<Extension<MtlsPeer>>,
ConnectInfo(remote): ConnectInfo<crate::listener::Peer>,
ConnectInfo(remote): ConnectInfo<std::net::SocketAddr>,
socket_stats: Option<Extension<crate::web::SocketStats>>,
admission: Option<Extension<crate::listener::Admission>>,
Extension(versions): Extension<moq_net::Versions>,
Expand Down Expand Up @@ -59,7 +59,7 @@ pub(crate) async fn serve_ws(
.with_versions(versions)
.with_extensions(extensions);
let mut options = moq_tokio::websocket::Options::new(url, server, active);
options.link.remote = Some(remote.0);
options.link.remote = Some(remote);
options.link.alpn = ws.selected_protocol().and_then(|p| p.to_str().ok()).map(str::to_owned);
options.identity = mtls.map(|Extension(MtlsPeer(identity))| identity);
options.socket_stats = socket_stats.map(|Extension(stats)| stats.0);
Expand Down
Loading