Skip to main content

zebra_rpc/config/
rpc.rs

1//! RPC config
2
3use std::{fmt, net::SocketAddr, path::PathBuf};
4
5use serde::{Deserialize, Serialize};
6
7use zebra_chain::common::default_cache_dir;
8
9/// A [`String`] whose `Debug` output is redacted, so secrets do not reach the logs.
10///
11/// Serialization is unaffected. Use [`RedactedString::as_str()`] to read the contents.
12#[derive(Clone, Default, Eq, PartialEq, Deserialize, Serialize)]
13#[serde(transparent)]
14pub struct RedactedString(String);
15
16impl fmt::Debug for RedactedString {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        f.pad("[REDACTED]")
19    }
20}
21
22impl RedactedString {
23    /// Returns the secret contents.
24    pub fn as_str(&self) -> &str {
25        &self.0
26    }
27}
28
29impl<S> From<S> for RedactedString
30where
31    S: Into<String>,
32{
33    fn from(value: S) -> Self {
34        Self(value.into())
35    }
36}
37
38/// The error returned when the static RPC credentials in [`Config`] are incomplete or unreadable.
39#[derive(Debug, thiserror::Error)]
40#[non_exhaustive]
41pub enum StaticCredentialsError {
42    /// A password is configured without a user.
43    #[error("rpc.rpc_password or rpc.rpc_password_file is set, but rpc.rpc_user is missing")]
44    MissingUser,
45
46    /// A user is configured without a password.
47    #[error("rpc.rpc_user is set, but neither rpc.rpc_password nor rpc.rpc_password_file is")]
48    MissingPassword,
49
50    /// The configured user is an empty string.
51    #[error("rpc.rpc_user must not be empty")]
52    EmptyUser,
53
54    /// The configured user contains a colon, so no HTTP Basic client could send it.
55    #[error("rpc.rpc_user must not contain ':', which separates the user from the password in HTTP Basic authentication")]
56    UserContainsColon,
57
58    /// The configured or loaded password is an empty string.
59    #[error("the RPC password must not be empty")]
60    EmptyPassword,
61
62    /// The password file could not be read.
63    #[error("reading rpc.rpc_password_file {path}: {source}")]
64    ReadPasswordFile {
65        /// The configured path.
66        path: PathBuf,
67        /// The I/O error.
68        source: std::io::Error,
69    },
70}
71
72/// RPC configuration section.
73#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
74#[serde(deny_unknown_fields, default)]
75pub struct Config {
76    /// IP address and port for the RPC server.
77    ///
78    /// Note: The RPC server is disabled by default.
79    /// To enable the RPC server, set a listen address in the config:
80    /// ```toml
81    /// [rpc]
82    /// listen_addr = '127.0.0.1:8232'
83    /// ```
84    ///
85    /// The recommended ports for the RPC server are:
86    /// - Mainnet: 127.0.0.1:8232
87    /// - Testnet: 127.0.0.1:18232
88    ///
89    /// # Security
90    ///
91    /// If you bind Zebra's RPC port to a public IP address,
92    /// anyone on the internet can send transactions via your node.
93    /// They can also query your node's state.
94    pub listen_addr: Option<SocketAddr>,
95
96    /// IP address and port for the indexer RPC server.
97    ///
98    /// Note: The indexer RPC server is disabled by default.
99    /// To enable the indexer RPC server, compile `zebrad` with the
100    /// `indexer` feature flag and set a listen address in the config:
101    /// ```toml
102    /// [rpc]
103    /// indexer_listen_addr = '127.0.0.1:8230'
104    /// ```
105    ///
106    /// # Security
107    ///
108    /// If you bind Zebra's indexer RPC port to a public IP address,
109    /// anyone on the internet can query your node's state.
110    pub indexer_listen_addr: Option<SocketAddr>,
111
112    /// IP address and port for the lightwalletd-compatible gRPC server.
113    ///
114    /// Note: The lightwalletd gRPC server is disabled by default.
115    /// To enable it, set a listen address in the config:
116    /// ```toml
117    /// [rpc]
118    /// lightwalletd_listen_addr = '127.0.0.1:9067'
119    /// ```
120    ///
121    /// This server implements the lightwalletd `CompactTxStreamer` service, so
122    /// Zcash light clients can connect directly to Zebra.
123    ///
124    /// This server is experimental: its behaviour and configuration may change
125    /// in any release, including in ways that break clients.
126    ///
127    /// # Security
128    ///
129    /// The port serves plaintext HTTP/2, with no TLS and no authentication —
130    /// cookie authentication does not apply to it. Anyone who can reach the
131    /// port can query your node's state and send transactions through it, and
132    /// anyone on the network path can read and modify the traffic, including
133    /// the addresses a light client is querying. Terminate TLS in a reverse
134    /// proxy, and bind Zebra to a loopback or private address.
135    ///
136    /// Run this on infrastructure you operate, not on end users' machines: a
137    /// loopback port is reachable by any local process, and by web pages
138    /// loaded in a browser on that machine.
139    pub lightwalletd_listen_addr: Option<SocketAddr>,
140
141    /// The number of threads used to process RPC requests and responses.
142    ///
143    /// This field is deprecated and could be removed in a future release.
144    /// We keep it just for backward compatibility but it actually do nothing.
145    /// It was something configurable when the RPC server was based in the jsonrpc-core crate,
146    /// not anymore since we migrated to jsonrpsee.
147    // TODO: Prefix this field name with an underscore so it's clear that it's now unused, and
148    //       use serde(rename) to continue successfully deserializing old configs.
149    pub parallel_cpu_threads: usize,
150
151    /// Test-only option that makes Zebra say it is at the chain tip,
152    /// no matter what the estimated height or local clock is.
153    pub debug_force_finished_sync: bool,
154
155    /// The directory where Zebra stores RPC cookies.
156    pub cookie_dir: PathBuf,
157
158    /// Enable cookie-based authentication for RPCs.
159    ///
160    /// Ignored when static credentials are configured, see [`Self::rpc_user`].
161    pub enable_cookie_auth: bool,
162
163    /// Username for static HTTP Basic RPC authentication.
164    ///
165    /// Must be set together with `rpc_password` or `rpc_password_file`, and must not
166    /// contain `:`. When set, every request to `listen_addr` needs these credentials, and
167    /// no cookie is written. The indexer and lightwalletd gRPC servers have no authentication.
168    ///
169    /// # Security
170    ///
171    /// HTTP Basic authentication sends the password unencrypted with every request.
172    pub rpc_user: Option<String>,
173
174    /// Password for static HTTP Basic RPC authentication.
175    ///
176    /// Prefer `rpc_password_file`, which keeps the secret out of the config file.
177    /// It can't be set through an environment variable.
178    pub rpc_password: Option<RedactedString>,
179
180    /// Path to a file containing the password for static HTTP Basic RPC authentication.
181    ///
182    /// Read once at startup with trailing newlines trimmed, so a new password needs a restart.
183    /// Takes precedence over `rpc_password`.
184    pub rpc_password_file: Option<PathBuf>,
185
186    /// The maximum size of the response body in bytes.
187    pub max_response_body_size: u32,
188}
189
190impl Config {
191    /// Returns `true` if any static credential field is set.
192    pub(crate) fn uses_static_auth(&self) -> bool {
193        self.rpc_user.is_some() || self.rpc_password.is_some() || self.rpc_password_file.is_some()
194    }
195
196    /// Returns the static user and password, `None` if they are not configured,
197    /// or an error if the configuration is partial or the password file is unreadable.
198    pub(crate) fn static_credentials(
199        &self,
200    ) -> Result<Option<(String, RedactedString)>, StaticCredentialsError> {
201        if !self.uses_static_auth() {
202            return Ok(None);
203        }
204
205        let user = self
206            .rpc_user
207            .clone()
208            .ok_or(StaticCredentialsError::MissingUser)?;
209        if user.is_empty() {
210            return Err(StaticCredentialsError::EmptyUser);
211        }
212        if user.contains(':') {
213            return Err(StaticCredentialsError::UserContainsColon);
214        }
215
216        let password = match (&self.rpc_password_file, &self.rpc_password) {
217            (Some(path), _) => {
218                let contents = std::fs::read_to_string(path).map_err(|source| {
219                    StaticCredentialsError::ReadPasswordFile {
220                        path: path.clone(),
221                        source,
222                    }
223                })?;
224                RedactedString::from(contents.trim_end_matches(['\r', '\n']))
225            }
226            (None, Some(password)) => password.clone(),
227            (None, None) => return Err(StaticCredentialsError::MissingPassword),
228        };
229        if password.as_str().is_empty() {
230            return Err(StaticCredentialsError::EmptyPassword);
231        }
232
233        Ok(Some((user, password)))
234    }
235}
236
237// This impl isn't derivable because it depends on features.
238#[allow(clippy::derivable_impls)]
239impl Default for Config {
240    fn default() -> Self {
241        Self {
242            // Disable RPCs by default.
243            listen_addr: None,
244
245            // Disable indexer RPCs by default.
246            indexer_listen_addr: None,
247
248            // Disable the lightwalletd gRPC server by default.
249            lightwalletd_listen_addr: None,
250
251            // Use multiple threads, because we pause requests during getblocktemplate long polling
252            parallel_cpu_threads: 0,
253
254            // Debug options are always off by default.
255            debug_force_finished_sync: false,
256
257            // Use the default cache dir for the auth cookie.
258            cookie_dir: default_cache_dir(),
259
260            // Enable cookie-based authentication by default.
261            enable_cookie_auth: true,
262
263            rpc_user: None,
264            rpc_password: None,
265            rpc_password_file: None,
266
267            // 50 MiB
268            max_response_body_size: 52_428_800,
269        }
270    }
271}
272
273#[cfg(test)]
274mod tests {
275    use std::io::Write;
276
277    use super::{Config, RedactedString, StaticCredentialsError};
278
279    fn config_with(user: Option<&str>, password: Option<&str>) -> Config {
280        Config {
281            rpc_user: user.map(str::to_string),
282            rpc_password: password.map(RedactedString::from),
283            ..Config::default()
284        }
285    }
286
287    #[test]
288    fn static_credentials_from_config_password() {
289        let config = config_with(Some("user"), Some("hunter2"));
290        assert_eq!(
291            config.static_credentials().unwrap(),
292            Some(("user".to_string(), RedactedString::from("hunter2")))
293        );
294    }
295
296    /// Zebra logs the whole config at startup, so the password must never appear in it.
297    #[test]
298    fn config_debug_does_not_contain_rpc_password() {
299        let config = config_with(Some("user"), Some("hunter2"));
300        let debug = format!("{config:?}");
301        assert!(!debug.contains("hunter2"), "{debug}");
302        assert!(debug.contains("[REDACTED]"), "{debug}");
303    }
304
305    #[test]
306    fn static_credentials_reject_partial_config() {
307        let cases = [
308            ("user without password", Some("user"), None),
309            ("password without user", None, Some("hunter2")),
310            ("empty user", Some(""), Some("hunter2")),
311            ("user with a colon", Some("us:er"), Some("hunter2")),
312            ("empty password", Some("user"), Some("")),
313        ];
314
315        for (case, user, password) in cases {
316            let result = config_with(user, password).static_credentials();
317            assert!(result.is_err(), "{case} should be rejected, got {result:?}");
318        }
319    }
320
321    #[test]
322    fn static_credentials_from_password_file_take_precedence_and_trim_newline() {
323        let mut file = tempfile::NamedTempFile::new().unwrap();
324        file.write_all(b"from-file\n").unwrap();
325
326        let config = Config {
327            rpc_password_file: Some(file.path().to_path_buf()),
328            ..config_with(Some("user"), Some("from-config"))
329        };
330        assert_eq!(
331            config.static_credentials().unwrap(),
332            Some(("user".to_string(), RedactedString::from("from-file")))
333        );
334    }
335
336    #[test]
337    fn static_credentials_reject_missing_password_file() {
338        let config = Config {
339            rpc_password_file: Some("/nonexistent/rpc-password".into()),
340            ..config_with(Some("user"), None)
341        };
342        assert!(matches!(
343            config.static_credentials(),
344            Err(StaticCredentialsError::ReadPasswordFile { .. })
345        ));
346    }
347}