Running a full assess -> plan -> apply -> verify against Infra/LXD and Infra/Docker in throwaway worktrees, and a bootstrap into a scratch directory, surfaced the same two mistakes repeated across both commands: a shape was read where evidence was available, and a missing answer became a silent default rather than a refusal. adopt: - classify secret-shaped paths by content, not by filename. A live credential blocks; a file tracked against the repository's own ignore rules and a name-only match are warnings; findings name keys, never values. In Infra/Docker this turned 14 false blockers into 2 true ones and surfaced 14 files committed despite `**/.env`. - carry assess findings into the plan and refuse while an error-severity finding is unresolved. An owner may accept one through `acknowledgedFindings` with a reason; the acknowledgement enters the plan and therefore planHash, so approval covers it. - derive metadata.name from the git remote instead of the clone directory, and refuse to plan without a confirmed owner (runbook section 9). - propose content roots from the whole content vocabulary rather than the winning type's markers, and recognise N sibling directories sharing a marker file as one file-set root with a selector, as runbook 7.2 already specified. Authority defaulted rather than derived now asks. init: apply the guards adopt already had. Answers are validated against the vocabularies that already existed in constants (name, type, lifecycle, access) so init can no longer create a repository that fails its own validate; owners are required; a directory that already holds the planned paths is refused at plan time and pointed at adopt; and every path from a plan is confined before the first byte is written -- init wrote outside the repository from an edited plan. validate: mask fenced blocks and inline code spans before scanning for Markdown links. A PowerShell snippet in Infra/Docker's CLAUDE.md parsed as a link and kept validate red for a reason unrelated to the repository. paths: allow "." as a whole content-root path, never as a segment, so the file-set root runbook 7.2 describes can be declared. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
160 lines
6.2 KiB
Python
160 lines
6.2 KiB
Python
"""What `init` must refuse before it writes a repository.
|
|
|
|
`init` is the one path where the tool controls every byte of the result, so a
|
|
repository it creates must pass `repoctl validate` by construction. Each case
|
|
here produced a `success` envelope before the fix: an invalid contract, an
|
|
unconfirmed owner, a plan that could never be applied, or a write outside the
|
|
repository from a hand-edited plan.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from stewardship import bootstrap, io
|
|
from stewardship.validate import validate_repository
|
|
|
|
VALID = {
|
|
"name": "services-mail",
|
|
"title": "Corporate mail service",
|
|
"owners": ["it-infrastructure"],
|
|
"repositoryType": "service-config",
|
|
"lifecycle": "production",
|
|
}
|
|
|
|
|
|
def _answers(**overrides):
|
|
data = dict(VALID)
|
|
data.update(overrides)
|
|
return data
|
|
|
|
|
|
# --- answers that would produce an invalid repository ------------------------
|
|
|
|
@pytest.mark.parametrize(
|
|
("overrides", "code"),
|
|
[
|
|
({"name": "Services/Mail"}, "INIT_NAME_INVALID"),
|
|
({"name": "Services Mail"}, "INIT_NAME_INVALID"),
|
|
({"name": "MAIL"}, "INIT_NAME_INVALID"),
|
|
({"name": "-leading-dash"}, "INIT_NAME_INVALID"),
|
|
({"repositoryType": "mail-server"}, "INIT_TYPE_UNKNOWN"),
|
|
({"lifecycle": "bogus"}, "INIT_LIFECYCLE_UNKNOWN"),
|
|
({"access": "semi-public"}, "INIT_ACCESS_UNKNOWN"),
|
|
({"owners": []}, "INIT_OWNER_UNKNOWN"),
|
|
({"name": ""}, "INIT_ANSWERS_INCOMPLETE"),
|
|
],
|
|
)
|
|
def test_answers_that_break_the_schema_are_refused(overrides, code) -> None:
|
|
with pytest.raises(bootstrap.BootstrapError) as excinfo:
|
|
bootstrap.BootstrapAnswers.from_mapping(_answers(**overrides))
|
|
assert excinfo.value.code == code
|
|
|
|
|
|
def test_a_rejected_name_comes_with_a_usable_suggestion() -> None:
|
|
"""An error that only says "invalid" makes the owner guess the rule."""
|
|
with pytest.raises(bootstrap.BootstrapError) as excinfo:
|
|
bootstrap.BootstrapAnswers.from_mapping(_answers(name="Services/Mail"))
|
|
assert "'services-mail'" in str(excinfo.value)
|
|
|
|
|
|
def test_owner_refusal_names_both_ways_to_answer() -> None:
|
|
"""An error that only says "refused" leaves the reader guessing the flag."""
|
|
with pytest.raises(bootstrap.BootstrapError) as excinfo:
|
|
bootstrap.BootstrapAnswers.from_mapping(_answers(owners=[]))
|
|
message = str(excinfo.value)
|
|
assert "--owner" in message and "owners:" in message
|
|
|
|
|
|
# --- the created repository must validate ------------------------------------
|
|
|
|
def test_a_freshly_created_repository_validates(tmp_path: Path) -> None:
|
|
repo = tmp_path / "mail"
|
|
repo.mkdir()
|
|
answers = bootstrap.BootstrapAnswers.from_mapping(_answers())
|
|
plan = bootstrap.build_bootstrap_plan(answers, repo)
|
|
bootstrap.apply_bootstrap_plan(repo, plan, plan["planHash"])
|
|
(repo / ".git").mkdir()
|
|
|
|
report = validate_repository(repo)
|
|
assert not [f for f in report.findings if f.severity == "error"]
|
|
# Content-root directories are deliberately not created (bootstrap docstring:
|
|
# no placeholder directories), so those warnings are expected, not failures.
|
|
assert {f.code for f in report.findings} <= {"CONTENT_ROOT_PATH_MISSING"}
|
|
|
|
|
|
# --- collisions belong to plan, not to apply ---------------------------------
|
|
|
|
def test_plan_refuses_a_directory_that_is_already_a_repository(tmp_path: Path) -> None:
|
|
repo = tmp_path / "existing"
|
|
(repo / "ops").mkdir(parents=True)
|
|
(repo / "ops" / "contract.yaml").write_text("existing: true\n", encoding="utf-8")
|
|
answers = bootstrap.BootstrapAnswers.from_mapping(_answers())
|
|
with pytest.raises(bootstrap.BootstrapError) as excinfo:
|
|
bootstrap.build_bootstrap_plan(answers, repo)
|
|
assert excinfo.value.code == "INIT_PATH_COLLISION"
|
|
assert "adopt" in str(excinfo.value)
|
|
|
|
|
|
def test_planning_without_a_target_still_works(tmp_path: Path) -> None:
|
|
"""`root` is optional; omitting it plans without the collision check."""
|
|
answers = bootstrap.BootstrapAnswers.from_mapping(_answers())
|
|
assert bootstrap.build_bootstrap_plan(answers)["planHash"].startswith("sha256:")
|
|
|
|
|
|
# --- a plan is an editable file, so apply confines every path ----------------
|
|
|
|
@pytest.mark.parametrize(
|
|
"escape",
|
|
["../ESCAPED.md", "../../ESCAPED.md", "ops/../../ESCAPED.md", "/etc/passwd", "C:/Windows/x"],
|
|
)
|
|
def test_apply_refuses_to_write_outside_the_repository(tmp_path: Path, escape: str) -> None:
|
|
repo = tmp_path / "inner"
|
|
repo.mkdir()
|
|
answers = bootstrap.BootstrapAnswers.from_mapping(_answers())
|
|
plan = bootstrap.build_bootstrap_plan(answers, repo)
|
|
plan["files"] = [{"path": escape, "content": "escaped\n"}]
|
|
plan.pop("planHash")
|
|
plan["planHash"] = io.sha256(plan)
|
|
|
|
with pytest.raises(bootstrap.BootstrapError) as excinfo:
|
|
bootstrap.apply_bootstrap_plan(repo, plan, plan["planHash"])
|
|
assert excinfo.value.code == "INIT_PATH_OUTSIDE_REPOSITORY"
|
|
assert not list(tmp_path.glob("ESCAPED.md"))
|
|
assert not list(tmp_path.parent.glob("ESCAPED.md"))
|
|
|
|
|
|
def test_a_refused_escape_writes_nothing_at_all(tmp_path: Path) -> None:
|
|
"""Confinement runs over every entry before the first byte is written."""
|
|
repo = tmp_path / "inner"
|
|
repo.mkdir()
|
|
answers = bootstrap.BootstrapAnswers.from_mapping(_answers())
|
|
plan = bootstrap.build_bootstrap_plan(answers, repo)
|
|
plan["files"].append({"path": "../ESCAPED.md", "content": "escaped\n"})
|
|
plan.pop("planHash")
|
|
plan["planHash"] = io.sha256(plan)
|
|
|
|
with pytest.raises(bootstrap.BootstrapError):
|
|
bootstrap.apply_bootstrap_plan(repo, plan, plan["planHash"])
|
|
assert not (repo / "ops" / "contract.yaml").exists()
|
|
|
|
|
|
# --- refusals stay machine-readable ------------------------------------------
|
|
|
|
def test_refusals_are_envelopes_not_stderr_lines(tmp_path: Path, capsys) -> None:
|
|
from stewardship.cli import main
|
|
|
|
repo = tmp_path / "mail"
|
|
repo.mkdir()
|
|
exit_code = main(
|
|
["init", "--repo", str(repo), "--name", "Services/Mail",
|
|
"--type", "service-config", "--owner", "x", "--output", "json"]
|
|
)
|
|
envelope = json.loads(capsys.readouterr().out)
|
|
assert exit_code != 0
|
|
assert envelope["outcome"] == "failure"
|
|
assert envelope["findings"][0]["code"] == "INIT_NAME_INVALID"
|