Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions crates/ox-core/src/config/load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1059,6 +1059,97 @@ mod tests {
assert!(!format!("{project:#}").contains("secret-marker"));
}

#[test]
fn a_private_key_error_names_the_shape_without_the_value() {
let dir = tempfile::tempdir().unwrap();
for (body, expected) in [
(
"client.auth = 'private-token-sentinel'",
"expected a table with type bearer, api-key, oauth, or login",
),
(
"client.auth = { type = 'private-token-sentinel', value = 'private-token-sentinel' }",
"in `client.auth.type`: expected one of `bearer`, `api-key`, `oauth`, `login`",
),
(
"client.auth = { type = 'bearer', value = ['private-token-sentinel'] }",
"in `client.auth`: expected a string",
),
(
"client.auth = { type = 'bearer', value = 987654321 }",
"in `client.auth`: expected a string",
),
(
"client.auth = { type = 'bearer', file = ['private-token-sentinel'] }",
"in `client.auth`: expected a string",
),
(
"client.auth = { type = 'bearer', value = 'private-token-sentinel', file = '/token' }",
"client.auth requires exactly one of value or file",
),
(
"client.auth = { type = 'login', value = 'private-token-sentinel' }",
"client.auth type login takes no other keys",
),
(
"client.auth = { type = 'bearer', value = 'private-token-sentinel', extra = true }",
"unknown field `extra`, expected `value` or `file`",
),
(
r#"client.auth = { type = "bearer", value = "private-token-sentinel\u0007" }"#,
"invalid client.auth.value: expected an HTTP header value",
),
(
"client.api_key = 'private-token-sentinel'",
"unknown field `api_key`",
),
(
"client.headers = 'private-header-sentinel'",
"in `client.headers`: expected a map",
),
(
"client.headers = { x-private = ['private-header-sentinel'] }",
"in `client.headers.x-private`: expected a string",
),
(
"client.headers = { 'private-header-sentinel name' = 'private-header-sentinel' }",
"invalid client.headers: invalid header name",
),
(
r#"client.headers = { x-private = "private-header-sentinel\nsecond-line" }"#,
"invalid client.headers: the x-private value contains a character a header \
cannot carry",
),
(
"client.headers = { X-Private = 'private-header-sentinel', x-private = 'private-header-sentinel' }",
"invalid client.headers: x-private is set more than once",
),
(
indoc! {"
client.auth = { type = 'bearer', value = 'private-token-sentinel' }
[private-token-sentinel
"},
"unclosed table, expected `]`",
),
] {
let path = write(&dir.path().join("config.toml"), body);

let err = read_layer(&Layer::User(path.clone())).expect_err(body);

let message = format!("{err:#}");
let prefix = format!("invalid config at {}: ", path.display());
assert!(message.starts_with(&prefix), "{body}: {message}");
assert!(message.contains(expected), "{body}: {message}");
for secret in [
"private-token-sentinel",
"private-header-sentinel",
"987654321",
] {
assert!(!message.contains(secret), "{body}: {message}");
}
}
}

#[test]
fn rejects_unknown_keys_at_every_level() {
let dir = tempfile::tempdir().unwrap();
Expand Down
140 changes: 140 additions & 0 deletions crates/ox-core/src/config/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,15 @@ mod tests {
use indoc::formatdoc;

use super::*;
use crate::util::path::testing::HOME_VAR;

/// The message the TOML parser reports for `body`, which must fail to parse as a config file.
fn rejection(body: &str) -> String {
toml::from_str::<FileConfig>(body)
.expect_err(body)
.message()
.to_owned()
}

mod file_config {
use super::*;
Expand Down Expand Up @@ -296,4 +305,135 @@ mod tests {
}
}
}

mod login_auth {
use super::*;

mod try_from {
use super::*;

#[test]
fn accepts_the_type_alone() {
let config: FileConfig =
toml::from_str("client.auth = { type = 'login' }").unwrap();

assert!(matches!(config.client.auth, Some(ClientAuth::Login(_))));
}

#[test]
fn rejects_any_other_key() {
for body in [
"client.auth = { type = 'login', value = 'token' }",
"client.auth = { type = 'login', file = '/token' }",
] {
assert_eq!(
rejection(body),
"client.auth type login takes no other keys",
"{body}"
);
}
}
}
}

mod auth_value {
use super::*;

mod try_from {
use super::*;

fn bearer_auth(fields: &str) -> Option<ClientAuth> {
let body = format!("client.auth = {{ type = 'bearer', {fields} }}");
let config: FileConfig = toml::from_str(&body).unwrap();
config.client.auth
}

#[test]
fn takes_an_inline_value() {
assert!(matches!(
bearer_auth("value = 'token'"),
Some(ClientAuth::Bearer(AuthValue::Value(value))) if value == "token"
));
}

#[test]
fn takes_an_absolute_or_home_relative_file() {
let dir = tempfile::tempdir().unwrap();
let absolute = dir.path().join("token");
let raw = toml::Value::String(absolute.display().to_string());

temp_env::with_var(HOME_VAR, Some(dir.path()), || {
for (fields, expected) in [
(format!("file = {raw}"), &absolute),
("file = '~/token'".to_owned(), &absolute),
] {
assert!(
matches!(
bearer_auth(&fields),
Some(ClientAuth::Bearer(AuthValue::File(ref path))) if path == expected
),
"{fields}"
);
}
});
}

#[test]
fn rejects_neither_or_both_sources() {
for fields in ["", ", value = 'token', file = '/token'"] {
let body = format!("client.auth = {{ type = 'bearer'{fields} }}");

assert_eq!(
rejection(&body),
"client.auth requires exactly one of value or file",
"{body}"
);
}
}

#[test]
fn rejects_an_empty_value() {
assert_eq!(
rejection("client.auth = { type = 'bearer', value = '' }"),
"client.auth.value must not be empty"
);
}

#[test]
fn rejects_a_file_path_that_is_not_absolute_or_under_home() {
for file in ["token", ""] {
let body = format!("client.auth = {{ type = 'bearer', file = '{file}' }}");

assert_eq!(
rejection(&body),
"invalid client.auth.file: expected an absolute or `~/` path",
"{file:?}"
);
}
}
}
}

mod inline_secret {
use super::*;

#[test]
fn passes_a_header_safe_value_through() {
assert_eq!(
inline_secret("client.auth.value", "token".to_owned()).unwrap(),
"token"
);
}

#[test]
fn rejects_a_value_no_header_can_carry() {
let err = inline_secret("client.auth.value", "bad\u{7}key".to_owned()).unwrap_err();

assert_eq!(
format!("{err:#}"),
"invalid client.auth.value: expected an HTTP header value: \
failed to parse header value"
);
}
}
}
3 changes: 2 additions & 1 deletion crates/ox-core/src/permission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1740,6 +1740,7 @@ mod tests {
};
let fs_root = slash_separated(base.ancestors().last().unwrap());
let base_raw = slash_separated(base);
let home_raw = slash_separated(&home);

temp_env::with_var(HOME_VAR, Some(&home), || {
for (raw, expected) in [
Expand All @@ -1748,7 +1749,7 @@ mod tests {
r#"invalid extra root "shared": expected an absolute or `~/` path"#
.to_owned(),
),
("~", too_broad("~")),
(home_raw.as_str(), too_broad(&home_raw)),
(fs_root.as_str(), too_broad(&fs_root)),
(base_raw.as_str(), too_broad(&base_raw)),
] {
Expand Down
35 changes: 23 additions & 12 deletions crates/ox-core/src/util/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use std::path::{Component, Path, PathBuf};

use anyhow::{Result, anyhow, ensure};
use anyhow::{Context as _, Result, ensure};
use strum::VariantArray;
use unicode_normalization::UnicodeNormalization as _;

Expand Down Expand Up @@ -94,21 +94,23 @@ pub fn expand_user(raw: &str) -> Result<PathBuf> {
if !(tail.is_empty() || tail.starts_with(std::path::is_separator)) {
return Ok(PathBuf::from(raw));
}
let home = std::env::home_dir()
.ok_or_else(|| anyhow!("failed to expand `~` in {raw:?}: no home directory"))?;
let home = std::env::home_dir().context("failed to expand `~`: no home directory")?;
if tail.is_empty() {
return Ok(home);
}
// `join` replaces `home` with an absolute argument, such as the `//foo` tail of `~//foo`.
Ok(home.join(tail.trim_start_matches(std::path::is_separator)))
}

/// Expands `raw` like [`expand_user`] and requires an absolute result, so a configured path cannot
/// depend on the working directory. Errors never quote `raw`, which may hold a pasted secret.
/// Expands `raw` like [`expand_user`] and requires an absolute path other than the home directory
/// itself, so a configured path cannot depend on the working directory. Errors never quote `raw`,
/// which may hold a pasted secret.
pub(crate) fn expand_absolute(raw: &str) -> Result<PathBuf> {
let path =
expand_user(raw).map_err(|_| anyhow!("cannot expand `~` without a home directory"))?;
ensure!(path.is_absolute(), "expected an absolute or `~/` path");
let path = expand_user(raw)?;
ensure!(
path.is_absolute() && raw.trim_end_matches(std::path::is_separator) != "~",
"expected an absolute or `~/` path"
);
Ok(path)
}

Expand Down Expand Up @@ -398,14 +400,23 @@ mod tests {
}

#[test]
fn rejects_a_relative_path_without_quoting_it() {
for raw in ["certs/ca.pem", "~alice/ca.pem"] {
let err = expand_absolute(raw).unwrap_err();
fn rejects_a_relative_path_or_the_bare_home_directory_without_quoting_it() {
let home = std::env::temp_dir();
let home = home.to_str().unwrap();
for (home, raw) in [
(home, "certs/ca.pem"),
(home, "~alice/ca.pem"),
(home, "~"),
(home, "~/"),
("relative-home", "~/ca.pem"),
] {
let err =
temp_env::with_var(HOME_VAR, Some(home), || expand_absolute(raw).unwrap_err());

assert_eq!(
err.to_string(),
"expected an absolute or `~/` path",
"{raw:?}"
"{raw:?} under {home:?}"
);
}
}
Expand Down
Loading
Loading