From 400264e31904673a755faa77b92833dfb60d7d8a Mon Sep 17 00:00:00 2001 From: Enrico Fusto Date: Thu, 11 Jun 2026 14:13:56 +0200 Subject: [PATCH] feat(iroh-relay): Add Bearer token access control without an external service (#4326) ## Description This PR adds a new `AccessConfig::SharedToken(Vec)` variant to the `iroh-relay` configuration, allowing self-hosted relays to require a shared bearer token from connecting clients, without using an external auth service. - Clients authenticate via `Authorization: Bearer ` header or `?token=` query param, using the existing `RelayConfig::with_auth_token()` / `RelayMap::with_auth_token()` API; - Token can be set via config file (`access.shared_token = ["token-a", "token-b"]`) or the `IROH_RELAY_ACCESS_TOKEN` environment variable (**the env var takes precedence**); - Empty token is rejected at startup; - A token set to the empty string, will make the server fail to start. [See related discussion](https://github.com/n0-computer/iroh/discussions/4316) ## Breaking Changes None. ## Notes & open questions - As we stated in the discussion, using an external service should always be considered the best choice for production. The static token variant is still useful for simpler deployments. - Supported the token list in config, as suggested by fokx ## Change checklist - [x] Self-review - [x] Documentation updates - [x] Tests Co-authored-by: fokx <36614441+fokx@users.noreply.github.com> --------- Co-authored-by: Franz Heinzmann --- iroh-relay/README.md | 60 ++++++++++++++++++++++++++ iroh-relay/src/main.rs | 98 ++++++++++++++++++++++++++++++++++++++---- 2 files changed, 150 insertions(+), 8 deletions(-) diff --git a/iroh-relay/README.md b/iroh-relay/README.md index 25f1af36d7..4fb89a1626 100644 --- a/iroh-relay/README.md +++ b/iroh-relay/README.md @@ -23,6 +23,66 @@ relays, including: Used in [iroh], created with love by the [n0 team](https://n0.computer/). +## Access control + +The relay server supports several access control modes, configured via the +`access` field in the TOML config file. + +### Allow everyone (default) + +```toml +access = "everyone" +``` + +### Allowlist / Denylist by endpoint ID + +```toml +# Allow only specific endpoints +access.allowlist = ["", ""] + +# Or block specific endpoints and allow everyone else +access.denylist = [""] +``` + +### Shared token (local, no external service) + +Requires connecting clients to present one of the configured shared secrets via an +`Authorization: Bearer ` header, or a `?token=` URL query parameter. + +```toml +access.shared_token = ["token-a", "token-b"] +``` + +The token list can also be overridden by the `IROH_RELAY_ACCESS_TOKEN` environment +variable, which sets a single allowed token and takes precedence over the config file +value. A single value is used (rather than a comma-separated list) to avoid restricting +the character set of tokens. + +The token list must not be empty, and no token may be an empty string; the server will +fail to start if either condition is violated. + +On the client side, set the token using +[`RelayConfig::with_auth_token`](https://docs.rs/iroh-relay/latest/iroh_relay/struct.RelayConfig.html#method.with_auth_token) +or +[`RelayMap::with_auth_token`](https://docs.rs/iroh-relay/latest/iroh_relay/struct.RelayMap.html#method.with_auth_token). + +> **Note:** this shared token does not support revocation other than updating the config and restarting the service. + +### HTTP callout (external auth service) + +The relay calls an external HTTP endpoint for each incoming connection, +passing the connecting endpoint's ID. The token below authenticates the relay +to your auth service (machine-to-machine), not the connecting client. + +```toml +access.http.url = "https://your-auth-service.example.com/relay-auth" +# Optional: authenticate the relay's outbound request to your service +access.http.bearer_token = "service-to-service-secret" +``` + +The bearer token can also be set via the `IROH_RELAY_HTTP_BEARER_TOKEN` +environment variable. + ## Local testing Advice for testing your application that uses `iroh` with a locally running `iroh-relay` server diff --git a/iroh-relay/src/main.rs b/iroh-relay/src/main.rs index 675b40274a..17fa821952 100644 --- a/iroh-relay/src/main.rs +++ b/iroh-relay/src/main.rs @@ -22,7 +22,7 @@ use iroh_relay::{ DEFAULT_CERT_RELOAD_INTERVAL, QuicConfig, reloading_resolver, }, }; -use n0_error::{Result, StdResultExt, bail_any}; +use n0_error::{AnyError, Result, StdResultExt, bail_any}; use serde::{Deserialize, Serialize}; use tracing::{debug, warn}; use tracing_subscriber::{EnvFilter, prelude::*}; @@ -35,6 +35,8 @@ const DEV_MODE_HTTP_PORT: u16 = 3340; const X_IROH_ENDPOINT_ID: &str = "X-Iroh-NodeId"; /// Environment variable to read a bearer token for HTTP auth requests from. const ENV_HTTP_BEARER_TOKEN: &str = "IROH_RELAY_HTTP_BEARER_TOKEN"; +/// Environment variable to verify relay access (without an external auth service) +const ENV_RELAY_ACCESS_TOKEN: &str = "IROH_RELAY_ACCESS_TOKEN"; /// A relay server for iroh. #[derive(Parser, Debug, Clone)] @@ -166,6 +168,27 @@ enum AccessConfig { /// To grant access, the HTTP endpoint must return a `200` response with `true` as the response text. /// In all other cases, the endpoint will be denied access. Http(HttpAccessConfig), + #[serde(rename = "shared_token")] + /// Allows only clients that present one of the configured bearer tokens. + /// + /// The token is read from the `Authorization: Bearer ` request header, + /// or from the `?token=` URL query parameter as a fallback. + /// All other connections are denied. + /// + /// The token list can also be overridden by the `IROH_RELAY_ACCESS_TOKEN` environment + /// variable, which sets a single allowed token and takes precedence over the config + /// file value. A single value is used (rather than a comma-separated list) to avoid + /// restricting the character set of tokens. + /// + /// The token list must not be empty, and no token may be an empty string; + /// the server will fail to start if either condition is violated. + /// + /// # Example + /// + /// ```toml + /// access.shared_token = ["token-a", "token-b"] + /// ``` + SharedToken(Vec), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -181,12 +204,14 @@ struct HttpAccessConfig { bearer_token: Option, } -impl From for Arc { - fn from(cfg: AccessConfig) -> Self { +impl TryFrom for Arc { + type Error = AnyError; + + fn try_from(cfg: AccessConfig) -> Result { match cfg { - 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::Everyone => Ok(Arc::new(iroh_relay::server::AllowAll)), + AccessConfig::Allowlist(allow_list) => Ok(Arc::new(AllowlistAccess(allow_list))), + AccessConfig::Denylist(deny_list) => Ok(Arc::new(DenylistAccess(deny_list))), AccessConfig::Http(mut config) => { let client = reqwest::Client::builder() .use_rustls_tls() @@ -196,7 +221,18 @@ impl From for Arc { if let Ok(token) = std::env::var(ENV_HTTP_BEARER_TOKEN) { config.bearer_token = Some(token); } - Arc::new(HttpAccess { client, config }) + Ok(Arc::new(HttpAccess { client, config })) + } + AccessConfig::SharedToken(mut tokens) => { + // A single env var token replaces the entire list. A comma-separated list + // is intentionally not supported to avoid restricting the token character set. + if let Ok(env_token) = std::env::var(ENV_RELAY_ACCESS_TOKEN) { + tokens = vec![env_token]; + } + if tokens.is_empty() || tokens.iter().any(|t| t.is_empty()) { + bail_any!("access.shared_token must not be empty or contain empty strings"); + } + Ok(Arc::new(SharedTokenAccess(tokens))) } } } @@ -230,6 +266,19 @@ impl AccessControl for DenylistAccess { } } +/// An [`AccessControl`] admitting only clients that present one of the configured bearer tokens. +#[derive(Debug)] +struct SharedTokenAccess(Vec); + +impl AccessControl for SharedTokenAccess { + async fn on_connect(&self, request: &ClientRequest) -> Access { + match request.auth_token() { + Some(token) if self.0.contains(&token) => Access::Allow, + _ => Access::Deny { reason: None }, + } + } +} + /// An [`AccessControl`] that delegates the decision to an HTTP endpoint. #[derive(Debug)] struct HttpAccess { @@ -676,7 +725,7 @@ async fn build_relay_config(cfg: Config) -> Result { relay_config.tls = tls_config; relay_config.limits = limits; relay_config.key_cache_capacity = cfg.key_cache_capacity; - relay_config.access = cfg.access.clone().into(); + relay_config.access = cfg.access.clone().try_into()?; Some(relay_config) } else { None @@ -809,6 +858,39 @@ mod tests { bearer_token: Some("foo".to_string()) }) ); + + let config = r#" + access.shared_token = ["token-a", "token-b"] + "# + .to_string(); + let config = Config::from_str(dbg!(&config))?; + assert_eq!( + config.access, + AccessConfig::SharedToken(vec!["token-a".to_string(), "token-b".to_string()]) + ); + + Ok(()) + } + + #[tokio::test] + async fn test_access_token_empty_is_rejected() -> Result { + let config = r#" + access.shared_token = [] + "#; + let config = Config::from_str(config)?; + assert!( + build_relay_config(config).await.is_err(), + "empty token list should be rejected at startup" + ); + + let config = r#" + access.shared_token = [""] + "#; + let config = Config::from_str(config)?; + assert!( + build_relay_config(config).await.is_err(), + "empty string token should be rejected at startup" + ); Ok(()) }