Skip to content

Commit 46d7b1a

Browse files
committed
fix(tmachine): harden the gateway TOML merge against unhandled statements
Treat array-of-tables headers as table boundaries so replacing a value before one no longer consumes its header. Require the overrides to be valid TOML, accept single- and double-quoted keys, and fail when any override value is missing from the merged result instead of silently dropping it. Add regression tests and a mise task for them. Signed-off-by: Evan Lezar <elezar@nvidia.com>
1 parent da7472e commit 46d7b1a

3 files changed

Lines changed: 144 additions & 7 deletions

File tree

‎tasks/test.toml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,13 @@ depends = [
2626
"test:maintainer-approval",
2727
"test:cargo-lockfile-alignment",
2828
"test:review-readiness",
29+
"test:merge-gateway-toml",
2930
]
3031

32+
["test:merge-gateway-toml"]
33+
description = "Test the tmachine gateway TOML merge script"
34+
run = "uv run --no-project --with pytest pytest tests/tmachine/ansible/roles/openshell_gateway/files/merge_gateway_toml_test.py"
35+
3136
["test:cargo-lockfile-alignment"]
3237
description = "Test the Cargo lockfile alignment check"
3338
run = "uv run --no-project --with pytest pytest tasks/scripts/check_cargo_lockfile_alignment_test.py"

‎tests/tmachine/ansible/roles/openshell_gateway/files/merge-gateway-toml.py‎

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@
1717
text is parsed as TOML before it is written, and the script fails, leaving BASE
1818
as it was, if it is not valid.
1919
20+
The overrides must be valid TOML, and the script fails if any of their values is
21+
missing from the merged result, so a statement it cannot rewrite is an error
22+
rather than a silent no-op.
23+
2024
Limits: a key's value in BASE is replaced as written lines, up to the next key,
2125
header, comment or blank line. A key can't be removed.
2226
"""
@@ -28,16 +32,26 @@
2832
import tomllib
2933

3034
HEADER = re.compile(r"^\s*\[([^\[\]]+)\]\s*(#.*)?$")
31-
KEY = re.compile(r"^\s*([A-Za-z0-9_-]+|\"[^\"]+\")\s*=")
35+
ARRAY_HEADER = re.compile(r"^\s*\[\[[^\[\]]+\]\]\s*(#.*)?$")
36+
KEY = re.compile(r"^\s*([A-Za-z0-9_-]+|\"[^\"]+\"|'[^']+')\s*=")
3237
MINIMAL = "[openshell]\nversion = 2\n"
3338

3439

3540
def table_name(line):
3641
return re.sub(r"\s+", "", HEADER.match(line).group(1))
3742

3843

44+
def is_boundary(line):
45+
"""A table or array-of-tables header ends the current table."""
46+
return bool(HEADER.match(line) or ARRAY_HEADER.match(line))
47+
48+
49+
def key_name(raw):
50+
return raw[1:-1] if raw[0] in "\"'" else raw
51+
52+
3953
def is_statement_start(line):
40-
return bool(HEADER.match(line) or KEY.match(line))
54+
return bool(is_boundary(line) or KEY.match(line))
4155

4256

4357
def is_break(line):
@@ -51,7 +65,7 @@ def statements(lines):
5165
for line in lines:
5266
key = KEY.match(line)
5367
if key:
54-
found.append((key.group(1), [line]))
68+
found.append((key_name(key.group(1)), [line]))
5569
elif found and not is_break(line):
5670
found[-1][1].append(line)
5771
return found
@@ -81,14 +95,14 @@ def apply(lines, table, new):
8195
return lines + ["", f"[{table}]", *(l for _, stmt in new for l in stmt)]
8296
for key, stmt in new:
8397
end = next(
84-
(i for i in range(start + 1, len(lines)) if HEADER.match(lines[i])),
98+
(i for i in range(start + 1, len(lines)) if is_boundary(lines[i])),
8599
len(lines),
86100
)
87101
existing = next(
88102
(
89103
i
90104
for i in range(start + 1, end)
91-
if (m := KEY.match(lines[i])) and m.group(1) == key
105+
if (m := KEY.match(lines[i])) and key_name(m.group(1)) == key
92106
),
93107
None,
94108
)
@@ -102,6 +116,15 @@ def apply(lines, table, new):
102116
return lines
103117

104118

119+
def contains(merged, expected):
120+
"""Whether every table and value in EXPECTED is present in MERGED."""
121+
if isinstance(expected, dict):
122+
return isinstance(merged, dict) and all(
123+
k in merged and contains(merged[k], v) for k, v in expected.items()
124+
)
125+
return merged == expected
126+
127+
105128
def main():
106129
parser = argparse.ArgumentParser()
107130
parser.add_argument("base")
@@ -117,13 +140,22 @@ def main():
117140
else:
118141
text = MINIMAL
119142
lines = text.splitlines()
120-
for table, new in override_tables(open(args.overrides).read()).items():
143+
override_text = open(args.overrides).read()
144+
try:
145+
wanted = tomllib.loads(override_text)
146+
except tomllib.TOMLDecodeError as error:
147+
sys.exit(f"{args.overrides} is not valid TOML: {error}")
148+
for table, new in override_tables(override_text).items():
121149
lines = apply(lines, table, new)
122150
merged = "\n".join(lines) + "\n"
123151
try:
124-
tomllib.loads(merged)
152+
result = tomllib.loads(merged)
125153
except tomllib.TOMLDecodeError as error:
126154
sys.exit(f"merged {args.base} is not valid TOML: {error}")
155+
# The rewriter works on lines, so confirm every override really landed
156+
# rather than trusting it to have handled each statement.
157+
if not contains(result, wanted):
158+
sys.exit(f"the overrides in {args.overrides} were not all applied to {args.base}")
127159
with open(args.base, "w") as out:
128160
out.write(merged)
129161
if created:
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
import subprocess
5+
import sys
6+
import tomllib
7+
from pathlib import Path
8+
9+
import pytest
10+
11+
SCRIPT = Path(__file__).with_name("merge-gateway-toml.py")
12+
BASE = '[openshell]\nversion = 2\n\n[openshell.drivers.podman]\n# keep\nhealth_check_interval_secs = 10\n'
13+
14+
15+
def merge(tmp_path, base, overrides, default=None):
16+
base_file, override_file = tmp_path / "gateway.toml", tmp_path / "overrides.toml"
17+
if base is not None:
18+
base_file.write_text(base)
19+
override_file.write_text(overrides)
20+
args = [sys.executable, str(SCRIPT), str(base_file), str(override_file)]
21+
if default is not None:
22+
default_file = tmp_path / "default.toml"
23+
default_file.write_text(default)
24+
args += ["--default", str(default_file)]
25+
run = subprocess.run(args, capture_output=True, text=True)
26+
return run, base_file
27+
28+
29+
def test_replaces_and_preserves_comments(tmp_path):
30+
run, base = merge(tmp_path, BASE, '[openshell.drivers.podman]\nhealth_check_interval_secs = 15\nuserns = "keep-id"\n')
31+
assert run.returncode == 0, run.stderr
32+
text = base.read_text()
33+
assert "# keep" in text
34+
assert tomllib.loads(text)["openshell"]["drivers"]["podman"] == {
35+
"health_check_interval_secs": 15,
36+
"userns": "keep-id",
37+
}
38+
39+
40+
def test_idempotent(tmp_path):
41+
overrides = '[openshell.drivers.podman]\nuserns = "private"\nuidmap = ["0:0:1",\n "1:1:65535"]\n'
42+
merge(tmp_path, BASE, overrides)
43+
first = (tmp_path / "gateway.toml").read_text()
44+
run, base = merge(tmp_path, first, overrides)
45+
assert run.returncode == 0 and base.read_text() == first
46+
47+
48+
def test_array_of_tables_header_is_a_boundary(tmp_path):
49+
base = (
50+
"[openshell.drivers.podman]\nhealth_check_interval_secs = 10\n"
51+
'[[openshell.supervisor.middleware]]\nname = "local-guard"\n'
52+
'grpc_endpoint = "https://127.0.0.1:50051"\n'
53+
)
54+
run, out = merge(tmp_path, base, "[openshell.drivers.podman]\nhealth_check_interval_secs = 15\n")
55+
assert run.returncode == 0, run.stderr
56+
parsed = tomllib.loads(out.read_text())["openshell"]
57+
assert parsed["drivers"]["podman"] == {"health_check_interval_secs": 15}
58+
assert parsed["supervisor"]["middleware"] == [
59+
{"name": "local-guard", "grpc_endpoint": "https://127.0.0.1:50051"}
60+
]
61+
62+
63+
@pytest.mark.parametrize("quote", ['"', "'"])
64+
def test_quoted_key_is_applied(tmp_path, quote):
65+
run, base = merge(tmp_path, BASE, f'[openshell.drivers.podman]\n{quote}userns{quote} = "keep-id"\n')
66+
assert run.returncode == 0, run.stderr
67+
assert tomllib.loads(base.read_text())["openshell"]["drivers"]["podman"]["userns"] == "keep-id"
68+
69+
70+
@pytest.mark.parametrize(
71+
"overrides",
72+
[
73+
'[openshell.drivers.podman]\nuserns "keep-id"\n',
74+
'[openshell.drivers.podman]\nuserns = "keep-id\n',
75+
'[[openshell.supervisor.middleware]]\nname = "x"\n',
76+
'userns = "keep-id"\n',
77+
],
78+
)
79+
def test_rejects_unusable_overrides_and_leaves_base(tmp_path, overrides):
80+
run, base = merge(tmp_path, BASE, overrides)
81+
assert run.returncode != 0
82+
assert base.read_text() == BASE
83+
84+
85+
def test_dotted_key_not_silently_dropped(tmp_path):
86+
run, base = merge(tmp_path, BASE, "[openshell.drivers]\npodman.userns = \"auto\"\n")
87+
if run.returncode == 0:
88+
assert tomllib.loads(base.read_text())["openshell"]["drivers"]["podman"]["userns"] == "auto"
89+
else:
90+
assert base.read_text() == BASE
91+
92+
93+
def test_creates_from_default_else_minimal(tmp_path):
94+
run, base = merge(tmp_path, None, '[openshell.drivers.podman]\nuserns = "auto"\n', default=BASE)
95+
assert run.returncode == 0 and "health_check_interval_secs = 10" in base.read_text()
96+
other = tmp_path / "other"
97+
other.mkdir()
98+
run, base = merge(other, None, '[openshell.drivers.podman]\nuserns = "auto"\n')
99+
parsed = tomllib.loads(base.read_text())
100+
assert parsed["openshell"]["version"] == 2

0 commit comments

Comments
 (0)