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
1190 lines
58 KiB
Python
1190 lines
58 KiB
Python
"""scripts/compose-contract-verdict.py의 시험. Compose 계약의 정적 판정이 고장 난 입력을 실패로 보는지 본다:
|
|
lane이 없는 계약, 파일이 없는 lane, 렌더 실패와 셸이 남기지 않은 렌더 기록, service 집합·Spring runtime·mount 중복,
|
|
role 분할, 기대 vendor가 없는 JPA lane, Redis 계정 대조(비밀번호의 `*`를 포함해), tmpfs 위의 heap dump 경로,
|
|
Keycloak realm의 `_` key. 정상 입력은 통과하는지도 같이 본다. 마지막으로
|
|
scripts/verify-compose-profile-contracts.sh를 가짜 `docker`로 돌려, 셸이 판정에 lane 인자와 렌더 결과를 넘기고
|
|
그 rc로 끝나는지 본다.
|
|
|
|
python3 -m unittest discover -s scripts/tests
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import importlib.util
|
|
import io
|
|
import json
|
|
import os
|
|
import shutil
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import textwrap
|
|
import unittest
|
|
from contextlib import redirect_stderr, redirect_stdout
|
|
from pathlib import Path
|
|
|
|
SCRIPTS = Path(__file__).resolve().parent.parent
|
|
VERDICT = SCRIPTS / "compose-contract-verdict.py"
|
|
SHELL = SCRIPTS / "verify-compose-profile-contracts.sh"
|
|
_spec = importlib.util.spec_from_file_location("compose_contract_verdict", VERDICT)
|
|
verdict = importlib.util.module_from_spec(_spec)
|
|
sys.modules["compose_contract_verdict"] = verdict
|
|
_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:
|
|
document = {
|
|
"minimumComposeVersion": "2.24.4",
|
|
"composeFiles": {"base": "compose.yaml", "lane": "lane-services.yaml"},
|
|
"preStartServices": ["schema"],
|
|
"oneShotServices": ["smoke"],
|
|
"capabilities": ["persistence-jpa", "redis"],
|
|
"lanes": list(lanes),
|
|
}
|
|
document.update(fields)
|
|
return document
|
|
|
|
|
|
def lane(**fields: object) -> dict:
|
|
document = {
|
|
"id": "off-local", "composeProfiles": [], "files": ["base"], "springRuntime": "local",
|
|
"services": ["app"], "longRunningServices": ["app"], "oneShotServices": [], "blocking": True,
|
|
"activationEnv": {}, "expectedCapabilitiesOn": [], "expectedPersistenceVendor": "none",
|
|
}
|
|
document.update(fields)
|
|
return document
|
|
|
|
|
|
def app(**fields: object) -> dict:
|
|
service = {"environment": {"SPRING_PROFILES_ACTIVE": "local"}, "tmpfs": ["/tmp:mode=1777,size=128m"]}
|
|
service.update(fields)
|
|
return service
|
|
|
|
|
|
def model(**services: dict) -> dict:
|
|
return {"services": services or {"app": app()}}
|
|
|
|
|
|
class Repository:
|
|
"""A repository root with the files the verdict reads: compose files, a Dockerfile, an ACL file."""
|
|
|
|
def __init__(self) -> None:
|
|
self._directory = tempfile.TemporaryDirectory()
|
|
self.root = Path(self._directory.name)
|
|
self.write("compose.yaml", "services: {}\n")
|
|
self.write("lane-services.yaml", "services: {}\n")
|
|
self.write("Dockerfile", f'ENV JAVA_TOOL_OPTIONS="-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath={HEAP} \\\n')
|
|
self.write("compose/redis/acl/lane.acl", ACL)
|
|
|
|
def write(self, relative: str, text: str) -> Path:
|
|
path = self.root / relative
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(text, encoding="utf-8")
|
|
return path
|
|
|
|
def close(self) -> None:
|
|
self._directory.cleanup()
|
|
|
|
|
|
def rendered(services: str = "app\n", document: object = None, services_rc: int | None = 0,
|
|
model_rc: int | None = 0, error: str = "") -> verdict.Rendered:
|
|
return verdict.Rendered(
|
|
services_rc=services_rc, services=services, services_error=error,
|
|
model_rc=model_rc, model=json.dumps(model() if document is None else document),
|
|
)
|
|
|
|
|
|
class RepositoryTestCase(unittest.TestCase):
|
|
|
|
def setUp(self) -> None:
|
|
self.repository = Repository()
|
|
self.addCleanup(self.repository.close)
|
|
self.root = self.repository.root
|
|
|
|
|
|
class ContractShapeTest(RepositoryTestCase):
|
|
|
|
def test_a_list_entry_that_is_not_a_name_fails_the_lane(self) -> None:
|
|
# given: strings() drops such an entry, so the role and report checks would never see it
|
|
cases = {
|
|
"expectedCapabilitiesOn": [None],
|
|
"longRunningServices": ["app", 1],
|
|
"services": ["app", ""],
|
|
"composeProfiles": [["jpa"]],
|
|
"oneShotServices": [None],
|
|
"preStartServices": [False],
|
|
}
|
|
for field, entries in cases.items():
|
|
with self.subTest(field=field):
|
|
# when
|
|
renderable, problems = verdict.lanes(contract(lane(**{field: entries})), self.root)
|
|
|
|
# then
|
|
self.assertEqual(renderable, [])
|
|
self.assertEqual(problems, [f"off-local: '{field}' holds {json.dumps(entries)}, and every entry must be a name"])
|
|
|
|
def test_a_contract_with_lanes_that_name_existing_files_is_renderable(self) -> None:
|
|
# given
|
|
document = contract(lane(), lane(id="off-dev", files=["base", "lane"], composeProfiles=["jpa"]))
|
|
|
|
# when
|
|
renderable, problems = verdict.lanes(document, self.root)
|
|
|
|
# then
|
|
self.assertEqual(problems, [])
|
|
self.assertEqual(
|
|
verdict.compose_arguments(document, renderable[1], self.root),
|
|
["-f", str(self.root / "compose.yaml"), "-f", str(self.root / "lane-services.yaml"), "--profile", "jpa"],
|
|
)
|
|
|
|
def test_a_contract_with_no_lanes_fails_rather_than_matching_all_of_none(self) -> None:
|
|
for lanes in ({"lanes": []}, {"lanes": None}):
|
|
with self.subTest(lanes=lanes):
|
|
# given
|
|
document = contract(**lanes)
|
|
|
|
# when
|
|
renderable, problems = verdict.lanes(document, self.root)
|
|
|
|
# then
|
|
self.assertEqual(renderable, [])
|
|
self.assertEqual(problems, ["the contract declares no lanes, so nothing would be checked"])
|
|
|
|
def test_a_lane_without_files_fails_rather_than_rendering_whatever_compose_finds(self) -> None:
|
|
# given
|
|
document = contract(lane(files=[]))
|
|
|
|
# when
|
|
renderable, problems = verdict.lanes(document, self.root)
|
|
|
|
# then
|
|
self.assertEqual(renderable, [])
|
|
self.assertEqual(len(problems), 1)
|
|
self.assertTrue(problems[0].startswith("off-local: names no compose file under 'files'"), problems)
|
|
|
|
def test_a_lane_naming_an_unknown_or_missing_file_fails(self) -> None:
|
|
# given
|
|
(self.root / "lane-services.yaml").unlink()
|
|
document = contract(lane(files=["base", "tls", "lane"]))
|
|
|
|
# when
|
|
_, problems = verdict.lanes(document, self.root)
|
|
|
|
# then
|
|
self.assertEqual(problems, [
|
|
"off-local: names compose file 'tls', which composeFiles does not list",
|
|
"off-local: lane-services.yaml is missing",
|
|
])
|
|
|
|
def test_a_lane_without_the_lists_the_smoke_wrapper_reads_fails(self) -> None:
|
|
# given
|
|
broken = lane()
|
|
del broken["composeProfiles"], broken["expectedCapabilitiesOn"], broken["springRuntime"]
|
|
|
|
# when
|
|
_, problems = verdict.lanes(contract(broken), self.root)
|
|
|
|
# then
|
|
self.assertEqual(problems, [
|
|
"off-local: has no 'composeProfiles' list; the smoke wrapper reads it as one",
|
|
"off-local: has no 'expectedCapabilitiesOn' list; the smoke wrapper reads it as one",
|
|
"off-local: names no springRuntime",
|
|
])
|
|
|
|
def test_two_lanes_with_one_id_fail_because_their_records_would_overwrite_each_other(self) -> None:
|
|
# given
|
|
document = contract(lane(), lane())
|
|
|
|
# when
|
|
renderable, problems = verdict.lanes(document, self.root)
|
|
|
|
# then
|
|
self.assertEqual(len(renderable), 1)
|
|
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
|
|
subject = lane(preStartServices=None, oneShotServices=False)
|
|
absent = lane(id="off-dev")
|
|
del absent["oneShotServices"]
|
|
|
|
# when
|
|
renderable, problems = verdict.lanes(contract(subject, absent), self.root)
|
|
|
|
# then
|
|
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):
|
|
|
|
def test_a_compose_at_or_above_the_floor_passes(self) -> None:
|
|
for actual in ("2.24.4", "v2.29.1", "2.30.0-desktop.1", "3.0"):
|
|
with self.subTest(actual=actual):
|
|
self.assertEqual(verdict.compose_version(contract(), actual), [])
|
|
|
|
def test_a_compose_below_the_floor_fails(self) -> None:
|
|
for actual in ("2.24.3", "2.24", "1.29.2"):
|
|
with self.subTest(actual=actual):
|
|
problems = verdict.compose_version(contract(), actual)
|
|
self.assertEqual(problems[0], f"docker compose {actual} is below the required 2.24.4;")
|
|
|
|
def test_a_version_that_cannot_be_read_fails(self) -> None:
|
|
self.assertEqual(
|
|
verdict.compose_version(contract(), ""),
|
|
["docker compose reports '', which is not a version"],
|
|
)
|
|
self.assertEqual(
|
|
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])
|
|
|
|
def test_a_lane_that_renders_its_services_and_a_clean_model_passes(self) -> None:
|
|
self.assertEqual(self.judge(rendered()), [])
|
|
|
|
def test_a_stack_that_does_not_render_fails_with_what_compose_said(self) -> None:
|
|
# given
|
|
record = rendered(services="", services_rc=1, error="service \"app\" refers to\nundefined volume\n")
|
|
|
|
# when
|
|
problems = self.judge(record)
|
|
|
|
# then
|
|
self.assertEqual(problems, ["the stack does not render: service \"app\" refers to undefined volume"])
|
|
|
|
def test_a_lane_the_shell_left_no_record_for_fails(self) -> None:
|
|
for record in (rendered(services_rc=None), rendered(model_rc=None)):
|
|
with self.subTest(record=record):
|
|
self.assertEqual(self.judge(record), ["the shell left no record of rendering this lane"])
|
|
|
|
def test_a_superset_or_a_subset_of_the_services_fails(self) -> None:
|
|
for services in ("app\npostgres\n", ""):
|
|
with self.subTest(services=services):
|
|
problems = self.judge(rendered(services=services))
|
|
self.assertEqual(len(problems), 1)
|
|
self.assertTrue(problems[0].startswith("services are ["), problems)
|
|
|
|
def test_the_order_of_the_rendered_services_does_not_matter(self) -> None:
|
|
# given
|
|
subject = lane(services=["postgres", "app"], longRunningServices=["app", "postgres"])
|
|
document = model(app=app(), postgres={})
|
|
|
|
# then
|
|
self.assertEqual(self.judge(rendered(services="app\npostgres\n", document=document), subject), [])
|
|
|
|
def test_a_model_that_is_not_json_fails(self) -> None:
|
|
# given
|
|
record = verdict.Rendered(services_rc=0, services="app\n", services_error="", model_rc=0, model="services:\n")
|
|
|
|
# then
|
|
self.assertEqual(self.judge(record), ["the merged model does not render as JSON"])
|
|
self.assertEqual(self.judge(rendered(model_rc=15)), ["the merged model does not render as JSON"])
|
|
|
|
def test_another_spring_runtime_fails(self) -> None:
|
|
# given
|
|
document = model(app=app(environment={"SPRING_PROFILES_ACTIVE": "prod"}))
|
|
|
|
# then
|
|
self.assertEqual(
|
|
self.judge(rendered(document=document)),
|
|
["app renders SPRING_PROFILES_ACTIVE='prod', the contract says 'local'"],
|
|
)
|
|
|
|
def test_a_mount_target_declared_twice_fails_naming_the_service(self) -> None:
|
|
# given
|
|
document = model(app=app(volumes=[{"type": "bind", "source": "/data", "target": "/tmp"}]))
|
|
|
|
# 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):
|
|
|
|
def test_a_service_filed_under_exactly_one_role_passes(self) -> None:
|
|
# given
|
|
subject = lane(services=["app", "schema", "smoke"], preStartServices=["schema"], oneShotServices=["smoke"])
|
|
|
|
# then
|
|
self.assertEqual(verdict.role_partition(contract(), subject), [])
|
|
|
|
def test_an_unfiled_a_not_rendered_and_a_twice_filed_service_fail(self) -> None:
|
|
# given
|
|
subject = lane(services=["app", "postgres"], longRunningServices=["app", "redis"], oneShotServices=["app"])
|
|
|
|
# when
|
|
problems = verdict.role_partition(contract(oneShotServices=["smoke", "app"]), subject)
|
|
|
|
# then
|
|
self.assertIn(
|
|
"services are not partitioned by role — unfiled=[postgres] not-rendered=[redis] twice=[app]",
|
|
problems,
|
|
)
|
|
|
|
def test_a_one_shot_listed_as_a_wait_target_fails(self) -> None:
|
|
# given
|
|
subject = lane(services=["app", "smoke"], longRunningServices=["app", "smoke"])
|
|
|
|
# then
|
|
self.assertEqual(
|
|
verdict.role_partition(contract(), subject),
|
|
["[smoke] are declared non-waiting but listed as --wait targets"],
|
|
)
|
|
|
|
def test_a_service_run_once_but_in_no_catalogue_fails(self) -> None:
|
|
# given
|
|
subject = lane(services=["app", "probe"], oneShotServices=["probe"])
|
|
|
|
# then
|
|
self.assertEqual(
|
|
verdict.role_partition(contract(), subject),
|
|
["[probe] are run with `run --rm` but are in neither top-level catalogue"],
|
|
)
|
|
|
|
|
|
class ApplicationReportTest(unittest.TestCase):
|
|
|
|
def test_a_vendor_that_agrees_with_persistence_jpa_passes(self) -> None:
|
|
on = lane(expectedCapabilitiesOn=["persistence-jpa"], expectedPersistenceVendor="postgresql")
|
|
self.assertEqual(verdict.application_report(contract(), on), [])
|
|
self.assertEqual(verdict.application_report(contract(), lane()), [])
|
|
|
|
def test_a_jpa_lane_without_an_expected_vendor_fails(self) -> None:
|
|
# given: the smoke wrapper compares the reported vendor with this field, so the lane fails every run
|
|
subject = lane(expectedCapabilitiesOn=["persistence-jpa"])
|
|
del subject["expectedPersistenceVendor"]
|
|
|
|
# when
|
|
problems = verdict.application_report(contract(), subject)
|
|
|
|
# then
|
|
self.assertEqual(problems, [
|
|
"the expected application report is unreachable — no expectedPersistenceVendor with persistence-jpa on",
|
|
])
|
|
|
|
def test_a_vendor_that_contradicts_persistence_jpa_fails(self) -> None:
|
|
cases = {
|
|
"none with jpa on": (lane(expectedCapabilitiesOn=["persistence-jpa"]), "vendor none with persistence-jpa on"),
|
|
"a vendor with jpa off": (lane(expectedPersistenceVendor="postgresql"), "vendor postgresql with persistence-jpa off"),
|
|
}
|
|
for case, (subject, reason) in cases.items():
|
|
with self.subTest(case=case):
|
|
self.assertEqual(
|
|
verdict.application_report(contract(), subject),
|
|
[f"the expected application report is unreachable — {reason}"],
|
|
)
|
|
|
|
def test_a_capability_outside_the_catalogue_fails(self) -> None:
|
|
# given
|
|
subject = lane(expectedCapabilitiesOn=["websocket"])
|
|
|
|
# then
|
|
self.assertEqual(
|
|
verdict.application_report(contract(), subject),
|
|
["the expected application report is unreachable — uncatalogued=[websocket]"],
|
|
)
|
|
|
|
|
|
class RedisAuthenticationTest(RepositoryTestCase):
|
|
|
|
def environment(self, **overrides: object) -> dict:
|
|
env = {
|
|
"APP_REDIS_ENABLED": "true",
|
|
"APP_REDIS_NAMESPACE_ENVIRONMENT": "prod",
|
|
"APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE": "secret://app@environment/REDIS_LANE_APPLICATION_PASSWORD",
|
|
"APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE":
|
|
"secret://app-advanced@environment/REDIS_LANE_ADVANCED_PASSWORD",
|
|
"REDIS_LANE_APPLICATION_PASSWORD": "example-app-password",
|
|
"REDIS_LANE_ADVANCED_PASSWORD": "example-advanced-password",
|
|
}
|
|
env.update(overrides)
|
|
return {key: value for key, value in env.items() if value is not None}
|
|
|
|
def redis(self, **fields: object) -> dict:
|
|
service = {
|
|
"command": ["redis-server", "--appendonly", "no", "--aclfile", "/etc/redis/acl/lane.acl"],
|
|
"volumes": [{"type": "bind", "source": str(self.root / "compose/redis/acl"),
|
|
"target": "/etc/redis/acl", "read_only": True}],
|
|
"healthcheck": {"test": ["CMD-SHELL", "redis-cli --user app --pass \"$$P\" ping"]},
|
|
}
|
|
service.update(fields)
|
|
return service
|
|
|
|
def problems(self, env: dict | None = None, redis: dict | None = None) -> list[str]:
|
|
subject = lane(activationEnv=self.environment() if env is None else env)
|
|
document = model(app=app(), redis=self.redis() if redis is None else redis)
|
|
return verdict.redis_authentication(subject, document, self.root)
|
|
|
|
def test_a_lane_that_names_accounts_its_redis_provisions_passes(self) -> None:
|
|
self.assertEqual(self.problems(), [])
|
|
|
|
def test_a_lane_that_does_not_switch_redis_on_is_not_checked(self) -> None:
|
|
self.assertEqual(self.problems(env={"APP_REDIS_ENABLED": "false"}, redis={}), [])
|
|
|
|
def test_a_password_with_a_star_does_not_match_an_account_with_another_password(self) -> None:
|
|
# given: '*' is a character of the password, not a wildcard
|
|
env = self.environment(REDIS_LANE_APPLICATION_PASSWORD="*")
|
|
|
|
# then
|
|
self.assertEqual(
|
|
self.problems(env=env),
|
|
["REDIS_LANE_APPLICATION_PASSWORD is not the password compose/redis/acl/lane.acl gives app"],
|
|
)
|
|
|
|
def test_a_wrong_password_fails(self) -> None:
|
|
self.assertEqual(
|
|
self.problems(env=self.environment(REDIS_LANE_ADVANCED_PASSWORD="example-app-password")),
|
|
["REDIS_LANE_ADVANCED_PASSWORD is not the password compose/redis/acl/lane.acl gives app-advanced"],
|
|
)
|
|
|
|
def test_a_user_name_with_a_dot_matches_only_itself(self) -> None:
|
|
# given: a regular expression read 'app.x' as 'app' plus any character plus 'x'
|
|
self.repository.write("compose/redis/acl/lane.acl", ACL + "user appXx on >example-x-password ~prod:* +@all\n")
|
|
env = self.environment(APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE="secret://app.x@environment/X",
|
|
X="example-x-password")
|
|
|
|
# then
|
|
self.assertEqual(
|
|
self.problems(env=env),
|
|
["APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE names app.x, which compose/redis/acl/lane.acl does not enable"],
|
|
)
|
|
|
|
def test_a_namespace_the_account_may_not_touch_fails(self) -> None:
|
|
problems = self.problems(env=self.environment(APP_REDIS_NAMESPACE_ENVIRONMENT="local"))
|
|
self.assertEqual(problems, [
|
|
"app may not touch local:*, the namespace this lane writes",
|
|
"app-advanced may not touch local:*, the namespace this lane writes",
|
|
])
|
|
|
|
def test_each_way_a_lane_falls_short_is_named(self) -> None:
|
|
cases = {
|
|
"anonymous": (self.environment(APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED=True), None,
|
|
"accepts anonymous Redis access"),
|
|
"no namespace": (self.environment(APP_REDIS_NAMESPACE_ENVIRONMENT=None), None,
|
|
"sets no APP_REDIS_NAMESPACE_ENVIRONMENT"),
|
|
"no aclfile": (None, self.redis(command=["redis-server"]), "starts Redis without --aclfile"),
|
|
"aclfile is the last word": (None, self.redis(command=["redis-server", "--aclfile"]),
|
|
"starts Redis without --aclfile"),
|
|
"writable mount": (None, self.redis(volumes=[{"type": "bind", "source": str(self.root / "compose/redis/acl"),
|
|
"target": "/etc/redis/acl"}]),
|
|
"which no read-only bind mount of a repository file provides"),
|
|
"healthcheck as default user": (None, self.redis(healthcheck={"test": ["CMD", "redis-cli", "ping"]}),
|
|
"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://<account>@environment/<variable>"),
|
|
"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://<account>@environment/<variable>"),
|
|
"unset variable": (self.environment(REDIS_LANE_APPLICATION_PASSWORD=None), None,
|
|
"reads REDIS_LANE_APPLICATION_PASSWORD, which the lane does not supply"),
|
|
}
|
|
for case, (env, redis, reason) in cases.items():
|
|
with self.subTest(case=case):
|
|
problems = self.problems(env=env, redis=redis)
|
|
self.assertTrue(any(reason in problem for problem in problems), problems)
|
|
|
|
def test_an_acl_file_that_leaves_the_default_user_on_or_enables_a_user_twice_fails(self) -> None:
|
|
# given
|
|
self.repository.write("compose/redis/acl/lane.acl", ACL.replace("user default off\n", "")
|
|
+ "user app on >example-app-password ~prod:* +@all\n")
|
|
|
|
# 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 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 <name>`, 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 <name>`, 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"),
|
|
"target": "/etc/redis/acl/lane.acl", "read_only": True}
|
|
|
|
# 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
|
|
cases = {
|
|
"short syntax at the path": app(tmpfs=["/tmp", f"{HEAP}:size=1g"]),
|
|
"short syntax above the path": app(tmpfs=["/var/tmp:size=1g"]),
|
|
"trailing slash above the path": app(tmpfs=["/var/tmp/"]),
|
|
"long syntax at the path": app(volumes=[{"type": "tmpfs", "target": HEAP}]),
|
|
"long syntax above the path": app(volumes=[{"type": "tmpfs", "target": "/var"}]),
|
|
}
|
|
for case, service in cases.items():
|
|
with self.subTest(case=case):
|
|
problems = verdict.heap_dump(model(app=service), HEAP)
|
|
self.assertEqual(len(problems), 1)
|
|
self.assertIn(f"which holds the heap dump path {HEAP}", problems[0])
|
|
|
|
def test_a_volume_or_bind_mount_at_the_heap_dump_path_is_not_a_tmpfs(self) -> None:
|
|
for kind, source in (("volume", "dumps"), ("bind", "./build/heap")):
|
|
with self.subTest(kind=kind):
|
|
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):
|
|
|
|
def test_a_compose_memory_size_or_none_passes(self) -> None:
|
|
self.assertEqual(verdict.memory_limit(lane(appMemoryLimit="1g")), [])
|
|
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", "1gb"):
|
|
with self.subTest(limit=limit):
|
|
self.assertEqual(
|
|
verdict.memory_limit(lane(appMemoryLimit=limit)),
|
|
[f"appMemoryLimit '{limit}' is not a Compose memory size such as 1g"],
|
|
)
|
|
|
|
|
|
class KeycloakRealmTest(RepositoryTestCase):
|
|
|
|
def test_no_realm_or_a_realm_without_annotations_passes(self) -> None:
|
|
self.assertEqual(verdict.keycloak_realm(self.root), [])
|
|
self.repository.write(verdict.REALM, json.dumps({"realm": "ca", "clients": [{"clientId": "web"}]}))
|
|
self.assertEqual(verdict.keycloak_realm(self.root), [])
|
|
|
|
def test_an_annotation_key_anywhere_in_the_tree_fails(self) -> None:
|
|
# given
|
|
self.repository.write(verdict.REALM, json.dumps({"_comment": "x", "clients": [{"_flowComment": "y"}]}))
|
|
|
|
# then
|
|
self.assertEqual(
|
|
verdict.keycloak_realm(self.root),
|
|
["the Keycloak realm carries key(s) Keycloak refuses to deserialize: _comment, _flowComment"],
|
|
)
|
|
|
|
def test_a_realm_that_is_not_json_fails(self) -> None:
|
|
self.repository.write(verdict.REALM, "{")
|
|
self.assertEqual(verdict.keycloak_realm(self.root), [f"{verdict.REALM} is not valid JSON"])
|
|
|
|
|
|
class CommandLineTest(RepositoryTestCase):
|
|
|
|
def record(self, directory: Path, lane_id: str, services: str = "app\n", document: object = None) -> None:
|
|
(directory / f"{lane_id}.services").write_text(services, encoding="utf-8")
|
|
(directory / f"{lane_id}.services.err").write_text("", encoding="utf-8")
|
|
(directory / f"{lane_id}.services.rc").write_text("0\n", encoding="utf-8")
|
|
(directory / f"{lane_id}.json").write_text(json.dumps(document or model()), encoding="utf-8")
|
|
(directory / f"{lane_id}.json.rc").write_text("0\n", encoding="utf-8")
|
|
|
|
def run_judge(self, document: dict) -> tuple[int, str, str]:
|
|
path = self.repository.write(CONTRACT_PATH, json.dumps(document))
|
|
stdout, stderr = io.StringIO(), io.StringIO()
|
|
with redirect_stdout(stdout), redirect_stderr(stderr):
|
|
rc = verdict.main(["--repo-root", str(self.root), "judge", str(path), str(self.root / "rendered")])
|
|
return rc, stdout.getvalue(), stderr.getvalue()
|
|
|
|
def setUp(self) -> None:
|
|
super().setUp()
|
|
(self.root / "rendered").mkdir()
|
|
|
|
def test_every_lane_matching_exits_zero_naming_each(self) -> None:
|
|
# given
|
|
self.record(self.root / "rendered", "off-local")
|
|
|
|
# when
|
|
rc, stdout, stderr = self.run_judge(contract(lane()))
|
|
|
|
# then
|
|
self.assertEqual((rc, stderr), (0, ""))
|
|
self.assertEqual(stdout.splitlines(), [
|
|
"off-local: app @ local",
|
|
f"verify-compose-profile-contracts: all 1 lanes match {CONTRACT_PATH}",
|
|
])
|
|
|
|
def test_each_lane_judgement_fails_the_command_on_its_own(self) -> None:
|
|
# given: one fault per case, each seen by one judgement only, so a judgement left out of
|
|
# judge_lane passes its case
|
|
no_vendor = lane(expectedCapabilitiesOn=["persistence-jpa"])
|
|
del no_vendor["expectedPersistenceVendor"]
|
|
redis_on = {"APP_REDIS_ENABLED": "true", "APP_REDIS_NAMESPACE_ENVIRONMENT": "prod"}
|
|
cases = {
|
|
"role partition": (lane(longRunningServices=[]), model(),
|
|
"services are not partitioned by role — unfiled=[app]"),
|
|
"application report": (no_vendor, model(),
|
|
"no expectedPersistenceVendor with persistence-jpa on"),
|
|
"redis authentication": (lane(activationEnv=redis_on), model(),
|
|
"starts Redis without --aclfile"),
|
|
"memory limit": (lane(appMemoryLimit="1G"), model(),
|
|
"appMemoryLimit '1G' is not a Compose memory size such as 1g"),
|
|
"heap dump": (lane(), model(app=app(tmpfs=["/var/tmp:size=64m"])),
|
|
f"which holds the heap dump path {HEAP}"),
|
|
}
|
|
for case, (subject, document, reason) in cases.items():
|
|
with self.subTest(case=case):
|
|
self.record(self.root / "rendered", "off-local", document=document)
|
|
|
|
# when
|
|
rc, stdout, stderr = self.run_judge(contract(subject))
|
|
|
|
# then
|
|
self.assertEqual((rc, stdout), (1, ""))
|
|
failures = [line for line in stderr.splitlines() if line.startswith(" FAIL: ")]
|
|
self.assertEqual(len(failures), 1, stderr)
|
|
self.assertTrue(failures[0].startswith(" FAIL: off-local: "), failures[0])
|
|
self.assertIn(reason, failures[0])
|
|
|
|
def test_a_realm_annotation_fails_the_command_although_every_lane_matches(self) -> None:
|
|
# given
|
|
self.record(self.root / "rendered", "off-local")
|
|
self.repository.write(verdict.REALM, json.dumps({"_comment": "x"}))
|
|
|
|
# when
|
|
rc, stdout, stderr = self.run_judge(contract(lane()))
|
|
|
|
# then
|
|
self.assertEqual(rc, 1)
|
|
self.assertEqual(stdout, "off-local: app @ local\n")
|
|
self.assertIn(" FAIL: the Keycloak realm carries key(s) Keycloak refuses to deserialize: _comment\n", stderr)
|
|
|
|
def test_a_failing_lane_exits_one_and_the_other_lanes_are_still_judged(self) -> None:
|
|
# given: off-dev has no record at all, and off-local renders a service too many
|
|
self.record(self.root / "rendered", "off-local", services="app\nextra\n")
|
|
|
|
# when
|
|
rc, stdout, stderr = self.run_judge(contract(lane(), lane(id="off-dev")))
|
|
|
|
# then
|
|
self.assertEqual(rc, 1)
|
|
self.assertEqual(stdout, "")
|
|
self.assertEqual(stderr.splitlines(), [
|
|
" FAIL: off-local: services are [app,extra], the contract says [app]",
|
|
" FAIL: off-dev: the shell left no record of rendering this lane",
|
|
f"verify-compose-profile-contracts: 2 problem(s) against {CONTRACT_PATH}",
|
|
])
|
|
|
|
def test_a_dockerfile_without_a_heap_dump_path_is_a_setup_error(self) -> None:
|
|
# given
|
|
self.repository.write("Dockerfile", "FROM eclipse-temurin:21-jre\n")
|
|
|
|
# when
|
|
rc, _, stderr = self.run_judge(contract(lane()))
|
|
|
|
# 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, "{")
|
|
|
|
# when
|
|
with redirect_stderr(io.StringIO()) as stderr:
|
|
rc = verdict.main(["--repo-root", str(self.root), "lanes", str(path)])
|
|
|
|
# then
|
|
self.assertEqual(rc, 1)
|
|
self.assertIn("is not valid JSON", stderr.getvalue())
|
|
|
|
|
|
FAKE_DOCKER = """\
|
|
#!{python}
|
|
# Answers `docker compose ...` the way the contract script calls it, from files beside this script.
|
|
import pathlib, sys
|
|
here = pathlib.Path(__file__).resolve().parent
|
|
with open(here / "calls.log", "a", encoding="utf-8") as log:
|
|
log.write(" ".join(sys.argv[1:]) + "\\n")
|
|
args = sys.argv[1:]
|
|
sys.stdin.read() # as a call that reads stdin would: the shell's lane list must not be what it reads
|
|
if args[:3] == ["compose", "version", "--short"]:
|
|
print((here / "version").read_text().strip())
|
|
sys.exit(0)
|
|
stack = "+".join(pathlib.Path(args[i + 1]).name for i, a in enumerate(args) if a == "-f")
|
|
kind = "json" if "--format" in args else "services"
|
|
answer = here / f"{{stack}}.{{kind}}"
|
|
if not answer.exists():
|
|
print(f"no such stack: {{stack}}", file=sys.stderr)
|
|
sys.exit(15)
|
|
sys.stdout.write(answer.read_text())
|
|
status = here / f"{{stack}}.{{kind}}.rc"
|
|
sys.exit(int(status.read_text()) if status.exists() else 0)
|
|
"""
|
|
|
|
|
|
class ContractScriptTest(RepositoryTestCase):
|
|
# The judgements above are only a gate while the shell gives them what docker rendered and exits
|
|
# with their status. This runs the real shell against a repository whose `docker` is a fake.
|
|
|
|
def setUp(self) -> None:
|
|
super().setUp()
|
|
(self.root / "scripts").mkdir()
|
|
for script in (SHELL, VERDICT):
|
|
shutil.copy(script, self.root / "scripts" / script.name)
|
|
self.fake = self.root / "fake-bin"
|
|
self.fake.mkdir()
|
|
docker = self.fake / "docker"
|
|
docker.write_text(FAKE_DOCKER.format(python=sys.executable), encoding="utf-8")
|
|
docker.chmod(docker.stat().st_mode | stat.S_IXUSR)
|
|
(self.fake / "version").write_text("2.29.1\n", encoding="utf-8")
|
|
self.answer("compose.yaml", "app\n", model())
|
|
self.answer("compose.yaml+lane-services.yaml", "app\nschema\n", model(app=app(), schema={}))
|
|
|
|
def answer(self, stack: str, services: str, document: dict) -> None:
|
|
(self.fake / f"{stack}.services").write_text(services, encoding="utf-8")
|
|
(self.fake / f"{stack}.json").write_text(json.dumps(document), encoding="utf-8")
|
|
|
|
def run_script(self, document: dict) -> subprocess.CompletedProcess:
|
|
self.repository.write(CONTRACT_PATH, json.dumps(document))
|
|
env = dict(os.environ, PATH=f"{self.fake}{os.pathsep}{os.environ.get('PATH', '')}", TMPDIR=str(self.root))
|
|
return subprocess.run(["bash", str(self.root / "scripts" / SHELL.name)],
|
|
stdin=subprocess.DEVNULL, capture_output=True, text=True, env=env, check=False)
|
|
|
|
def calls(self) -> list[str]:
|
|
log = self.fake / "calls.log"
|
|
return log.read_text(encoding="utf-8").splitlines() if log.exists() else []
|
|
|
|
def two_lanes(self) -> dict:
|
|
return contract(lane(), lane(id="schema-lane", files=["base", "lane"], composeProfiles=["jpa"],
|
|
services=["app", "schema"], preStartServices=["schema"]))
|
|
|
|
def test_lanes_that_render_what_they_claim_pass_and_each_is_rendered_with_its_files_and_profiles(self) -> None:
|
|
# when
|
|
result = self.run_script(self.two_lanes())
|
|
|
|
# then
|
|
self.assertEqual(result.returncode, 0, result.stderr)
|
|
self.assertEqual(result.stdout.splitlines(), [
|
|
"compose version 2.29.1 >= 2.24.4",
|
|
"off-local: app @ local",
|
|
"schema-lane: app,schema @ local",
|
|
f"verify-compose-profile-contracts: all 2 lanes match {CONTRACT_PATH}",
|
|
])
|
|
base, extra = self.root / "compose.yaml", self.root / "lane-services.yaml"
|
|
self.assertEqual(self.calls(), [
|
|
"compose version --short",
|
|
f"compose -f {base} config --services",
|
|
f"compose -f {base} config --format json",
|
|
f"compose -f {base} -f {extra} --profile jpa config --services",
|
|
f"compose -f {base} -f {extra} --profile jpa config --format json",
|
|
])
|
|
self.assertEqual(sorted(path.name for path in self.root.glob("compose-contract.*")), [])
|
|
|
|
def test_a_lane_whose_stack_does_not_render_fails_and_the_next_lane_is_still_rendered(self) -> None:
|
|
# given
|
|
(self.fake / "compose.yaml.services").unlink()
|
|
|
|
# when
|
|
result = self.run_script(self.two_lanes())
|
|
|
|
# then
|
|
self.assertEqual(result.returncode, 1)
|
|
self.assertIn(" FAIL: off-local: the stack does not render: no such stack: compose.yaml\n", result.stderr)
|
|
self.assertIn("schema-lane: app,schema @ local\n", result.stdout)
|
|
|
|
def test_a_model_render_that_exits_non_zero_fails_although_it_printed_json(self) -> None:
|
|
# given: the JSON is a model that would pass; only the exit status says the render failed
|
|
(self.fake / "compose.yaml.json.rc").write_text("1\n", encoding="utf-8")
|
|
|
|
# when
|
|
result = self.run_script(self.two_lanes())
|
|
|
|
# then
|
|
self.assertEqual(result.returncode, 1)
|
|
self.assertIn(" FAIL: off-local: the merged model does not render as JSON\n", result.stderr)
|
|
self.assertIn("schema-lane: app,schema @ local\n", result.stdout)
|
|
|
|
def test_a_contract_with_no_lanes_fails(self) -> None:
|
|
# when
|
|
result = self.run_script(contract())
|
|
|
|
# then
|
|
self.assertEqual(result.returncode, 1)
|
|
self.assertIn("the contract declares no lanes", result.stderr)
|
|
|
|
def test_a_compose_below_the_floor_fails_before_any_lane_is_rendered(self) -> None:
|
|
# given
|
|
(self.fake / "version").write_text("2.20.0\n", encoding="utf-8")
|
|
|
|
# when
|
|
result = self.run_script(self.two_lanes())
|
|
|
|
# then
|
|
self.assertEqual(result.returncode, 1)
|
|
self.assertIn("docker compose 2.20.0 is below the required 2.24.4;", result.stderr)
|
|
self.assertEqual(self.calls(), ["compose version --short"])
|
|
|
|
def test_the_shell_keeps_no_judgement_of_its_own(self) -> None:
|
|
# Every judgement is in the verdict, where the cases above can reach it.
|
|
script = SHELL.read_text(encoding="utf-8")
|
|
commands = "\n".join(line for line in script.splitlines() if not line.lstrip().startswith("#"))
|
|
self.assertNotRegex(commands, r"\bjq\b")
|
|
self.assertRegex(script, r'\npython3 "\$\{VERDICT\}" judge "\$\{CONTRACTS\}" "\$\{RENDERED\}"\n$')
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|