diff --git a/Cargo.lock b/Cargo.lock index 1b933fc..3583f8b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2279,9 +2279,9 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "aws-lc-rs", "ring", @@ -3156,9 +3156,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] diff --git a/README.md b/README.md index 374a4e6..7173551 100644 --- a/README.md +++ b/README.md @@ -130,9 +130,9 @@ history and in the process list. Use a file, the environment, or the prompt. ### A shared profile for the inbuxa server -`import` (into a JMAP server) and `import-directory` write to an inbuxa -server. Instead of giving its address and key each time, name it once in -`~/.config/inbuxa/config.toml`, which `inbuxa-cli` reads too: +`import-directory` writes to an inbuxa server. Instead of giving its address +and key each time, name it once in `~/.config/inbuxa/config.toml`, which +`inbuxa-cli` reads too: [profile.default] url = "https://mail.example.org" @@ -147,9 +147,14 @@ holding the key, so the key stays out of the config). Keep the file to yourself -- `chmod 600 ~/.config/inbuxa/config.toml`. Without `--profile` or `$INBUXA_PROFILE`, the `default` section is used; `--profile staging` picks another. A `--url`, or any `INBUXA_MIGRATE_*` variable, still wins, so the -profile is only the fallback and `--url` becomes optional on these two -commands when it is set. The other commands connect to IMAP, DAV and the like, -not to the inbuxa server, so they don't read the profile. +profile is only the fallback and `--url` becomes optional when it is set. The +key goes only to the profile's own server: a `--url` with another scheme, host +or port gets no key from the profile, and is asked for one as usual. + +The `import` commands, `import jmap` among them, read from a source server -- +often another provider's -- not the inbuxa server, so they never read the +profile and its key is never sent to a source. Give the source's own +credentials with a flag, an `INBUXA_MIGRATE_*` variable, or the prompt. ## Installing diff --git a/docs/usage.md b/docs/usage.md index 5e55e6e..74b5aed 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -63,9 +63,9 @@ by the same variable with `_FILE` appended (the Docker and systemd secrets convention), or a prompt; see [Credentials](../README.md#credentials). The command line takes them too, but should not be given them. -`import` and `import-directory` write to an inbuxa server. Its address and API -key can be named once in a shared profile, `~/.config/inbuxa/config.toml` -(which `inbuxa-cli` reads too), so `--url` and the key need not be repeated: +`import-directory` writes to an inbuxa server. Its address and API key can be +named once in a shared profile, `~/.config/inbuxa/config.toml` (which +`inbuxa-cli` reads too), so `--url` and the key need not be repeated: ```toml [profile.default] @@ -76,8 +76,12 @@ api-key = "API_…" `--profile` or `$INBUXA_PROFILE` pick a `[profile.]` section, and the default is `default`; a section gives `url` and either `api-key` or `api-key-file` (a path to a file holding the key). A `--url`, or any -`INBUXA_MIGRATE_*` variable, still takes precedence, so `--url` is optional on -these two commands only when a profile supplies it. See +`INBUXA_MIGRATE_*` variable, still takes precedence, so `--url` is optional +only when a profile supplies it. The key goes only to the profile's own +server: a `--url` with another scheme, host or port gets no key from the +profile. The `import` commands read from a source server, not the inbuxa +server, so they never read the profile; give them the source's own +credentials. See [Credentials](../README.md#a-shared-profile-for-the-inbuxa-server). ## Import diff --git a/src/cli.rs b/src/cli.rs index 0e4da6d..8faec48 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -265,16 +265,9 @@ struct JmapImportArgs { #[arg( long, value_name = "URL", - help = "The target inbuxa server: base URL or full JMAP session URL (else the profile's url)" + help = "The source JMAP server: base URL or full JMAP session URL" )] - url: Option, - - #[arg( - long, - value_name = "NAME", - help = "Profile in ~/.config/inbuxa/config.toml (or $INBUXA_PROFILE) for the url and API key not given here" - )] - profile: Option, + url: String, #[arg( long, @@ -1599,17 +1592,14 @@ fn resolve_dav_auth( fn resolve_jmap_import(args: JmapImportArgs) -> Result { let common = common_config(&args.global, args.archive); - let profile = Profile::load(args.profile.as_deref())?; - let url = args.url.or(profile.url).ok_or_else(|| { - Error::Usage( - "no target server: pass --url, or name one in ~/.config/inbuxa/config.toml".to_owned(), - ) - })?; + // The source is another server, so the shared profile -- the inbuxa + // server's url and key -- is never read here: its key would go to + // whatever --url names. let auth = resolve_auth( args.auth_basic.as_deref(), args.auth_password.as_deref(), args.auth_bearer.as_ref(), - profile.api_key.as_deref(), + None, )?; let account = resolve_account(args.account_id, args.account_name)?; let objects = args.objects.as_deref().map(parse_object_list).transpose()?; @@ -1619,7 +1609,7 @@ fn resolve_jmap_import(args: JmapImportArgs) -> Result { ImportConfig { connect: ConnectConfig { stay_on_url: args.stay_on_url, - url, + url: args.url, auth, account, }, @@ -2079,7 +2069,8 @@ fn resolve_export_directory(args: ExportDirectoryArgs) -> Result fn resolve_import_directory(args: ImportDirectoryArgs) -> Result { let profile = Profile::load(args.profile.as_deref())?; - let url = args.url.or(profile.url).ok_or_else(|| { + let profile_key = profile_key_for(args.url.as_deref(), &profile); + let url = args.url.or_else(|| profile.url.clone()).ok_or_else(|| { Error::Usage( "no inbuxa server: pass --url, or name one in ~/.config/inbuxa/config.toml".to_owned(), ) @@ -2088,7 +2079,7 @@ fn resolve_import_directory(args: ImportDirectoryArgs) -> Result args.auth_basic.as_deref(), args.auth_password.as_deref(), args.auth_bearer.as_ref(), - profile.api_key.as_deref(), + profile_key, )?; Ok(Action::ImportDirectory(ImportDirectoryConfig { stay_on_url: args.stay_on_url, @@ -2667,6 +2658,20 @@ fn common_config(global: &GlobalArgs, archive: PathBuf) -> CommonConfig { } } +/// The profile's API key, for the profile's own server only. With no --url +/// the profile's url is used and so is its key; a --url naming another +/// origin (scheme, host or port) gets no key from the profile, and the flag, +/// the environment or a prompt supplies one instead. +fn profile_key_for<'a>(url_flag: Option<&str>, profile: &'a Profile) -> Option<&'a str> { + let key = profile.api_key.as_deref()?; + let Some(flag) = url_flag else { + return Some(key); + }; + let profile_url = url::Url::parse(profile.url.as_deref()?).ok()?; + let flag_url = url::Url::parse(flag).ok()?; + (flag_url.origin() == profile_url.origin()).then_some(key) +} + fn resolve_auth( auth_basic: Option<&str>, auth_password: Option<&str>, @@ -3105,6 +3110,154 @@ mod tests { unsafe { env::remove_var("INBUXA_MIGRATE_API_KEY") }; } + const PROFILE_KEY: &str = "profile-secret"; + + /// A shared profile file naming https://mail.example.org and its key, + /// in its own config directory, with nothing in the environment to win + /// over it. Undone on drop. Hold `lock()` while it lives. + struct ProfileHome(PathBuf); + + impl ProfileHome { + fn new(tag: &str) -> ProfileHome { + let dir = env::temp_dir().join(format!( + "inbuxa-migrate-cli-profile-{tag}-{}", + std::process::id() + )); + std::fs::create_dir_all(dir.join("inbuxa")).unwrap(); + std::fs::write( + dir.join("inbuxa/config.toml"), + format!( + "[profile.default]\nurl = \"https://mail.example.org\"\napi-key = \"{PROFILE_KEY}\"\n" + ), + ) + .unwrap(); + unsafe { + env::set_var("XDG_CONFIG_HOME", &dir); + env::remove_var("INBUXA_PROFILE"); + for var in secret::API_KEY_VARS { + env::remove_var(var); + env::remove_var(format!("{var}_FILE")); + } + } + ProfileHome(dir) + } + } + + impl Drop for ProfileHome { + fn drop(&mut self) { + unsafe { env::remove_var("XDG_CONFIG_HOME") }; + std::fs::remove_dir_all(&self.0).ok(); + } + } + + fn is_profile_key(auth: &Auth) -> bool { + matches!(auth, Auth::Bearer { token } if token == PROFILE_KEY) + } + + /// `import jmap` reads from a source server, often another provider's. + /// The shared profile names the inbuxa server and its key, so neither may + /// be taken from it: the key would go to whatever --url names. + #[test] + fn import_jmap_never_takes_the_url_or_key_from_the_profile() { + use std::io::IsTerminal; + let _g = lock(); + let _p = ProfileHome::new("jmap"); + + // Without --url there is no source; the profile's url is not one. + let no_url = Cli::try_parse_from([ + "inbuxa-migrate", + "import", + "jmap", + "--account-name", + "a@example.org", + "archive.sqlite", + ]); + if let Ok(cli) = no_url { + if let Ok(Action::Import(_, c)) = cli.resolve() { + panic!( + "import jmap took its source from the profile: {} (profile key: {})", + c.connect.url, + is_profile_key(&c.connect.auth) + ); + } + } + + // With --url and a bare --auth-bearer, the key comes from the + // environment or a prompt, never the profile. On a terminal this + // would prompt, so that half only runs without one (as under CI). + if std::io::stdin().is_terminal() { + return; + } + let cli = Cli::try_parse_from([ + "inbuxa-migrate", + "import", + "jmap", + "--url", + "https://source.example.net/jmap/session", + "--auth-bearer", + "--account-name", + "a@example.org", + "archive.sqlite", + ]) + .unwrap_or_else(|e| panic!("clap rejected: {e}")); + match cli.resolve() { + Ok(Action::Import(_, c)) => assert!( + !is_profile_key(&c.connect.auth), + "the profile's key was sent to the source {}", + c.connect.url + ), + Ok(_) => panic!("expected Import"), + Err(e) => assert!(e.to_string().contains("API key"), "{e}"), + } + } + + fn import_directory(extra: &[&str]) -> Result { + let mut argv = vec!["inbuxa-migrate", "import-directory", "--dry-run"]; + argv.extend_from_slice(extra); + argv.push("dir"); + let cli = Cli::try_parse_from(argv).unwrap_or_else(|e| panic!("clap rejected: {e}")); + match cli.resolve()? { + Action::ImportDirectory(config) => Ok(config), + _ => panic!("expected ImportDirectory"), + } + } + + /// import-directory writes to the inbuxa server, so it may use the + /// profile -- but the key goes only to the profile's own server, never to + /// another --url. + #[test] + fn import_directory_sends_the_profile_key_only_to_the_profile_url() { + use std::io::IsTerminal; + let _g = lock(); + let _p = ProfileHome::new("dir"); + + let c = import_directory(&[]).unwrap(); + assert_eq!(c.url, "https://mail.example.org"); + assert!(is_profile_key(&c.auth)); + + let c = import_directory(&["--url", "https://MAIL.example.org:443/jmap/session"]).unwrap(); + assert!(is_profile_key(&c.auth), "same origin keeps the key"); + + // Another server: the key must come from elsewhere (a prompt on a + // terminal, so this half runs only without one). + if std::io::stdin().is_terminal() { + return; + } + for other in [ + "https://other.example.net", + "http://mail.example.org", + "https://mail.example.org:8443", + ] { + match import_directory(&["--url", other]) { + Ok(c) => assert!( + !is_profile_key(&c.auth), + "the profile's key was sent to {other}" + ), + Err(e) => assert!(e.to_string().contains("API key"), "{e}"), + } + } + } + fn ews_auth(extra: &[&str]) -> Result { let mut argv = vec!["inbuxa-migrate", "import", "exchange-ews", "archive.sqlite"]; argv.extend_from_slice(extra); diff --git a/src/profile.rs b/src/profile.rs index 6b906d6..e35bd27 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -7,7 +7,9 @@ //! The shared `~/.config/inbuxa` profile. A `config.toml` names an inbuxa //! server once, so this and `inbuxa-cli` read the same server address and API //! key instead of each being told again. For `inbuxa-migrate` it supplies the -//! inbuxa server the `import` and `import-directory` commands write to: +//! inbuxa server the `import-directory` command writes to, and its key goes +//! only to that server. The `import` commands read from a source server, so +//! they never read the profile: //! //! ```toml //! [profile.default] diff --git a/src/secret.rs b/src/secret.rs index cfaf159..21ab34e 100644 --- a/src/secret.rs +++ b/src/secret.rs @@ -51,7 +51,7 @@ pub fn resolve_any_or( return prompt_no_echo(prompt_label); } Err(Error::Usage(format!( - "no {prompt_label} provided: pass the flag, set ${0} or ${0}_FILE, name one in a profile, or run on a TTY for an interactive prompt", + "no {prompt_label} provided: pass the flag, set ${0} or ${0}_FILE, or run on a TTY for an interactive prompt", env_vars[0] ))) }