From 2d4d3abfd371e0be419dd69b2215ec15bba2c89d Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 10:32:13 +0900 Subject: [PATCH] =?UTF-8?q?fix(compose):=20=EA=B3=84=EC=95=BD=20=ED=8C=90?= =?UTF-8?q?=EC=A0=95=EA=B8=B0=EA=B0=80=20heap=20dump=20=EA=B2=BD=EB=A1=9C?= =?UTF-8?q?=C2=B7=EA=B2=B9=EC=B9=9C=20mount=C2=B7ACL=20=EC=A4=84=EC=9D=84?= =?UTF-8?q?=20=EC=8B=A4=EC=A0=9C=EC=B2=98=EB=9F=BC=20=EC=9D=BD=EB=8A=94?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: compose 계약 판정기(scripts/compose-contract-verdict.py)가 입력을 실제로 쓰는 쪽과 다르게 읽어, 틀린 계약을 통과시키거나 맞는 계약을 떨어뜨린다. - heap dump 경로 정규식이 줄바꿈을 넘어 잡는다. 주석이 옵션으로 끝나거나, 따옴표 없는 ENV 줄 끝이거나, 빈 값이거나, 한 줄에 두 번이면 엉뚱한 경로를 읽고, 진짜 경로의 tmpfs가 rc=0으로 지나간다. - tmpfs 아래 더 깊은 volume·bind가 heap 경로를 잡아도 실패로 본다. 겹친 bind에서는 목록에 먼저 나온 쪽 ACL 파일을 읽는다. Docker는 선언 순서와 상관없이 더 깊은 mount를 위에 붙인다. - 역할 목록·최상위 목록이 문자열·숫자·object면 빈 목록으로 읽는다. - 같은 사용자가 두 줄이어도 둘 다 `on`일 때만 잡는다. Redis는 이름이 겹치면 기동을 거절한다. - ACL 줄을 str.split()으로 잘라, Redis가 거절하는 탭·U+00A0·공백 둘· lone CR·주석 줄을 통과시킨다. 줄 앞 공백·`on`이 이름 바로 뒤가 아닌 줄처럼 Redis가 받는 것은 떨어뜨린다. 같은 줄의 `on` 뒤 `off`·`reset`은 켜진 계정으로 본다. - 꺼진 계정 조건과 lane id `fullmatch`를 약하게 바꿔도 시험이 통과한다. 고른 방법: - Dockerfile은 LF에서만 자르고 주석 줄을 뺀 뒤 한 줄씩 값을 읽는다. 값이 여럿이면 JVM이 어느 것을 받을지 명령마다 달라, 모두 판정한다. 마지막 값이 비면 78이다. - mount는 target을 한 번 정규화해 `Mount`로 두고, 경로를 품은 가장 깊은 mount를 고르는 함수 하나를 heap dump와 ACL 파일이 같이 쓴다. 중복 target도 정규화한 값으로 비교한다. - ACL은 redis-server --aclfile처럼 읽는 함수 하나로 줄 번호와 낱말을 만든다. `user `으로 시작하지 않는 줄, 겹친 이름, 마지막 on/off/reset으로 정한 켜짐을 그 결과로 판정한다. - 선택 목록은 없음·null·false 또는 이름의 목록만 받는다. - 버린 안: 카드의 첫 줄 MULTILINE 검색(이어진 줄에 두 번이면 앞 값을 읽는다), 마지막 값 하나만 판정(뒤 명령의 다른 값이 앞의 tmpfs를 가린다), 건마다 카드(같은 두 파일에서 충돌한다). 전제(C2): desktop Docker 29.6.1·compose 5.3.0·redis:7.4로 각 항목을 실제로 돌렸고 모두 위 동작과 맞았다. 틀린 전제는 없어 미적용 항목이 없다. 위험·한계: - 값이 여럿인 Dockerfile은 JVM이 실제로 받지 않는 값이 tmpfs에 놓여도 실패한다. 게이트가 막는 쪽으로 틀린다. - ACL은 Redis 문법을 다 검사하지 않는다. 판정이 보는 낱말(이름, on·off· reset, >비밀번호, ~키 패턴)과 줄 머리만 Redis처럼 읽는다. - `user default off`는 그 낱말 셋인 줄만 받는다(base와 같다). 검증(노트북): python3 -m unittest discover -s scripts/tests 371개 OK. 새 시험을 base 판정기로 돌리면 실패하고, 지키는 줄을 하나씩 약하게 바꾼 변이 38개가 모두 시험을 실패시킨다. desktop pr 단계는 이 커밋 트리로 돌린다. Refs: REV-BE-0053 --- scripts/compose-contract-verdict.py | 211 +++++++--- .../tests/test_compose_contract_verdict.py | 372 +++++++++++++++++- scripts/verify-compose-profile-contracts.sh | 4 +- 3 files changed, 520 insertions(+), 67 deletions(-) diff --git a/scripts/compose-contract-verdict.py b/scripts/compose-contract-verdict.py index 6262b7ca..05ae4856 100644 --- a/scripts/compose-contract-verdict.py +++ b/scripts/compose-contract-verdict.py @@ -18,7 +18,8 @@ four of them passed input that should have failed them (scripts/tests has the ca The ten checks, and why each exists, are listed in scripts/verify-compose-profile-contracts.sh. Exit status 0 is a pass, 1 a failure with its reasons on stderr, 2 a call this script does not know, -78 a repository this script cannot read (no contract file, no -XX:HeapDumpPath in the Dockerfile). +78 a repository this script cannot read (no contract file, a Dockerfile with no -XX:HeapDumpPath or an +empty last one). python3 scripts/compose-contract-verdict.py version python3 scripts/compose-contract-verdict.py lanes @@ -41,12 +42,15 @@ import re import shlex import sys from dataclasses import dataclass -from pathlib import Path +from pathlib import Path, PurePosixPath DEFAULT_REPO_ROOT = Path(__file__).resolve().parent.parent CONTRACT_LABEL = "src/bootstrap/app/compose-lanes/compose-profile-contracts.json" REALM = "compose/keycloak/realms/ca-skeleton-realm.json" -HEAP_DUMP_PATH = re.compile(r'-XX:HeapDumpPath=([^ \\"]*)') +# The value runs to the first whitespace, backslash or quote. Matched one line at a time, so an option +# at a line end is read as itself rather than joined to the next line's first word (REV-BE-0053). +HEAP_DUMP_PATH = re.compile(r'-XX:HeapDumpPath=([^\s\\"]*)') +DOCKERFILE_COMMENT = re.compile(r"\s*#") LANE_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*") VERSION = re.compile(r"v?(\d+(?:\.\d+)*)(?:[-+].*)?") MEMORY_SIZE = re.compile(r"[1-9][0-9]*[kmg]") @@ -56,6 +60,8 @@ REDIS_REFERENCES = ( "APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE", ) SETUP = 78 +ROLE_LISTS = ("longRunningServices", "preStartServices", "oneShotServices") +CATALOGUES = ("preStartServices", "oneShotServices", "capabilities") class SetupError(Exception): @@ -89,6 +95,23 @@ def strings(value: object) -> list[str]: return [] +def names_problem(field: str, value: object) -> str | None: + """Why a field the checks read as a list of names is not one; None when it is, or is left out. + + strings() reads anything but a list as an empty one, so a string, number or object here would take + the field out of every check unseen, while the smoke wrapper reads it and fails the lane. Left out, + null and false are no entries, as jq's `// []` read them; a field that must be there is checked by + its caller. + """ + if value is None or value is False: + return None + if not isinstance(value, list): + return f"'{field}' is {json.dumps(value)}, not a list of names" + if not all(isinstance(entry, str) and entry for entry in value): + return f"'{field}' holds {json.dumps(value)}, and every entry must be a name" + return None + + # ---- 1. Compose version floor ---------------------------------------------------------------- def version_key(text: str) -> tuple[int, ...] | None: @@ -137,13 +160,15 @@ def lane_shape(contract: dict, lane: object, repo_root: Path) -> list[str]: for field in ("composeProfiles", "expectedCapabilitiesOn"): if not isinstance(lane.get(field), list): problems.append(f"has no '{field}' list; the smoke wrapper reads it as one") - # The checks below read these lists as names. An entry that is not one (null, a number, "") would - # drop out of them unseen, while the smoke wrapper reads every entry and fails the lane on it. - for field in ("composeProfiles", "expectedCapabilitiesOn", "services", "longRunningServices", - "preStartServices", "oneShotServices"): + # The checks below read these lists as names. A role list may be left out; the other three must be + # lists, and are reported once, above and below, when they are not. + for field in ("composeProfiles", "expectedCapabilitiesOn", "services", *ROLE_LISTS): entries = lane.get(field) - if isinstance(entries, list) and not all(isinstance(entry, str) and entry for entry in entries): - problems.append(f"'{field}' holds {json.dumps(entries)}, and every entry must be a name") + if field not in ROLE_LISTS and not isinstance(entries, list): + continue + problem = names_problem(field, entries) + if problem: + problems.append(problem) if not isinstance(lane.get("springRuntime"), str) or not lane["springRuntime"]: problems.append("names no springRuntime") if not isinstance(lane.get("services"), list) or not lane["services"]: @@ -153,11 +178,12 @@ def lane_shape(contract: dict, lane: object, repo_root: Path) -> list[str]: def lanes(contract: dict, repo_root: Path) -> tuple[list[dict], list[str]]: """The lanes that can be rendered, and the reasons the others cannot (each with its lane id).""" + problems = [f"the contract's {problem}" for field in CATALOGUES + if (problem := names_problem(field, contract.get(field)))] entries = contract.get("lanes") if not isinstance(entries, list) or not entries: - return [], ["the contract declares no lanes, so nothing would be checked"] + return [], [*problems, "the contract declares no lanes, so nothing would be checked"] renderable: list[dict] = [] - problems: list[str] = [] seen: set[str] = set() for index, lane in enumerate(entries): lane_id = lane.get("id") if isinstance(lane, dict) else None @@ -215,13 +241,13 @@ def spring_runtime(lane: dict, model: dict) -> list[str]: return [] -def tmpfs_targets(service: dict) -> list[str]: - """Every tmpfs the service mounts: the short `tmpfs:` list and long-syntax volumes of type tmpfs.""" - short = service.get("tmpfs") - entries = [short] if isinstance(short, str) else strings(short) - targets = [entry.split(":")[0] for entry in entries] - targets += [volume["target"] for volume in mounts(service) if volume.get("type") == "tmpfs"] - return targets +@dataclass(frozen=True) +class Mount: + """One mount of a service: its normalised target, and its long-syntax entry (None for `tmpfs:`).""" + + target: str + kind: str + volume: dict | None def mounts(service: dict) -> list[dict]: @@ -231,15 +257,40 @@ def mounts(service: dict) -> list[dict]: return [volume for volume in volumes if isinstance(volume, dict) and isinstance(volume.get("target"), str)] +def service_mounts(service: dict) -> list[Mount]: + """Every mount the service declares: the short `tmpfs:` list and the long-syntax volumes.""" + short = service.get("tmpfs") + entries = [short] if isinstance(short, str) else strings(short) + return ([Mount(posixpath.normpath(entry.split(":")[0]), "tmpfs", None) for entry in entries] + + [Mount(posixpath.normpath(volume["target"]), scalar(volume.get("type")), volume) + for volume in mounts(service)]) + + +def mount_holding(service: dict, path: str) -> Mount | None: + """The mount a file at path lands on, or None when it lands on the image's own filesystem. + + Of the mounts at the path or at a directory above it, the deepest: Docker mounts a parent before + its children whatever order they are listed in, so the deeper one hides the parent there. Docker + 29.6 showed it both ways (REV-BE-0053 C2): a volume or bind below a tmpfs holds the path, and a + tmpfs below a volume does. Two mounts at one target fail duplicate_mounts, whichever of them is + returned here. + """ + path = posixpath.normpath(path) + holding = [mount for mount in service_mounts(service) if contains(mount.target, path)] + return max(holding, key=lambda mount: len(PurePosixPath(mount.target).parts), default=None) + + +def contains(directory: str, path: str) -> bool: + return path == directory or path.startswith(directory.rstrip("/") + "/") + + def duplicate_mounts(model: dict) -> list[str]: """4. No service declares the same mount target twice.""" problems: list[str] = [] for name, service in (model.get("services") or {}).items(): if not isinstance(service, dict): continue - short = service.get("tmpfs") - entries = [short] if isinstance(short, str) else strings(short) - targets = [volume["target"] for volume in mounts(service)] + [entry.split(":")[0] for entry in entries] + targets = [mount.target for mount in service_mounts(service)] twice = sorted({target for target in targets if targets.count(target) > 1}) if twice: problems.append(f"a mount target is declared twice — {name}: {', '.join(twice)}") @@ -327,9 +378,17 @@ def redis_authentication(lane: dict, model: dict, repo_root: Path) -> list[str]: "repository file provides") return problems label = relative(acl_file, repo_root) - acl_lines = acl_file.read_text(encoding="utf-8", errors="replace").splitlines() - if "user default off" not in acl_lines: + lines = acl_lines(read(acl_file) or "") + rules = [words for _, words in lines] + if ["user", "default", "off"] not in rules: problems.append(f"{label} leaves the default user on, which makes every account restriction optional") + unreadable = [str(number) for number, words in lines if words[0] != "user" or len(words) < 2] + if unreadable: + problems.append(f"{label} has a line that does not start with `user `, which Redis refuses to " + f"load (line {', '.join(unreadable)})") + declared = [words[1] for words in rules if words[0] == "user" and len(words) > 1] + repeated = sorted({user for user in declared if declared.count(user) > 1}) + problems += [f"{label} declares {user} on more than one line, which Redis refuses to load" for user in repeated] test = (redis.get("healthcheck") or {}).get("test") probe = test if isinstance(test, str) else " ".join(strings(test)) if "--user " not in probe: @@ -347,35 +406,59 @@ def redis_authentication(lane: dict, model: dict, repo_root: Path) -> list[str]: if not value: problems.append(f"{setting} reads {name}, which the lane does not supply") continue + if user in repeated: + continue # Whole words, not patterns: the account is the line whose second word is the user name, so # '.' in it is a dot, and the password is the exact word after '>'. - accounts = [line.split() for line in acl_lines if line.split()[:3] == ["user", user, "on"]] - if not accounts: + account = next((words[2:] for words in rules if words[:2] == ["user", user]), None) + if account is None or not enabled(account): problems.append(f"{setting} names {user}, which {label} does not enable") continue - if len(accounts) > 1: - problems.append(f"{label} enables {user} on more than one line, which Redis refuses to load") - continue - if f">{value}" not in accounts[0]: + if f">{value}" not in account: problems.append(f"{name} is not the password {label} gives {user}") - if namespace and f"~{namespace}:*" not in accounts[0]: + if namespace and f"~{namespace}:*" not in account: problems.append(f"{user} may not touch {namespace}:*, the namespace this lane writes") return problems +def enabled(rules: list[str]) -> bool: + """Whether Redis leaves an account on after its rules: it starts off, and the last of `on`, `off` + and `reset` (any case) decides, wherever on the line it stands (REV-BE-0053 C2).""" + state = False + for rule in rules: + if rule.lower() == "on": + state = True + elif rule.lower() in ("off", "reset"): + state = False + return state + + +def acl_lines(text: str) -> list[tuple[int, list[str]]]: + """The ACL file as redis-server --aclfile reads it: each non-empty line's number and words. + + Redis cuts the file at LF only, trims spaces, tabs, CR and LF off both ends of each line, splits + what is left at every single space, and trims tabs, CR and LF off both ends of each word after the + user name. A tab, a lone CR or a no-break space inside a word therefore stays there, and a second + space makes an empty word; str.split() read each of those as the intended words, and passed files + redis:7.4 refuses to start on (REV-BE-0053 C2). + """ + numbered: list[tuple[int, list[str]]] = [] + for number, line in enumerate(text.split("\n"), 1): + words = line.strip(" \t\r\n").split(" ") + if words != [""]: + numbered.append((number, words[:2] + [word.strip("\t\r\n") for word in words[2:]])) + return numbered + + def acl_source(redis: dict, acl_path: str) -> Path | None: - """The repository file a read-only bind mount puts at acl_path, if one does.""" - for volume in mounts(redis): - if volume.get("type") != "bind" or volume.get("read_only") is not True: - continue - target, source = volume["target"], volume.get("source") - if not isinstance(source, str): - continue - if acl_path == target: - return Path(source) - if acl_path.startswith(target.rstrip("/") + "/"): - return Path(source + acl_path[len(target.rstrip("/")):]) - return None + """The repository file Redis reads at acl_path: the deepest mount there, when it is a read-only bind.""" + mount = mount_holding(redis, acl_path) + if mount is None or mount.volume is None or mount.kind != "bind" or mount.volume.get("read_only") is not True: + return None + source = mount.volume.get("source") + if not isinstance(source, str): + return None + return Path(source) / posixpath.relpath(posixpath.normpath(acl_path), mount.target) def memory_limit(lane: dict) -> list[str]: @@ -387,14 +470,12 @@ def memory_limit(lane: dict) -> list[str]: def heap_dump(model: dict, heap_path: str) -> list[str]: - """9. The heap dump path is on no tmpfs: not one at that path, and not one at a directory above it.""" + """9. The heap dump path is not on a tmpfs: the deepest mount at that path or above it is not one.""" app = model.get("services", {}).get("app") or {} - path = posixpath.normpath(heap_path) - for target in tmpfs_targets(app): - mount = posixpath.normpath(target) - if path == mount or path.startswith(mount.rstrip("/") + "/"): - return [f"app mounts {target} as a tmpfs, which holds the heap dump path {heap_path}; a tmpfs " - "counts against the memory limit and is gone when the container exits"] + mount = mount_holding(app, heap_path) + if mount is not None and mount.kind == "tmpfs": + return [f"app mounts {mount.target} as a tmpfs, which holds the heap dump path {heap_path}; a tmpfs " + "counts against the memory limit and is gone when the container exits"] return [] @@ -424,7 +505,7 @@ def underscore_keys(tree: object) -> list[str]: return [] -def judge_lane(contract: dict, lane: dict, rendered: Rendered, repo_root: Path, heap_path: str) -> list[str]: +def judge_lane(contract: dict, lane: dict, rendered: Rendered, repo_root: Path, heap_paths: list[str]) -> list[str]: """The reasons one lane does not match the contract; empty when it does.""" if rendered.services_rc is None or rendered.model_rc is None: return ["the shell left no record of rendering this lane"] @@ -446,17 +527,17 @@ def judge_lane(contract: dict, lane: dict, rendered: Rendered, repo_root: Path, *application_report(contract, lane), *redis_authentication(lane, model, repo_root), *memory_limit(lane), - *heap_dump(model, heap_path), + *(problem for heap_path in heap_paths for problem in heap_dump(model, heap_path)), ] def judge(contract: dict, render_dir: Path, repo_root: Path) -> tuple[list[str], list[str]]: """The lines for the lanes that matched, and every reason the contract did not.""" - heap_path = dockerfile_heap_dump_path(repo_root) + heap_paths = dockerfile_heap_dump_paths(repo_root) renderable, problems = lanes(contract, repo_root) matched: list[str] = [] for lane in renderable: - lane_problems = judge_lane(contract, lane, recorded(render_dir, lane["id"]), repo_root, heap_path) + lane_problems = judge_lane(contract, lane, recorded(render_dir, lane["id"]), repo_root, heap_paths) if lane_problems: problems += [f"{lane['id']}: {problem}" for problem in lane_problems] else: @@ -467,12 +548,23 @@ def judge(contract: dict, render_dir: Path, repo_root: Path) -> tuple[list[str], # ---- files ------------------------------------------------------------------------------------ -def dockerfile_heap_dump_path(repo_root: Path) -> str: - dockerfile = repo_root / "Dockerfile" - match = HEAP_DUMP_PATH.search(read(dockerfile) or "") - if match is None or not match.group(1): +def dockerfile_heap_dump_paths(repo_root: Path) -> list[str]: + """Every heap dump path the image's JVM may be given: each -XX:HeapDumpPath outside a comment line. + + Lines are cut as Docker cuts them, at LF with a trailing CR dropped, and a comment line is dropped + even inside a continued instruction. Which of several values the JVM ends up with depends on the + instruction they sit in (it keeps the last of a repeated option; a later ENV replaces an earlier + one), so each is judged rather than one guessed. An empty last value leaves the JVM its default, + which this script cannot place. + """ + lines = (line.removesuffix("\r") for line in (read(repo_root / "Dockerfile") or "").split("\n")) + values = [match.group(1) for line in lines if not DOCKERFILE_COMMENT.match(line) + for match in HEAP_DUMP_PATH.finditer(line)] + if not values: raise SetupError("the Dockerfile sets no -XX:HeapDumpPath") - return match.group(1) + if not values[-1]: + raise SetupError("the Dockerfile gives -XX:HeapDumpPath no value") + return list(dict.fromkeys(value for value in values if value)) def recorded(render_dir: Path, lane_id: str) -> Rendered: @@ -492,8 +584,9 @@ def status(text: str | None) -> int | None: def read(path: Path) -> str | None: + """The file's text with its line ends as written: read_text() would turn a lone CR into LF.""" try: - return path.read_text(encoding="utf-8", errors="replace") + return path.read_bytes().decode("utf-8", errors="replace") except FileNotFoundError: return None diff --git a/scripts/tests/test_compose_contract_verdict.py b/scripts/tests/test_compose_contract_verdict.py index 8996aa97..fd94c5b4 100644 --- a/scripts/tests/test_compose_contract_verdict.py +++ b/scripts/tests/test_compose_contract_verdict.py @@ -35,6 +35,8 @@ _spec.loader.exec_module(verdict) CONTRACT_PATH = "src/bootstrap/app/compose-lanes/compose-profile-contracts.json" HEAP = "/var/tmp/heap" ACL = "user default off\nuser app on >example-app-password ~prod:* +@all\nuser app-advanced on >example-advanced-password ~prod:* +@all\n" +APP_LINE = "user app on >example-app-password ~prod:* +@all" +NOT_ENABLED = "APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE names app, which compose/redis/acl/lane.acl does not enable" def contract(*lanes: dict, **fields: object) -> dict: @@ -208,14 +210,69 @@ class ContractShapeTest(RepositoryTestCase): self.assertEqual(problems, ["off-local: the id is used by more than one lane"]) def test_an_id_that_is_not_a_file_name_fails(self) -> None: + # given: the id names the render files, so a name that only starts like one would write + # `off-local/../../escape.services` outside the render directory + for lane_id in ("../escape", "off-local/../../escape", "off local"): + with self.subTest(lane_id=lane_id): + # when + _, problems = verdict.lanes(contract(lane(id=lane_id)), self.root) + + # then + self.assertEqual(problems, [f"lane 0: id {lane_id!r} is not a name such as off-local"]) + + def test_a_role_list_that_is_not_a_list_fails_naming_the_field(self) -> None: + # given: read as an empty list, a string, number or object here filed no service under the + # role while the smoke wrapper failed on it + for field in ("longRunningServices", "preStartServices", "oneShotServices"): + for value in ("app", 1, {"app": True}, "", 0): + with self.subTest(field=field, value=value): + # when + renderable, problems = verdict.lanes(contract(lane(**{field: value})), self.root) + + # then + self.assertEqual(renderable, []) + self.assertEqual(problems, [f"off-local: '{field}' is {json.dumps(value)}, not a list of names"]) + + def test_a_lane_that_leaves_out_a_role_list_or_sets_it_null_or_false_is_renderable(self) -> None: # given - document = contract(lane(id="../escape")) + subject = lane(preStartServices=None, oneShotServices=False) + absent = lane(id="off-dev") + del absent["oneShotServices"] # when - _, problems = verdict.lanes(document, self.root) + renderable, problems = verdict.lanes(contract(subject, absent), self.root) # then - self.assertEqual(problems, ["lane 0: id '../escape' is not a name such as off-local"]) + self.assertEqual(problems, []) + self.assertEqual([entry["id"] for entry in renderable], ["off-local", "off-dev"]) + + def test_a_catalogue_that_is_not_a_list_of_names_fails_naming_the_field(self) -> None: + # given: read as an empty list, these let every lane's role and report checks pass on nothing + for field in ("preStartServices", "oneShotServices", "capabilities"): + cases = { + "a string": (f"{field!r} is \"smoke\", not a list of names", "smoke"), + "a number": (f"{field!r} is 1, not a list of names", 1), + "an object": (f"{field!r} is {{\"smoke\": true}}, not a list of names", {"smoke": True}), + "an entry that is not a name": (f"{field!r} holds [1], and every entry must be a name", [1]), + } + for case, (reason, value) in cases.items(): + with self.subTest(field=field, case=case): + # when + _, problems = verdict.lanes(contract(lane(), **{field: value}), self.root) + + # then + self.assertEqual(problems, [f"the contract's {reason}"]) + + def test_a_contract_that_leaves_out_a_catalogue_or_sets_it_null_or_false_passes(self) -> None: + # given + document = contract(lane(), preStartServices=None, oneShotServices=False) + del document["capabilities"] + + # when + renderable, problems = verdict.lanes(document, self.root) + + # then + self.assertEqual((len(renderable), problems), (1, [])) class ComposeVersionTest(unittest.TestCase): @@ -240,13 +297,18 @@ class ComposeVersionTest(unittest.TestCase): verdict.compose_version(contract(minimumComposeVersion=None), "2.29.1"), ["minimumComposeVersion '' is not a version such as 2.24.4"], ) + # a version followed by anything other than a pre-release or build suffix is not one + self.assertEqual( + verdict.compose_version(contract(), "2.29.1 (build 1)"), + ["docker compose reports '2.29.1 (build 1)', which is not a version"], + ) class RenderTest(RepositoryTestCase): def judge(self, record: verdict.Rendered, subject: dict | None = None) -> list[str]: subject = subject or lane() - return verdict.judge_lane(contract(subject), subject, record, self.root, HEAP) + return verdict.judge_lane(contract(subject), subject, record, self.root, [HEAP]) def test_a_lane_that_renders_its_services_and_a_clean_model_passes(self) -> None: self.assertEqual(self.judge(rendered()), []) @@ -306,6 +368,17 @@ class RenderTest(RepositoryTestCase): # then self.assertEqual(self.judge(rendered(document=document)), ["a mount target is declared twice — app: /tmp"]) + def test_a_mount_target_declared_twice_with_a_trailing_slash_fails(self) -> None: + # given: compose 5.3 renders a short tmpfs at `/var/tmp/heap/` beside a volume at + # `/var/tmp/heap`, and Docker 29.6 mounts both there (REV-BE-0053 C2) + document = model(app=app(tmpfs=["/tmp", f"{HEAP}/"], volumes=[{"type": "volume", "source": "dumps", "target": HEAP}])) + + # when + problems = self.judge(rendered(document=document)) + + # then + self.assertEqual(problems[0], f"a mount target is declared twice — app: {HEAP}") + class RolePartitionTest(unittest.TestCase): @@ -480,6 +553,9 @@ class RedisAuthenticationTest(RepositoryTestCase): "the Redis healthcheck does not authenticate"), "malformed reference": (self.environment(APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE="secret://env/X"), None, "is 'secret://env/X', not secret://@environment/"), + "reference with a tail": (self.environment( + APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE="secret://app@environment/REDIS_LANE_APPLICATION_PASSWORD/x"), + None, "/REDIS_LANE_APPLICATION_PASSWORD/x', not secret://@environment/"), "unset variable": (self.environment(REDIS_LANE_APPLICATION_PASSWORD=None), None, "reads REDIS_LANE_APPLICATION_PASSWORD, which the lane does not supply"), } @@ -496,9 +572,133 @@ class RedisAuthenticationTest(RepositoryTestCase): # then self.assertEqual(self.problems(), [ "compose/redis/acl/lane.acl leaves the default user on, which makes every account restriction optional", - "compose/redis/acl/lane.acl enables app on more than one line, which Redis refuses to load", + "compose/redis/acl/lane.acl declares app on more than one line, which Redis refuses to load", ]) + def test_a_user_on_two_lines_fails_whether_each_line_turns_it_on_or_off(self) -> None: + # given: redis:7.4 refuses to start on any repeated user name (REV-BE-0053 C2), not only on + # a name enabled twice, so the lane's Redis provisions nothing at all + app_off = "user app off >example-other-password ~prod:* +@all\n" + cases = { + "on, then off": (ACL + app_off, "app"), + "off, then on": (ACL.replace("user app on", app_off + "user app on"), "app"), + "an account the lane does not use": (ACL + ACL.splitlines(keepends=True)[2], "app-advanced"), + "the default user": (ACL + "user default off\n", "default"), + } + for case, (text, user) in cases.items(): + with self.subTest(case=case): + self.repository.write("compose/redis/acl/lane.acl", text) + + # then + self.assertEqual(self.problems(), [ + f"compose/redis/acl/lane.acl declares {user} on more than one line, which Redis refuses to load", + ]) + + def test_an_account_redis_leaves_off_is_not_one_the_lane_can_authenticate_as(self) -> None: + # given: an account starts off, and the last of on, off and reset on its line decides + cases = { + "off": "user app off >example-app-password ~prod:* +@all", + "on, then off later in the line": "user app on >example-app-password ~prod:* +@all off", + "on, then reset": "user app on >example-app-password ~prod:* +@all reset", + "neither on nor off": "user app >example-app-password ~prod:* +@all", + } + for case, line in cases.items(): + with self.subTest(case=case): + self.repository.write("compose/redis/acl/lane.acl", ACL.replace(APP_LINE, line)) + + # then + self.assertEqual(self.problems(), [NOT_ENABLED]) + + def test_an_account_redis_leaves_on_passes_wherever_on_stands_and_in_any_case(self) -> None: + # given: redis:7.4 accepted each of these and let the account in (REV-BE-0053 C2) + cases = { + "on after the password": "user app >example-app-password on ~prod:* +@all", + "off, then on": "user app off >example-app-password ~prod:* +@all on", + "upper-case ON": "user app ON >example-app-password ~prod:* +@all", + } + for case, line in cases.items(): + with self.subTest(case=case): + self.repository.write("compose/redis/acl/lane.acl", ACL.replace(APP_LINE, line)) + + # then + self.assertEqual(self.problems(), []) + + def test_a_line_redis_splits_otherwise_than_on_single_spaces_fails(self) -> None: + # given: redis:7.4 cuts the file at LF only and a line at every single space, and refuses to + # start on each of these (REV-BE-0053 C2); str.split() read them as the intended words + not_a_user_line = ("compose/redis/acl/lane.acl has a line that does not start with `user `, which " + "Redis refuses to load (line 2)") + cases = { + "a tab after user": (APP_LINE.replace("user ", "user\t"), [not_a_user_line, NOT_ENABLED]), + "a no-break space after user": (APP_LINE.replace("user ", "user\u00a0"), [not_a_user_line, NOT_ENABLED]), + "two spaces after user": (APP_LINE.replace("user ", "user "), [NOT_ENABLED]), + "a tab after the name": (APP_LINE.replace("app ", "app\t ", 1), [NOT_ENABLED]), + "a tab between on and the password": (APP_LINE.replace("on ", "on\t"), [NOT_ENABLED]), + "a no-break space between on and the password": (APP_LINE.replace("on ", "on\u00a0"), [NOT_ENABLED]), + } + for case, (line, problems) in cases.items(): + with self.subTest(case=case): + self.repository.write("compose/redis/acl/lane.acl", ACL.replace(APP_LINE, line)) + + # then + self.assertEqual(self.problems(), problems) + + def test_an_acl_file_whose_lines_end_in_a_lone_cr_is_one_line_to_redis(self) -> None: + # given + self.repository.write("compose/redis/acl/lane.acl", ACL.replace("\n", "\r")) + + # then + self.assertEqual(self.problems(), [ + "compose/redis/acl/lane.acl leaves the default user on, which makes every account restriction optional", + NOT_ENABLED, + "APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE names app-advanced, which compose/redis/acl/lane.acl " + "does not enable", + ]) + + def test_a_no_break_space_ending_the_default_line_fails(self) -> None: + # given: Redis trims spaces, tabs, CR and LF only, so `off\u00a0` is a word it refuses + self.repository.write("compose/redis/acl/lane.acl", ACL.replace("user default off", "user default off\u00a0")) + + # then + self.assertEqual(self.problems(), [ + "compose/redis/acl/lane.acl leaves the default user on, which makes every account restriction optional", + ]) + + def test_a_line_that_does_not_start_with_user_and_a_name_fails(self) -> None: + # given: redis:7.4 has no comment lines, and refused to start on `# lane accounts` (REV-BE-0053 C2) + cases = {"a comment": ("# lane accounts\n" + ACL, 1), "user alone": (ACL + "user\n", 4)} + for case, (text, number) in cases.items(): + with self.subTest(case=case): + self.repository.write("compose/redis/acl/lane.acl", text) + + # then + self.assertEqual(self.problems(), [ + "compose/redis/acl/lane.acl has a line that does not start with `user `, which Redis " + f"refuses to load (line {number})", + ]) + + def test_line_ends_and_word_ends_redis_trims_still_pass(self) -> None: + # given: Redis trims spaces, tabs, CR and LF off both ends of a line, and tabs, CR and LF off + # both ends of every word after the name; redis:7.4 accepted each of these (REV-BE-0053 C2) + cases = { + "CRLF line ends": ACL.replace("\n", "\r\n"), + "spaces before each line": "".join(f" {line}\n" for line in ACL.splitlines()), + "a tab before each line": "".join(f"\t{line}\n" for line in ACL.splitlines()), + "spaces after each line": "".join(f"{line} \n" for line in ACL.splitlines()), + # an empty word after the name is a rule Redis skips + "two spaces before on": ACL.replace("user app on", "user app on"), + "two spaces after on": ACL.replace("user app on", "user app on "), + "a tab ending on": ACL.replace("user app on ", "user app on\t "), + "a CR ending on": ACL.replace("user app on ", "user app on\r "), + "a tab ending the password": ACL.replace("example-app-password ", "example-app-password\t "), + } + for case, text in cases.items(): + with self.subTest(case=case): + self.repository.write("compose/redis/acl/lane.acl", text) + + # then + self.assertEqual(self.problems(), []) + def test_an_acl_file_mounted_as_a_file_is_read(self) -> None: # given mount = {"type": "bind", "source": str(self.root / "compose/redis/acl/lane.acl"), @@ -507,12 +707,48 @@ class RedisAuthenticationTest(RepositoryTestCase): # then self.assertEqual(self.problems(redis=self.redis(volumes=[mount])), []) + def test_of_two_overlapping_mounts_the_deeper_one_provides_the_acl_file_in_either_order(self) -> None: + # given: Docker mounts a parent before its child whatever order they are listed in, so the + # file mount hides the directory mount's lane.acl (REV-BE-0053 C2) + self.repository.write("compose/redis/other.acl", ACL.replace("user default off\n", "")) + directory = self.redis()["volumes"][0] + file = {"type": "bind", "source": str(self.root / "compose/redis/other.acl"), + "target": "/etc/redis/acl/lane.acl", "read_only": True} + for order, volumes in (("directory first", [directory, file]), ("file first", [file, directory])): + with self.subTest(order=order): + # then + self.assertEqual(self.problems(redis=self.redis(volumes=volumes)), [ + "compose/redis/other.acl leaves the default user on, which makes every account restriction optional", + ]) + + def test_a_deeper_mount_that_is_not_a_read_only_bind_hides_the_repository_acl_file(self) -> None: + # given + directory = self.redis()["volumes"][0] + cases = { + "a volume": {"type": "volume", "source": "acl", "target": "/etc/redis/acl/lane.acl"}, + # a source that is a repository file, so only the kind of the mount can refuse it + "a read-only volume": {"type": "volume", "source": str(self.root / "compose/redis/acl/lane.acl"), + "target": "/etc/redis/acl/lane.acl", "read_only": True}, + "a writable bind": {"type": "bind", "source": str(self.root / "compose/redis/acl/lane.acl"), + "target": "/etc/redis/acl/lane.acl"}, + } + for case, deeper in cases.items(): + for volumes in ([directory, deeper], [deeper, directory]): + with self.subTest(case=case, first=volumes[0]["type"]): + # then + self.assertEqual(self.problems(redis=self.redis(volumes=volumes)), [ + "starts Redis with --aclfile /etc/redis/acl/lane.acl, which no read-only bind mount of a " + "repository file provides", + ]) + class HeapDumpTest(unittest.TestCase): def test_a_tmpfs_away_from_the_heap_dump_path_passes(self) -> None: self.assertEqual(verdict.heap_dump(model(), HEAP), []) self.assertEqual(verdict.heap_dump(model(app=app(tmpfs=["/var/tmp/heapless"])), HEAP), []) + # a target that only begins like a directory above the path is not one + self.assertEqual(verdict.heap_dump(model(app=app(tmpfs=["/var/tmp/hea"])), HEAP), []) def test_a_tmpfs_at_the_path_or_a_directory_above_it_fails(self) -> None: # given: only an exact entry of the short list was compared @@ -535,6 +771,36 @@ class HeapDumpTest(unittest.TestCase): service = app(volumes=[{"type": kind, "source": source, "target": HEAP}]) self.assertEqual(verdict.heap_dump(model(app=service), HEAP), []) + def test_a_volume_or_bind_mount_below_a_tmpfs_holds_the_heap_dump_path_in_either_order(self) -> None: + # given: Docker mounts the deeper target last, so the dump lands on the disk-backed mount + # whatever order the mounts are listed in (REV-BE-0053 C2) + for kind, source in (("volume", "dumps"), ("bind", "./build/heap")): + disk = {"type": kind, "source": source, "target": HEAP} + cases = { + "short tmpfs": app(tmpfs=["/var/tmp:size=1g"], volumes=[disk]), + "long tmpfs listed first": app(volumes=[{"type": "tmpfs", "target": "/var/tmp"}, disk]), + "long tmpfs listed last": app(volumes=[disk, {"type": "tmpfs", "target": "/var/tmp"}]), + } + for case, service in cases.items(): + with self.subTest(kind=kind, case=case): + self.assertEqual(verdict.heap_dump(model(app=service), HEAP), []) + + def test_a_tmpfs_below_a_volume_still_holds_the_heap_dump_path_in_either_order(self) -> None: + # given + disk = {"type": "volume", "source": "var", "target": "/var"} + cases = { + "short tmpfs": app(tmpfs=["/var/tmp:size=1g"], volumes=[disk]), + "long tmpfs listed first": app(volumes=[{"type": "tmpfs", "target": "/var/tmp"}, disk]), + "long tmpfs listed last": app(volumes=[disk, {"type": "tmpfs", "target": "/var/tmp"}]), + } + for case, service in cases.items(): + with self.subTest(case=case): + # then + self.assertEqual(verdict.heap_dump(model(app=service), HEAP), [ + f"app mounts /var/tmp as a tmpfs, which holds the heap dump path {HEAP}; a tmpfs counts against " + "the memory limit and is gone when the container exits", + ]) + class MemoryLimitTest(unittest.TestCase): @@ -543,7 +809,7 @@ class MemoryLimitTest(unittest.TestCase): self.assertEqual(verdict.memory_limit(lane()), []) def test_a_size_compose_does_not_read_fails(self) -> None: - for limit in ("1G", "1.5g", "1024", "0m"): + for limit in ("1G", "1.5g", "1024", "0m", "1gb"): with self.subTest(limit=limit): self.assertEqual( verdict.memory_limit(lane(appMemoryLimit=limit)), @@ -678,6 +944,100 @@ class CommandLineTest(RepositoryTestCase): # then self.assertEqual((rc, stderr), (78, "the Dockerfile sets no -XX:HeapDumpPath\n")) + def test_the_heap_dump_path_is_the_value_the_jvm_is_given(self) -> None: + # given: app mounts a tmpfs at the heap dump path, so every Dockerfile below that may give the + # JVM that path fails the lane. A value read across a line end, only the first of two options, or + # a value from a comment was compared instead and passed it (REV-BE-0053). + tmpfs = model(app=app(tmpfs=["/tmp", f"{HEAP}:size=64m"])) + cases = { + "the shipped form": f'ENV JAVA_TOOL_OPTIONS="\\\n -XX:+HeapDumpOnOutOfMemoryError \\\n' + f' -XX:HeapDumpPath={HEAP} \\\n -Dserver.tomcat.basedir=/tmp"\n', + "a comment that ends with the option": f"# dumps go to -XX:HeapDumpPath={HEAP}\n" + f'ENV JAVA_TOOL_OPTIONS="-XX:HeapDumpPath={HEAP}"\n', + "an unquoted ENV that ends with the option": f"ENV JAVA_TOOL_OPTIONS=-XX:HeapDumpPath={HEAP}\nUSER app\n", + "the option twice on one line": f'ENV JAVA_TOOL_OPTIONS="-XX:HeapDumpPath=/srv/heap -XX:HeapDumpPath={HEAP}"\n', + "the option twice on continued lines": f'ENV JAVA_TOOL_OPTIONS="\\\n -XX:HeapDumpPath=/srv/heap \\\n' + f' -XX:HeapDumpPath={HEAP}"\n', + "a later comment that names another path": f'ENV JAVA_TOOL_OPTIONS="-XX:HeapDumpPath={HEAP}"\n' + " # the old image used -XX:HeapDumpPath=/srv/heap\n", + "a tab after the value": f'ENV JAVA_TOOL_OPTIONS="-XX:HeapDumpPath={HEAP}\t-Dserver.tomcat.basedir=/tmp"\n', + # which value the JVM ends up with depends on the instruction, so each one is judged + "a later instruction that names another path": f'ENV JAVA_TOOL_OPTIONS="-XX:HeapDumpPath={HEAP}"\n' + "RUN echo -XX:HeapDumpPath=/srv/heap\n", + "the tmpfs path first and another last": f'ENV JAVA_TOOL_OPTIONS="-XX:HeapDumpPath={HEAP} ' + '-XX:HeapDumpPath=/srv/heap"\n', + # Docker cuts lines at LF only: the lone CR stays inside the comment line, with what follows it + "a lone CR inside a later comment": f'ENV JAVA_TOOL_OPTIONS="-XX:HeapDumpPath={HEAP}"\n' + "# was\r-XX:HeapDumpPath=\n", + "CRLF line ends": f'ENV JAVA_TOOL_OPTIONS=-XX:HeapDumpPath={HEAP}\r\nUSER app\r\n', + } + self.record(self.root / "rendered", "off-local", document=tmpfs) + for case, dockerfile in cases.items(): + with self.subTest(case=case): + self.repository.write("Dockerfile", dockerfile) + + # when + rc, stdout, stderr = self.run_judge(contract(lane())) + + # then + self.assertEqual((rc, stdout), (1, "")) + self.assertEqual(stderr.splitlines()[0], f" FAIL: off-local: app mounts {HEAP} as a tmpfs, " + f"which holds the heap dump path {HEAP}; a tmpfs counts against the memory limit and " + "is gone when the container exits") + + def test_a_heap_dump_path_the_dockerfile_leaves_empty_or_only_in_a_comment_is_a_setup_error(self) -> None: + # given: the JVM keeps the last of a repeated option, so an empty last one leaves it its default + cases = { + "empty at a line end": ("ENV JAVA_TOOL_OPTIONS=-XX:HeapDumpPath=\nUSER app\n", + "the Dockerfile gives -XX:HeapDumpPath no value"), + "empty after one with a value": (f'ENV JAVA_TOOL_OPTIONS="-XX:HeapDumpPath={HEAP} -XX:HeapDumpPath="\n', + "the Dockerfile gives -XX:HeapDumpPath no value"), + "only in a comment": (f"# -XX:HeapDumpPath={HEAP}\nENV JAVA_TOOL_OPTIONS=-XX:+HeapDumpOnOutOfMemoryError\n", + "the Dockerfile sets no -XX:HeapDumpPath"), + } + for case, (dockerfile, reason) in cases.items(): + with self.subTest(case=case): + self.repository.write("Dockerfile", dockerfile) + + # when + rc, _, stderr = self.run_judge(contract(lane())) + + # then + self.assertEqual((rc, stderr), (78, f"{reason}\n")) + + def test_a_list_field_that_is_not_a_list_of_names_fails_the_command_naming_the_field(self) -> None: + # given + self.record(self.root / "rendered", "off-local") + cases = { + "a lane's role list": (contract(lane(oneShotServices="smoke")), + " FAIL: off-local: 'oneShotServices' is \"smoke\", not a list of names"), + "a top-level catalogue": (contract(lane(), capabilities={"redis": True}), + " FAIL: the contract's 'capabilities' is {\"redis\": true}, not a list of names"), + } + for case, (document, failure) in cases.items(): + with self.subTest(case=case): + # when + rc, _, stderr = self.run_judge(document) + + # then + self.assertEqual(rc, 1) + self.assertEqual([line for line in stderr.splitlines() if line.startswith(" FAIL: ")], [failure]) + + def test_a_lane_without_the_role_lists_it_does_not_use_passes_the_command(self) -> None: + # given + self.record(self.root / "rendered", "off-local") + subject = lane() + del subject["oneShotServices"] + document = contract(subject) + del document["preStartServices"], document["oneShotServices"] + + # when + rc, stdout, stderr = self.run_judge(document) + + # then + self.assertEqual((rc, stderr), (0, "")) + self.assertEqual(stdout.splitlines()[0], "off-local: app @ local") + def test_a_contract_that_is_not_json_fails(self) -> None: # given path = self.repository.write(CONTRACT_PATH, "{") diff --git a/scripts/verify-compose-profile-contracts.sh b/scripts/verify-compose-profile-contracts.sh index c7811686..f71c80e6 100755 --- a/scripts/verify-compose-profile-contracts.sh +++ b/scripts/verify-compose-profile-contracts.sh @@ -33,8 +33,8 @@ # would hide the same trade in production; the lane has to look like a deployment instead. # 8. a lane's appMemoryLimit, when it has one, is a Compose memory size, because the smoke wrapper # writes it into the application's mem_limit and a malformed one fails only at `up`. -# 9. the application's heap dump path (-XX:HeapDumpPath in the Dockerfile) is on no tmpfs, neither -# one at that path nor one at a directory above it, because a tmpfs is charged to the +# 9. the application's heap dump path (-XX:HeapDumpPath in the Dockerfile) is not on a tmpfs: the +# deepest mount at that path or at a directory above it is not one, because a tmpfs is charged to the # container's memory limit and is gone once the container exits: the dump written at an # OutOfMemoryError could only push the container into an OOM kill and was never there to read # (2026-11-12 review). -- 2.54.0