diff --git a/src/sshctl/config/generator.py b/src/sshctl/config/generator.py index 3d20a83..5b401ab 100644 --- a/src/sshctl/config/generator.py +++ b/src/sshctl/config/generator.py @@ -13,7 +13,16 @@ def generate_config_text(config: SshConfig, *, include_header: bool = True) -> s lines.append("# Generated by sshctl — do not hand-edit") lines.append("") - for block in config.blocks: + # OpenSSH uses the first value it finds for each option: specific hosts + # (Includes, then named blocks) must precede the `Host *` defaults. Includes + # also have to sit before any Host line, or they are scoped to that block. + for inc in config.raw_includes: + lines.append(f"Include {inc}") + if config.raw_includes: + lines.append("") + + defaults = [b for b in config.blocks if b.alias.strip() == "*"] + for block in [b for b in config.blocks if b not in defaults] + defaults: lines.append(f"Host {block.alias}") for key in _option_order(block): val = block.get(key) @@ -21,9 +30,6 @@ def generate_config_text(config: SshConfig, *, include_header: bool = True) -> s lines.append(f" {key} {val}") lines.append("") - for inc in config.raw_includes: - lines.append(f"Include {inc}") - return "\n".join(lines) diff --git a/tests/test_generator.py b/tests/test_generator.py index a7057dd..1194f2e 100644 --- a/tests/test_generator.py +++ b/tests/test_generator.py @@ -35,9 +35,12 @@ Include conf.d/98-jumpservers.conf reparsed = parse_config(generated) assert len(reparsed.blocks) == len(parsed.blocks) - assert reparsed.blocks[0].alias == parsed.blocks[0].alias - assert reparsed.blocks[1].hostname == parsed.blocks[1].hostname - assert reparsed.blocks[1].user == parsed.blocks[1].user + # Same blocks and values; order is normalised (Host * moves last). + by_alias = {b.alias: b for b in reparsed.blocks} + for block in parsed.blocks: + assert block.alias in by_alias + assert by_alias[block.alias].hostname == block.hostname + assert by_alias[block.alias].user == block.user def test_generate_config_header() -> None: @@ -101,3 +104,20 @@ def test_roundtrip_preserves_options() -> None: assert reblock.user == "deploy" assert reblock.proxy_jump == "gw" assert reblock.get("ForwardAgent") == "yes" + + +def test_includes_first_and_host_star_last() -> None: + # OpenSSH keeps the first value it finds for each option, so global defaults + # must come after everything more specific, or they override it. The + # generator used to write Host blocks first and Includes last, which made a + # `Host *` default (e.g. User root) beat every host in conf.d. + cfg = SshConfig(raw_includes=["conf.d/*.conf"]) + star = HostBlock(alias="*") + star.set("User", "root") + web = HostBlock(alias="web") + web.set("User", "deploy") + cfg.blocks = [star, web] + + lines = [ln for ln in generate_config_text(cfg, include_header=False).splitlines() if ln] + assert lines[0] == "Include conf.d/*.conf" + assert lines.index("Host web") < lines.index("Host *")