Skip to main content

rings_node/native/
api_auth.rs

1//! Authentication and browser-origin policy for the native JSON-RPC listeners.
2//!
3//! A node serves two listeners. The internal listener is the operator's control surface and
4//! gates every route behind the Bearer token. The external listener is the surface peers dial to
5//! perform the HTTP handshake: its `nodeDid` and `answerOffer` methods are public, while its
6//! status and registry reads stay gated. The requirement for one request is the pure function
7//! `required(listener, body) = floor(listener) ⊔ class(body)` over the join-semilattice
8//! [`rings_rpc::method::AuthorizationClass`]; this module owns the listener floor and that
9//! function, and the endpoint layer only applies its verdict.
10
11use std::fs;
12use std::fs::OpenOptions;
13use std::io::Write;
14use std::net::SocketAddr;
15#[cfg(unix)]
16use std::os::unix::fs::OpenOptionsExt;
17#[cfg(unix)]
18use std::os::unix::fs::PermissionsExt;
19use std::path::Path;
20use std::path::PathBuf;
21
22use axum::http::header::HeaderName;
23use axum::http::header::HeaderValue;
24use axum::http::header::ACCEPT;
25use axum::http::header::AUTHORIZATION;
26use axum::http::header::CONTENT_TYPE;
27use axum::http::Method;
28use rand::rngs::OsRng;
29use rand::RngCore;
30use rings_rpc::method::AuthorizationClass;
31use subtle::ConstantTimeEq;
32use tower_http::cors::AllowOrigin;
33use tower_http::cors::CorsLayer;
34
35use crate::util::expand_home;
36
37/// The response header that names this node's crate version on every API response (#1104),
38/// exposed to browsers by the CORS policy so a client reads it before joining.
39pub(crate) const NODE_VERSION_HEADER: HeaderName = HeaderName::from_static("x-node-version");
40
41const API_TOKEN_BYTES: usize = 32;
42const MIN_API_TOKEN_LEN: usize = 32;
43const DEFAULT_API_TOKEN_FILE: &str = "api-token";
44
45/// Errors raised while configuring API authentication or managing its token file.
46#[derive(Debug, thiserror::Error)]
47pub enum ApiSecurityError {
48    /// A configured path could not be expanded or resolved.
49    #[error("invalid API token path: {0}")]
50    InvalidPath(String),
51    /// The token file could not be read, created, inspected, or written.
52    #[error("API token file operation failed for {path}: {source}")]
53    TokenFileIo {
54        /// Token file involved in the failed operation.
55        path: PathBuf,
56        /// Underlying filesystem error.
57        source: std::io::Error,
58    },
59    /// The token file grants access to group or other users.
60    #[error("API token file {path} must not be accessible by group or other users")]
61    InsecureTokenPermissions {
62        /// Insecure token file path.
63        path: PathBuf,
64    },
65    /// The token is too short or contains whitespace.
66    #[error("API token must contain at least {MIN_API_TOKEN_LEN} non-whitespace characters")]
67    InvalidToken,
68    /// A CORS origin is not one exact HTTP(S) origin.
69    #[error("invalid API allowed origin {0:?}")]
70    InvalidAllowedOrigin(String),
71    /// A non-loopback external listener was requested without explicit opt-in.
72    #[error("external API address {0} is non-loopback; set allow_remote_external_api explicitly")]
73    RemoteExternalApiDisabled(SocketAddr),
74}
75
76/// An API authentication token loaded from its owner-only file.
77pub struct LoadedApiToken {
78    path: PathBuf,
79    secret: String,
80}
81
82impl LoadedApiToken {
83    /// Return the token file path without exposing the secret.
84    pub fn path(&self) -> &Path {
85        &self.path
86    }
87
88    /// Borrow the token for configuring an authenticated client or server.
89    pub fn secret(&self) -> &str {
90        &self.secret
91    }
92
93    /// Consume the loaded file and return its token secret.
94    pub fn into_secret(self) -> String {
95        self.secret
96    }
97}
98
99/// The two JSON-RPC listeners a native node serves, distinguished by their authorization floor.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum ApiListener {
102    /// Loopback control listener: every route demands the token.
103    Internal,
104    /// Peer-facing listener: the HTTP handshake is public, everything else demands the token.
105    External,
106}
107
108impl ApiListener {
109    /// Return the least class this listener demands of any request, `floor(self)`.
110    pub fn authorization_floor(self) -> AuthorizationClass {
111        match self {
112            ApiListener::Internal => AuthorizationClass::Gated,
113            ApiListener::External => AuthorizationClass::Public,
114        }
115    }
116
117    /// Return the class this listener demands of one JSON-RPC body:
118    /// `floor(self) ⊔ class(body)`.
119    ///
120    /// `None` stands for a body that did not decode as JSON-RPC. It carries no classifiable call
121    /// and is `⊤`, so a decoding failure is reported only to an authenticated caller.
122    pub fn required_authorization(
123        self,
124        body: Option<&jsonrpc_core::Request>,
125    ) -> AuthorizationClass {
126        let body_class = body.map_or(AuthorizationClass::Gated, AuthorizationClass::of_request);
127        self.authorization_floor().join(body_class)
128    }
129}
130
131/// Immutable authentication and browser-origin policy shared by both listeners of one node.
132pub struct ApiSecurity {
133    token: Box<str>,
134    allowed_origins: Vec<HeaderValue>,
135    allow_remote_external_api: bool,
136}
137
138impl ApiSecurity {
139    /// Validate and construct an API policy from a token and exact allowed origins.
140    pub fn new(
141        token: String,
142        allowed_origins: &[String],
143        allow_remote_external_api: bool,
144    ) -> Result<Self, ApiSecurityError> {
145        validate_token(&token)?;
146        let allowed_origins = allowed_origins
147            .iter()
148            .map(|origin| parse_allowed_origin(origin))
149            .collect::<Result<Vec<_>, _>>()?;
150        Ok(Self {
151            token: token.into_boxed_str(),
152            allowed_origins,
153            allow_remote_external_api,
154        })
155    }
156
157    /// Return whether the request contains exactly one valid Bearer credential.
158    pub fn authorizes(&self, headers: &axum::http::HeaderMap) -> bool {
159        let mut values = headers.get_all(AUTHORIZATION).iter();
160        let Some(value) = values.next() else {
161            return false;
162        };
163        if values.next().is_some() {
164            return false;
165        }
166        let Ok(value) = value.to_str() else {
167            return false;
168        };
169        let Some((scheme, provided)) = value.split_once(' ') else {
170            return false;
171        };
172        scheme.eq_ignore_ascii_case("Bearer")
173            && provided.as_bytes().ct_eq(self.token.as_bytes()).into()
174    }
175
176    /// Build the explicit CORS layer for the internal operator listener.
177    pub fn cors_layer(&self) -> CorsLayer {
178        CorsLayer::new()
179            .allow_origin(AllowOrigin::list(self.allowed_origins.clone()))
180            .allow_methods([Method::GET, Method::POST, Method::OPTIONS])
181            .allow_headers([AUTHORIZATION, CONTENT_TYPE, ACCEPT])
182            .expose_headers([NODE_VERSION_HEADER])
183    }
184
185    /// Build the credential-less CORS layer for the peer-facing external listener so browser
186    /// clients from arbitrary DApp origins can complete HTTP WebRTC handshakes and preflights.
187    pub fn external_cors_layer(&self) -> CorsLayer {
188        CorsLayer::new()
189            .allow_origin(AllowOrigin::any())
190            .allow_methods([Method::GET, Method::POST, Method::OPTIONS])
191            .allow_headers([AUTHORIZATION, CONTENT_TYPE, ACCEPT])
192            .expose_headers([NODE_VERSION_HEADER])
193    }
194
195    /// Validate an external listener address against the explicit remote-bind policy.
196    pub fn validate_external_listener(&self, address: SocketAddr) -> Result<(), ApiSecurityError> {
197        if address.ip().is_loopback() || self.allow_remote_external_api {
198            Ok(())
199        } else {
200            Err(ApiSecurityError::RemoteExternalApiDisabled(address))
201        }
202    }
203}
204
205/// Resolve and load the configured API token without creating a missing file.
206pub fn load_api_token(
207    config_path: impl AsRef<Path>,
208    configured_path: Option<&str>,
209) -> Result<LoadedApiToken, ApiSecurityError> {
210    let path = resolve_api_token_path(config_path, configured_path)?;
211    read_api_token(path)
212}
213
214/// Resolve and load the configured API token, creating a random owner-only token if absent.
215pub fn load_or_create_api_token(
216    config_path: impl AsRef<Path>,
217    configured_path: Option<&str>,
218) -> Result<LoadedApiToken, ApiSecurityError> {
219    let path = resolve_api_token_path(config_path, configured_path)?;
220    match create_api_token(&path) {
221        Ok(token) => Ok(LoadedApiToken {
222            path,
223            secret: token,
224        }),
225        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => read_api_token(path),
226        Err(source) => Err(ApiSecurityError::TokenFileIo { path, source }),
227    }
228}
229
230/// Load and validate a token from an explicit file path.
231pub fn load_api_token_file(path: impl AsRef<Path>) -> Result<LoadedApiToken, ApiSecurityError> {
232    let path = expand_home(path.as_ref()).map_err(|error| {
233        ApiSecurityError::InvalidPath(format!("{}: {error}", path.as_ref().display()))
234    })?;
235    read_api_token(path)
236}
237
238fn resolve_api_token_path(
239    config_path: impl AsRef<Path>,
240    configured_path: Option<&str>,
241) -> Result<PathBuf, ApiSecurityError> {
242    let config_path = expand_home(config_path.as_ref()).map_err(|error| {
243        ApiSecurityError::InvalidPath(format!("{}: {error}", config_path.as_ref().display()))
244    })?;
245    let parent = config_path.parent().ok_or_else(|| {
246        ApiSecurityError::InvalidPath(format!("{} has no parent", config_path.display()))
247    })?;
248    let Some(configured_path) = configured_path else {
249        return Ok(parent.join(DEFAULT_API_TOKEN_FILE));
250    };
251    let expanded = expand_home(configured_path)
252        .map_err(|error| ApiSecurityError::InvalidPath(format!("{configured_path}: {error}")))?;
253    if expanded.is_absolute() {
254        Ok(expanded)
255    } else {
256        Ok(parent.join(expanded))
257    }
258}
259
260fn create_api_token(path: &Path) -> std::io::Result<String> {
261    if let Some(parent) = path.parent() {
262        fs::create_dir_all(parent)?;
263    }
264    let mut options = OpenOptions::new();
265    options.write(true).create_new(true);
266    #[cfg(unix)]
267    options.mode(0o600);
268    let mut file = options.open(path)?;
269    let mut bytes = [0_u8; API_TOKEN_BYTES];
270    OsRng.fill_bytes(&mut bytes);
271    let token = base64::encode_config(bytes, base64::URL_SAFE_NO_PAD);
272    file.write_all(token.as_bytes())?;
273    file.write_all(b"\n")?;
274    file.sync_all()?;
275    Ok(token)
276}
277
278fn read_api_token(path: PathBuf) -> Result<LoadedApiToken, ApiSecurityError> {
279    ensure_private_permissions(&path)?;
280    let secret = fs::read_to_string(&path)
281        .map_err(|source| ApiSecurityError::TokenFileIo {
282            path: path.clone(),
283            source,
284        })?
285        .trim()
286        .to_string();
287    validate_token(&secret)?;
288    Ok(LoadedApiToken { path, secret })
289}
290
291#[cfg(unix)]
292fn ensure_private_permissions(path: &Path) -> Result<(), ApiSecurityError> {
293    let metadata = fs::metadata(path).map_err(|source| ApiSecurityError::TokenFileIo {
294        path: path.to_path_buf(),
295        source,
296    })?;
297    if metadata.permissions().mode() & 0o077 == 0 {
298        Ok(())
299    } else {
300        Err(ApiSecurityError::InsecureTokenPermissions {
301            path: path.to_path_buf(),
302        })
303    }
304}
305
306#[cfg(not(unix))]
307fn ensure_private_permissions(_path: &Path) -> Result<(), ApiSecurityError> {
308    Ok(())
309}
310
311fn validate_token(token: &str) -> Result<(), ApiSecurityError> {
312    if token.len() < MIN_API_TOKEN_LEN || token.chars().any(char::is_whitespace) {
313        Err(ApiSecurityError::InvalidToken)
314    } else {
315        Ok(())
316    }
317}
318
319fn parse_allowed_origin(origin: &str) -> Result<HeaderValue, ApiSecurityError> {
320    let parsed = reqwest::Url::parse(origin)
321        .map_err(|_| ApiSecurityError::InvalidAllowedOrigin(origin.to_string()))?;
322    let exact_origin = matches!(parsed.scheme(), "http" | "https")
323        && parsed.host_str().is_some()
324        && parsed.username().is_empty()
325        && parsed.password().is_none()
326        && parsed.path() == "/"
327        && parsed.query().is_none()
328        && parsed.fragment().is_none();
329    if !exact_origin || origin == "*" {
330        return Err(ApiSecurityError::InvalidAllowedOrigin(origin.to_string()));
331    }
332    HeaderValue::from_str(parsed.origin().ascii_serialization().as_str())
333        .map_err(|_| ApiSecurityError::InvalidAllowedOrigin(origin.to_string()))
334}
335
336#[cfg(test)]
337mod tests {
338    use std::time::Duration;
339    use std::time::SystemTime;
340    use std::time::UNIX_EPOCH;
341
342    use rings_rpc::method::Method as RpcMethod;
343
344    use super::*;
345
346    const SEED_ENV: &str = "RINGS_DECODE_BOUNDARY_SEED";
347    const CASES_ENV: &str = "RINGS_DECODE_BOUNDARY_CASES";
348    const DEFAULT_CASES: usize = 128;
349
350    fn token() -> String {
351        "0123456789abcdef0123456789abcdef".to_string()
352    }
353
354    #[test]
355    fn bearer_auth_requires_exactly_one_constant_time_secret_match() {
356        let security = ApiSecurity::new(token(), &[], false);
357        assert!(security.is_ok());
358        let security = security.ok();
359        assert!(security.is_some());
360        let Some(security) = security else {
361            return;
362        };
363        let mut headers = axum::http::HeaderMap::new();
364        headers.insert(
365            AUTHORIZATION,
366            HeaderValue::from_static("Bearer 0123456789abcdef0123456789abcdef"),
367        );
368        assert!(security.authorizes(&headers));
369
370        headers.append(
371            AUTHORIZATION,
372            HeaderValue::from_static("Bearer 0123456789abcdef0123456789abcdef"),
373        );
374        assert!(!security.authorizes(&headers));
375
376        headers.remove(AUTHORIZATION);
377        headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer wrong"));
378        assert!(!security.authorizes(&headers));
379    }
380
381    #[test]
382    fn the_listener_floor_joins_with_the_body_class() {
383        let handshake = jsonrpc_core::Request::Batch(vec![call("nodeDid"), call("answerOffer")]);
384        let status = jsonrpc_core::Request::Single(call("nodeInfo"));
385        assert_eq!(
386            ApiListener::External.required_authorization(Some(&handshake)),
387            AuthorizationClass::Public
388        );
389        assert_eq!(
390            ApiListener::External.required_authorization(Some(&status)),
391            AuthorizationClass::Gated
392        );
393        assert_eq!(
394            ApiListener::External.required_authorization(None),
395            AuthorizationClass::Gated
396        );
397        assert_eq!(
398            ApiListener::Internal.required_authorization(Some(&handshake)),
399            AuthorizationClass::Gated
400        );
401    }
402
403    fn call(method: &str) -> jsonrpc_core::Call {
404        jsonrpc_core::Call::MethodCall(jsonrpc_core::MethodCall {
405            jsonrpc: Some(jsonrpc_core::Version::V2),
406            method: method.to_string(),
407            params: jsonrpc_core::Params::None,
408            id: jsonrpc_core::Id::Num(1),
409        })
410    }
411
412    #[test]
413    fn generated_jsonrpc_decode_boundary_bodies_classify_without_public_fail_open() {
414        let mut generator = DecodeBoundaryGenerator::named("node-jsonrpc");
415        let cases = generated_case_count();
416        eprintln!(
417            "{SEED_ENV}={} {CASES_ENV}={cases} target=node-jsonrpc",
418            generator.seed()
419        );
420
421        for _ in 0..cases {
422            let body = generated_jsonrpc_body(&mut generator);
423            let decoded = crate::native::endpoint::DecodedJsonRpc::decode(&body);
424            let external = ApiListener::External.required_authorization(decoded.request());
425            let internal = ApiListener::Internal.required_authorization(decoded.request());
426            assert_eq!(internal, AuthorizationClass::Gated);
427            match decoded.request() {
428                None => assert_eq!(external, AuthorizationClass::Gated),
429                Some(request) => assert_eq!(
430                    external == AuthorizationClass::Public,
431                    every_call_is_public(request)
432                ),
433            }
434        }
435    }
436
437    fn generated_jsonrpc_body(generator: &mut DecodeBoundaryGenerator) -> Vec<u8> {
438        match generator.usize(6) {
439            0 => generator.bytes(2048),
440            1 => method_call(generator, true).into_bytes(),
441            2 => method_call(generator, false).into_bytes(),
442            3 => batch_call(generator).into_bytes(),
443            4 => br#"{"jsonrpc":"2.0","id":4}"#.to_vec(),
444            _ => br#"[{"jsonrpc":"2.0","id":1}]"#.to_vec(),
445        }
446    }
447
448    fn method_call(generator: &mut DecodeBoundaryGenerator, include_id: bool) -> String {
449        let method = generator.method();
450        if include_id {
451            format!(
452                r#"{{"jsonrpc":"2.0","id":{},"method":"{method}","params":[]}}"#,
453                generator.next_u64()
454            )
455        } else {
456            format!(r#"{{"jsonrpc":"2.0","method":"{method}","params":[]}}"#)
457        }
458    }
459
460    fn batch_call(generator: &mut DecodeBoundaryGenerator) -> String {
461        format!(
462            "[{},{}]",
463            method_call(generator, true),
464            method_call(generator, true)
465        )
466    }
467
468    fn every_call_is_public(request: &jsonrpc_core::Request) -> bool {
469        match request {
470            jsonrpc_core::Request::Single(call) => call_is_public(call),
471            jsonrpc_core::Request::Batch(calls) => {
472                calls.len() <= rings_rpc::method::MAX_PUBLIC_BATCH_CALLS
473                    && calls.iter().all(call_is_public)
474            }
475        }
476    }
477
478    fn call_is_public(call: &jsonrpc_core::Call) -> bool {
479        match call {
480            jsonrpc_core::Call::MethodCall(call) => method_is_public(call.method.as_str()),
481            jsonrpc_core::Call::Notification(notification) => {
482                method_is_public(notification.method.as_str())
483            }
484            jsonrpc_core::Call::Invalid { .. } => false,
485        }
486    }
487
488    fn method_is_public(name: &str) -> bool {
489        matches!(
490            RpcMethod::try_from(name),
491            Ok(RpcMethod::NodeDid | RpcMethod::AnswerOffer | RpcMethod::AcceptAnswer)
492        )
493    }
494
495    fn generated_case_count() -> usize {
496        std::env::var(CASES_ENV)
497            .ok()
498            .and_then(|value| value.parse::<usize>().ok())
499            .map(|cases| cases.clamp(1, 50_000))
500            .unwrap_or(DEFAULT_CASES)
501    }
502
503    struct DecodeBoundaryGenerator {
504        seed: u64,
505        state: u64,
506    }
507
508    impl DecodeBoundaryGenerator {
509        fn named(label: &str) -> Self {
510            let seed = std::env::var(SEED_ENV)
511                .ok()
512                .and_then(|value| value.parse::<u64>().ok())
513                .unwrap_or_else(time_seed);
514            let state = fold_label(seed, label);
515            Self { seed, state }
516        }
517
518        fn seed(&self) -> u64 {
519            self.seed
520        }
521
522        fn next_u64(&mut self) -> u64 {
523            self.state = splitmix64(self.state);
524            self.state
525        }
526
527        fn bytes(&mut self, max_len: usize) -> Vec<u8> {
528            let len = self.usize(max_len.saturating_add(1));
529            let mut bytes = Vec::with_capacity(len);
530            for _ in 0..len {
531                bytes.push(self.byte());
532            }
533            bytes
534        }
535
536        fn byte(&mut self) -> u8 {
537            u8::try_from(self.next_u64() & 0xff).unwrap_or(0)
538        }
539
540        fn usize(&mut self, upper: usize) -> usize {
541            let upper = u64::try_from(upper).unwrap_or(u64::MAX).max(1);
542            usize::try_from(self.next_u64() % upper).unwrap_or(0)
543        }
544
545        fn method(&mut self) -> &'static str {
546            match self.usize(5) {
547                0 => "nodeDid",
548                1 => "answerOffer",
549                2 => "nodeInfo",
550                3 => "disconnect",
551                _ => "generatedUnknown",
552            }
553        }
554    }
555
556    fn time_seed() -> u64 {
557        let duration = SystemTime::now()
558            .duration_since(UNIX_EPOCH)
559            .unwrap_or(Duration::ZERO);
560        let nanos = u64::try_from(duration.as_nanos()).unwrap_or(duration.as_secs());
561        nanos ^ u64::from(std::process::id())
562    }
563
564    fn fold_label(seed: u64, label: &str) -> u64 {
565        label
566            .bytes()
567            .fold(seed, |state, byte| splitmix64(state ^ u64::from(byte)))
568    }
569
570    fn splitmix64(mut state: u64) -> u64 {
571        state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
572        let mut mixed = state;
573        mixed = (mixed ^ (mixed >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
574        mixed = (mixed ^ (mixed >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
575        mixed ^ (mixed >> 31)
576    }
577
578    #[test]
579    fn wildcard_and_non_origin_cors_values_are_rejected() {
580        for origin in ["*", "https://example.com/path", "file:///tmp/page"] {
581            assert!(matches!(
582                ApiSecurity::new(token(), &[origin.to_string()], false),
583                Err(ApiSecurityError::InvalidAllowedOrigin(_))
584            ));
585        }
586        assert!(ApiSecurity::new(token(), &["https://example.com".to_string()], false).is_ok());
587    }
588
589    #[test]
590    fn remote_external_bind_requires_explicit_opt_in() {
591        let local = "127.0.0.1:50001".parse::<SocketAddr>();
592        let remote = "0.0.0.0:50001".parse::<SocketAddr>();
593        let security = ApiSecurity::new(token(), &[], false);
594        assert!(matches!(
595            (security, local, remote),
596            (Ok(security), Ok(local), Ok(remote))
597                if security.validate_external_listener(local).is_ok()
598                    && matches!(
599                        security.validate_external_listener(remote),
600                        Err(ApiSecurityError::RemoteExternalApiDisabled(_))
601                    )
602        ));
603    }
604
605    #[test]
606    fn generated_token_is_reused_from_an_owner_only_file() {
607        let root = std::env::temp_dir().join(format!("rings-api-auth-{}", uuid::Uuid::new_v4()));
608        let config = root.join("config.yaml");
609        let first = load_or_create_api_token(&config, None);
610        let second = load_or_create_api_token(&config, None);
611        assert!(matches!(
612            (&first, &second),
613            (Ok(first), Ok(second))
614                if first.secret() == second.secret()
615                    && first.path() == root.join(DEFAULT_API_TOKEN_FILE)
616        ));
617        let _ = fs::remove_file(root.join(DEFAULT_API_TOKEN_FILE));
618        let _ = fs::remove_dir(root);
619    }
620}