Skip to content
Draft
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
3 changes: 2 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion crates/weaver-config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ url = { version = "2.5", features = ["serde"] }

[target.'cfg(unix)'.dependencies]
dirs.workspace = true
libc = "0.2"
nix = { version = "0.31", features = ["user"] }

[dev-dependencies]
googletest.workspace = true
Expand All @@ -35,6 +35,7 @@ rstest.workspace = true
rstest-bdd.workspace = true
rstest-bdd-macros.workspace = true
tempfile.workspace = true
temp-env = "0.3.6"
once_cell.workspace = true
weaver-test-macros = { path = "../weaver-test-macros" }
cap-std = { workspace = true }
Expand Down
53 changes: 30 additions & 23 deletions crates/weaver-config/src/capability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,26 +86,27 @@ impl FromStr for CapabilityDirective {
type Err = CapabilityDirectiveParseError;

fn from_str(input: &str) -> Result<Self, Self::Err> {
let (language, rest) = input
let (language_text, rest) = input
.split_once(':')
.ok_or_else(|| CapabilityDirectiveParseError::MissingLanguage(input.to_string()))?;
let language = language.trim();
.ok_or_else(|| CapabilityDirectiveParseError::MissingLanguage(input.to_owned()))?;
let language = language_text.trim();
if language.is_empty() {
return Err(CapabilityDirectiveParseError::EmptyLanguage(
input.to_string(),
input.to_owned(),
));
}
let (capability, directive) = rest
let (capability_text, directive_text) = rest
.split_once('=')
.ok_or_else(|| CapabilityDirectiveParseError::MissingDirective(input.to_string()))?;
let capability = capability.trim();
.ok_or_else(|| CapabilityDirectiveParseError::MissingDirective(input.to_owned()))?;
let capability = capability_text.trim();
if capability.is_empty() {
return Err(CapabilityDirectiveParseError::EmptyCapability(
input.to_string(),
input.to_owned(),
));
}
let directive = CapabilityOverride::from_str(directive.trim())
.map_err(|_| CapabilityDirectiveParseError::InvalidDirective(directive.to_string()))?;
let directive = CapabilityOverride::from_str(directive_text.trim()).map_err(|_| {
CapabilityDirectiveParseError::InvalidDirective(directive_text.to_owned())
})?;
Ok(Self::new(language, capability, directive))
}
}
Expand Down Expand Up @@ -143,20 +144,20 @@ impl CapabilityMatrix {
capability: impl Into<String>,
directive: CapabilityOverride,
) {
let language = normalize_key(&language.into());
let capability = normalize_key(&capability.into());
let entry = self.languages.entry(language).or_default();
entry.overrides.insert(capability, directive);
let language_key = normalize_key(&language.into());
let capability_key = normalize_key(&capability.into());
let entry = self.languages.entry(language_key).or_default();
entry.overrides.insert(capability_key, directive);
}

/// Retrieves an override for a capability, when present.
#[must_use]
pub fn override_for(&self, language: &str, capability: &str) -> Option<CapabilityOverride> {
let language = normalize_key(language);
let capability = normalize_key(capability);
let language_key = normalize_key(language);
let capability_key = normalize_key(capability);
self.languages
.get(&language)
.and_then(|caps| caps.overrides.get(&capability).copied())
.get(&language_key)
.and_then(|caps| caps.overrides.get(&capability_key).copied())
}
}

Expand All @@ -174,13 +175,16 @@ pub fn deduplicate_directives(directives: &mut Vec<CapabilityDirective>) {
for mut directive in directives.drain(..) {
let language = normalize_key(&directive.language);
let capability = normalize_key(&directive.capability);
directive.language = language.clone();
directive.capability = capability.clone();
directive.language.clone_from(&language);
directive.capability.clone_from(&capability);
merged.insert((language, capability), directive);
}
*directives = merged.into_values().collect();
}

/// Trims surrounding whitespace and converts a key to lowercase.
///
/// For example, `" Rust "` becomes `"rust"`.
fn normalize_key(key: &str) -> String { key.trim().to_lowercase() }

#[cfg(test)]
Expand Down Expand Up @@ -209,9 +213,12 @@ mod tests {
deduplicate_directives(&mut directives);

assert_eq!(directives.len(), 1);
assert_eq!(directives[0].directive, CapabilityOverride::Deny);
assert_eq!(directives[0].language, "rust");
assert_eq!(directives[0].capability, "observe.rename");
let directive = directives
.first()
.expect("deduplication should leave one directive");
assert_eq!(directive.directive, CapabilityOverride::Deny);
assert_eq!(directive.language, "rust");
assert_eq!(directive.capability, "observe.rename");
}

#[test]
Expand Down
30 changes: 17 additions & 13 deletions crates/weaver-config/src/defaults.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use camino::Utf8PathBuf;
#[cfg(unix)]
use dirs::runtime_dir;
#[cfg(unix)]
use libc::geteuid;
use nix::unistd::Uid;

use crate::socket::SocketEndpoint;

Expand All @@ -24,23 +24,26 @@ pub const DEFAULT_TCP_PORT: u16 = 9779;
pub const DEFAULT_LOG_FILTER: &str = "info";

/// Default log filter expression used by the binaries.
pub fn default_log_filter() -> &'static str { DEFAULT_LOG_FILTER }
#[must_use]
pub const fn default_log_filter() -> &'static str { DEFAULT_LOG_FILTER }

/// Owned log filter value used where allocation is required (e.g. serde).
pub fn default_log_filter_string() -> String { DEFAULT_LOG_FILTER.to_string() }
#[must_use]
pub fn default_log_filter_string() -> String { DEFAULT_LOG_FILTER.to_owned() }

/// Default logging format for the binaries.
pub fn default_log_format() -> crate::logging::LogFormat { crate::logging::LogFormat::Json }
#[must_use]
pub const fn default_log_format() -> crate::logging::LogFormat { crate::logging::LogFormat::Json }

/// Computes the default socket endpoint for the daemon.
#[must_use]
pub fn default_socket_endpoint() -> SocketEndpoint { default_socket_endpoint_inner() }

/// Selects the XDG runtime path or a user-namespaced temporary fallback.
#[cfg(unix)]
fn default_socket_endpoint_inner() -> SocketEndpoint {
let (mut base, apply_namespace) = match runtime_base_directory() {
Some(dir) => (dir, false),
None => (fallback_base_directory(), true),
};
let (mut base, apply_namespace) = runtime_base_directory()
.map_or_else(|| (fallback_base_directory(), true), |dir| (dir, false));

base.push("weaver");
if apply_namespace {
Expand All @@ -51,26 +54,27 @@ fn default_socket_endpoint_inner() -> SocketEndpoint {
SocketEndpoint::unix(socket_path)
}

/// Returns the UTF-8 XDG runtime directory when the platform provides one.
#[cfg(unix)]
fn runtime_base_directory() -> Option<Utf8PathBuf> {
runtime_dir().and_then(|path| Utf8PathBuf::from_path_buf(path).ok())
}

/// Chooses a UTF-8 temporary directory for the Unix socket fallback.
#[cfg(unix)]
fn fallback_base_directory() -> Utf8PathBuf {
let candidate = env::temp_dir();
match Utf8PathBuf::from_path_buf(candidate) {
Ok(path) => path,
Err(_) => Utf8PathBuf::from("/tmp"),
}
Utf8PathBuf::from_path_buf(candidate).unwrap_or_else(|_| Utf8PathBuf::from("/tmp"))
}

/// Namespaces fallback sockets by the effective Unix user ID.
#[cfg(unix)]
fn user_namespace() -> String {
let uid = unsafe { geteuid() };
let uid = Uid::effective();
format!("uid-{uid}")
}

/// Selects a loopback TCP endpoint where Unix sockets are unavailable.
#[cfg(not(unix))]
fn default_socket_endpoint_inner() -> SocketEndpoint {
SocketEndpoint::tcp("127.0.0.1", DEFAULT_TCP_PORT)
Expand Down
39 changes: 30 additions & 9 deletions crates/weaver-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,10 @@ pub use runtime::{RuntimePaths, RuntimePathsError};
use serde::{Deserialize, Serialize};
pub use socket::{SocketEndpoint, SocketParseError, SocketPreparationError};

/// Returns the locale used when configuration does not specify one.
fn default_locale() -> Locale { Locale::en_us() }

/// Help text for configuration fields exposed through the CLI.
const CONFIG_FIELD_HELP: &[(&str, &str)] = &[
(
"weaver.fields.daemon_socket.help",
Expand All @@ -74,6 +76,7 @@ const CONFIG_FIELD_HELP: &[(&str, &str)] = &[
"Selects the operator-facing locale",
),
];
/// Fallback help text for configuration fields without a specific entry.
const DEFAULT_CONFIG_FIELD_HELP: &str = "Overrides a shared configuration value";

/// Returns the canonical short help text for a configuration field help ID.
Expand Down Expand Up @@ -163,6 +166,11 @@ impl Config {
/// This wrapper does not introduce its own panic paths, but the
/// `ortho_config` generated loader may panic if its generated discovery or
/// CLI metadata trips an internal debug assertion.
///
/// # Errors
///
/// Returns an error when configuration discovery, parsing, or merging
/// fails.
pub fn load() -> ortho_config::OrthoResult<Self> { <Self as OrthoConfig>::load() }

/// Loads configuration using a custom iterator of CLI arguments.
Expand All @@ -172,6 +180,11 @@ impl Config {
/// This wrapper does not introduce its own panic paths, but the
/// `ortho_config` generated loader may panic if its generated discovery or
/// CLI metadata trips an internal debug assertion.
///
/// # Errors
///
/// Returns an error when the supplied arguments or other configuration
/// sources cannot be parsed or merged.
pub fn load_from_iter<I, T>(iter: I) -> ortho_config::OrthoResult<Self>
where
I: IntoIterator<Item = T>,
Expand All @@ -182,15 +195,15 @@ impl Config {

/// Accessor for the configured daemon socket.
#[must_use]
pub fn daemon_socket(&self) -> &SocketEndpoint { &self.daemon_socket }
pub const fn daemon_socket(&self) -> &SocketEndpoint { &self.daemon_socket }

/// Accessor for the logging filter expression.
#[must_use]
pub fn log_filter(&self) -> &str { self.log_filter.as_str() }
pub const fn log_filter(&self) -> &str { self.log_filter.as_str() }

/// Accessor for the logging format.
#[must_use]
pub fn log_format(&self) -> LogFormat { self.log_format }
pub const fn log_format(&self) -> LogFormat { self.log_format }

/// Builds a [`CapabilityMatrix`] from the configured directives.
#[must_use]
Expand All @@ -200,8 +213,9 @@ impl Config {

/// Accessor for the configured locale.
#[must_use]
pub fn locale(&self) -> &Locale { &self.locale }
pub const fn locale(&self) -> &Locale { &self.locale }

/// Removes duplicate capability overrides after configuration sources merge.
fn normalize_capability_overrides(&mut self) {
deduplicate_directives(&mut self.capability_overrides);
}
Expand Down Expand Up @@ -277,17 +291,24 @@ mod tests {
) {
let mut layers = [Vec::new(), Vec::new(), Vec::new(), Vec::new()];
for (directive, layer) in assignments {
layers[layer].push(directive);
let layer_directives = layers
.get_mut(layer)
.ok_or_else(|| TestCaseError::fail("layer index must be within 0..4"))?;
layer_directives.push(directive);
}

let [default_layer, file_layer, environment_layer, cli_layer] = &layers;
let mut defaults = serde_json::to_value(Config::default())
.map_err(|error| TestCaseError::fail(error.to_string()))?;
defaults["capability_overrides"] = json!(&layers[0]);
let default_overrides = defaults
.get_mut("capability_overrides")
.ok_or_else(|| TestCaseError::fail("missing capability_overrides default"))?;
*default_overrides = json!(default_layer);
let mut composer = MergeComposer::with_capacity(4);
composer.push_defaults(defaults);
composer.push_file(json!({ "capability_overrides": &layers[1] }), None);
composer.push_environment(json!({ "capability_overrides": &layers[2] }));
composer.push_cli(json!({ "capability_overrides": &layers[3] }));
composer.push_file(json!({ "capability_overrides": file_layer }), None);
composer.push_environment(json!({ "capability_overrides": environment_layer }));
composer.push_cli(json!({ "capability_overrides": cli_layer }));

let config = Config::merge_from_layers(composer.layers())
.map_err(|error| TestCaseError::fail(error.to_string()))?;
Expand Down
7 changes: 4 additions & 3 deletions crates/weaver-config/src/locale.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub struct Locale(LanguageIdentifier, String);
#[derive(Debug, Clone, Error, PartialEq, Eq)]
#[error("invalid locale {input:?}")]
pub struct LocaleParseError {
/// Original string that failed locale parsing.
input: String,
}

Expand All @@ -28,7 +29,7 @@ impl Locale {
#[must_use]
pub fn en_us() -> Self {
let language_identifier = langid!("en-US");
Self(language_identifier, "en-US".to_string())
Self(language_identifier, "en-US".to_owned())
}
}

Expand All @@ -45,15 +46,15 @@ impl FromStr for Locale {

fn from_str(value: &str) -> Result<Self, Self::Err> {
let locale = value.parse::<IcuLocale>().map_err(|_| Self::Err {
input: value.to_string(),
input: value.to_owned(),
})?;
let canonical = locale.to_string();
let language_identifier = locale
.id
.to_string()
.parse::<LanguageIdentifier>()
.map_err(|_| Self::Err {
input: value.to_string(),
input: value.to_owned(),
})?;
Ok(Self(language_identifier, canonical))
}
Expand Down
Loading
Loading