diff --git a/iroh-relay/src/main.rs b/iroh-relay/src/main.rs index 387eea94ba..675b40274a 100644 --- a/iroh-relay/src/main.rs +++ b/iroh-relay/src/main.rs @@ -18,12 +18,11 @@ use iroh_relay::{ DEFAULT_HTTP_PORT, DEFAULT_HTTPS_PORT, DEFAULT_METRICS_PORT, DEFAULT_RELAY_QUIC_PORT, }, server::{ - self as relay, AcmeConfig, ClientRateLimit, DEFAULT_CERT_RELOAD_INTERVAL, QuicConfig, - reloading_resolver, + self as relay, Access, AccessControl, AcmeConfig, ClientRateLimit, ClientRequest, + DEFAULT_CERT_RELOAD_INTERVAL, QuicConfig, reloading_resolver, }, }; use n0_error::{Result, StdResultExt, bail_any}; -use n0_future::FutureExt; use serde::{Deserialize, Serialize}; use tracing::{debug, warn}; use tracing_subscriber::{EnvFilter, prelude::*}; @@ -182,40 +181,12 @@ struct HttpAccessConfig { bearer_token: Option, } -impl From for iroh_relay::server::AccessConfig { +impl From for Arc { fn from(cfg: AccessConfig) -> Self { match cfg { - AccessConfig::Everyone => iroh_relay::server::AccessConfig::Everyone, - AccessConfig::Allowlist(allow_list) => { - let allow_list = Arc::new(allow_list); - iroh_relay::server::AccessConfig::Restricted(Box::new(move |request| { - let allow_list = allow_list.clone(); - let endpoint_id = request.endpoint_id(); - async move { - if allow_list.contains(&endpoint_id) { - iroh_relay::server::Access::Allow - } else { - iroh_relay::server::Access::Deny - } - } - .boxed() - })) - } - AccessConfig::Denylist(deny_list) => { - let deny_list = Arc::new(deny_list); - iroh_relay::server::AccessConfig::Restricted(Box::new(move |request| { - let deny_list = deny_list.clone(); - let endpoint_id = request.endpoint_id(); - async move { - if deny_list.contains(&endpoint_id) { - iroh_relay::server::Access::Deny - } else { - iroh_relay::server::Access::Allow - } - } - .boxed() - })) - } + AccessConfig::Everyone => Arc::new(iroh_relay::server::AllowAll), + AccessConfig::Allowlist(allow_list) => Arc::new(AllowlistAccess(allow_list)), + AccessConfig::Denylist(deny_list) => Arc::new(DenylistAccess(deny_list)), AccessConfig::Http(mut config) => { let client = reqwest::Client::builder() .use_rustls_tls() @@ -225,35 +196,61 @@ impl From for iroh_relay::server::AccessConfig { if let Ok(token) = std::env::var(ENV_HTTP_BEARER_TOKEN) { config.bearer_token = Some(token); } - let config = Arc::new(config); - iroh_relay::server::AccessConfig::Restricted(Box::new(move |request| { - let client = client.clone(); - let config = config.clone(); - let endpoint_id = request.endpoint_id(); - async move { http_access_check(&client, &config, endpoint_id).await }.boxed() - })) + Arc::new(HttpAccess { client, config }) } } } } -#[tracing::instrument("http-access-check", skip_all, fields(endpoint_id=%endpoint_id.fmt_short()))] -async fn http_access_check( - client: &reqwest::Client, - config: &HttpAccessConfig, - endpoint_id: EndpointId, -) -> iroh_relay::server::Access { - use iroh_relay::server::Access; - debug!(url=%config.url, "Check relay access via HTTP POST"); +/// An [`AccessControl`] admitting only an allowlist of endpoints. +#[derive(Debug)] +struct AllowlistAccess(Vec); - match http_access_check_inner(client, config, endpoint_id).await { - Ok(()) => { - debug!("HTTP access check OK: Allow access"); +impl AccessControl for AllowlistAccess { + async fn on_connect(&self, request: &ClientRequest) -> Access { + if self.0.contains(&request.endpoint_id()) { + Access::Allow + } else { + Access::Deny { reason: None } + } + } +} + +/// An [`AccessControl`] admitting everyone except a denylist of endpoints. +#[derive(Debug)] +struct DenylistAccess(Vec); + +impl AccessControl for DenylistAccess { + async fn on_connect(&self, request: &ClientRequest) -> Access { + if self.0.contains(&request.endpoint_id()) { + Access::Deny { reason: None } + } else { Access::Allow } - Err(err) => { - debug!("HTTP access check failed: Deny access (reason: {err:#})"); - Access::Deny + } +} + +/// An [`AccessControl`] that delegates the decision to an HTTP endpoint. +#[derive(Debug)] +struct HttpAccess { + client: reqwest::Client, + config: HttpAccessConfig, +} + +impl AccessControl for HttpAccess { + #[tracing::instrument("http-access-check", skip_all, fields(endpoint_id=%request.endpoint_id().fmt_short()))] + async fn on_connect(&self, request: &ClientRequest) -> Access { + debug!(url=%self.config.url, "Check relay access via HTTP POST"); + + match http_access_check_inner(&self.client, &self.config, request.endpoint_id()).await { + Ok(()) => { + debug!("HTTP access check OK: Allow access"); + Access::Allow + } + Err(err) => { + debug!("HTTP access check failed: Deny access (reason: {err:#})"); + Access::Deny { reason: None } + } } } } diff --git a/iroh-relay/src/protos/handshake.rs b/iroh-relay/src/protos/handshake.rs index 027c1f59e1..f7a254ec9b 100644 --- a/iroh-relay/src/protos/handshake.rs +++ b/iroh-relay/src/protos/handshake.rs @@ -24,6 +24,9 @@ //! //! [Concealed HTTP Auth RFC]: https://datatracker.ietf.org/doc/rfc9729/ //! [RFC 5705]: https://datatracker.ietf.org/doc/html/rfc5705 +#[cfg(feature = "server")] +use std::sync::Arc; + use bytes::{BufMut, Bytes, BytesMut}; use data_encoding::BASE32HEX_NOPAD as HEX; #[cfg(not(wasm_browser))] @@ -42,6 +45,8 @@ use super::{ streams::BytesStreamSink, }; use crate::ExportKeyingMaterial; +#[cfg(feature = "server")] +use crate::server::{Access, ClientRequest, DynAccessControl, OnDisconnectGuard}; /// Domain separation string for the [`ServerChallenge`] signature const DOMAIN_SEP_CHALLENGE: &str = "iroh-relay handshake v1 challenge signature"; @@ -474,6 +479,32 @@ pub async fn serverside( #[cfg(feature = "server")] impl SuccessfulAuthentication { + /// Authorizes a [`ClientRequest`] and completes the authorization protocol. + /// + /// This invokes [`AccessControl::on_connect`] with the [`ClientRequest`] and informs the client about the + /// authorization decision. + /// + /// Returns [`OnDisconnectGuard`] in case the authorization was successful and the confirmation + /// message was sent to the client. The handshake protocol is now complete. + /// + /// Returns an error if the authorization failed or if the confirmation message could not be sent. + /// + /// [`AccessControl::on_connect`]: crate::server::AccessControl::on_connect + pub async fn authorize_with( + self, + request: &ClientRequest, + access_control: &Arc, + io: &mut (impl BytesStreamSink + ExportKeyingMaterial), + ) -> Result { + match access_control.on_connect(request).await { + Access::Allow => { + let guard = OnDisconnectGuard::for_access_control(access_control.clone(), request); + self.accept(io).await?; + Ok(guard) + } + Access::Deny { reason } => Err(self.deny(reason, io).await), + } + } /// Completes the authorization protocol by notifying the client of success or failure. /// /// After a client has been successfully authenticated via [`serverside`], the server must @@ -481,7 +512,7 @@ impl SuccessfulAuthentication { /// the authorization decision to the client and completes the handshake protocol. /// /// # Arguments - /// * `is_authorized` - Whether to grant access to the authenticated client + /// * `access` - Whether to grant access to the authenticated client /// * `io` - The WebSocket stream to send the authorization response on /// /// # Returns @@ -489,22 +520,37 @@ impl SuccessfulAuthentication { /// * `Err(Error)` - If authorization was denied or communication failed pub async fn authorize_if( self, - is_authorized: bool, + access: Access, io: &mut (impl BytesStreamSink + ExportKeyingMaterial), ) -> Result { - if is_authorized { - trace!("authorizing client"); - write_frame(io, ServerConfirmsAuth).await?; - Ok(self.client_key) - } else { - trace!("denying client auth"); - let denial = ServerDeniesAuth { - reason: "not authorized".into(), - }; - write_frame(io, denial.clone()).await?; - Err(e!(Error::ServerDeniedAuth { + match access { + Access::Allow => self.accept(io).await, + Access::Deny { reason } => Err(self.deny(reason, io).await), + } + } + + async fn accept( + self, + io: &mut (impl BytesStreamSink + ExportKeyingMaterial), + ) -> Result { + trace!("authorizing client"); + write_frame(io, ServerConfirmsAuth).await?; + Ok(self.client_key) + } + + async fn deny( + self, + reason: Option, + io: &mut (impl BytesStreamSink + ExportKeyingMaterial), + ) -> Error { + trace!("denying client auth"); + let reason = reason.unwrap_or_else(|| "not authorized".into()); + let denial = ServerDeniesAuth { reason }; + match write_frame(io, denial.clone()).await { + Err(err) => err, + Ok(()) => e!(Error::ServerDeniedAuth { reason: denial.reason - })) + }), } } } @@ -575,7 +621,7 @@ mod tests { use super::{ ClientAuth, KeyMaterialClientAuth, Mechanism, ServerChallenge, ServerConfirmsAuth, }; - use crate::ExportKeyingMaterial; + use crate::{ExportKeyingMaterial, server::Access}; struct TestKeyingMaterial { shared_secret: Option, @@ -688,7 +734,10 @@ mod tests { .await .context("serverside")?; let mechanism = auth_n.mechanism; - let is_authorized = restricted_to.is_none_or(|key| key == auth_n.client_key); + let is_authorized = match restricted_to.is_none_or(|key| key == auth_n.client_key) { + true => Access::Allow, + false => Access::Deny { reason: None }, + }; let key = auth_n.authorize_if(is_authorized, &mut server_io).await?; Ok((key, mechanism)) } diff --git a/iroh-relay/src/server.rs b/iroh-relay/src/server.rs index 581cea6bef..c50251e30e 100644 --- a/iroh-relay/src/server.rs +++ b/iroh-relay/src/server.rs @@ -16,8 +16,16 @@ //! - HTTPS `/generate_204`: Used for net_report probes. use std::{ - borrow::Cow, future::Future, net::SocketAddr, num::NonZeroU32, path::PathBuf, pin::Pin, - sync::Arc, + borrow::Cow, + future::Future, + net::SocketAddr, + num::NonZeroU32, + path::PathBuf, + pin::Pin, + sync::{ + Arc, + atomic::{AtomicU64, Ordering}, + }, }; use derive_more::Debug; @@ -48,7 +56,7 @@ use tracing::{Instrument, debug, error, info, info_span, instrument}; use self::http_server::{BytesBody, HyperError, HyperResult}; use crate::{ defaults::DEFAULT_KEY_CACHE_CAPACITY, - http::{AUTH_TOKEN_URL_QUERY_PARAM, RELAY_PROBE_PATH}, + http::{AUTH_TOKEN_URL_QUERY_PARAM, ProtocolVersion, RELAY_PROBE_PATH}, quic::server::{QuicServer, QuicSpawnError, ServerHandle as QuicServerHandle}, }; @@ -133,34 +141,54 @@ pub struct RelayConfig { pub limits: Limits, /// Key cache capacity. pub key_cache_capacity: Option, - /// Access configuration. - pub access: AccessConfig, + /// Access control for incoming connections. + pub access: Arc, } impl RelayConfig { /// Creates a new [`RelayConfig`] bound to `http_bind_addr` with default settings. /// /// TLS is disabled, default [`Limits`] are used, the key cache capacity is unset, and - /// access defaults to [`AccessConfig::Everyone`]. Adjust any of these by assigning to - /// the corresponding fields after construction. + /// access defaults to [`AllowAll`]. Adjust any of these by assigning to the + /// corresponding fields after construction. pub fn new(http_bind_addr: impl Into) -> Self { Self { http_bind_addr: http_bind_addr.into(), tls: None, limits: Limits::default(), key_cache_capacity: None, - access: AccessConfig::Everyone, + access: Arc::new(AllowAll), } } } +/// A process-unique identifier for a single relay client connection. +/// +/// A new id is assigned to every incoming connection when its [`ClientRequest`] +/// is created, before the access check runs. The same id is passed to +/// [`AccessControl::on_connect`] and [`AccessControl::on_disconnect`], so an +/// implementation can match the two callbacks even when one endpoint holds +/// several concurrent connections. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, derive_more::Display)] +#[display("{_0}")] +pub struct ConnectionId(u64); + +impl ConnectionId { + /// Returns a fresh, process-unique connection id. + fn next() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + Self(NEXT.fetch_add(1, Ordering::Relaxed)) + } +} + /// Details about an incoming relay client connection. /// -/// Passed to the [`AccessConfig::Restricted`] callback to decide whether to -/// admit the endpoint. +/// Passed to [`AccessControl::on_connect`] to decide whether to admit the connection. #[derive(Debug, Clone)] pub struct ClientRequest { + connection_id: ConnectionId, endpoint_id: EndpointId, + protocol_version: ProtocolVersion, request: http::request::Parts, } @@ -168,14 +196,30 @@ impl ClientRequest { /// Creates a new [`ClientRequest`] from an [`EndpointId`] and HTTP request parts. /// /// The [`EndpointId`] must be proven by the relay handshake. The request parts - /// come from the client's WebSocket request. - pub fn new(endpoint_id: EndpointId, request: http::request::Parts) -> Self { + /// come from the client's WebSocket request. A fresh [`ConnectionId`] is assigned. + pub fn new( + endpoint_id: EndpointId, + protocol_version: ProtocolVersion, + request: http::request::Parts, + ) -> Self { Self { + connection_id: ConnectionId::next(), endpoint_id, + protocol_version, request, } } + /// Returns the [`ConnectionId`] assigned to this connection. + pub fn connection_id(&self) -> ConnectionId { + self.connection_id + } + + /// Returns the [`ProtocolVersion`] negotiated for this connection. + pub fn protocol_version(&self) -> ProtocolVersion { + self.protocol_version + } + /// Returns the [`EndpointId`] of the client. /// /// The relay handshake authenticates this id before the access hook @@ -231,48 +275,152 @@ impl ClientRequest { } } -/// Access check callback used by [`AccessConfig::Restricted`]. +/// Controls which endpoints may use the relay and observes their lifecycle. /// -/// Returns [`Access::Allow`] to admit the endpoint or [`Access::Deny`] to -/// reject it. The returned future may borrow from the [`ClientRequest`]. -pub type AccessCheck = Box< - dyn for<'a> Fn(&'a ClientRequest) -> Pin + Send + 'a>> - + Send - + Sync - + 'static, ->; +/// Implement this trait to gate access to a relay server. +/// +/// Both callbacks carry the connection's [`ConnectionId`], so an implementation +/// can index connections precisely even when one endpoint holds several. +pub trait AccessControl: std::fmt::Debug + Send + Sync + 'static { + /// Decides whether a connecting client is admitted. + /// + /// Called once per incoming connection, before the connection is + /// registered. Returns [`Access::Allow`] to admit it or [`Access::Deny`] + /// to reject it. + /// + /// Can be implemented as `async fn on_connect(&self, request: &ClientRequest) -> Access`. + fn on_connect(&self, request: &ClientRequest) -> impl Future + Send; -/// Controls which endpoints are allowed to use the relay. -#[derive(derive_more::Debug)] -#[non_exhaustive] -pub enum AccessConfig { - /// Allows every endpoint. - Everyone, - /// Delegates the decision to a callback invoked for every connection. - #[debug("restricted")] - Restricted(AccessCheck), + /// Notifies that a connection has ended. + /// + /// Called once for every connection that [`Self::on_connect`] admitted, + /// identified by the same [`ConnectionId`]. + /// + /// Note that this is a sync method being called in an async context. Make sure that your + /// implementation does not block the runtime. + fn on_disconnect(&self, endpoint_id: EndpointId, connection_id: ConnectionId) { + let _ = (endpoint_id, connection_id); + } } -impl AccessConfig { - /// Returns whether the given client request should be admitted. - pub async fn is_allowed(&self, request: &ClientRequest) -> bool { - match self { - Self::Everyone => true, - Self::Restricted(check) => { - let res = check(request).await; - matches!(res, Access::Allow) - } - } +/// A dyn-compatible version of [`AccessControl`] that returns boxed futures. +/// +/// Any type that implements [`AccessControl`] automatically implements +/// `DynAccessControl`. Wrap it in an `Arc` to store it as an +/// `Arc`, for example in [`RelayConfig::access`]. +pub trait DynAccessControl: std::fmt::Debug + Send + Sync + 'static { + /// See [`AccessControl::on_connect`]. + fn on_connect<'a>( + &'a self, + request: &'a ClientRequest, + ) -> Pin + Send + 'a>>; + + /// See [`AccessControl::on_disconnect`]. + fn on_disconnect(&self, endpoint_id: EndpointId, connection_id: ConnectionId); +} + +impl DynAccessControl for T { + fn on_connect<'a>( + &'a self, + request: &'a ClientRequest, + ) -> Pin + Send + 'a>> { + Box::pin(::on_connect(self, request)) + } + + fn on_disconnect(&self, endpoint_id: EndpointId, connection_id: ConnectionId) { + ::on_disconnect(self, endpoint_id, connection_id) + } +} + +/// An [`AccessControl`] that admits every endpoint. +/// +/// This is the default used by [`RelayConfig::new`]. +#[derive(Debug, Clone, Copy)] +pub struct AllowAll; + +impl AccessControl for AllowAll { + async fn on_connect(&self, _request: &ClientRequest) -> Access { + Access::Allow } } /// Access restriction for an endpoint. -#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum Access { /// Access is allowed. Allow, /// Access is denied. - Deny, + Deny { + /// Optional reason for denial to send back to the client. + reason: Option, + }, +} + +/// Reports a connection's disconnect to [`AccessControl`] when dropped. +/// +/// A guard is created the moment [`AccessControl::on_connect`] admits a +/// connection, and is then held for the connection's entire lifetime. Dropping +/// it - whether the connection closed cleanly, hit an error, or setup returned +/// early - calls [`AccessControl::on_disconnect`] exactly once. +/// +/// Threading the guard through connection setup and into the connection actor +/// makes it impossible to admit a connection without eventually reporting its +/// disconnect, even as the surrounding code changes. +/// +/// Embedders that register connections through [`Clients::register`] construct +/// the guard themselves; see that method for the expected lifecycle. +/// +/// [`Clients::register`]: crate::server::clients::Clients::register +#[derive(Debug)] +pub struct OnDisconnectGuard { + access: Option>, + endpoint_id: EndpointId, + connection_id: ConnectionId, +} + +impl OnDisconnectGuard { + /// Creates a guard for the connection described by `request`. + /// + /// Dropping the guard calls [`AccessControl::on_disconnect`] on `access` + /// with the request's [`EndpointId`] and [`ConnectionId`]. Create it only + /// once [`AccessControl::on_connect`] has admitted the connection. + pub fn for_access_control(access: Arc, request: &ClientRequest) -> Self { + Self { + access: Some(access), + endpoint_id: request.endpoint_id(), + connection_id: request.connection_id(), + } + } + + /// Creates a no-op guard for `endpoint_id`. + /// + /// The guard carries `endpoint_id` and a fresh [`ConnectionId`] but has no + /// access control attached, so dropping it does nothing. + pub fn empty(endpoint_id: EndpointId) -> Self { + Self { + access: None, + endpoint_id, + connection_id: ConnectionId::next(), + } + } + + /// Returns the [`EndpointId`] of the guarded connection. + pub fn endpoint_id(&self) -> EndpointId { + self.endpoint_id + } + + /// Returns the [`ConnectionId`] of the guarded connection. + pub fn connection_id(&self) -> ConnectionId { + self.connection_id + } +} + +impl Drop for OnDisconnectGuard { + fn drop(&mut self) { + if let Some(access) = self.access.as_ref() { + access.on_disconnect(self.endpoint_id, self.connection_id); + } + } } /// Configuration for the QUIC server. @@ -461,6 +609,8 @@ pub struct Server { quic_addr: Option, /// Handle to the relay server. relay_handle: Option, + /// Handle to the relay service for runtime control. + relay_service: Option, /// Handle to the quic server. quic_handle: Option, /// The main task running the server. @@ -655,6 +805,7 @@ impl Server { // relay_server is serving HTTP, including the /generate_204 service. let relay_addr = relay_server.as_ref().map(|srv| srv.addr()); let relay_handle = relay_server.as_ref().map(|srv| srv.handle()); + let relay_service = relay_server.as_ref().map(|srv| srv.service().clone()); let quic_server = match config.quic { Some(quic_config) => { @@ -682,6 +833,7 @@ impl Server { https_addr: http_addr.and(relay_addr), quic_addr, relay_handle, + relay_service, quic_handle, supervisor: AbortOnDropHandle::new(task), metrics, @@ -761,6 +913,11 @@ impl Server { pub fn metrics(&self) -> &RelayMetrics { &self.metrics } + + /// Returns a handle to the embedded [`RelayService`] for runtime control. + pub fn relay_service(&self) -> Option<&RelayService> { + self.relay_service.as_ref() + } } /// Supervisor for the relay server tasks. @@ -1005,14 +1162,14 @@ mod tests { use iroh_base::{EndpointId, RelayUrl, SecretKey}; use iroh_dns::dns::DnsResolver; use n0_error::Result; - use n0_future::{FutureExt, SinkExt, StreamExt}; + use n0_future::{SinkExt, StreamExt}; use n0_tracing_test::traced_test; use rand::{RngExt, SeedableRng}; use tracing::{info, instrument}; use super::{ - Access, AccessConfig, NO_CONTENT_CHALLENGE_HEADER, NO_CONTENT_RESPONSE_HEADER, RelayConfig, - Server, ServerConfig, SpawnError, + Access, AccessControl, ClientRequest, NO_CONTENT_CHALLENGE_HEADER, + NO_CONTENT_RESPONSE_HEADER, RelayConfig, Server, ServerConfig, SpawnError, }; use crate::{ client::{ClientBuilder, ConnectError}, @@ -1023,15 +1180,21 @@ mod tests { tls::{CaRootsConfig, default_provider}, }; + /// An [`AccessControl`] backed by a closure, for tests. + #[derive(derive_more::Debug)] + struct TestAccess(#[debug("access fn")] Box Access + Send + Sync>); + + impl AccessControl for TestAccess { + async fn on_connect(&self, request: &ClientRequest) -> Access { + (self.0)(request) + } + } + async fn spawn_local_relay() -> std::result::Result { + let mut relay = RelayConfig::new((Ipv4Addr::LOCALHOST, 0)); + relay.key_cache_capacity = Some(1024); Server::spawn(ServerConfig { - relay: Some(RelayConfig { - http_bind_addr: (Ipv4Addr::LOCALHOST, 0).into(), - tls: None, - limits: Default::default(), - key_cache_capacity: Some(1024), - access: AccessConfig::Everyone, - }), + relay: Some(relay), quic: None, metrics_addr: None, }) @@ -1091,14 +1254,10 @@ mod tests { #[tokio::test] #[traced_test] async fn test_conflicting_bind() { + let mut relay = RelayConfig::new((Ipv4Addr::LOCALHOST, 1234)); + relay.key_cache_capacity = Some(1024); let res = Server::spawn(ServerConfig { - relay: Some(RelayConfig { - http_bind_addr: (Ipv4Addr::LOCALHOST, 1234).into(), - tls: None, - limits: Default::default(), - key_cache_capacity: Some(1024), - access: AccessConfig::Everyone, - }), + relay: Some(relay), quic: None, metrics_addr: Some((Ipv4Addr::LOCALHOST, 1234).into()), }) @@ -1227,26 +1386,20 @@ mod tests { let a_secret_key = SecretKey::from_bytes(&rng.random()); let a_key = a_secret_key.public(); + let mut relay = RelayConfig::new((Ipv4Addr::LOCALHOST, 0)); + relay.key_cache_capacity = Some(1024); + relay.access = Arc::new(TestAccess(Box::new(move |request| { + let endpoint_id = request.endpoint_id(); + info!("checking {}", endpoint_id); + // reject endpoint a + if endpoint_id == a_key { + Access::Deny { reason: None } + } else { + Access::Allow + } + }))); let server = Server::spawn(ServerConfig { - relay: Some(RelayConfig { - http_bind_addr: (Ipv4Addr::LOCALHOST, 0).into(), - tls: None, - limits: Default::default(), - key_cache_capacity: Some(1024), - access: AccessConfig::Restricted(Box::new(move |request| { - async move { - let endpoint_id = request.endpoint_id(); - info!("checking {}", endpoint_id); - // reject endpoint a - if endpoint_id == a_key { - Access::Deny - } else { - Access::Allow - } - } - .boxed() - })), - }), + relay: Some(relay), quic: None, metrics_addr: None, }) @@ -1307,7 +1460,7 @@ mod tests { } /// Verifies that [`ClientBuilder::auth_token`] forwards a token to the - /// relay so the [`AccessConfig::Restricted`] hook can read it via + /// relay so the [`AccessControl::on_connect`] hook can read it via /// [`ClientRequest::auth_token`]. #[tokio::test] #[traced_test] @@ -1319,23 +1472,17 @@ mod tests { .client_config(default_provider()) .unwrap(); + let mut relay = RelayConfig::new((Ipv4Addr::LOCALHOST, 0)); + relay.key_cache_capacity = Some(1024); + relay.access = Arc::new(TestAccess(Box::new(move |request| { + if request.auth_token().as_deref() == Some(TOKEN) { + Access::Allow + } else { + Access::Deny { reason: None } + } + }))); let server = Server::spawn(ServerConfig { - relay: Some(RelayConfig { - http_bind_addr: (Ipv4Addr::LOCALHOST, 0).into(), - tls: None, - limits: Default::default(), - key_cache_capacity: Some(1024), - access: AccessConfig::Restricted(Box::new(move |request| { - async move { - if request.auth_token().as_deref() == Some(TOKEN) { - Access::Allow - } else { - Access::Deny - } - } - .boxed() - })), - }), + relay: Some(relay), quic: None, metrics_addr: None, }) diff --git a/iroh-relay/src/server/client.rs b/iroh-relay/src/server/client.rs index fddd792353..aa0df70e4d 100644 --- a/iroh-relay/src/server/client.rs +++ b/iroh-relay/src/server/client.rs @@ -26,6 +26,7 @@ use crate::{ streams::BytesStreamSink, }, server::{ + ConnectionId, OnDisconnectGuard, clients::Clients, metrics::Metrics, streams::{RecvError as RelayRecvError, RelayedStream, SendError as RelaySendError}, @@ -47,8 +48,10 @@ pub(super) struct Packet { #[derive(Debug)] #[non_exhaustive] pub struct Config { - /// The endpoint ID of the client - pub endpoint_id: EndpointId, + /// Reports the disconnect once the connection ends. + /// + /// Also the owner of this connection's [`EndpointId`] and [`ConnectionId`]. + pub guard: OnDisconnectGuard, /// The relayed stream connection pub stream: RelayedStream, /// Write timeout for the client connection @@ -61,13 +64,15 @@ pub struct Config { impl Config { /// Creates a new config with sensible default values for `write_timeout` and `channel_capacity`. + /// + /// The endpoint and connection ids are taken from `guard`. pub fn new( - endpoint_id: EndpointId, + guard: OnDisconnectGuard, stream: RelayedStream, protocol_version: ProtocolVersion, ) -> Self { Self { - endpoint_id, + guard, stream, protocol_version, write_timeout: SERVER_WRITE_TIMEOUT, @@ -81,11 +86,11 @@ impl Config { /// [`Server`]: crate::server::Server /// [`Client`]: crate::client::Client #[derive(Debug)] -pub struct Client { +pub(super) struct Client { /// Identity of the connected peer. endpoint_id: EndpointId, /// Connection identifier. - connection_id: u64, + connection_id: ConnectionId, /// Used to close the connection loop. done: CancellationToken, /// Actor handle. @@ -101,23 +106,24 @@ pub struct Client { impl Client { /// Creates a client from a connection & starts a read and write loop to handle io to and from /// the client + /// + /// The `guard` is moved into the connection actor and reports the disconnect to access + /// control once the connection ends. + /// /// Call [`Client::shutdown`] to close the read and write loops before dropping the [`Client`] - pub(super) fn new( - config: Config, - connection_id: u64, - clients: &Clients, - metrics: Arc, - ) -> Client + pub(super) fn new(config: Config, clients: &Clients, metrics: Arc) -> Client where S: BytesStreamSink + Send + 'static, { let Config { - endpoint_id, + guard, stream, write_timeout, channel_capacity, protocol_version, } = config; + let endpoint_id = guard.endpoint_id; + let connection_id = guard.connection_id; let (packet_send_queue_s, packet_send_queue_r) = mpsc::channel(channel_capacity); let (message_send_queue_s, message_send_queue_r) = mpsc::channel(channel_capacity); @@ -128,8 +134,7 @@ impl Client { timeout: write_timeout, packet_send_queue: packet_send_queue_r, message_send_queue: message_send_queue_r, - endpoint_id, - connection_id, + guard, clients: clients.clone(), client_counter: ClientCounter::default(), ping_tracker: PingTracker::default(), @@ -141,7 +146,7 @@ impl Client { let handle = tokio::task::spawn(actor.run(io_done).instrument(tracing::info_span!( "client-connection-actor", remote_endpoint = %endpoint_id.fmt_short(), - connection_id = connection_id + connection_id = %connection_id ))); Client { @@ -155,7 +160,7 @@ impl Client { } } - pub(super) fn connection_id(&self) -> u64 { + pub(super) fn connection_id(&self) -> ConnectionId { self.connection_id } @@ -290,10 +295,10 @@ struct Actor { packet_send_queue: mpsc::Receiver, /// Receiver for non-packet messages to be sent to the client. message_send_queue: mpsc::Receiver, - /// [`EndpointId`] of this client - endpoint_id: EndpointId, - /// Connection identifier. - connection_id: u64, + /// Reports the disconnect to access control when dropped. + /// + /// Also the owner of this connection's [`EndpointId`] and [`ConnectionId`]. + guard: OnDisconnectGuard, /// Reference to the other connected clients. clients: Clients, /// Statistics about the connected clients @@ -311,7 +316,7 @@ where // connection is accepted long before this in the HTTP server, but it is clearer to // handle the metric here. self.metrics.accepts.inc(); - if self.client_counter.update(self.endpoint_id) { + if self.client_counter.update(self.guard.endpoint_id()) { self.metrics.unique_client_keys.inc(); } match self.run_inner(done).await { @@ -323,8 +328,7 @@ where } } - self.clients - .unregister(self.connection_id, self.endpoint_id, &self.metrics); + self.clients.unregister(self.guard, &self.metrics); self.metrics.disconnects.inc(); } @@ -366,7 +370,7 @@ where } // Last priority, sending other message message = self.message_send_queue.recv() => { - let message = message .ok_or_else(|| e!(RunError::HandleDropped))?; + let message = message.ok_or_else(|| e!(RunError::HandleDropped))?; trace!("send {message:?}"); self.write_frame(message) .await @@ -479,7 +483,7 @@ where ) -> Result<(), ForwardPacketError> { self.metrics.send_packets_recv.inc(); self.clients - .send_packet(dst, data, self.endpoint_id, &self.metrics)?; + .send_packet(dst, data, self.guard.endpoint_id(), &self.metrics)?; Ok(()) } @@ -594,8 +598,7 @@ mod tests { timeout: Duration::from_secs(1), packet_send_queue: send_queue_r, message_send_queue: message_r, - connection_id: 0, - endpoint_id, + guard: OnDisconnectGuard::empty(endpoint_id), clients: clients.clone(), client_counter: ClientCounter::default(), ping_tracker: PingTracker::default(), @@ -677,16 +680,11 @@ mod tests { protocol_version: ProtocolVersion, ) -> (Config>>, Conn) { let (server, client) = tokio::io::duplex(1024); - ( - Config { - endpoint_id: key, - stream: ServerRelayedStream::test(server), - write_timeout: Duration::from_secs(1), - channel_capacity: 10, - protocol_version, - }, - Conn::test(client, protocol_version), - ) + let guard = OnDisconnectGuard::empty(key); + let mut config = Config::new(guard, ServerRelayedStream::test(server), protocol_version); + config.write_timeout = Duration::from_secs(1); + config.channel_capacity = 10; + (config, Conn::test(client, protocol_version)) } #[tokio::test] diff --git a/iroh-relay/src/server/clients.rs b/iroh-relay/src/server/clients.rs index 98353f7e5a..bc791ee252 100644 --- a/iroh-relay/src/server/clients.rs +++ b/iroh-relay/src/server/clients.rs @@ -1,13 +1,7 @@ //! The "Server" side of the client. Uses the `ClientConnManager`. // Based on tailscale/derp/derp_server.go -use std::{ - collections::HashSet, - sync::{ - Arc, - atomic::{AtomicU64, Ordering}, - }, -}; +use std::{collections::HashSet, sync::Arc}; use dashmap::DashMap; use iroh_base::EndpointId; @@ -15,7 +9,10 @@ use n0_future::IterExt; use tokio::sync::mpsc::error::TrySendError; use tracing::{debug, trace}; -use super::client::{Client, Config, ForwardPacketError}; +use super::{ + ConnectionId, OnDisconnectGuard, + client::{Client, Config, ForwardPacketError}, +}; use crate::{ protos::{ relay::{Datagrams, Status}, @@ -25,7 +22,7 @@ use crate::{ }; /// Manages the connections to all currently connected clients. -#[derive(Debug, Default, Clone)] +#[derive(Debug, Clone, Default)] /// Registry of connected relay clients. /// /// This type manages the collection of active client connections and @@ -38,8 +35,6 @@ struct Inner { clients: DashMap, /// Map of which client has sent where sent_to: DashMap>, - /// Connection ID Counter - next_connection_id: AtomicU64, } #[derive(Debug)] @@ -73,15 +68,17 @@ impl Clients { } /// Builds the client handler and starts the read & write loops for the connection. + /// + /// Once the client disconnects, the [`OnDisconnectGuard`] set in `config` will be dropped, + /// allowing callers to be notified of the disconnect. pub fn register(&self, client_config: Config, metrics: Arc) where S: BytesStreamSink + Send + 'static, { - let endpoint_id = client_config.endpoint_id; - let connection_id = self.get_connection_id(); + let endpoint_id = client_config.guard.endpoint_id; trace!(remote_endpoint = %endpoint_id.fmt_short(), "registering client"); - let client = Client::new(client_config, connection_id, self, metrics.clone()); + let client = Client::new(client_config, self, metrics.clone()); match self.0.clients.entry(endpoint_id) { dashmap::Entry::Occupied(mut entry) => { let state = entry.get_mut(); @@ -105,24 +102,17 @@ impl Clients { } } - fn get_connection_id(&self) -> u64 { - self.0.next_connection_id.fetch_add(1, Ordering::Relaxed) - } - /// Removes the client from the map of clients, & sends a notification /// to each client that peers has sent data to, to let them know that /// peer is gone from the network. /// /// Must be passed a matching connection_id. - pub(super) fn unregister( - &self, - connection_id: u64, - endpoint_id: EndpointId, - metrics: &Metrics, - ) { + pub(super) fn unregister(&self, guard: OnDisconnectGuard, metrics: &Metrics) { + let endpoint_id = guard.endpoint_id; + let connection_id = guard.connection_id; trace!( endpoint_id = %endpoint_id.fmt_short(), - connection_id, "unregistering client" + %connection_id, "unregistering client" ); let mut notify_peers = None; @@ -180,6 +170,33 @@ impl Clients { } } + /// Disconnects connections registered for `endpoint_id`. + /// + /// With `Some(connection_id)`, disconnects only that connection (active or + /// an inactive duplicate). With `None`, disconnects every connection for the + /// endpoint. Returns `true` if a matching connection was found, or `false` + /// otherwise. + /// + /// Shutdown happens asynchronously: each per-connection actor exits its run + /// loop and unregisters itself after this call returns. + pub fn disconnect(&self, endpoint_id: EndpointId, connection_id: Option) -> bool { + let Some(state) = self.0.clients.get(&endpoint_id) else { + return false; + }; + let mut clients = state.inactive.iter().chain([&state.active]); + if let Some(id) = connection_id { + let Some(client) = clients.find(|c| c.connection_id() == id) else { + return false; + }; + client.start_shutdown(); + } else { + for client in clients { + client.start_shutdown(); + } + } + true + } + /// Attempt to send a packet to client with [`EndpointId`] `dst`. pub(super) fn send_packet( &self, @@ -218,7 +235,7 @@ impl Clients { } #[cfg(test)] - fn active_connection_id(&self, endpoint_id: EndpointId) -> Option { + fn active_connection_id(&self, endpoint_id: EndpointId) -> Option { self.0 .clients .get(&endpoint_id) @@ -239,6 +256,7 @@ mod tests { use super::*; use crate::{ client::conn::Conn, + http::ProtocolVersion, protos::{common::FrameType, relay::RelayToClientMsg, streams::WsBytesFramed}, server::streams::{MaybeTlsStream, RateLimited, ServerRelayedStream}, }; @@ -270,17 +288,12 @@ mod tests { key: EndpointId, ) -> (Config>>, Conn) { let (server, client) = tokio::io::duplex(1024); - let protocol_version = Default::default(); - ( - Config { - endpoint_id: key, - stream: ServerRelayedStream::test(server), - write_timeout: Duration::from_secs(1), - channel_capacity: 10, - protocol_version: Default::default(), - }, - Conn::test(client, protocol_version), - ) + let guard = OnDisconnectGuard::empty(key); + let protocol_version = ProtocolVersion::default(); + let mut config = Config::new(guard, ServerRelayedStream::test(server), protocol_version); + config.write_timeout = Duration::from_secs(1); + config.channel_capacity = 10; + (config, Conn::test(client, protocol_version)) } #[tokio::test] diff --git a/iroh-relay/src/server/http_server.rs b/iroh-relay/src/server/http_server.rs index ad7003f8b0..93fc7f0e2b 100644 --- a/iroh-relay/src/server/http_server.rs +++ b/iroh-relay/src/server/http_server.rs @@ -32,7 +32,8 @@ use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle}; use tracing::{Instrument, debug, error, info, info_span, trace, warn, warn_span}; use super::{ - AccessConfig, ClientRequest, SpawnError, clients::Clients, streams::InvalidBucketConfig, + AllowAll, ClientRequest, DynAccessControl, SpawnError, clients::Clients, + streams::InvalidBucketConfig, }; use crate::{ KeyCache, @@ -41,11 +42,7 @@ use crate::{ CLIENT_AUTH_HEADER, ProtocolVersion, RELAY_PATH, SUPPORTED_WEBSOCKET_VERSION, WEBSOCKET_UPGRADE_PROTOCOL, }, - protos::{ - handshake, - relay::{MAX_FRAME_SIZE, PER_CLIENT_SEND_QUEUE_DEPTH}, - streams::WsBytesFramed, - }, + protos::{handshake, relay::MAX_FRAME_SIZE, streams::WsBytesFramed}, server::{ ClientRateLimit, client::Config, @@ -114,6 +111,7 @@ pub(super) struct Server { addr: SocketAddr, http_server_task: AbortOnDropHandle<()>, cancel_server_loop: CancellationToken, + service: RelayService, } impl Server { @@ -145,6 +143,11 @@ impl Server { pub(super) fn addr(&self) -> SocketAddr { self.addr } + + /// Returns the [`RelayService`] driving this server. + pub(super) fn service(&self) -> &RelayService { + &self.service + } } /// A handle for the [`Server`]. @@ -347,8 +350,8 @@ pub(super) struct ServerBuilder { client_rx_ratelimit: Option, /// The capacity of the key cache. key_cache_capacity: usize, - /// Access config for endpoints. - access: AccessConfig, + /// Access control for endpoints. + access: Arc, metrics: Option>, establish_timeout: Duration, } @@ -363,7 +366,7 @@ impl ServerBuilder { headers: HeaderMap::new(), client_rx_ratelimit: None, key_cache_capacity: DEFAULT_KEY_CACHE_CAPACITY, - access: AccessConfig::Everyone, + access: Arc::new(AllowAll), metrics: None, establish_timeout: ESTABLISH_TIMEOUT, } @@ -375,8 +378,8 @@ impl ServerBuilder { self } - /// Set the access configuration. - pub(super) fn access(mut self, access: AccessConfig) -> Self { + /// Set the access control. + pub(super) fn access(mut self, access: Arc) -> Self { self.access = access; self } @@ -464,8 +467,10 @@ impl ServerBuilder { info!("[{http_str}] relay: serving on {addr}"); let cancel = cancel_token.clone(); + let loop_service = service.clone(); let task = tokio::task::spawn( async move { + let service = loop_service; // create a join set to track all our connection tasks let mut set = tokio::task::JoinSet::new(); loop { @@ -510,6 +515,7 @@ impl ServerBuilder { addr, http_server_task: AbortOnDropHandle::new(task), cancel_server_loop: cancel_token, + service, }) } } @@ -528,7 +534,7 @@ struct Inner { write_timeout: Duration, rate_limit: Option, key_cache: KeyCache, - access: AccessConfig, + access: Arc, metrics: Arc, } @@ -686,7 +692,7 @@ impl RelayServiceWithNotify { /// # use iroh_relay::{ /// # KeyCache, /// # server::{ -/// # AccessConfig, Metrics, +/// # AllowAll, Metrics, /// # http_server::{Handlers, RelayService, RelayServiceWithNotify}, /// # streams::MaybeTlsStream /// # }, @@ -697,7 +703,7 @@ impl RelayServiceWithNotify { /// HeaderMap::new(), /// None, /// KeyCache::new(1024), -/// AccessConfig::Everyone, +/// Arc::new(AllowAll), /// Arc::new(Metrics::default()), /// ); /// let service = RelayServiceWithNotify::new(service, Arc::new(Notify::new())); @@ -863,9 +869,13 @@ impl Inner { trace!(?authentication.mechanism, "accept: verified authentication"); - let request = ClientRequest::new(authentication.client_key, request_parts); - let is_authorized = self.access.is_allowed(&request).await; - let client_key = authentication.authorize_if(is_authorized, &mut io).await?; + let request = + ClientRequest::new(authentication.client_key, protocol_version, request_parts); + + // Authorize the request against the configured `AccessControl`. + let guard = authentication + .authorize_with(&request, &self.access, &mut io) + .await?; trace!("accept: verified authorization"); @@ -875,16 +885,9 @@ impl Inner { }; trace!("accept: build client conn"); - let client_conn_builder = Config { - endpoint_id: client_key, - stream: io, - write_timeout: self.write_timeout, - channel_capacity: PER_CLIENT_SEND_QUEUE_DEPTH, - protocol_version, - }; - trace!("accept: create client"); - let endpoint_id = client_conn_builder.endpoint_id; - trace!(endpoint_id = %endpoint_id.fmt_short(), "create client"); + let mut client_conn_builder = Config::new(guard, io, protocol_version); + client_conn_builder.write_timeout = self.write_timeout; + trace!(endpoint_id = %request.endpoint_id().fmt_short(), "create client"); // build and register client, starting up read & write loops for the client // connection @@ -913,7 +916,7 @@ impl RelayService { headers: HeaderMap, rate_limit: Option, key_cache: KeyCache, - access: AccessConfig, + access: Arc, metrics: Arc, ) -> Self { Self(Arc::new(Inner { @@ -933,6 +936,14 @@ impl RelayService { self.0.clients.shutdown().await; } + /// Returns a reference to the registry of currently connected clients. + /// + /// The returned [`Clients`] handle can be used at runtime to disconnect a + /// connected endpoint via [`Clients::disconnect`]. + pub fn clients(&self) -> &Clients { + &self.0.clients + } + /// Handle the incoming connection. /// /// If a `tls_config` is given, will serve the connection using HTTPS, otherwise HTTP. @@ -947,7 +958,7 @@ impl RelayService { /// # use tokio::net::TcpStream; /// # use http::HeaderMap; /// # use iroh_relay::server::http_server::{Handlers, RelayService, TlsConfig}; - /// # use iroh_relay::{KeyCache, server::{AccessConfig, Metrics}}; + /// # use iroh_relay::{KeyCache, server::{AllowAll, Metrics}}; /// # use webpki_types::{CertificateDer, PrivateKeyDer}; /// # async fn example(stream: TcpStream) -> Result<(), Box> { /// // Create a relay service @@ -960,7 +971,7 @@ impl RelayService { /// headers, /// None, // No rate limiting /// key_cache, - /// AccessConfig::Everyone, + /// Arc::new(AllowAll), /// metrics, /// ); /// @@ -1468,7 +1479,7 @@ mod tests { Default::default(), None, KeyCache::test(), - AccessConfig::Everyone, + Arc::new(crate::server::AllowAll), metrics.clone(), ); @@ -1580,7 +1591,7 @@ mod tests { Default::default(), None, KeyCache::test(), - AccessConfig::Everyone, + Arc::new(crate::server::AllowAll), Default::default(), ); diff --git a/iroh-relay/src/server/testing.rs b/iroh-relay/src/server/testing.rs index 98276363f3..f8676282df 100644 --- a/iroh-relay/src/server/testing.rs +++ b/iroh-relay/src/server/testing.rs @@ -1,7 +1,7 @@ //! Exposes functions to quickly configure a server suitable for testing. -use std::net::Ipv4Addr; +use std::{net::Ipv4Addr, sync::Arc}; -use super::{AccessConfig, CertConfig, QuicConfig, RelayConfig, ServerConfig, TlsConfig}; +use super::{AllowAll, CertConfig, QuicConfig, RelayConfig, ServerConfig, TlsConfig}; /// Creates a [`rustls::ServerConfig`] and certificates suitable for testing. /// @@ -56,7 +56,7 @@ pub fn relay_config() -> RelayConfig { tls: Some(tls_config()), limits: Default::default(), key_cache_capacity: Some(1024), - access: AccessConfig::Everyone, + access: Arc::new(AllowAll), } } diff --git a/iroh-relay/tests/relay_axum.rs b/iroh-relay/tests/relay_axum.rs index 9344da8776..e8c57817aa 100644 --- a/iroh-relay/tests/relay_axum.rs +++ b/iroh-relay/tests/relay_axum.rs @@ -36,7 +36,7 @@ use iroh_relay::{ http::{CLIENT_AUTH_HEADER, ProtocolVersion, RELAY_PATH, RELAY_PROBE_PATH}, protos::{handshake, streams::StreamError}, server::{ - AccessConfig, ClientRequest, Metrics, client::Config, clients::Clients, + AllowAll, ClientRequest, DynAccessControl, Metrics, client::Config, clients::Clients, streams::RelayedStream, }, tls::{CaRootsConfig, default_provider}, @@ -51,7 +51,7 @@ use tracing::{trace, warn}; #[derive(Clone, Debug)] struct RelayState { key_cache: KeyCache, - access: Arc, + access: Arc, metrics: Arc, clients: Clients, } @@ -60,7 +60,7 @@ impl RelayState { fn new() -> Self { Self { key_cache: KeyCache::new(1024), - access: Arc::new(AccessConfig::Everyone), + access: Arc::new(AllowAll), metrics: Arc::new(Metrics::default()), clients: Clients::default(), } @@ -187,15 +187,18 @@ async fn handle_relay_websocket( let authentication = handshake::serverside(&mut adapter, client_auth_header).await?; trace!(?authentication.mechanism, "verified authentication"); - let request = ClientRequest::new(authentication.client_key, request_parts); - let is_authorized = state.access.is_allowed(&request).await; - let client_key = authentication - .authorize_if(is_authorized, &mut adapter) + let request = ClientRequest::new( + authentication.client_key, + ProtocolVersion::V2, + request_parts, + ); + let guard = authentication + .authorize_with(&request, &state.access, &mut adapter) .await?; trace!("verified authorization"); let stream = RelayedStream::new(adapter, state.key_cache.clone()); - let config = Config::new(client_key, stream, ProtocolVersion::V2); + let config = Config::new(guard, stream, ProtocolVersion::V2); state.clients.register(config, state.metrics.clone()); Ok(()) } diff --git a/iroh-relay/tests/relay_hyper.rs b/iroh-relay/tests/relay_hyper.rs index a5e9c54c59..4617b3f7fc 100644 --- a/iroh-relay/tests/relay_hyper.rs +++ b/iroh-relay/tests/relay_hyper.rs @@ -23,7 +23,7 @@ use iroh_relay::{ client::ClientBuilder, http::{RELAY_PATH, RELAY_PROBE_PATH}, server::{ - AccessConfig, Metrics, + AllowAll, Metrics, http_server::{BytesBody, Handlers, RelayService, RelayServiceWithNotify}, streams::MaybeTlsStream, }, @@ -59,7 +59,7 @@ async fn serve_hyper() -> Result<(SocketAddr, AbortOnDropHandle<()>)> { HeaderMap::new(), None, KeyCache::new(1024), - AccessConfig::Everyone, + Arc::new(AllowAll), Arc::new(Metrics::default()), ); diff --git a/iroh-relay/tests/runtime_auth.rs b/iroh-relay/tests/runtime_auth.rs new file mode 100644 index 0000000000..b994f6008e --- /dev/null +++ b/iroh-relay/tests/runtime_auth.rs @@ -0,0 +1,366 @@ +//! Runtime revocation of relay access via the [`AccessControl`] trait. +//! +//! These tests drive a [`RestrictedServer`]: a relay [`Server`] fronted by a +//! runtime-mutable token allow-list. Its [`AccessControl`] implementation +//! records the auth token of every admitted connection through +//! `on_connect`/`on_disconnect`, so revoking a token yields the connections to +//! evict through [`Clients::disconnect`]. +//! +//! [`AccessControl`]: iroh_relay::server::AccessControl +//! [`Clients::disconnect`]: iroh_relay::server::clients::Clients::disconnect + +#![cfg(feature = "server")] + +use std::{ + collections::HashMap, + net::Ipv4Addr, + sync::{Arc, Mutex}, + time::Duration, +}; + +use iroh_base::{EndpointId, RelayUrl, SecretKey}; +use iroh_dns::dns::DnsResolver; +use iroh_relay::{ + client::{Client, ClientBuilder, ConnectError}, + protos::{ + handshake, + relay::{ClientToRelayMsg, RelayToClientMsg}, + }, + server::{ + Access, AccessControl, ClientRequest, ConnectionId, RelayConfig, Server, ServerConfig, + }, + tls::{CaRootsConfig, default_provider}, +}; +use n0_error::{Result, StackResultExt, StdResultExt}; +use n0_future::{SinkExt, StreamExt}; +use n0_tracing_test::traced_test; +use rand::RngExt; + +/// Shared state behind [`TokenAccess`]. +#[derive(Debug, Default)] +struct AccessState { + next_token_id: u64, + /// Auth tokens currently permitted to connect. + tokens: HashMap, + /// Auth token recorded for each connected connection. + /// + /// Built from `on_connect`/`on_disconnect`. + connections: HashMap<(EndpointId, ConnectionId), u64>, +} + +/// An [`AccessControl`] with a runtime-mutable token allow-list. +/// +/// Admits a connection if its auth token is currently allowed, and records the +/// token each admitted connection used, so a revoked token maps back to the +/// connections that must be evicted. `on_disconnect` prunes the index. +#[derive(Debug, Default)] +struct TokenAccess(Mutex); + +impl TokenAccess { + fn new(allowed: impl IntoIterator) -> Arc { + let this = TokenAccess::default(); + for token in allowed { + this.allow(token); + } + Arc::new(this) + } + + /// Adds `token` to the allow-list. + fn allow(&self, token: &str) { + let mut state = self.0.lock().expect("poisoned"); + if !state.tokens.contains_key(token) { + let id = state.next_token_id; + state.next_token_id += 1; + state.tokens.insert(token.to_string(), id); + } + } + + /// Removes `token` from the allow-list and returns its indexed connections. + fn revoke(&self, revoked_token: &str) -> Vec<(EndpointId, ConnectionId)> { + let mut state = self.0.lock().expect("poisoned"); + let mut removed = vec![]; + if let Some(revoked_id) = state.tokens.remove(revoked_token) { + state.connections.retain(|conn_id, token_id| { + if *token_id == revoked_id { + removed.push(*conn_id); + false + } else { + true + } + }); + } + removed + } +} + +impl AccessControl for TokenAccess { + async fn on_connect(&self, request: &ClientRequest) -> Access { + let mut state = self.0.lock().expect("poisoned"); + match request.auth_token() { + Some(token) => { + if let Some(token_id) = state.tokens.get(&token).copied() { + let conn_id = (request.endpoint_id(), request.connection_id()); + state.connections.insert(conn_id, token_id); + Access::Allow + } else { + Access::Deny { reason: None } + } + } + None => Access::Deny { reason: None }, + } + } + + fn on_disconnect(&self, endpoint_id: EndpointId, connection_id: ConnectionId) { + let mut state = self.0.lock().expect("poisoned"); + state.connections.remove(&(endpoint_id, connection_id)); + } +} + +/// A relay [`Server`] paired with the [`TokenAccess`] guarding it. +/// +/// Bundles the token allow-list with the running server so tests can grant and +/// revoke tokens, and have revocation evict the matching connections. +struct RestrictedServer { + server: Server, + access: Arc, +} + +impl RestrictedServer { + /// Spawns a relay server that initially admits `allowed` tokens. + async fn spawn(allowed: impl IntoIterator) -> Result { + let access = TokenAccess::new(allowed); + + let mut relay = RelayConfig::new((Ipv4Addr::LOCALHOST, 0)); + relay.access = access.clone(); + let mut config = ServerConfig::default(); + config.relay = Some(relay); + let server = Server::spawn(config).await?; + + Ok(Self { server, access }) + } + + /// Returns the relay URL clients should connect to. + fn relay_url(&self) -> RelayUrl { + format!("http://{}", self.server.http_addr().expect("http addr")) + .parse() + .expect("valid relay url") + } + + /// Allows `token`: connection attempts that present it now succeed. + fn add_token(&self, token: &str) { + self.access.allow(token); + } + + /// Revokes `token` and disconnects every connection that used it. + fn remove_token(&self, token: &str) { + let clients = self + .server + .relay_service() + .expect("relay configured") + .clients(); + for (endpoint_id, connection_id) in self.access.revoke(token) { + clients.disconnect(endpoint_id, Some(connection_id)); + } + } + + /// Returns the number of currently connected connections. + fn connection_count(&self) -> usize { + self.access.0.lock().expect("poisoned").connections.len() + } +} + +/// A token that is not on the allow-list is rejected during the handshake. +#[tokio::test] +#[traced_test] +async fn unknown_token_is_denied() -> Result<()> { + let server = RestrictedServer::spawn(["token-a"]).await?; + assert_denied(connect(&server.relay_url(), "token-b").await); + Ok(()) +} + +/// A token added to the allow-list at runtime admits new connections. +#[tokio::test] +#[traced_test] +async fn token_added_at_runtime_is_admitted() -> Result<()> { + let server = RestrictedServer::spawn(["token-b"]).await?; + let url = server.relay_url(); + + // token-a is not on the initial allow-list. + assert_denied(connect(&url, "token-a").await); + + // Adding it at runtime lets a new connection through. + server.add_token("token-a"); + let mut client = connect(&url, "token-a").await?; + ping_round_trip(&mut client, [1u8; 8]).await?; + + Ok(()) +} + +/// Revoking a token disconnects its connection and leaves others untouched. +#[tokio::test] +#[traced_test] +async fn revoked_token_disconnects_its_connection() -> Result<()> { + let server = RestrictedServer::spawn(["token-a", "token-b"]).await?; + let url = server.relay_url(); + + let mut revoked = connect(&url, "token-a").await?; + let mut kept = connect(&url, "token-b").await?; + ping_round_trip(&mut revoked, [1u8; 8]).await?; + ping_round_trip(&mut kept, [2u8; 8]).await?; + + // Revoking token-a evicts its connection; the token-b connection survives. + server.remove_token("token-a"); + assert_disconnected(&mut revoked).await; + ping_round_trip(&mut kept, [3u8; 8]).await?; + + Ok(()) +} + +/// Revoking a token disconnects every connection of a shared endpoint. +#[tokio::test] +#[traced_test] +async fn revoked_token_disconnects_every_endpoint_connection() -> Result<()> { + let server = RestrictedServer::spawn(["token-a", "token-b"]).await?; + let url = server.relay_url(); + + // One endpoint opens two connections, both authenticating with token-a. + let shared = SecretKey::from_bytes(&rand::rng().random()); + let mut conn1 = connect_as(&url, &shared, "token-a").await?; + ping_round_trip(&mut conn1, [1u8; 8]).await?; + let mut conn2 = connect_as(&url, &shared, "token-a").await?; + ping_round_trip(&mut conn2, [2u8; 8]).await?; + + // A second endpoint connects with token-b. + let mut other = connect_as(&url, &shared, "token-b").await?; + ping_round_trip(&mut other, [3u8; 8]).await?; + assert_eq!(server.connection_count(), 3); + + // Revoking token-a disconnects both connections of the shared endpoint, + // told apart by their distinct connection ids. + server.remove_token("token-a"); + assert_disconnected(&mut conn1).await; + assert_disconnected(&mut conn2).await; + + // The token-b endpoint keeps working, and the index is pruned to it alone. + ping_round_trip(&mut other, [4u8; 8]).await?; + wait_for(Duration::from_secs(5), || server.connection_count() == 1).await; + + Ok(()) +} + +/// Once revoked, a token can no longer be used to connect. +#[tokio::test] +#[traced_test] +async fn revoked_token_cannot_reconnect() -> Result<()> { + let server = RestrictedServer::spawn(["token-a"]).await?; + let url = server.relay_url(); + + // The token works before it is revoked. + let mut client = connect(&url, "token-a").await?; + ping_round_trip(&mut client, [1u8; 8]).await?; + + // After revocation it no longer admits connections. + server.remove_token("token-a"); + assert_denied(connect(&url, "token-a").await); + + Ok(()) +} + +/// A connection that closes on its own is pruned from the access index. +#[tokio::test] +#[traced_test] +async fn disconnected_connections_are_pruned() -> Result<()> { + let server = RestrictedServer::spawn(["token-a"]).await?; + let url = server.relay_url(); + + let mut client = connect(&url, "token-a").await?; + ping_round_trip(&mut client, [1u8; 8]).await?; + assert_eq!(server.connection_count(), 1); + + // Dropping the client closes the connection; `on_disconnect` then prunes + // the index, so a long-lived server does not accumulate stale entries. + drop(client); + wait_for(Duration::from_secs(5), || server.connection_count() == 0).await; + + Ok(()) +} + +/// Connects a relay client for a fresh random endpoint, authenticating with `token`. +async fn connect(relay_url: &RelayUrl, token: &str) -> Result { + let secret = SecretKey::from_bytes(&rand::rng().random()); + connect_as(relay_url, &secret, token).await +} + +/// Connects a relay client for `secret`'s endpoint, authenticating with `token`. +async fn connect_as( + relay_url: &RelayUrl, + secret: &SecretKey, + token: &str, +) -> Result { + let tls = CaRootsConfig::default() + .client_config(default_provider()) + .expect("valid client config"); + ClientBuilder::new(relay_url.clone(), secret.clone(), DnsResolver::new()) + .tls_client_config(tls) + .auth_token(token) + .connect() + .await +} + +/// Sends a relay-level ping and asserts the matching pong comes back. +async fn ping_round_trip(client: &mut Client, data: [u8; 8]) -> Result<()> { + client.send(ClientToRelayMsg::Ping(data)).await?; + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let msg = client.next().await.context("stream ended")??; + match msg { + RelayToClientMsg::Ping(payload) => { + client.send(ClientToRelayMsg::Pong(payload)).await?; + } + RelayToClientMsg::Pong(echo) => { + n0_error::ensure_any!(echo == data, "pong mismatch"); + break; + } + other => n0_error::bail_any!("expected pong, got {other:?}"), + } + } + n0_error::Ok(()) + }) + .await + .std_context("ping roundtrip timeout")? +} + +/// Asserts that `client`'s stream closes within a few seconds. +async fn assert_disconnected(client: &mut Client) { + tokio::time::timeout(Duration::from_secs(5), async { + while let Some(msg) = client.next().await { + let _ = msg.expect("expected message, got error"); + } + }) + .await + .expect("timeout while waiting for disconnect"); +} + +/// Asserts that a connection attempt was rejected by the access hook. +fn assert_denied(result: Result) { + let result = result.map(|_| ()); + assert!( + matches!( + result, + Err(ConnectError::Handshake { source: handshake::Error::ServerDeniedAuth { ref reason, .. }, .. }) + if reason == "not authorized" + ), + "expected handshake denial, got {result:?}", + ); +} + +/// Polls `cond` until it is true or the timeout elapses. +async fn wait_for(timeout: Duration, cond: impl Fn() -> bool) { + tokio::time::timeout(timeout, async { + while !cond() { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("condition not met within timeout"); +} diff --git a/iroh/src/endpoint.rs b/iroh/src/endpoint.rs index 8530ff0ef4..2372531c47 100644 --- a/iroh/src/endpoint.rs +++ b/iroh/src/endpoint.rs @@ -1935,11 +1935,7 @@ mod tests { use iroh_base::{EndpointAddr, EndpointId, RelayUrl, SecretKey, TransportAddr}; use iroh_dns::endpoint_info::UserData; - use iroh_relay::{ - RelayConfig, - server::{Access, AccessConfig}, - tls::CaRootsConfig, - }; + use iroh_relay::{RelayConfig, server::Access, tls::CaRootsConfig}; use n0_error::{AnyError as Error, Result, StdResultExt}; use n0_future::{BufferedStreamExt, StreamExt, future::now_or_never, stream, time}; use n0_tracing_test::traced_test; @@ -3905,22 +3901,28 @@ mod tests { } /// Verifies that an endpoint configured with [`RelayConfig::with_auth_token`] - /// is admitted to a relay that uses [`AccessConfig::Restricted`] only when + /// is admitted to a relay whose access control checks the token only when /// the token matches. #[tokio::test] #[traced_test] async fn test_endpoint_relay_auth_token() -> Result { const TOKEN: &str = "valid-token"; - let access = AccessConfig::Restricted(Box::new(|request| { - Box::pin(async move { - if request.auth_token().as_deref() == Some(TOKEN) { + /// Admits a connection only if it carries the expected auth token. + #[derive(Debug)] + struct TokenAccess(&'static str); + + impl iroh_relay::server::AccessControl for TokenAccess { + async fn on_connect(&self, request: &iroh_relay::server::ClientRequest) -> Access { + if request.auth_token().as_deref() == Some(self.0) { Access::Allow } else { - Access::Deny + Access::Deny { reason: None } } - }) - })); + } + } + + let access = Arc::new(TokenAccess(TOKEN)); let (_relay_map, relay_url, _guard) = run_relay_server_with_access(false, access).await?; // Wrong token: the connection attempt fails and last_error reports diff --git a/iroh/src/test_utils.rs b/iroh/src/test_utils.rs index c38e27c92a..cb80b18be0 100644 --- a/iroh/src/test_utils.rs +++ b/iroh/src/test_utils.rs @@ -1,12 +1,12 @@ //! Internal utilities to support testing. -use std::net::Ipv4Addr; +use std::{net::Ipv4Addr, sync::Arc}; use iroh_base::RelayUrl; use iroh_relay::{ RelayConfig, RelayMap, RelayQuicConfig, server::{ - AccessConfig, CertConfig, QuicConfig, RelayConfig as RelayServerConfig, Server, - ServerConfig, SpawnError, TlsConfig, + AllowAll, CertConfig, DynAccessControl, QuicConfig, RelayConfig as RelayServerConfig, + Server, ServerConfig, SpawnError, TlsConfig, }, }; use tokio::sync::oneshot; @@ -42,15 +42,15 @@ pub async fn run_relay_server() -> Result<(RelayMap, RelayUrl, Server), SpawnErr /// /// The return value is similar to [`run_relay_server`]. pub async fn run_relay_server_with(quic: bool) -> Result<(RelayMap, RelayUrl, Server), SpawnError> { - run_relay_server_with_access(quic, AccessConfig::Everyone).await + run_relay_server_with_access(quic, Arc::new(AllowAll)).await } -/// Runs a relay server with a custom [`AccessConfig`]. +/// Runs a relay server with a custom access control. /// /// See [`run_relay_server_with`] for details on `quic`. pub async fn run_relay_server_with_access( quic: bool, - access: AccessConfig, + access: Arc, ) -> Result<(RelayMap, RelayUrl, Server), SpawnError> { let (_certs, server_config) = iroh_relay::server::testing::self_signed_tls_certs_and_config(); diff --git a/iroh/tests/patchbay/util.rs b/iroh/tests/patchbay/util.rs index 463c12eb27..21a90ee7a5 100644 --- a/iroh/tests/patchbay/util.rs +++ b/iroh/tests/patchbay/util.rs @@ -476,13 +476,16 @@ fn addr_relay_only(addr: EndpointAddr) -> EndpointAddr { } mod relay { - use std::net::{IpAddr, Ipv6Addr}; + use std::{ + net::{IpAddr, Ipv6Addr}, + sync::Arc, + }; use iroh_base::RelayUrl; use iroh_relay::{ RelayConfig, RelayMap, RelayQuicConfig, server::{ - AccessConfig, CertConfig, QuicConfig, RelayConfig as RelayServerConfig, Server, + AllowAll, CertConfig, QuicConfig, RelayConfig as RelayServerConfig, Server, ServerConfig, SpawnError, TlsConfig, testing::self_signed_tls_certs_and_config, }, }; @@ -501,7 +504,7 @@ mod relay { let mut relay = RelayServerConfig::new((bind_ip, 80)); relay.tls = Some(tls); relay.key_cache_capacity = Some(1024); - relay.access = AccessConfig::Everyone; + relay.access = Arc::new(AllowAll); let mut config = ServerConfig::default(); config.relay = Some(relay);