pr / done (pull_request) Successful in 3m5s
문제: 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 <name>`으로 시작하지 않는 줄, 겹친 이름, 마지막 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
666 lines
30 KiB
Python
666 lines
30 KiB
Python
"""Judges the static Compose contract: every lane renders, and renders exactly what it claims.
|
|
|
|
Called by scripts/verify-compose-profile-contracts.sh, which keeps the docker calls: it asks this
|
|
script which lanes to render and with which arguments, writes what `docker compose config` printed and
|
|
exited with to one directory, and hands that directory back here. The judgements live here rather
|
|
than in jq inside the shell because a jq branch cannot be tried on a broken input without Docker, and
|
|
four of them passed input that should have failed them (scripts/tests has the cases):
|
|
|
|
- a contract with no lanes passed as "all 0 lanes match";
|
|
- a lane that turns persistence-jpa on and names no expectedPersistenceVendor passed, although the
|
|
smoke wrapper compares the reported vendor with that field and fails every run of the lane;
|
|
- the heap dump path passed when the tmpfs was a directory above it, or a long-syntax volume of
|
|
type tmpfs, because only an exact entry of the short `tmpfs:` list was compared;
|
|
- a Redis account was looked up with its name as a regular expression, so a lane that names
|
|
`ca.skeleton-application` passed on the ACL line of `ca-skeleton-application`, an account it never
|
|
authenticates as.
|
|
|
|
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, a Dockerfile with no -XX:HeapDumpPath or an
|
|
empty last one).
|
|
|
|
python3 scripts/compose-contract-verdict.py version <contracts.json> <docker compose version>
|
|
python3 scripts/compose-contract-verdict.py lanes <contracts.json>
|
|
python3 scripts/compose-contract-verdict.py judge <contracts.json> <render-dir>
|
|
|
|
`lanes` prints one line per lane the contract lets it render: the lane id, then the arguments for
|
|
`docker compose`, separated by tabs. `judge` expects, for each of those lanes, `<id>.services` and
|
|
`<id>.services.err` from `config --services`, `<id>.json` from `config --format json`, and the exit
|
|
status of each call in `<id>.services.rc` and `<id>.json.rc`. A lane the contract describes but the
|
|
shell left no record for fails, so a broken loop in the shell cannot pass as a lane that matched.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import posixpath
|
|
import re
|
|
import shlex
|
|
import sys
|
|
from dataclasses import dataclass
|
|
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"
|
|
# 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]")
|
|
CREDENTIAL_REFERENCE = re.compile(r"secret://([A-Za-z0-9_.-]+)@environment/([A-Za-z_][A-Za-z0-9_]*)")
|
|
REDIS_REFERENCES = (
|
|
"APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE",
|
|
"APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE",
|
|
)
|
|
SETUP = 78
|
|
ROLE_LISTS = ("longRunningServices", "preStartServices", "oneShotServices")
|
|
CATALOGUES = ("preStartServices", "oneShotServices", "capabilities")
|
|
|
|
|
|
class SetupError(Exception):
|
|
"""The repository lacks something every judgement needs; exit 78 rather than judge."""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Rendered:
|
|
"""What the shell recorded for one lane. None is a file the shell never wrote."""
|
|
|
|
services_rc: int | None
|
|
services: str
|
|
services_error: str
|
|
model_rc: int | None
|
|
model: str
|
|
|
|
|
|
def scalar(value: object) -> str:
|
|
"""The value as `jq -r '... // empty'` prints it: null and false print nothing."""
|
|
if value is None or value is False:
|
|
return ""
|
|
if value is True:
|
|
return "true"
|
|
return str(value)
|
|
|
|
|
|
def strings(value: object) -> list[str]:
|
|
"""A list of strings, or an empty list for anything else (`// []`)."""
|
|
if isinstance(value, list):
|
|
return [item for item in value if isinstance(item, 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:
|
|
match = VERSION.fullmatch(text.strip())
|
|
if match is None:
|
|
return None
|
|
return tuple(int(part) for part in match.group(1).split("."))
|
|
|
|
|
|
def compose_version(contract: dict, actual: str) -> list[str]:
|
|
"""The reasons this Compose is too old for the contract; empty when it is new enough."""
|
|
required = scalar(contract.get("minimumComposeVersion"))
|
|
floor, found = version_key(required), version_key(actual)
|
|
if floor is None:
|
|
return [f"minimumComposeVersion '{required}' is not a version such as 2.24.4"]
|
|
if found is None:
|
|
return [f"docker compose reports '{actual.strip()}', which is not a version"]
|
|
width = max(len(floor), len(found))
|
|
if found + (0,) * (width - len(found)) < floor + (0,) * (width - len(floor)):
|
|
return [
|
|
f"docker compose {actual.strip()} is below the required {required};",
|
|
" the dev overlay needs !override to replace the base tmpfs rather than merge with it.",
|
|
]
|
|
return []
|
|
|
|
|
|
# ---- the shape of the contract ----------------------------------------------------------------
|
|
|
|
def lane_shape(contract: dict, lane: object, repo_root: Path) -> list[str]:
|
|
"""The reasons a lane cannot be rendered or run as the contract writes it; empty when it can."""
|
|
if not isinstance(lane, dict):
|
|
return ["the lane is not an object"]
|
|
problems: list[str] = []
|
|
files = lane.get("files")
|
|
catalogue = contract.get("composeFiles") if isinstance(contract.get("composeFiles"), dict) else {}
|
|
if not isinstance(files, list) or not files:
|
|
problems.append("names no compose file under 'files', so `docker compose` would render whatever "
|
|
"file it finds in the repository root")
|
|
else:
|
|
for key in files:
|
|
path = catalogue.get(key) if isinstance(key, str) else None
|
|
if not isinstance(path, str):
|
|
problems.append(f"names compose file '{key}', which composeFiles does not list")
|
|
elif not (repo_root / path).is_file():
|
|
problems.append(f"{path} is missing")
|
|
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. 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 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"]:
|
|
problems.append("lists no services")
|
|
return problems
|
|
|
|
|
|
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 [], [*problems, "the contract declares no lanes, so nothing would be checked"]
|
|
renderable: list[dict] = []
|
|
seen: set[str] = set()
|
|
for index, lane in enumerate(entries):
|
|
lane_id = lane.get("id") if isinstance(lane, dict) else None
|
|
if not isinstance(lane_id, str) or LANE_ID.fullmatch(lane_id) is None:
|
|
problems.append(f"lane {index}: id {lane_id!r} is not a name such as off-local")
|
|
continue
|
|
if lane_id in seen:
|
|
problems.append(f"{lane_id}: the id is used by more than one lane")
|
|
continue
|
|
seen.add(lane_id)
|
|
shape = lane_shape(contract, lane, repo_root)
|
|
if shape:
|
|
problems.extend(f"{lane_id}: {problem}" for problem in shape)
|
|
continue
|
|
renderable.append(lane)
|
|
return renderable, problems
|
|
|
|
|
|
def compose_arguments(contract: dict, lane: dict, repo_root: Path) -> list[str]:
|
|
arguments: list[str] = []
|
|
for key in lane["files"]:
|
|
arguments += ["-f", str(repo_root / contract["composeFiles"][key])]
|
|
for profile in strings(lane["composeProfiles"]):
|
|
if profile:
|
|
arguments += ["--profile", profile]
|
|
return arguments
|
|
|
|
|
|
# ---- per-lane checks --------------------------------------------------------------------------
|
|
|
|
def service_set(lane: dict, rendered: str) -> list[str]:
|
|
"""2. The stack renders exactly the lane's services: not a superset, not a subset."""
|
|
expected = sorted(strings(lane.get("services")))
|
|
actual = sorted(line.strip() for line in rendered.splitlines() if line.strip())
|
|
if actual != expected:
|
|
return [f"services are [{','.join(actual)}], the contract says [{','.join(expected)}]"]
|
|
return []
|
|
|
|
|
|
def environment(service: dict) -> dict[str, object]:
|
|
value = service.get("environment")
|
|
if isinstance(value, dict):
|
|
return value
|
|
if isinstance(value, list):
|
|
return dict(item.split("=", 1) if "=" in item else (item, None) for item in strings(value))
|
|
return {}
|
|
|
|
|
|
def spring_runtime(lane: dict, model: dict) -> list[str]:
|
|
"""3. The application renders the Spring runtime the lane names."""
|
|
app = model.get("services", {}).get("app") or {}
|
|
rendered = scalar(environment(app).get("SPRING_PROFILES_ACTIVE"))
|
|
if rendered != lane["springRuntime"]:
|
|
return [f"app renders SPRING_PROFILES_ACTIVE='{rendered}', the contract says '{lane['springRuntime']}'"]
|
|
return []
|
|
|
|
|
|
@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]:
|
|
volumes = service.get("volumes")
|
|
if not isinstance(volumes, list):
|
|
return []
|
|
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
|
|
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)}")
|
|
return problems
|
|
|
|
|
|
def role_partition(contract: dict, lane: dict) -> list[str]:
|
|
"""5. Every rendered service plays exactly one role, and no one-shot is a --wait target."""
|
|
problems: list[str] = []
|
|
services = strings(lane.get("services"))
|
|
waiting = strings(lane.get("longRunningServices"))
|
|
pre_start = strings(lane.get("preStartServices"))
|
|
one_shot = strings(lane.get("oneShotServices"))
|
|
filed = waiting + pre_start + one_shot
|
|
unfiled = [service for service in services if service not in filed]
|
|
not_rendered = [service for service in filed if service not in services]
|
|
twice = sorted({service for service in filed if filed.count(service) > 1})
|
|
if unfiled or not_rendered or twice:
|
|
problems.append(
|
|
f"services are not partitioned by role — unfiled=[{','.join(unfiled)}] "
|
|
f"not-rendered=[{','.join(not_rendered)}] twice=[{','.join(twice)}]"
|
|
)
|
|
catalogue = strings(contract.get("preStartServices")) + strings(contract.get("oneShotServices"))
|
|
never_waiting = [service for service in waiting if service in catalogue]
|
|
if never_waiting:
|
|
problems.append(f"[{','.join(never_waiting)}] are declared non-waiting but listed as --wait targets")
|
|
uncatalogued = [service for service in pre_start + one_shot if service not in catalogue]
|
|
if uncatalogued:
|
|
problems.append(
|
|
f"[{','.join(uncatalogued)}] are run with `run --rm` but are in neither top-level catalogue"
|
|
)
|
|
return problems
|
|
|
|
|
|
def application_report(contract: dict, lane: dict) -> list[str]:
|
|
"""6. What the lane expects /actuator/info to report is something the application can report."""
|
|
expected_on = strings(lane.get("expectedCapabilitiesOn"))
|
|
unknown = [name for name in expected_on if name not in strings(contract.get("capabilities"))]
|
|
jpa = "persistence-jpa" in expected_on
|
|
state = "on" if jpa else "off"
|
|
vendor = lane.get("expectedPersistenceVendor")
|
|
reasons: list[str] = []
|
|
if unknown:
|
|
reasons.append(f"uncatalogued=[{','.join(unknown)}]")
|
|
if not isinstance(vendor, str) or not vendor:
|
|
reasons.append(f"no expectedPersistenceVendor with persistence-jpa {state}")
|
|
elif jpa == (vendor == "none"):
|
|
reasons.append(f"vendor {vendor} with persistence-jpa {state}")
|
|
if reasons:
|
|
return [f"the expected application report is unreachable — {' '.join(reasons)}"]
|
|
return []
|
|
|
|
|
|
def redis_authentication(lane: dict, model: dict, repo_root: Path) -> list[str]:
|
|
"""7. A lane that switches Redis on authenticates as an account its own Redis provisions.
|
|
|
|
Read against the rendered model, so the ACL file checked is the one the container mounts. User,
|
|
password and key pattern are each compared, because each fails differently and only at runtime:
|
|
an unknown user or a wrong password is WRONGPASS at the first connection, and a key pattern that
|
|
does not cover the lane's namespace is NOPERM on the first key a capability writes.
|
|
"""
|
|
env = lane.get("activationEnv") if isinstance(lane.get("activationEnv"), dict) else {}
|
|
if scalar(env.get("APP_REDIS_ENABLED")) != "true":
|
|
return []
|
|
problems: list[str] = []
|
|
if scalar(env.get("APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED")) == "true":
|
|
problems.append("accepts anonymous Redis access; the lane's Redis turns the default user off, "
|
|
"so the application has to name an account")
|
|
namespace = scalar(env.get("APP_REDIS_NAMESPACE_ENVIRONMENT"))
|
|
if not namespace:
|
|
problems.append("sets no APP_REDIS_NAMESPACE_ENVIRONMENT, so nothing says the account's key "
|
|
"pattern covers the keys the lane writes")
|
|
|
|
redis = model.get("services", {}).get("redis") or {}
|
|
command = redis.get("command")
|
|
words = shlex.split(command) if isinstance(command, str) else strings(command)
|
|
position = words.index("--aclfile") if "--aclfile" in words else None
|
|
acl_path = words[position + 1] if position is not None and position + 1 < len(words) else ""
|
|
if not acl_path:
|
|
problems.append("starts Redis without --aclfile, so the default user is open and nothing authenticates")
|
|
return problems
|
|
acl_file = acl_source(redis, acl_path)
|
|
if acl_file is None or not acl_file.is_file() or not os.access(acl_file, os.R_OK):
|
|
problems.append(f"starts Redis with --aclfile {acl_path}, which no read-only bind mount of a "
|
|
"repository file provides")
|
|
return problems
|
|
label = relative(acl_file, repo_root)
|
|
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 <name>`, 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:
|
|
problems.append("the Redis healthcheck does not authenticate as a named account, so it cannot "
|
|
"pass with the default user off")
|
|
|
|
for setting in REDIS_REFERENCES:
|
|
reference = scalar(env.get(setting))
|
|
match = CREDENTIAL_REFERENCE.fullmatch(reference)
|
|
if match is None:
|
|
problems.append(f"{setting} is '{reference}', not secret://<account>@environment/<variable>")
|
|
continue
|
|
user, name = match.group(1), match.group(2)
|
|
value = scalar(env.get(name))
|
|
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 '>'.
|
|
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 f">{value}" not in account:
|
|
problems.append(f"{name} is not the password {label} gives {user}")
|
|
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 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]:
|
|
"""8. The lane's own memory limit, when it sets one, is a Compose memory size."""
|
|
limit = scalar(lane.get("appMemoryLimit"))
|
|
if limit and MEMORY_SIZE.fullmatch(limit) is None:
|
|
return [f"appMemoryLimit '{limit}' is not a Compose memory size such as 1g"]
|
|
return []
|
|
|
|
|
|
def heap_dump(model: dict, heap_path: str) -> list[str]:
|
|
"""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 {}
|
|
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 []
|
|
|
|
|
|
def keycloak_realm(repo_root: Path) -> list[str]:
|
|
"""10. The Keycloak realm artifact carries no key Keycloak refuses to deserialize."""
|
|
realm = repo_root / REALM
|
|
if not realm.is_file():
|
|
return []
|
|
try:
|
|
tree = json.loads(realm.read_text(encoding="utf-8"))
|
|
except (ValueError, UnicodeDecodeError):
|
|
return [f"{REALM} is not valid JSON"]
|
|
annotations = sorted(set(underscore_keys(tree)))
|
|
if annotations:
|
|
return [f"the Keycloak realm carries key(s) Keycloak refuses to deserialize: {', '.join(annotations)}"]
|
|
return []
|
|
|
|
|
|
def underscore_keys(tree: object) -> list[str]:
|
|
if isinstance(tree, dict):
|
|
found = [key for key in tree if key.startswith("_")]
|
|
for value in tree.values():
|
|
found += underscore_keys(value)
|
|
return found
|
|
if isinstance(tree, list):
|
|
return [key for item in tree for key in underscore_keys(item)]
|
|
return []
|
|
|
|
|
|
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"]
|
|
if rendered.services_rc != 0:
|
|
return [f"the stack does not render: {' '.join(rendered.services_error.split())}"]
|
|
problems = service_set(lane, rendered.services)
|
|
if problems:
|
|
return problems
|
|
try:
|
|
model = json.loads(rendered.model) if rendered.model_rc == 0 else None
|
|
except ValueError:
|
|
model = None
|
|
if not isinstance(model, dict) or not isinstance(model.get("services"), dict):
|
|
return ["the merged model does not render as JSON"]
|
|
return [
|
|
*spring_runtime(lane, model),
|
|
*duplicate_mounts(model),
|
|
*role_partition(contract, lane),
|
|
*application_report(contract, lane),
|
|
*redis_authentication(lane, model, repo_root),
|
|
*memory_limit(lane),
|
|
*(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_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_paths)
|
|
if lane_problems:
|
|
problems += [f"{lane['id']}: {problem}" for problem in lane_problems]
|
|
else:
|
|
matched.append(f"{lane['id']}: {','.join(sorted(lane['services']))} @ {lane['springRuntime']}")
|
|
problems += keycloak_realm(repo_root)
|
|
return matched, problems
|
|
|
|
|
|
# ---- files ------------------------------------------------------------------------------------
|
|
|
|
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")
|
|
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:
|
|
return Rendered(
|
|
services_rc=status(read(render_dir / f"{lane_id}.services.rc")),
|
|
services=read(render_dir / f"{lane_id}.services") or "",
|
|
services_error=read(render_dir / f"{lane_id}.services.err") or "",
|
|
model_rc=status(read(render_dir / f"{lane_id}.json.rc")),
|
|
model=read(render_dir / f"{lane_id}.json") or "",
|
|
)
|
|
|
|
|
|
def status(text: str | None) -> int | None:
|
|
if text is None or not text.strip().isdigit():
|
|
return None
|
|
return int(text.strip())
|
|
|
|
|
|
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_bytes().decode("utf-8", errors="replace")
|
|
except FileNotFoundError:
|
|
return None
|
|
|
|
|
|
def relative(path: Path, root: Path) -> str:
|
|
try:
|
|
return str(path.resolve().relative_to(root.resolve()))
|
|
except ValueError:
|
|
return str(path)
|
|
|
|
|
|
def load_contract(path: Path) -> dict:
|
|
text = read(path)
|
|
if text is None:
|
|
raise SetupError(f"missing {path}")
|
|
try:
|
|
contract = json.loads(text)
|
|
except ValueError as error:
|
|
raise ContractError(f"{path} is not valid JSON: {error}") from error
|
|
if not isinstance(contract, dict):
|
|
raise ContractError(f"{path} is not a JSON object")
|
|
return contract
|
|
|
|
|
|
class ContractError(Exception):
|
|
"""The contract file cannot be read as a contract; a failure, not a setup problem."""
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
parser.add_argument("--repo-root", type=Path, default=DEFAULT_REPO_ROOT,
|
|
help="the repository the contract's paths are relative to")
|
|
commands = parser.add_subparsers(dest="command", required=True)
|
|
version_command = commands.add_parser("version")
|
|
version_command.add_argument("contract", type=Path)
|
|
version_command.add_argument("actual")
|
|
commands.add_parser("lanes").add_argument("contract", type=Path)
|
|
judge_command = commands.add_parser("judge")
|
|
judge_command.add_argument("contract", type=Path)
|
|
judge_command.add_argument("render_dir", type=Path)
|
|
args = parser.parse_args(argv)
|
|
|
|
try:
|
|
contract = load_contract(args.contract)
|
|
if args.command == "version":
|
|
problems = compose_version(contract, args.actual)
|
|
for problem in problems:
|
|
print(problem, file=sys.stderr)
|
|
if not problems:
|
|
print(f"compose version {args.actual.strip().removeprefix('v')} >= {contract['minimumComposeVersion']}")
|
|
return 1 if problems else 0
|
|
if args.command == "lanes":
|
|
for lane in lanes(contract, args.repo_root)[0]:
|
|
print("\t".join([lane["id"], *compose_arguments(contract, lane, args.repo_root)]))
|
|
return 0
|
|
matched, problems = judge(contract, args.render_dir, args.repo_root)
|
|
except SetupError as error:
|
|
print(error, file=sys.stderr)
|
|
return SETUP
|
|
except ContractError as error:
|
|
print(f" FAIL: {error}", file=sys.stderr)
|
|
return 1
|
|
for line in matched:
|
|
print(line)
|
|
for problem in problems:
|
|
print(f" FAIL: {problem}", file=sys.stderr)
|
|
if problems:
|
|
print(f"verify-compose-profile-contracts: {len(problems)} problem(s) against {CONTRACT_LABEL}",
|
|
file=sys.stderr)
|
|
return 1
|
|
print(f"verify-compose-profile-contracts: all {len(matched)} lanes match {CONTRACT_LABEL}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|