Skip to content

Commit b651d44

Browse files
committed
fix(gateway): reject non-integer versions and allow an empty config dir
Require every layer to declare `[openshell] version` as an integer so a malformed value cannot be hidden by a later drop-in that declares 2. Report an error about a whole table that several files contribute to as an error in the merged configuration, not in the last file that touches it. Treat an empty `--config-dir` or `OPENSHELL_GATEWAY_CONFIG_DIR` as turning drop-in configs off, including the implicit `gateway.d` directory. Signed-off-by: Evan Lezar <elezar@nvidia.com>
1 parent 12855a4 commit b651d44

5 files changed

Lines changed: 152 additions & 16 deletions

File tree

‎crates/openshell-server/src/cli.rs‎

Lines changed: 64 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,12 @@ enum ConfigCommand {
5959
Preflight(ConfigPreflightArgs),
6060
}
6161

62+
/// Parse a path, accepting the empty string that clap's `PathBuf` parser rejects.
63+
fn allow_empty_path() -> impl clap::builder::TypedValueParser<Value = PathBuf> {
64+
use clap::builder::TypedValueParser as _;
65+
clap::builder::OsStringValueParser::new().map(PathBuf::from)
66+
}
67+
6268
#[derive(clap::Args, Debug, Default)]
6369
struct ConfigPreflightArgs {
6470
/// Explicit configuration path. Overrides `OPENSHELL_GATEWAY_CONFIG` and XDG discovery.
@@ -68,7 +74,12 @@ struct ConfigPreflightArgs {
6874
path: Option<PathBuf>,
6975

7076
/// Explicit drop-in directory. Defaults to `gateway.d` next to the base file.
71-
#[arg(long, conflicts_with = "gateway_args")]
77+
/// An empty value disables drop-in configs.
78+
#[arg(
79+
long,
80+
conflicts_with = "gateway_args",
81+
value_parser = allow_empty_path()
82+
)]
7283
config_dir: Option<PathBuf>,
7384

7485
/// Gateway daemon arguments to replay after `--`.
@@ -91,8 +102,9 @@ struct RunArgs {
91102
///
92103
/// Drop-in configs apply in lexical order and a later drop-in config wins. Tables
93104
/// merge key by key; scalars and arrays replace. Defaults to `gateway.d`
94-
/// next to the base file when that directory exists.
95-
#[arg(long, env = "OPENSHELL_GATEWAY_CONFIG_DIR")]
105+
/// next to the base file when that directory exists. An empty value
106+
/// disables drop-in configs.
107+
#[arg(long, env = "OPENSHELL_GATEWAY_CONFIG_DIR", value_parser = allow_empty_path())]
96108
config_dir: Option<PathBuf>,
97109

98110
/// Operator-assigned name for this gateway installation.
@@ -1454,10 +1466,11 @@ fn resolve_config_sources(
14541466
Ok(_) | Err(_) => Some(default_path),
14551467
}
14561468
};
1457-
// An explicit directory must exist. Otherwise use `gateway.d` beside the
1458-
// base file (or beside the default location) when it is there.
1469+
// An explicit directory must exist, and an empty one turns drop-in configs
1470+
// off. Otherwise use `gateway.d` beside the base file (or beside the
1471+
// default location) when it is there.
14591472
let dir = if let Some(dir) = dir_override.or_else(|| args.config_dir.clone()) {
1460-
Some(dir)
1473+
(!dir.as_os_str().is_empty()).then_some(dir)
14611474
} else {
14621475
let anchor = match base.clone() {
14631476
Some(path) => path,
@@ -3864,6 +3877,51 @@ require_client_auth = true
38643877
});
38653878
}
38663879

3880+
#[test]
3881+
fn an_empty_config_dir_disables_drop_in_configs() {
3882+
let tmp = tempfile::tempdir().unwrap();
3883+
let base = tmp.path().join("gateway.toml");
3884+
std::fs::write(&base, "[openshell]\nversion = 2\n").unwrap();
3885+
std::fs::create_dir(tmp.path().join("gateway.d")).unwrap();
3886+
std::fs::write(
3887+
tmp.path().join("gateway.d").join("10-a.toml"),
3888+
"[openshell]\nversion = 2\n",
3889+
)
3890+
.unwrap();
3891+
let base_arg = base.to_str().unwrap();
3892+
// The flag, then the environment variable.
3893+
Environment::new()
3894+
.remove("OPENSHELL_GATEWAY_CONFIG")
3895+
.remove("OPENSHELL_GATEWAY_CONFIG_DIR")
3896+
.run(|| {
3897+
let (args, _) = parse_with_args(&[
3898+
"openshell-gateway",
3899+
"--config",
3900+
base_arg,
3901+
"--config-dir",
3902+
"",
3903+
]);
3904+
assert_eq!(
3905+
super::resolve_config_sources(&args, None, None)
3906+
.unwrap()
3907+
.dir,
3908+
None
3909+
);
3910+
});
3911+
Environment::new()
3912+
.remove("OPENSHELL_GATEWAY_CONFIG")
3913+
.set("OPENSHELL_GATEWAY_CONFIG_DIR", "")
3914+
.run(|| {
3915+
let (args, _) = parse_with_args(&["openshell-gateway", "--config", base_arg]);
3916+
assert_eq!(
3917+
super::resolve_config_sources(&args, None, None)
3918+
.unwrap()
3919+
.dir,
3920+
None
3921+
);
3922+
});
3923+
}
3924+
38673925
#[test]
38683926
fn preflight_merges_drop_ins_and_names_a_bad_drop_in() {
38693927
let tmp = tempfile::tempdir().unwrap();

‎crates/openshell-server/src/config_file.rs‎

Lines changed: 82 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1328,6 +1328,10 @@ pub enum ConfigFileError {
13281328
"unsupported gateway config version {version}; this build requires version {SCHEMA_VERSION}; migrate legacy fields to the version {SCHEMA_VERSION} schema"
13291329
)]
13301330
UnsupportedVersion { version: u32 },
1331+
#[error(
1332+
"invalid gateway config version; `openshell.version` must be the integer {SCHEMA_VERSION}"
1333+
)]
1334+
InvalidVersion,
13311335
#[error(
13321336
"`{field}` is not allowed in the gateway config file — set the {env} env var or pass {cli} on the command line"
13331337
)]
@@ -1745,7 +1749,8 @@ fn preflight_error(
17451749
"future_version"
17461750
}
17471751
ConfigFileError::UnsupportedVersion { .. } => "unsupported_version",
1748-
ConfigFileError::Parse { .. }
1752+
ConfigFileError::InvalidVersion
1753+
| ConfigFileError::Parse { .. }
17491754
| ConfigFileError::MergedParse { .. }
17501755
| ConfigFileError::InFile { .. }
17511756
| ConfigFileError::SecretInFile { .. }
@@ -1893,7 +1898,10 @@ fn check_version(table: &toml::Table) -> Result<(), ConfigFileError> {
18931898
version: u32::try_from(*version).unwrap_or(u32::MAX),
18941899
})
18951900
}
1896-
Some(_) => Ok(()),
1901+
Some(toml::Value::Integer(_)) => Ok(()),
1902+
// A string or table here could be overwritten by a later file that
1903+
// declares the integer, so each file must declare it itself.
1904+
Some(_) => Err(ConfigFileError::InvalidVersion),
18971905
}
18981906
}
18991907

@@ -2014,6 +2022,17 @@ fn has_path(table: &toml::Table, path: &[String]) -> bool {
20142022
}
20152023
}
20162024

2025+
/// The value at `path` in `table`.
2026+
fn value_at<'a>(table: &'a toml::Table, path: &[String]) -> Option<&'a toml::Value> {
2027+
let (first, rest) = path.split_first()?;
2028+
let value = table.get(first)?;
2029+
if rest.is_empty() {
2030+
Some(value)
2031+
} else {
2032+
value_at(value.as_table()?, rest)
2033+
}
2034+
}
2035+
20172036
/// The file that sets the key at `path`: the last one, whose value wins, or
20182037
/// the first one for a key that is wrong wherever it appears.
20192038
fn locate<'a>(layers: &'a [Layer], path: &[String], first: bool) -> Option<&'a Path> {
@@ -2037,6 +2056,7 @@ fn describe_layers(layers: &[Layer]) -> String {
20372056
/// Report a deserialization error against the file that holds the key.
20382057
fn attribute_parse(
20392058
layers: &[Layer],
2059+
merged: &toml::Table,
20402060
error: &serde_path_to_error::Error<toml::de::Error>,
20412061
) -> ConfigFileError {
20422062
let message = error.inner().message().trim_end();
@@ -2057,8 +2077,17 @@ fn attribute_parse(
20572077
{
20582078
path.push(name.to_string());
20592079
}
2060-
// A missing key is a property of the merged table, not of one file.
2061-
let owner = if message.starts_with("missing field") {
2080+
// A missing key is a property of the merged table, not of one file. So is
2081+
// an error about a whole table that several files contribute to, such as a
2082+
// rule over two of its keys.
2083+
let spans_files = unknown.is_none()
2084+
&& value_at(merged, &path).is_some_and(toml::Value::is_table)
2085+
&& layers
2086+
.iter()
2087+
.filter(|layer| has_path(&layer.table, &path))
2088+
.count()
2089+
> 1;
2090+
let owner = if message.starts_with("missing field") || spans_files {
20622091
None
20632092
} else {
20642093
locate(layers, &path, unknown.is_some())
@@ -2105,8 +2134,8 @@ fn attribute_semantic(layers: &[Layer], error: ConfigFileError) -> ConfigFileErr
21052134
/// Deserialize and validate the merged table.
21062135
fn finish_layered(layers: &[Layer], merged: toml::Table) -> Result<ConfigFile, ConfigFileError> {
21072136
check_version(&merged)?;
2108-
let file: ConfigFile = serde_path_to_error::deserialize(toml::Value::Table(merged))
2109-
.map_err(|error| attribute_parse(layers, &error))?;
2137+
let file: ConfigFile = serde_path_to_error::deserialize(toml::Value::Table(merged.clone()))
2138+
.map_err(|error| attribute_parse(layers, &merged, &error))?;
21102139
validate_loaded(file).map_err(|error| attribute_semantic(layers, error))
21112140
}
21122141

@@ -4381,6 +4410,53 @@ ssh_gateway_port = 8080
43814410
assert!(error.to_string().contains("10-backend.toml"), "{error}");
43824411
}
43834412

4413+
#[test]
4414+
fn layered_a_non_integer_version_is_rejected_even_when_a_later_file_overrides_it() {
4415+
let (_dir, base, frags) = layered_dir(
4416+
"[openshell]\nversion = \"two\"\n",
4417+
&[("10-ok.toml", "[openshell]\nversion = 2\n")],
4418+
);
4419+
let error = load_layered(Some(&base), Some(&frags)).unwrap_err();
4420+
assert!(matches!(error.root(), ConfigFileError::InvalidVersion));
4421+
assert!(error.to_string().contains("gateway.toml"), "{error}");
4422+
4423+
let (_dir, base, frags) =
4424+
layered_dir(BASE, &[("10-bad.toml", "[openshell]\nversion = \"two\"\n")]);
4425+
let error = load_layered(Some(&base), Some(&frags)).unwrap_err();
4426+
assert!(matches!(error.root(), ConfigFileError::InvalidVersion));
4427+
assert!(error.to_string().contains("10-bad.toml"), "{error}");
4428+
}
4429+
4430+
#[test]
4431+
fn layered_whole_table_error_across_files_names_the_merged_config() {
4432+
let log =
4433+
|body: &str| format!("[openshell]\nversion = 2\n[openshell.gateway.ocsf_log]\n{body}");
4434+
let (_dir, base, frags) = layered_dir(
4435+
&log("path = 'log'\nrotation = 'never'\nmax_files = 7\n"),
4436+
&[("10-path.toml", &log("path = 'other'\n"))],
4437+
);
4438+
let error = load_layered(Some(&base), Some(&frags)).unwrap_err();
4439+
assert!(
4440+
matches!(error.root(), ConfigFileError::MergedParse { .. }),
4441+
"{error}"
4442+
);
4443+
assert!(
4444+
error.to_string().contains("max_files requires daily"),
4445+
"{error}"
4446+
);
4447+
4448+
// One file owns the whole table, so it is named.
4449+
let (_dir, base, frags) = layered_dir(
4450+
"[openshell]\nversion = 2\n",
4451+
&[(
4452+
"10-log.toml",
4453+
&log("path = 'log'\nrotation = 'never'\nmax_files = 7\n"),
4454+
)],
4455+
);
4456+
let error = load_layered(Some(&base), Some(&frags)).unwrap_err();
4457+
assert!(error.to_string().contains("10-log.toml"), "{error}");
4458+
}
4459+
43844460
#[test]
43854461
fn layered_preflight_keeps_unavailable_for_a_malformed_version() {
43864462
let (_dir, base, frags) = layered_dir(BASE, &[]);

‎deploy/man/openshell-gateway.8.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,8 @@ configured in the TOML file passed with **--config**.
165165
: Directory of **\*.toml** drop-in configs merged over the **--config**
166166
file. Drop-in configs apply in lexical order and a later drop-in config wins. Each file must declare **version = 2**; a drop-in config may set only some keys of a table. Tables
167167
merge key by key; scalars and arrays replace. Defaults to **gateway.d**
168-
next to the config file when that directory exists.
168+
next to the config file when that directory exists. An empty value turns
169+
drop-in configs off.
169170
Environment: **OPENSHELL_GATEWAY_CONFIG_DIR**.
170171

171172
# CONFIGURATION PREFLIGHT

‎deploy/rpm/CONFIGURATION.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,8 @@ arrays replace. For example, `gateway.d/10-podman.toml` containing
7373
`[openshell]` with `version = 2` and `[openshell.drivers.podman]` with
7474
`userns = "keep-id"` changes only that key. Every drop-in config declares the
7575
version.
76-
Set `OPENSHELL_GATEWAY_CONFIG_DIR` to use a different directory.
76+
Set `OPENSHELL_GATEWAY_CONFIG_DIR` to use a different directory, or to an empty
77+
value to turn drop-in configs off.
7778

7879
To override the path to the TOML config file entirely:
7980

‎docs/how-it-works/gateways/configuration.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,9 @@ preflight and gateway startup.
5858

5959
## Drop-In Configs
6060

61-
The gateway merges `*.toml` drop-in configs from a directory over the base file. Use drop-in configs to customize a package-seeded `gateway.toml` without editing it. Set the directory with `--config-dir` or `OPENSHELL_GATEWAY_CONFIG_DIR`. When you do not set it, the gateway uses `gateway.d` next to the base file if that directory exists. An explicit directory must exist.
61+
The gateway merges `*.toml` drop-in configs from a directory over the base file. Use drop-in configs to customize a package-seeded `gateway.toml` without editing it. Set the directory with `--config-dir` or `OPENSHELL_GATEWAY_CONFIG_DIR`. When you do not set it, the gateway uses `gateway.d` next to the base file if that directory exists. An explicit directory must exist. Set `--config-dir` or `OPENSHELL_GATEWAY_CONFIG_DIR` to an empty value to turn drop-in configs off.
6262

63-
Drop-in configs apply in lexical order by file name, and a later one wins. Each file must declare `[openshell] version = 2`. The merge works as follows:
63+
Drop-in configs apply in lexical order by file name, and a later one wins. Each file must declare `[openshell] version = 2` as an integer. The merge works as follows:
6464

6565
- Tables merge key by key.
6666
- Scalars and arrays replace the earlier value. An array in a drop-in config replaces the whole array.

0 commit comments

Comments
 (0)