summaryrefslogtreecommitdiff
path: root/crates/arti-relay/src/cli.rs
blob: d4e09219a347f652eed077b44660dcee96f86226 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
//! The command-line interface.
//!
//! See [`Cli`].

use std::ffi::OsString;
use std::path::PathBuf;

use clap::{Args, Command, Parser, Subcommand, ValueEnum};
use fs_mistrust::anon_home::PathExt as _;
use std::sync::LazyLock;
use tor_config::{ConfigurationSource, ConfigurationSources};
use tor_config_path::CfgPathError;

use crate::config::default_config_paths;

/// A cached copy of the default config paths.
///
/// We cache the values to ensure they are consistent between the help text and the values used.
static DEFAULT_CONFIG_PATHS: LazyLock<Result<Vec<PathBuf>, CfgPathError>> =
    LazyLock::new(default_config_paths);

/// A Rust Tor relay implementation.
#[derive(Clone, Debug, Parser)]
#[command(author = "The Tor Project Developers")]
#[command(version)]
#[command(defer = cli_cmd_post_processing)]
pub(crate) struct Cli {
    /// Sub-commands.
    #[command(subcommand)]
    pub(crate) command: Commands,

    /// Global arguments available for all sub-commands.
    ///
    /// These arguments may be specified before or after the subcommand argument.
    #[clap(flatten)]
    pub(crate) global: GlobalArgs,
}

/// Perform post-processing on the [`Command`] generated by clap for [`Cli`].
///
/// We use this to append the default config paths to the help text.
fn cli_cmd_post_processing(cli: Command) -> Command {
    /// Append the paths to the help text.
    fn fmt_help(help: Option<&str>, paths: &[PathBuf]) -> String {
        let help = help.map(|x| format!("{x}\n\n")).unwrap_or("".to_string());
        let paths: Vec<_> = paths
            .iter()
            .map(|path| {
                let mut anon = path.anonymize_home().to_string();
                // Best-effort attempt to re-add the trailing '/'
                // if it was stripped by `anonymize_home()`.
                // If the original string ended with '/' and the anonymized
                // path doesn't, then re-add it.
                if path.to_string_lossy().ends_with('/') && !anon.ends_with('/') {
                    anon.push('/');
                }
                anon
            })
            .collect();
        let paths = paths.join("\n");

        const DESC: &str =
            "If no paths are provided, the following config paths will be used if they exist:";
        format!("{help}{DESC}\n\n{paths}")
    }

    // Show the default paths in the "--help" text.
    match &*DEFAULT_CONFIG_PATHS {
        Ok(paths) => cli.mut_arg("config", |arg| {
            if let Some(help) = arg.get_long_help() {
                let help = help.to_string();
                arg.long_help(fmt_help(Some(&help), paths))
            } else if let Some(help) = arg.get_help() {
                let help = help.to_string();
                arg.long_help(fmt_help(Some(&help), paths))
            } else {
                arg.long_help(fmt_help(None, paths))
            }
        }),
        Err(_e) => cli,
    }
}

/// Main subcommands.
#[derive(Clone, Debug, Subcommand)]
pub(crate) enum Commands {
    /// Run the relay.
    Run(RunArgs),
    /// Print build information.
    BuildInfo,
}

/// Global arguments for all commands.
// NOTE: `global = true` should be set for each field (see the `global_args_are_global` unit test)
#[derive(Clone, Debug, Args)]
pub(crate) struct GlobalArgs {
    /// Override the log level from the configuration.
    #[arg(long, short, global = true)]
    #[arg(value_name = "LEVEL")]
    pub(crate) log_level: Option<LogLevel>,

    /// Don't check permissions on the files we use.
    #[arg(long, global = true)]
    pub(crate) disable_fs_permission_checks: bool,

    /// Override config file parameters, using TOML-like syntax.
    #[arg(long = "option", short, global = true)]
    #[arg(value_name = "KEY=VALUE")]
    pub(crate) options: Vec<String>,

    /// Config files and directories to read.
    // NOTE: We append the default config paths to the help text in `cli_cmd_post_processing`.
    // NOTE: This value does not take into account the default config paths,
    // so this is private while the `GlobalArgs::config()` method is public instead.
    #[arg(long, short, global = true)]
    #[arg(value_name = "PATH")]
    config: Vec<OsString>,
}

impl GlobalArgs {
    /// Get the configuration sources.
    ///
    /// You may also want to set a [`Mistrust`](fs_mistrust::Mistrust)
    /// and any additional configuration option overrides
    /// using [`push_option`](ConfigurationSources::push_option).
    pub(crate) fn config(&self) -> Result<ConfigurationSources, CfgPathError> {
        // Use `try_from_cmdline` to be consistent with Arti.
        let mut cfg_sources = ConfigurationSources::try_from_cmdline(
            || {
                Ok(DEFAULT_CONFIG_PATHS
                    .as_ref()
                    .map_err(Clone::clone)?
                    .iter()
                    .map(ConfigurationSource::from_path))
            },
            &self.config,
            &self.options,
        )?;

        // TODO: These text strings may become stale if the configuration structure changes,
        // and they're not checked at compile time.
        // Can we change `ConfigurationSources` in some way to allow overrides from an existing
        // builder?
        if self.disable_fs_permission_checks {
            cfg_sources.push_option("storage.permissions.dangerously_trust_everyone=true");
        }

        if let Some(log_level) = self.log_level {
            cfg_sources.push_option(format!("logging.console={log_level}"));
        }

        Ok(cfg_sources)
    }
}

/// Arguments when running an Arti relay.
#[derive(Clone, Debug, Args)]
pub(crate) struct RunArgs {}

/// Log levels allowed by the cli.
#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
pub(crate) enum LogLevel {
    /// See [`tracing::Level::ERROR`].
    #[value(help = None)]
    Error,
    /// See [`tracing::Level::WARN`].
    #[value(help = None)]
    Warn,
    /// See [`tracing::Level::INFO`].
    #[value(help = None)]
    Info,
    /// See [`tracing::Level::DEBUG`].
    #[value(help = None)]
    Debug,
    /// See [`tracing::Level::TRACE`].
    #[value(help = None)]
    Trace,
}

impl std::fmt::Display for LogLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Error => write!(f, "error"),
            Self::Warn => write!(f, "warn"),
            Self::Info => write!(f, "info"),
            Self::Debug => write!(f, "debug"),
            Self::Trace => write!(f, "trace"),
        }
    }
}

impl From<LogLevel> for tracing::metadata::Level {
    fn from(x: LogLevel) -> Self {
        match x {
            LogLevel::Error => Self::ERROR,
            LogLevel::Warn => Self::WARN,
            LogLevel::Info => Self::INFO,
            LogLevel::Debug => Self::DEBUG,
            LogLevel::Trace => Self::TRACE,
        }
    }
}

#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->

    use super::*;

    #[test]
    fn common_flags() {
        Cli::parse_from(["arti-relay", "build-info"]);
        Cli::parse_from(["arti-relay", "run"]);

        let cli = Cli::parse_from(["arti-relay", "--log-level", "warn", "run"]);
        assert_eq!(cli.global.log_level, Some(LogLevel::Warn));
        let cli = Cli::parse_from(["arti-relay", "run", "--log-level", "warn"]);
        assert_eq!(cli.global.log_level, Some(LogLevel::Warn));

        let cli = Cli::parse_from(["arti-relay", "--disable-fs-permission-checks", "run"]);
        assert!(cli.global.disable_fs_permission_checks);
        let cli = Cli::parse_from(["arti-relay", "run", "--disable-fs-permission-checks"]);
        assert!(cli.global.disable_fs_permission_checks);
    }

    #[test]
    fn clap_bug() {
        let cli = Cli::parse_from(["arti-relay", "-o", "foo=1", "run"]);
        assert_eq!(cli.global.options, vec!["foo=1"]);

        let cli = Cli::parse_from(["arti-relay", "-o", "foo=1", "-o", "bar=2", "run"]);
        assert_eq!(cli.global.options, vec!["foo=1", "bar=2"]);

        // this is https://github.com/clap-rs/clap/issues/3938
        // TODO: this is a footgun, and we should consider alternatives to clap's 'global' args
        let cli = Cli::parse_from(["arti-relay", "-o", "foo=1", "run", "-o", "bar=2"]);
        assert_eq!(cli.global.options, vec!["bar=2"]);
    }

    #[test]
    fn global_args_are_global() {
        let cmd = Command::new("test");
        let cmd = GlobalArgs::augment_args(cmd);

        // check that each argument in `GlobalArgs` has "global" set
        for arg in cmd.get_arguments() {
            assert!(
                arg.is_global_set(),
                "'global' must be set for {:?}",
                arg.get_long()
            );
        }
    }
}