From 01446e91f5c997bdd499deb6a551f630bd203299 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Wed, 7 Oct 2026 17:12:14 +0900 Subject: [PATCH] =?UTF-8?q?HTTP=20healthcheck=20=EA=B2=80=EC=A6=9D?= =?UTF-8?q?=EA=B3=BC=20Runtime=20smoke=20=EC=A0=84=EB=8B=AC=20=EA=B3=84?= =?UTF-8?q?=EC=95=BD=20=EB=B3=B4=EC=99=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/challenge-supply-chain.yml | 3 +- docs/challenge-execution-settings.md | 53 ++++++++++++++++-- docs/gcp-runtime-https-smoke.md | 14 ++++- scripts/README.md | 8 +++ scripts/healthcheck_contract.py | 40 ++++++++++++++ scripts/runtime_api_smoke_runner.py | 8 +++ scripts/validate_info_spec.py | 29 +++------- tests/test_generate_publish_bundle.py | 17 ++++++ tests/test_healthcheck_contract.py | 43 +++++++++++++++ tests/test_runtime_api_smoke_runner.py | 49 +++++++++++++++++ tests/test_validate_info_spec.py | 56 ++++++++++++++++++++ tests/test_workflow_contracts.py | 13 +++++ 12 files changed, 304 insertions(+), 29 deletions(-) create mode 100644 scripts/healthcheck_contract.py create mode 100644 tests/test_healthcheck_contract.py diff --git a/.github/workflows/challenge-supply-chain.yml b/.github/workflows/challenge-supply-chain.yml index c7f978c..48db8f5 100644 --- a/.github/workflows/challenge-supply-chain.yml +++ b/.github/workflows/challenge-supply-chain.yml @@ -684,6 +684,7 @@ jobs: aws s3 cp dist/artifact-v2.json "s3://${BUCKET}/${prefix}/artifact-v2.json" aws s3 cp dist/runtime-smoke-config.json "s3://${BUCKET}/${prefix}/runtime-smoke-config.json" aws s3 cp .msgctf-ci/scripts/runtime_api_smoke_runner.py "s3://${BUCKET}/${prefix}/runtime_api_smoke_runner.py" + aws s3 cp .msgctf-ci/scripts/healthcheck_contract.py "s3://${BUCKET}/${prefix}/healthcheck_contract.py" - name: SSM으로 Secure Provisioner smoke test 실행 env: @@ -696,7 +697,7 @@ jobs: --instance-ids "$INSTANCE_ID" \ --document-name AWS-RunShellScript \ --comment "MSGCTF Secure Provisioner runtime smoke deployment" \ - --parameters "commands=[\"set -euo pipefail\",\"install -d -m 0700 ${remote_dir}\",\"trap 'rm -rf ${remote_dir}' EXIT\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/artifact-v2.json ${remote_dir}/artifact-v2.json\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/runtime-smoke-config.json ${remote_dir}/runtime-smoke-config.json\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/runtime_api_smoke_runner.py ${remote_dir}/runtime_api_smoke_runner.py\",\"python3 ${remote_dir}/runtime_api_smoke_runner.py --artifact ${remote_dir}/artifact-v2.json --config ${remote_dir}/runtime-smoke-config.json --timeout 180 --cleanup-timeout 180\"]" \ + --parameters "commands=[\"set -euo pipefail\",\"install -d -m 0700 ${remote_dir}\",\"trap 'rm -rf ${remote_dir}' EXIT\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/artifact-v2.json ${remote_dir}/artifact-v2.json\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/runtime-smoke-config.json ${remote_dir}/runtime-smoke-config.json\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/runtime_api_smoke_runner.py ${remote_dir}/runtime_api_smoke_runner.py\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/healthcheck_contract.py ${remote_dir}/healthcheck_contract.py\",\"python3 ${remote_dir}/runtime_api_smoke_runner.py --artifact ${remote_dir}/artifact-v2.json --config ${remote_dir}/runtime-smoke-config.json --timeout 180 --cleanup-timeout 180\"]" \ --query 'Command.CommandId' --output text)" for _ in $(seq 1 150); do status="$(aws ssm get-command-invocation --command-id "$command_id" --instance-id "$INSTANCE_ID" --query Status --output text 2>/dev/null || true)" diff --git a/docs/challenge-execution-settings.md b/docs/challenge-execution-settings.md index 700ea45..7e78aea 100644 --- a/docs/challenge-execution-settings.md +++ b/docs/challenge-execution-settings.md @@ -21,7 +21,7 @@ Scheduler는 생성·reset 전달, Runtime은 설정 적용·격리·준비 상 | build / image | workload.containers[].image | GHCR digest 고정 이미지로 발행 | | ports / expose | workload.containers[].ports[].port/public | Runtime smoke에서는 ports/exposed_ports로 변환, expose 미전송 | | deployment.resource_profile | resource_profile | CPU·메모리·임시 저장 용량 합산 지원 | -| deployment.healthcheck.container/port/path | workload.healthcheck | CI가 이미 보존함. Backend 릴리스 PR은 저장함. Scheduler 생성 요청과 Runtime 적용은 추가 연결 필요 | +| deployment.healthcheck.container/port/path | workload.healthcheck | CI 검증·보존 및 직접 Runtime smoke 전달 지원. Backend #26·Scheduler #59·Runtime 연결의 실제 생성 검증은 별도 필요 | | flag | 없음 | CI output·bundle에 값 미포함. 런타임 FLAG 주입으로 자동 변환하지 않음 | | registry_revision | registry_revision | workflow 입력으로 지정, release 식별 및 이력 관리 | @@ -93,7 +93,7 @@ checker 등 운영 보조 서비스이거나 이름 차이일 수 있으므로 2. FLAG·DB 비밀번호·인증키는 원문 대신 승인된 비밀 참조를 bundle에 기록하는 방향으로 협의합니다. 참조 발급·접근 범위·동적 값 생성·reset 처리 소유자는 Backend/Runtime/보안팀이 정합니다. CI가 info.yaml.flag를 그대로 복사하지 않습니다. -3. healthcheck의 기존 HTTP 구조는 끝까지 보존합니다. TCP/exec, 시간 제한, +3. healthcheck의 기존 HTTP 구조는 아래 계약대로 끝까지 보존합니다. TCP/exec, 시간 제한, startup/readiness 판정이 필요하면 공통 계약을 추가합니다. Runtime에 없는 키를 먼저 보내지 않습니다. 4. 쓰기 경로·용량은 제한된 storage 계약으로 정의합니다. hostPath나 임의 호스트 마운트는 입력받지 않습니다. Compose volume을 그대로 복사하지 않습니다. @@ -128,6 +128,53 @@ Runtime 담당과 확인해야 합니다. [Kubernetes Pod 네트워크](https://kubernetes.io/docs/concepts/workloads/pods/), [NetworkPolicy](https://kubernetes.io/docs/concepts/services-networking/network-policies/). +## HTTP healthcheck 계약과 연결 현황 + +2026-10-07 확인 기준으로 기존 HTTP 검사 구조는 다음과 같습니다. 새 info.yaml +옵션을 추가한 것이 아니라 이미 있는 값을 검증하고 직접 smoke 요청에 보존합니다. + +```yaml +deployment: + healthcheck: + container: web + port: 9090 + path: /healthz +``` + +- container는 선언된 컨테이너 이름과 정확히 일치해야 합니다. +- port는 해당 컨테이너가 선언한 1..65535 정수 포트이며 비공개 포트도 가능합니다. + healthcheck를 지정했다고 공개 포트로 바꾸지 않습니다. +- path는 `/`로 시작하고 공백·제어 문자를 포함하지 않아야 합니다. + Scheduler·Runtime과 동일하게 UTF-16 코드 단위 1024개 이하로 제한합니다. + 앞뒤 공백을 자동 삭제하지 않고 잘못된 입력으로 거절합니다. +- 생략 또는 null이면 bundle과 smoke 요청에 별도 healthcheck를 넣지 않습니다. + 빈 객체나 일부 필드 누락, 미지원 필드는 거절합니다. +- TCP/exec 검사와 출제자 지정 timeout은 지원 계약에 포함하지 않습니다. + 특히 PWN 준비 상태 기준은 별도 합의 없이 추가하지 않습니다. + +| 단계 | 확인된 코드 | 아직 확인할 내용 | +|---|---|---| +| DevSecOps | info.yaml 검증 → bundle 보존 → 직접 smoke의 workload.healthcheck 전달 | 병합 후 caller SHA 갱신 및 실제 발행 bundle 시험 | +| Backend #26 | 릴리스 저장, 생성 요청의 healthcheck 전달 | 병합·배포, 실제 DB 왕복 및 연동 | +| Scheduler #59 | 저장·reset 보존, Runtime 요청 전달 코드 | 병합·배포와 SCHEDULER_INSTANCE_POLICY_HEALTHCHECK_ENABLED 설정 | +| Runtime | 컨테이너 HTTP readiness 적용, 준비 실패 시 WORKLOAD_NOT_READY와 정리 코드 | 승인된 실제 이미지로 정상·실패 생성 시험 | + +Runtime의 HTTP 검사 구현은 배포 기준 커밋 +[`701567f4`](https://github.com/MSG-CTF/secure-provisioner/blob/701567f410a68518bb628463c8d5480559f31efc/internal/provisioner/readiness.go), +요청 적용은 [create 처리](https://github.com/MSG-CTF/secure-provisioner/blob/701567f410a68518bb628463c8d5480559f31efc/internal/httpapi/create.go)에서 확인했습니다. +Backend는 [PR #26](https://github.com/MSG-CTF/msg-backend/pull/26), +Scheduler는 [PR #59](https://github.com/MSG-CTF/instance-scheduler/pull/59) 기준입니다. +코드가 있다는 사실과 전체 경로의 실제 성공은 구분합니다. + +직접 Runtime smoke는 Backend·Scheduler를 거치지 않습니다. 모의 서버 테스트는 +요청에 값이 전달되는지와 기존 삭제 처리를 확인하며, 실제 K3s probe 성공의 증거가 아닙니다. +healthcheck를 생략해도 Runtime 이미지 정책에 기본 검사가 있을 수 있으므로, +생략을 검사 완전 비활성이나 애플리케이션 정상 보장으로 해석하지 않습니다. + +실제 연동에서는 정상 HTTP 검사 성공과 실패 경로를 각각 확인합니다. +실패한 컨테이너를 RUNNING으로 기록하지 않는지, 실패 정리가 완료되는지, +reset 뒤 동일한 healthcheck가 유지되는지도 각 담당과 확인해야 합니다. + ## 담당별 요청 | 담당 | 요청 | 완료 조건 | @@ -180,7 +227,7 @@ Actions에도 반영됩니다. 이번 PR에서 문제 저장소는 변경하지 - GCP Runtime의 무인증 HTTPS 연결 점검은 실제 생성·접속·reset·삭제 검증과 다릅니다. 실제 문제 배포 성공이나 전체 Linux/Docker 실행 검증으로 기록하지 않습니다. -확인 기준: +2026-10-05 당시 확인 기준 (최신 HTTP 계약은 위 2026-10-07 항목 참조): - DevSecOps main: b39f232fc4759b70928c4960e7a17bb33264bcec - Backend 릴리스 PR #26: fb9d0df3fac0ec0bb424eabdbc1e9ff75d48b883 (apps/instances/releases.py의 healthcheck 보존 확인, PR은 확인 시 Open) diff --git a/docs/gcp-runtime-https-smoke.md b/docs/gcp-runtime-https-smoke.md index 7a68b27..e1df669 100644 --- a/docs/gcp-runtime-https-smoke.md +++ b/docs/gcp-runtime-https-smoke.md @@ -10,11 +10,20 @@ 발행 bundle의 `artifact-v2.json`을 기존 `runtime_api_smoke_runner.py`에 입력한다. runner는 기본 인증서 검증을 켠 HTTPS로 create → Operation 조회 → delete → Operation 조회를 수행한다. 토큰은 runner 임시 파일에만 쓰고 작업 종료 시 지운다. 결과에는 토큰이나 FLAG 원문을 넣지 않는다. 발행된 digest가 아직 Provisioner 정책에 없으면 생성이 실패하며, 이미지 정책 검토·배포 후 재실행한다. 자동 승인이나 임의 digest 허용은 하지 않는다. +bundle에 `workload.healthcheck`가 있으면 `container`, `port`, `path`를 검증한 뒤 +같은 위치의 Runtime 요청 필드로 전달한다. 생략/null이면 요청에서 생략한다. +컨테이너·포트 일치, 공백·제어 문자 금지, UTF-16 길이 1024 제한은 CI와 같은 +검증 함수를 사용한다. 비공개 검사 포트를 exposed_ports에 추가하지 않는다. +기존 expose와 internal_connections 미전송 원칙도 유지한다. + ## 단계적 적용과 복구 기존 AWS SSM smoke job 및 `enable_k3s_smoke_deploy` 입력은 그대로 둔다. 새 HTTPS job은 별도 플래그로만 실행한다. 먼저 승인된 Grade digest를 이용한 수동 GitHub runner 시험으로 공개 TLS·토큰·생성·삭제 Operation을 검증한다. 그다음 호출 저장소가 새 재사용 workflow 커밋을 고정하고, 발행할 digest의 정책 승인을 확인한 뒤 `ENABLE_RUNTIME_HTTPS_SMOKE=true`를 설정한다. 오류가 발생하면 이 변수만 `false`로 바꿔 자동 실행을 중단한다. -기존 검사·발행·AWS job의 실행 코드는 변경하지 않는다. 다만 HTTPS smoke가 실패하면 전체 workflow도 실패하므로, 성공한 workflow만 수집하는 Backend Poller는 해당 실행의 bundle을 등록할 수 없다. 정책 미승인 digest로 자동 job을 먼저 활성화하지 않는다. +기존 검사·발행과 AWS job의 활성화 조건을 유지한다. 공유 healthcheck 검증 모듈은 +AWS staging에서도 runner와 함께 전달한다. HTTPS smoke가 실패하면 전체 workflow도 +실패하므로, 성공한 workflow만 수집하는 Backend Poller는 해당 실행의 bundle을 +등록할 수 없다. 정책 미승인 digest로 자동 job을 먼저 활성화하지 않는다. ## 검증 범위 @@ -23,11 +32,12 @@ 현재 runner와 자동 job이 확인하는 항목은 다음과 같다. - Runtime API의 HTTPS 인증서 검증과 인증된 요청. +- bundle의 HTTP healthcheck 검증·전달. 실제 probe 수행과 준비 상태 판정은 Runtime 소유다. - 생성 Operation의 `SUCCEEDED`와 결과의 workload 식별자 확인. - 반환된 endpoint의 형식과 공개 포트 계약 확인. endpoint 주소로 실제 접속하는 검사는 아니다. - 삭제 Operation의 `SUCCEEDED` 확인. K3s 리소스를 직접 조회한 삭제 확인은 아니다. -공개 문제 URL의 HTTP 응답·healthcheck, 실행 이미지 digest 대조, K3s Namespace·Pod·Service 잔존 여부, 팀·인스턴스 격리는 별도 검증이 필요하다. 새 digest 자동 승인, Scheduler reset, PWN/gVisor, 팀 인증 게이트웨이도 이 변경에 포함하지 않는다. +공개 문제 URL의 실제 HTTP 응답, 전달된 healthcheck의 정상·실패 동작, 실행 이미지 digest 대조, K3s Namespace·Pod·Service 잔존 여부, 팀·인스턴스 격리는 별도 검증이 필요하다. 새 digest 자동 승인, Scheduler reset, PWN/gVisor, 팀 인증 게이트웨이도 이 변경에 포함하지 않는다. 이번 보완은 실제 서버를 호출하거나 HTTPS smoke를 활성화하지 않는다. ## 확인된 실행 기록 diff --git a/scripts/README.md b/scripts/README.md index bbfc799..686d093 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -63,6 +63,14 @@ Backend poller는 성공한 `-publish-bundle` artifact에서 이 파일을 수 public/private port는 publish bundle에 포트별로 보존하고 Runtime smoke 요청에서는 전체 `ports`와 공개할 `exposed_ports`로 변환합니다. +### `healthcheck_contract.py` + +info.yaml 검증과 Runtime smoke에서 같은 HTTP healthcheck 검증을 사용합니다. +컨테이너·선언 포트 일치, 공백·제어 문자 금지, UTF-16 길이 1024 제한을 확인합니다. +별도 외부 의존성이 없으며 AWS staging에서도 runner와 함께 전달합니다. +smoke는 bundle의 healthcheck를 Runtime 요청에 보존하되 공개 포트 목록을 바꾸지 않습니다. +실제 HTTP probe 실행과 준비 상태 판정은 Runtime 담당입니다. + ### `pipeline_timing.py` GitHub Actions의 컨테이너별 `Build/Pull`, `Scan`, `GHCR Push` 구간을 측정하고 diff --git a/scripts/healthcheck_contract.py b/scripts/healthcheck_contract.py new file mode 100644 index 0000000..ccfd4fd --- /dev/null +++ b/scripts/healthcheck_contract.py @@ -0,0 +1,40 @@ +"""Validate the shared HTTP readiness contract without optional dependencies.""" + +import unicodedata + + +MAX_PATH_UTF16_UNITS = 1024 + + +def validate_healthcheck(raw, containers): + if raw is None: + return None + if not isinstance(raw, dict): + raise ValueError("deployment.healthcheck must be an object") + if any(key not in {"container", "port", "path"} for key in raw): + raise ValueError("healthcheck contains unsupported fields") + + name = raw.get("container") + if not isinstance(name, str) or not name: + raise ValueError("healthcheck.container must be a non-empty string") + by_name = {container["name"]: container for container in containers} + if name not in by_name: + raise ValueError("healthcheck.container must reference a declared container") + port = raw.get("port") + if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535: + raise ValueError("healthcheck.port must be an integer in 1..65535") + if port not in by_name[name]["ports"]: + raise ValueError("healthcheck.port must reference a declared container port") + + path = raw.get("path") + if not isinstance(path, str) or not path.startswith("/"): + raise ValueError("healthcheck.path must be an absolute HTTP path") + if any( + character.isspace() or unicodedata.category(character) in {"Cc", "Cs"} + for character in path + ): + raise ValueError("healthcheck.path must not contain whitespace or control characters") + # Scheduler counts UTF-16 units; Runtime uses the same length convention. + if sum(2 if ord(character) > 0xFFFF else 1 for character in path) > MAX_PATH_UTF16_UNITS: + raise ValueError("healthcheck.path must not exceed 1024 UTF-16 units") + return {"container": name, "port": port, "path": path} diff --git a/scripts/runtime_api_smoke_runner.py b/scripts/runtime_api_smoke_runner.py index 19b1dee..3183825 100644 --- a/scripts/runtime_api_smoke_runner.py +++ b/scripts/runtime_api_smoke_runner.py @@ -16,6 +16,11 @@ from urllib.parse import urlsplit, urlunsplit from urllib.request import HTTPRedirectHandler, HTTPSHandler, Request, build_opener +if __package__: + from .healthcheck_contract import validate_healthcheck +else: + from healthcheck_contract import validate_healthcheck + DIGEST_IMAGE = re.compile(r"^.+@sha256:[0-9a-f]{64}$") SERVICE_TOKEN = re.compile(r"^[A-Za-z0-9_-]{43,128}$") @@ -179,6 +184,9 @@ def build_create_request( raise ValueError("PWN workload must declare exactly one exposed container") runtime_workload = {"containers": runtime_containers} + healthcheck = validate_healthcheck(workload.get("healthcheck"), runtime_containers) + if healthcheck is not None: + runtime_workload["healthcheck"] = healthcheck resource_profile = artifact.get("resource_profile") if not isinstance(resource_profile, dict): diff --git a/scripts/validate_info_spec.py b/scripts/validate_info_spec.py index 2180a65..16b6715 100644 --- a/scripts/validate_info_spec.py +++ b/scripts/validate_info_spec.py @@ -6,6 +6,11 @@ import yaml +if __package__: + from .healthcheck_contract import validate_healthcheck +else: + from healthcheck_contract import validate_healthcheck + SAFE_NAME = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$") CATEGORY = re.compile(r"^[a-z][a-z0-9-]{0,31}$") @@ -110,28 +115,6 @@ def _validate_container(challenge_path, raw): return container -def _validate_healthcheck(raw, containers): - if raw is None: - return None - if not isinstance(raw, dict): - raise ValueError("deployment.healthcheck must be an object") - _reject_unknown_fields(raw, {"container", "port", "path"}, "healthcheck") - container_name = _required_string( - raw.get("container"), - "healthcheck.container", - ) - by_name = {container["name"]: container for container in containers} - if container_name not in by_name: - raise ValueError("healthcheck.container must reference a declared container") - port = _positive_int(raw.get("port"), "healthcheck.port") - if port > 65535 or port not in by_name[container_name]["ports"]: - raise ValueError("healthcheck.port must reference a declared container port") - path = _required_string(raw.get("path"), "healthcheck.path") - if not path.startswith("/") or any(ord(character) < 32 for character in path): - raise ValueError("healthcheck.path must be an absolute HTTP path") - return {"container": container_name, "port": port, "path": path} - - def validate_spec(challenge_path): challenge_path = Path(challenge_path).resolve() if not challenge_path.is_dir(): @@ -240,7 +223,7 @@ def validate_spec(challenge_path): "containers": containers, "resource_profile": resource_profile, }) - healthcheck = _validate_healthcheck(deployment.get("healthcheck"), containers) + healthcheck = validate_healthcheck(deployment.get("healthcheck"), containers) if healthcheck: metadata["healthcheck"] = healthcheck return metadata diff --git a/tests/test_generate_publish_bundle.py b/tests/test_generate_publish_bundle.py index 49b2c0d..ea0a78b 100644 --- a/tests/test_generate_publish_bundle.py +++ b/tests/test_generate_publish_bundle.py @@ -4,6 +4,7 @@ from pathlib import Path from scripts.generate_publish_bundle import generate_bundle +from scripts.runtime_api_smoke_runner import build_create_request DIGEST_A = "sha256:" + "a" * 64 @@ -70,6 +71,22 @@ class GeneratePublishBundleTests(unittest.TestCase): + def test_generated_bundle_preserves_healthcheck_in_runtime_request(self): + bundle = generate_bundle(METADATA, RESULTS, SOURCE_REF, SOURCE_SHA, 3, EVIDENCE_ROOT) + artifact = json.loads(json.dumps(bundle["artifact"])) + request = build_create_request( + artifact, + target_id="broker-test2", + instance_id="00000000-0000-4000-8000-000000000001", + team_id="00000000-0000-4000-8000-000000000002", + ) + self.assertEqual(request["workload"]["healthcheck"], METADATA["healthcheck"]) + self.assertEqual( + [container["image"] for container in request["workload"]["containers"]], + [result["image"] for result in RESULTS], + ) + self.assertNotIn("internal_connections", request["workload"]) + def test_generates_runtime_artifact_and_registry_publish_document(self): bundle = generate_bundle( METADATA, RESULTS, SOURCE_REF, SOURCE_SHA, 3, EVIDENCE_ROOT diff --git a/tests/test_healthcheck_contract.py b/tests/test_healthcheck_contract.py new file mode 100644 index 0000000..1c3401a --- /dev/null +++ b/tests/test_healthcheck_contract.py @@ -0,0 +1,43 @@ +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from scripts.healthcheck_contract import validate_healthcheck + + +class HealthcheckContractTests(unittest.TestCase): + def test_rejects_invalid_unicode_path_without_echoing_it(self): + path = "/sensitive-value\ud800" + with self.assertRaisesRegex(ValueError, "healthcheck.path") as raised: + validate_healthcheck( + {"container": "web", "port": 8080, "path": path}, + [{"name": "web", "ports": [8080]}], + ) + self.assertNotIn("sensitive-value", str(raised.exception)) + + def test_rejects_unknown_field_without_echoing_secret_values(self): + with self.assertRaisesRegex(ValueError, "unsupported fields") as raised: + validate_healthcheck( + {"container": "web", "port": 8080, "path": "/", "secret-key": "secret-value"}, + [{"name": "web", "ports": [8080]}], + ) + self.assertNotIn("secret-key", str(raised.exception)) + self.assertNotIn("secret-value", str(raised.exception)) + + def test_staged_runner_imports_without_repository_or_site_packages(self): + scripts = Path(__file__).resolve().parents[1] / "scripts" + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + for name in ("runtime_api_smoke_runner.py", "healthcheck_contract.py"): + shutil.copyfile(scripts / name, root / name) + result = subprocess.run( + [sys.executable, "-S", str(root / "runtime_api_smoke_runner.py"), "--help"], + cwd=root, + capture_output=True, + text=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("--artifact", result.stdout) diff --git a/tests/test_runtime_api_smoke_runner.py b/tests/test_runtime_api_smoke_runner.py index a68d7b6..02ee9c5 100644 --- a/tests/test_runtime_api_smoke_runner.py +++ b/tests/test_runtime_api_smoke_runner.py @@ -268,6 +268,7 @@ def test_builds_runtime_team_multi_container_contract(self): "run_as_user": 10001, } ], + "healthcheck": ARTIFACT["workload"]["healthcheck"], "resource_limits": ARTIFACT["resource_profile"], }, ) @@ -289,6 +290,9 @@ def test_builds_mixed_public_private_ports_with_exposed_ports(self): "ports": [{"port": 5432, "public": False}], }, ] + artifact["workload"]["healthcheck"] = { + "container": "web", "port": 9000, "path": "/healthz" + } request = build_create_request( artifact, target_id="aws-k3s-lab", @@ -323,6 +327,46 @@ def test_builds_mixed_public_private_ports_with_exposed_ports(self): ) ) self.assertNotIn("internal_connections", request["workload"]) + self.assertEqual(request["workload"]["healthcheck"], artifact["workload"]["healthcheck"]) + self.assertEqual(request["workload"]["containers"][0]["exposed_ports"], [8080]) + + def test_omits_absent_or_null_healthcheck(self): + for present in (False, True): + with self.subTest(present=present): + artifact = copy.deepcopy(ARTIFACT) + artifact["workload"].pop("healthcheck") + if present: + artifact["workload"]["healthcheck"] = None + request = build_create_request( + artifact, target_id="broker-test2", instance_id=INSTANCE_ID, team_id=TEAM_ID + ) + self.assertNotIn("healthcheck", request["workload"]) + + def test_rejects_malformed_healthcheck_before_runtime_request(self): + cases = [ + {}, [], "http://invalid", {"container": "missing", "port": 9090, "path": "/"}, + {"container": "service", "port": True, "path": "/"}, + {"container": "service", "port": 9999, "path": "/"}, + {"container": "service", "port": 9090, "path": "/secret value"}, + {"container": "service", "port": 9090, "path": "/" + "x" * 1024}, + {"container": "service", "port": 9090, "path": "/", "timeout": 3}, + ] + for healthcheck in cases: + with self.subTest(healthcheck=healthcheck): + artifact = copy.deepcopy(ARTIFACT) + artifact["workload"]["healthcheck"] = healthcheck + with self.assertRaisesRegex(ValueError, "healthcheck"): + build_create_request( + artifact, target_id="broker-test2", instance_id=INSTANCE_ID, team_id=TEAM_ID + ) + + def test_healthcheck_forwarding_does_not_mutate_bundle(self): + artifact = copy.deepcopy(ARTIFACT) + request = build_create_request( + artifact, target_id="broker-test2", instance_id=INSTANCE_ID, team_id=TEAM_ID + ) + request["workload"]["healthcheck"]["path"] = "/changed" + self.assertEqual(artifact, ARTIFACT) def test_does_not_forward_legacy_internal_connections(self): artifact = copy.deepcopy(ARTIFACT) @@ -382,6 +426,10 @@ def test_creates_polls_and_always_deletes_runtime_workload(self): for _method, _path, headers, _body in RuntimeHandler.requests: self.assertEqual(headers["Authorization"], f"Bearer {'A' * 43}") delete_body = RuntimeHandler.requests[2][3] + self.assertEqual( + RuntimeHandler.requests[0][3]["workload"]["healthcheck"], + ARTIFACT["workload"]["healthcheck"], + ) self.assertEqual(delete_body["runtime_workload_id"], "aws-k3s-001/ctf-test/challenge") self.assertEqual(delete_body["delete_reason"], "ADMIN_FORCED") @@ -669,6 +717,7 @@ def test_maps_pwn_category_to_pwn_isolation_profile(self): artifact = copy.deepcopy(ARTIFACT) artifact["category"] = "pwn" artifact["isolation_profile"] = "PWN" + artifact["workload"].pop("healthcheck") artifact["workload"]["containers"][0]["ports"] = [ {"port": 31337, "public": True} ] diff --git a/tests/test_validate_info_spec.py b/tests/test_validate_info_spec.py index df0f3bb..90eebfd 100644 --- a/tests/test_validate_info_spec.py +++ b/tests/test_validate_info_spec.py @@ -267,6 +267,62 @@ def test_rejects_healthcheck_for_unknown_container(self): def _raw_fixture(self): return copy.deepcopy(yaml.safe_load((FIXTURE / "info.yaml").read_text())) + def test_rejects_healthcheck_path_whitespace_controls_and_invalid_types(self): + paths = [ + " /healthz", "/healthz ", "/health check", "/health\tcheck", "/health\ncheck", + "/health\x7f", "/health\x85", "/health\u00a0", "relative", "", None, 123, + ] + for path in paths: + with self.subTest(path=path): + raw = self._raw_fixture() + raw["deployment"]["healthcheck"]["path"] = path + with self.assertRaisesRegex(ValueError, "healthcheck.path"): + self._validate_raw(raw) + + def test_healthcheck_path_limit_matches_utf16_contract(self): + for path in ("/" + "x" * 1023, "/" + "\U0001f600" * 511 + "x"): + with self.subTest(units=1024, path_length=len(path)): + raw = self._raw_fixture() + raw["deployment"]["healthcheck"]["path"] = path + self.assertEqual(self._validate_raw(raw)["healthcheck"]["path"], path) + for path in ("/" + "x" * 1024, "/" + "\U0001f600" * 512): + with self.subTest(units=1025, path_length=len(path)): + raw = self._raw_fixture() + raw["deployment"]["healthcheck"]["path"] = path + with self.assertRaisesRegex(ValueError, "1024 UTF-16"): + self._validate_raw(raw) + + def test_accepts_private_healthcheck_port_without_exposing_it(self): + raw = self._raw_fixture() + raw["deployment"]["healthcheck"] = { + "container": "helper", "port": 9091, "path": "/ready" + } + metadata = self._validate_raw(raw) + self.assertEqual(metadata["healthcheck"], raw["deployment"]["healthcheck"]) + self.assertFalse(metadata["containers"][1]["expose"]) + + def test_rejects_incomplete_healthcheck_and_invalid_ports(self): + cases = [{}, [], {"container": "web", "port": 9090}] + cases += [ + {"container": "web", "port": port, "path": "/healthz"} + for port in (True, "9090", 0, 65536, 9999) + ] + for healthcheck in cases: + with self.subTest(healthcheck=healthcheck): + raw = self._raw_fixture() + raw["deployment"]["healthcheck"] = healthcheck + with self.assertRaisesRegex(ValueError, "healthcheck"): + self._validate_raw(raw) + + def test_omits_absent_or_null_healthcheck(self): + for present in (False, True): + with self.subTest(present=present): + raw = self._raw_fixture() + raw["deployment"].pop("healthcheck") + if present: + raw["deployment"]["healthcheck"] = None + self.assertNotIn("healthcheck", self._validate_raw(raw)) + def _validate_raw(self, raw, empty_build_directory=None): with tempfile.TemporaryDirectory() as temp_dir: challenge = Path(temp_dir) / "challenge" diff --git a/tests/test_workflow_contracts.py b/tests/test_workflow_contracts.py index 2b6c5e7..b8f74f5 100644 --- a/tests/test_workflow_contracts.py +++ b/tests/test_workflow_contracts.py @@ -330,6 +330,19 @@ def test_challenge_supply_chain_keeps_production_runtime_ownership(self): self.assertNotIn("render_k3s_smoke_manifest.py", text) self.assertNotIn("kubectl", text) self.assertIn("runtime_api_smoke_runner.py", text) + staging = next(step for step in smoke["steps"] if step.get("name") == "S3 staging 경로 업로드") + execution = next( + step for step in smoke["steps"] + if step.get("name") == "SSM으로 Secure Provisioner smoke test 실행" + ) + self.assertIn( + 'aws s3 cp .msgctf-ci/scripts/healthcheck_contract.py "s3://${BUCKET}/${prefix}/healthcheck_contract.py"', + staging["run"], + ) + self.assertIn( + "aws s3 cp s3://${BUCKET}/${PREFIX}/healthcheck_contract.py ${remote_dir}/healthcheck_contract.py", + execution["run"], + ) self.assertIn("inputs.runtime_target_id", text) self.assertIn("GHCR_PULL_SECRET_ARN", workflow["on"]["workflow_call"]["secrets"]) self.assertNotIn("GHCR_PULL_SECRET_ARN", str(smoke))