1
//! Types and functions to configure a Tor Relay.
2

            
3
// TODO: It would be nice to remove the builder aspect of these config objects, as we don't need
4
// them for arti-relay. But I don't think we can do so while still using tor-config. See:
5
// https://gitlab.torproject.org/tpo/core/arti/-/issues/2253
6

            
7
mod bandwidth;
8
mod dns;
9
mod listen;
10
mod relay;
11
mod testing;
12

            
13
use std::borrow::Cow;
14
use std::path::PathBuf;
15

            
16
use derive_deftly::Deftly;
17
use derive_more::AsRef;
18
use directories::ProjectDirs;
19
use fs_mistrust::{Mistrust, MistrustBuilder};
20
use std::sync::LazyLock;
21
use tor_chanmgr::{ChannelConfig, ChannelConfigBuilder};
22
use tor_circmgr::{CircuitTiming, PathConfig, PreemptiveCircuitConfig};
23
use tor_config::derive::prelude::*;
24
use tor_config::{
25
    ConfigBuildError, ExplicitOrAuto, extend_builder::extend_with_replace, mistrust::BuilderExt,
26
};
27
use tor_config_path::{CfgPath, CfgPathError, CfgPathResolver};
28
use tor_config_shared::metrics::{MetricsConfig, MetricsConfigBuilder};
29
use tor_dircommon::authority::AuthorityContacts;
30
use tor_dircommon::config::{NetworkConfig, NetworkConfigBuilder};
31
use tor_dircommon::fallback::FallbackList;
32
use tor_guardmgr::bridge::BridgeConfig;
33
use tor_guardmgr::{VanguardConfig, VanguardConfigBuilder, VanguardMode};
34
use tor_keymgr::config::{ArtiKeystoreConfig, ArtiKeystoreConfigBuilder};
35
use tracing::metadata::Level;
36
use tracing_subscriber::filter::EnvFilter;
37

            
38
pub(crate) use bandwidth::{BandwidthConfig, BandwidthConfigBuilder};
39
pub(crate) use dns::{DnsConfig, DnsConfigBuilder};
40
pub(crate) use listen::Listen;
41
pub(crate) use relay::Advertise;
42
pub(crate) use relay::{RelayConfig, RelayConfigBuilder};
43
pub(crate) use testing::{TestingConfig, TestingConfigBuilder};
44

            
45
/// Paths used for default configuration files.
46
1
pub(crate) fn default_config_paths() -> Result<Vec<PathBuf>, CfgPathError> {
47
    // the base path resolver includes the 'ARTI_RELAY_CONFIG' variable
48
1
    let resolver = base_resolver();
49
1
    [
50
1
        "${ARTI_RELAY_CONFIG}/arti-relay.toml",
51
1
        "${ARTI_RELAY_CONFIG}/arti-relay.d/",
52
1
    ]
53
1
    .into_iter()
54
2
    .map(|f| CfgPath::new(f.into()).path(&resolver))
55
    .collect()
56
1
}
57

            
58
/// A [`CfgPathResolver`] with the base variables configured for a Tor relay.
59
///
60
/// A relay should have a single `CfgPathResolver` that is passed around where needed to ensure that
61
/// all parts of the relay are resolving paths consistently using the same variables.
62
/// If you need to resolve a path,
63
/// you likely want a reference to the existing resolver,
64
/// and not to create a new one here.
65
///
66
/// The supported variables are:
67
///   - `ARTI_RELAY_CACHE`:
68
///     An arti-specific cache directory.
69
///   - `ARTI_RELAY_CONFIG`:
70
///     An arti-specific configuration directory.
71
///   - `ARTI_RELAY_LOCAL_DATA`:
72
///     An arti-specific directory in the user's "local data" space.
73
///   - `PROGRAM_DIR`:
74
///     The directory of the currently executing binary.
75
///     See documentation for [`std::env::current_exe`] for security notes.
76
///   - `USER_HOME`:
77
///     The user's home directory.
78
///
79
/// These variables are implemented using the [`directories`] crate,
80
/// and so should use appropriate system-specific overrides under the hood.
81
/// (Some of those overrides are based on environment variables.)
82
/// For more information, see that crate's documentation.
83
//
84
// NOTE: We intentionally don't expose an `ARTI_RELAY_SHARED_DATA`
85
// (analogous to `ARTI_SHARED_DATA` in arti).
86
// This is almost certainly never intended over `ARTI_RELAY_LOCAL_DATA`,
87
// so by removing it we don't need to worry about bugs from mixing them up.
88
// We can introduce it later if really needed.
89
2
pub(crate) fn base_resolver() -> CfgPathResolver {
90
2
    let arti_relay_cache = project_dirs().map(|x| Cow::Owned(x.cache_dir().to_owned()));
91
2
    let arti_relay_config = project_dirs().map(|x| Cow::Owned(x.config_dir().to_owned()));
92
2
    let arti_relay_local_data = project_dirs().map(|x| Cow::Owned(x.data_local_dir().to_owned()));
93
2
    let program_dir = get_program_dir().map(Cow::Owned);
94
2
    let user_home = tor_config_path::home().map(Cow::Borrowed);
95

            
96
2
    let mut resolver = CfgPathResolver::default();
97

            
98
2
    resolver.set_var("ARTI_RELAY_CACHE", arti_relay_cache);
99
2
    resolver.set_var("ARTI_RELAY_CONFIG", arti_relay_config);
100
2
    resolver.set_var("ARTI_RELAY_LOCAL_DATA", arti_relay_local_data);
101
2
    resolver.set_var("PROGRAM_DIR", program_dir);
102
2
    resolver.set_var("USER_HOME", user_home);
103

            
104
2
    resolver
105
2
}
106

            
107
/// The directory holding the currently executing program.
108
3
fn get_program_dir() -> Result<PathBuf, CfgPathError> {
109
3
    let binary = std::env::current_exe().map_err(|_| CfgPathError::NoProgramPath)?;
110
3
    let directory = binary.parent().ok_or(CfgPathError::NoProgramDir)?;
111
3
    Ok(directory.to_owned())
112
3
}
113

            
114
/// A `ProjectDirs` object for Arti relays.
115
7
fn project_dirs() -> Result<&'static ProjectDirs, CfgPathError> {
116
    /// lazy lock holding the ProjectDirs object.
117
    static PROJECT_DIRS: LazyLock<Option<ProjectDirs>> =
118
1
        LazyLock::new(|| ProjectDirs::from("org", "torproject", "Arti-Relay"));
119

            
120
7
    PROJECT_DIRS.as_ref().ok_or(CfgPathError::NoProjectDirs)
121
7
}
122

            
123
/// A configuration used by a TorRelay.
124
///
125
/// This is a builder so that it works with tor-config.
126
/// We don't expect to ever use it as a builder since we don't provide this as a public rust API.
127
#[derive(Clone, Deftly, Debug, Eq, PartialEq, AsRef)]
128
#[derive_deftly(TorConfig)]
129
#[deftly(tor_config(no_default_trait))]
130
#[deftly(tor_config(post_build = "TorRelayConfig::post_build_validate"))]
131
#[non_exhaustive]
132
pub(crate) struct TorRelayConfig {
133
    /// Configuration for the "relay" part of the relay.
134
    // TODO: Add a better doc comment here once we figure out exactly how we want the config to be
135
    // structured.
136
    #[deftly(tor_config(sub_builder))]
137
    pub(crate) relay: RelayConfig,
138

            
139
    /// Information about the Tor network we want to connect to.
140
    #[deftly(tor_config(sub_builder))]
141
    pub(crate) tor_network: NetworkConfig,
142

            
143
    /// Logging configuration
144
    #[deftly(tor_config(sub_builder))]
145
    pub(crate) logging: LoggingConfig,
146

            
147
    /// Metrics configuration
148
    #[deftly(tor_config(sub_builder))]
149
    pub(crate) metrics: MetricsConfig,
150

            
151
    /// Directories for storing information on disk
152
    #[deftly(tor_config(sub_builder))]
153
    pub(crate) storage: StorageConfig,
154

            
155
    /// Information about how to build paths through the network.
156
    #[deftly(tor_config(sub_builder))]
157
    pub(crate) channel: ChannelConfig,
158

            
159
    /// Configuration for system resources
160
    #[deftly(tor_config(sub_builder))]
161
    pub(crate) system: SystemConfig,
162

            
163
    /// Information about how to build paths through the network.
164
    // We don't expose this field in the config.
165
    #[deftly(tor_config(skip, build = "|_| Default::default()"))]
166
    // Needed to implement `CircMgrConfig`.
167
    #[as_ref]
168
    pub(crate) path_rules: PathConfig,
169

            
170
    /// Information about vanguards.
171
    // We don't expose this field in the config.
172
    #[deftly(tor_config(
173
        skip,
174
        build = r#"|_|
175
        VanguardConfigBuilder::default()
176
            .mode(ExplicitOrAuto::Explicit(VanguardMode::Disabled))
177
            .build()
178
            .expect("Could not build a disabled `VanguardConfig`")"#
179
    ))]
180
    // Needed to implement `CircMgrConfig`.
181
    #[as_ref]
182
    pub(crate) vanguards: VanguardConfig,
183

            
184
    /// Information about how to retry and expire circuits and request for circuits.
185
    // We don't expose this field in the config.
186
    #[deftly(tor_config(skip, build = "|_| Default::default()"))]
187
    // Needed to implement `CircMgrConfig`.
188
    #[as_ref]
189
    pub(crate) circuit_timing: CircuitTiming,
190

            
191
    /// Information about preemptive circuits.
192
    // We don't expose this field in the config.
193
    #[deftly(tor_config(skip, build = "|_| disabled_preemptive_circuits()"))]
194
    // Needed to implement `CircMgrConfig`.
195
    #[as_ref]
196
    pub(crate) preemptive_circuits: PreemptiveCircuitConfig,
197
}
198

            
199
/// Return a [`PreemptiveCircuitConfig`] that disables preemptive circuits.
200
///
201
/// A threshold of 0 disables them since the relay has no use for them.
202
fn disabled_preemptive_circuits() -> PreemptiveCircuitConfig {
203
    PreemptiveCircuitConfig::builder()
204
        .disable_at_threshold(0)
205
        .build()
206
        .expect("Could not build a disabled `PreemptiveCircuitConfig`")
207
}
208

            
209
impl TorRelayConfig {
210
    /// Validate the config after building it.
211
    fn post_build_validate(self) -> Result<Self, ConfigBuildError> {
212
        let testing_options_changed = self.relay.testing != TestingConfig::default();
213
        let default_authorities_used = self
214
            .tor_network
215
            .authorities()
216
            .intersects(&AuthorityContacts::default());
217

            
218
        // The testing options are refused on the real/main network. If a single testing
219
        // value is set, then we require custom authorities.
220
        if testing_options_changed && default_authorities_used {
221
            return Err(ConfigBuildError::Inconsistent {
222
                fields: vec![
223
                    "relay.testing".to_owned(),
224
                    "tor_network.authorities".to_owned(),
225
                ],
226
                problem: "Testing options require custom directory authorities".to_owned(),
227
            });
228
        }
229
        Ok(self)
230
    }
231
}
232

            
233
impl tor_config::load::TopLevel for TorRelayConfig {
234
    type Builder = TorRelayConfigBuilder;
235
}
236

            
237
impl tor_circmgr::CircMgrConfig for TorRelayConfig {}
238

            
239
// Needed to implement `GuardMgrConfig`.
240
impl AsRef<FallbackList> for TorRelayConfig {
241
    fn as_ref(&self) -> &FallbackList {
242
        self.tor_network.fallback_caches()
243
    }
244
}
245

            
246
// Needed to implement `GuardMgrConfig`.
247
impl AsRef<[BridgeConfig]> for TorRelayConfig {
248
    fn as_ref(&self) -> &[BridgeConfig] {
249
        // Relays don't use bridges.
250
        &[]
251
    }
252
}
253

            
254
impl tor_guardmgr::GuardMgrConfig for TorRelayConfig {
255
    fn bridges_enabled(&self) -> bool {
256
        // Relays don't use bridges.
257
        false
258
    }
259
}
260

            
261
/// Default log level.
262
pub(crate) const DEFAULT_LOG_LEVEL: Level = Level::INFO;
263

            
264
/// Logging configuration options.
265
#[derive(Debug, Clone, Deftly, Eq, PartialEq)]
266
#[derive_deftly(TorConfig)]
267
#[deftly(tor_config(pre_build = "Self::validate"))]
268
#[non_exhaustive]
269
pub(crate) struct LoggingConfig {
270
    /// Filtering directives that determine tracing levels as described at
271
    /// <https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/targets/struct.Targets.html#impl-FromStr-for-Targets>
272
    ///
273
    /// You can override this setting with the `-l`, `--log-level` command line parameter.
274
    ///
275
    /// Example: "info,tor_proto::channel=trace"
276
    #[deftly(tor_config(default = "DEFAULT_LOG_LEVEL.to_string()"))]
277
    pub(crate) console: String,
278

            
279
    /// If set to false, we avoid logging sensitive information at level `info` or higher.
280
    /// This `info` level distinction is not enforced through any technical means,
281
    /// but is according to our `doc/dev/Safelogging.md` guidelines.
282
    ///
283
    /// If set to true, we disable safe logging on all logs,
284
    /// and store potentially sensitive information at all log levels.
285
    ///
286
    /// This can be useful for debugging, but it increases the value of your logs to an attacker.
287
    /// Do not turn this on in production unless you have a good log rotation mechanism.
288
    #[deftly(tor_config(default))]
289
    pub(crate) log_sensitive_information: bool,
290

            
291
    /// Configuration for logging spans with OpenTelemetry.
292
    #[deftly(tor_config(
293
        sub_builder,
294
        cfg = r#" feature = "opentelemetry" "#,
295
        cfg_desc = "with opentelemetry support"
296
    ))]
297
    opentelemetry: tor_config_shared::opentelemetry::OpentelemetryConfig,
298
}
299

            
300
impl LoggingConfigBuilder {
301
    /// Validate the options provided to the builder.
302
2
    fn validate(&self) -> Result<(), ConfigBuildError> {
303
2
        if let Some(console) = &self.console {
304
            EnvFilter::builder()
305
                .parse(console)
306
                .map_err(|e| ConfigBuildError::Invalid {
307
                    field: "console".to_string(),
308
                    problem: e.to_string(),
309
                })?;
310
2
        }
311
2
        Ok(())
312
2
    }
313
}
314

            
315
/// Configuration for where information should be stored on disk.
316
///
317
/// By default, cache information will be stored in `${ARTI_RELAY_CACHE}`, and
318
/// persistent state will be stored in `${ARTI_RELAY_LOCAL_DATA}`. That means that
319
/// _all_ programs using these defaults will share their cache and state data.
320
/// If that isn't what you want, you'll need to override these directories.
321
///
322
/// On unix, the default directories will typically expand to `~/.cache/arti`
323
/// and `~/.local/share/arti/` respectively, depending on the user's
324
/// environment. Other platforms will also use suitable defaults. For more
325
/// information, see the documentation for [`CfgPath`].
326
///
327
/// This section is for read/write storage.
328
///
329
/// You cannot change this section on a running relay.
330
#[derive(Debug, Clone, Deftly, Eq, PartialEq)]
331
#[derive_deftly(TorConfig)]
332
#[non_exhaustive]
333
pub(crate) struct StorageConfig {
334
    /// Location on disk for cached information.
335
    ///
336
    /// This follows the rules for `/var/cache`: "sufficiently old" filesystem objects
337
    /// in it may be deleted outside of the control of Arti,
338
    /// and Arti will continue to function properly.
339
    /// It is also fine to delete the directory as a whole, while Arti is not running.
340
    ///
341
    /// Should be accessed through the `cache_dir()` getter to provide better error messages when
342
    /// resolving the path.
343
    //
344
    // Usage note, for implementations of Arti components:
345
    //
346
    // When files in this directory are to be used by a component, the cache_dir
347
    // value should be passed through to the component as-is, and the component is
348
    // then responsible for constructing an appropriate sub-path (for example,
349
    // tor-dirmgr receives cache_dir, and appends components such as "dir_blobs".
350
    //
351
    // (This consistency rule is not current always followed by every component.)
352
    #[deftly(tor_config(default = "default_cache_dir()", setter(into)))]
353
    cache_dir: CfgPath,
354

            
355
    /// Location on disk for less-sensitive persistent state information.
356
    ///
357
    /// Should be accessed through the `state_dir()` getter to provide better error messages when
358
    /// resolving the path.
359
    // Usage note: see the note for `cache_dir`, above.
360
    #[deftly(tor_config(default = "default_state_dir()", setter(into)))]
361
    state_dir: CfgPath,
362

            
363
    /// Location on disk for the Arti keystore.
364
    #[deftly(tor_config(sub_builder))]
365
    keystore: ArtiKeystoreConfig,
366

            
367
    /// Configuration about which permissions we want to enforce on our files.
368
    // NOTE: This 'build_for_arti()' hard-codes the config field name as `permissions` and the
369
    // environment variable as `ARTI_FS_DISABLE_PERMISSION_CHECKS`. These things should be
370
    // configured by the application, not lower-level libraries, but some other lower-level
371
    // libraries like `tor-hsservice` also use 'build_for_arti()'. So we're stuck with it for now.
372
    // It might be confusing in the future if relays use some environment variables prefixed with
373
    // "ARTI_" and others with "ARTI_RELAY_", so we should probably stick to just "ARTI_".
374
    #[deftly(tor_config(
375
        sub_builder(build_fn = "build_for_arti"),
376
        extend_with = "extend_with_replace"
377
    ))]
378
    permissions: Mistrust,
379
}
380

            
381
impl StorageConfig {
382
    /// Return the FS permissions to use for state and cache directories.
383
    pub(crate) fn permissions(&self) -> &Mistrust {
384
        &self.permissions
385
    }
386

            
387
    /// Return the fully expanded path of the state directory.
388
    pub(crate) fn state_dir(
389
        &self,
390
        resolver: &CfgPathResolver,
391
    ) -> Result<PathBuf, ConfigBuildError> {
392
        resolve_cfg_path(&self.state_dir, "state_dir", resolver)
393
    }
394

            
395
    /// Return the fully expanded path of the cache directory.
396
    pub(crate) fn cache_dir(
397
        &self,
398
        resolver: &CfgPathResolver,
399
    ) -> Result<PathBuf, ConfigBuildError> {
400
        resolve_cfg_path(&self.cache_dir, "cache_dir", resolver)
401
    }
402
}
403

            
404
/// Configuration for system resources used by the relay.
405
#[derive(Debug, Clone, Deftly, Eq, PartialEq)]
406
#[derive_deftly(TorConfig)]
407
#[non_exhaustive]
408
pub(crate) struct SystemConfig {
409
    /// Memory limits (approximate)
410
    #[deftly(tor_config(sub_builder))]
411
    pub(crate) memory: tor_memquota::Config,
412
}
413

            
414
/// Return the default cache directory.
415
2
fn default_cache_dir() -> CfgPath {
416
2
    CfgPath::new("${ARTI_RELAY_CACHE}".to_owned())
417
2
}
418

            
419
/// Return the default state directory.
420
2
fn default_state_dir() -> CfgPath {
421
2
    CfgPath::new("${ARTI_RELAY_LOCAL_DATA}".to_owned())
422
2
}
423

            
424
/// Helper to return a `ConfigBuildError` if the path could not be resolved.
425
fn resolve_cfg_path(
426
    path: &CfgPath,
427
    name: &str,
428
    resolver: &CfgPathResolver,
429
) -> Result<PathBuf, ConfigBuildError> {
430
    path.path(resolver).map_err(|e| ConfigBuildError::Invalid {
431
        field: name.to_owned(),
432
        problem: e.to_string(),
433
    })
434
}
435

            
436
#[cfg(test)]
437
mod test {
438
    // @@ begin test lint list maintained by maint/add_warning @@
439
    #![allow(clippy::bool_assert_comparison)]
440
    #![allow(clippy::clone_on_copy)]
441
    #![allow(clippy::dbg_macro)]
442
    #![allow(clippy::mixed_attributes_style)]
443
    #![allow(clippy::print_stderr)]
444
    #![allow(clippy::print_stdout)]
445
    #![allow(clippy::single_char_pattern)]
446
    #![allow(clippy::unwrap_used)]
447
    #![allow(clippy::unchecked_time_subtraction)]
448
    #![allow(clippy::useless_vec)]
449
    #![allow(clippy::needless_pass_by_value)]
450
    #![allow(clippy::string_slice)] // See arti#2571
451
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
452

            
453
    use super::*;
454

            
455
    fn cfg_variables() -> impl IntoIterator<Item = (&'static str, PathBuf)> {
456
        let project_dirs = project_dirs().unwrap();
457
        let list = [
458
            ("ARTI_RELAY_CACHE", project_dirs.cache_dir()),
459
            ("ARTI_RELAY_CONFIG", project_dirs.config_dir()),
460
            ("ARTI_RELAY_LOCAL_DATA", project_dirs.data_local_dir()),
461
            ("PROGRAM_DIR", &get_program_dir().unwrap()),
462
            ("USER_HOME", tor_config_path::home().unwrap()),
463
        ];
464

            
465
        list.into_iter()
466
            .map(|(a, b)| (a, b.to_owned()))
467
            .collect::<Vec<_>>()
468
    }
469

            
470
    #[cfg(not(target_family = "windows"))]
471
    #[test]
472
    fn expand_variables() {
473
        let path_resolver = base_resolver();
474

            
475
        for (var, val) in cfg_variables() {
476
            let p = CfgPath::new(format!("${{{var}}}/example"));
477
            assert_eq!(p.to_string(), format!("${{{var}}}/example"));
478

            
479
            let expected = val.join("example");
480
            assert_eq!(p.path(&path_resolver).unwrap().to_str(), expected.to_str());
481
        }
482

            
483
        let p = CfgPath::new("${NOT_A_REAL_VAR}/example".to_string());
484
        assert!(p.path(&path_resolver).is_err());
485
    }
486

            
487
    #[cfg(target_family = "windows")]
488
    #[test]
489
    fn expand_variables() {
490
        let path_resolver = base_resolver();
491

            
492
        for (var, val) in cfg_variables() {
493
            let p = CfgPath::new(format!("${{{var}}}\\example"));
494
            assert_eq!(p.to_string(), format!("${{{var}}}\\example"));
495

            
496
            let expected = val.join("example");
497
            assert_eq!(p.path(&path_resolver).unwrap().to_str(), expected.to_str());
498
        }
499

            
500
        let p = CfgPath::new("${NOT_A_REAL_VAR}\\example".to_string());
501
        assert!(p.path(&path_resolver).is_err());
502
    }
503
}