From edab3b181bbfb6c0329a8df5abc5c41fdcd9d0ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Sat, 29 Aug 2026 02:26:49 +0900 Subject: [PATCH 01/13] Record GHCR pull smoke evidence --- docs/aws-k3s-cd-smoke.md | 50 ++++++++++++++++++++- scripts/runtime_api_smoke_runner.py | 13 +++++- tests/test_runtime_api_smoke_runner.py | 61 ++++++++++++++++++++++++++ 3 files changed, 122 insertions(+), 2 deletions(-) diff --git a/docs/aws-k3s-cd-smoke.md b/docs/aws-k3s-cd-smoke.md index 86023ca..3223e3d 100644 --- a/docs/aws-k3s-cd-smoke.md +++ b/docs/aws-k3s-cd-smoke.md @@ -72,12 +72,58 @@ S3 파일과 Runtime API body에는 GHCR credential을 포함하지 않습니다 4. `GET /internal/v1/operations/{operation_id}`를 `SUCCEEDED`까지 조회합니다. 5. 같은 instance를 `DELETE /internal/v1/instances/{instance_id}`로 정리합니다. 6. 삭제 Operation도 `SUCCEEDED`인지 확인합니다. -7. Actions Summary에 `target_id`, `runtime_workload_id`, 생성·삭제 결과를 남깁니다. +7. Actions Summary에 `target_id`, `runtime_workload_id`, digest 이미지 목록, + `endpoints`, 생성·삭제 결과와 단계별 소요 시간을 남깁니다. 8. 성공과 실패 모두 S3 staging 파일을 삭제합니다. Smoke instance와 team UUID는 GitHub run 정보로 결정적으로 생성됩니다. 같은 run을 재시도해도 Runtime의 `request_id` 멱등 계약을 사용할 수 있습니다. +정상 실행 결과에는 다음 증거가 포함됩니다. + +```json +{ + "images": [ + { + "name": "web", + "image": "ghcr.io/msg-ctf/challenges/example/web@sha256:..." + } + ], + "endpoints": [], + "create_status": "SUCCEEDED", + "create_elapsed_seconds": 12.345, + "delete_status": "SUCCEEDED", + "delete_elapsed_seconds": 1.234 +} +``` + +`create_elapsed_seconds`는 생성 요청을 처음 제출한 시점부터 생성 Operation이 +`SUCCEEDED`가 될 때까지의 시간입니다. 이미지 pull뿐 아니라 Pod와 Service 준비 +시간도 포함하므로 순수 네트워크 처리량으로 해석하지 않습니다. + +## GHCR pull 검증 + +Issue #30을 닫기 전 정상 cold pull, GHCR 인증 실패와 `ImagePullBackOff`를 각각 +재현합니다. 장애 주입은 승인된 publish bundle을 변조하지 않고 Secure Provisioner +팀이 제공하는 전용 test target에서 수행합니다. + +| 시나리오 | DevSecOps 증거 | Secure Provisioner 준비와 확인 | +|---|---|---| +| cold pull | 실제 digest와 `create_elapsed_seconds` 기록 | 실행 전 해당 test digest의 node cache 제거 | +| 인증 실패 | 정상 검사된 private GHCR digest 제공 | 잘못되거나 제거된 pull credential을 가진 전용 target에서 실패 재현 | +| `ImagePullBackOff` | 운영 bundle과 분리된 테스트임을 기록 | 존재하지 않는 digest로 Pod 상태와 Operation 오류를 확인 | + +cold pull 확인은 같은 digest가 없는 상태에서 한 번 실행하고, 같은 node에서 다시 +실행한 warm-cache 결과와 비교합니다. cache 제거, pull credential 변경과 Pod 상태 +수집은 Runtime 소유 작업이며 CI가 `crictl`, `containerd`, Kubernetes Secret 또는 +`kubectl`을 직접 조작하지 않습니다. + +GHCR 인증 실패와 `ImagePullBackOff`는 정상 문제 발행의 성공 조건이 아닙니다. +따라서 일반 `k3s-smoke-deploy` job에 가짜 digest나 credential을 넣지 않고 Runtime +통합 테스트에서 실패 Operation의 `last_error_code`, Pod waiting reason과 cleanup +결과를 증거로 남깁니다. credential, service token과 raw pull 오류는 Actions Summary, +S3 staging 파일 또는 API body에 기록하지 않습니다. + ## 현재 제약 - Runtime팀 API의 현재 격리 profile에 맞춰 `pwn`은 `PWN`, 나머지는 `WEB`을 사용합니다. @@ -94,3 +140,5 @@ Smoke instance와 team UUID는 GitHub run 정보로 결정적으로 생성됩니 - `PROVISIONER_CLUSTER_REGISTRY`의 target과 K3s kubeconfig가 유효해야 합니다. - K3s/containerd가 private GHCR digest를 pull할 수 있어야 합니다. - 실패 후 Runtime Operation과 Namespace가 남지 않았는지 확인해야 합니다. +- cold pull 검증은 다른 workload가 없는 전용 target에서 Runtime팀이 image cache + 상태를 확인한 뒤 실행해야 합니다. diff --git a/scripts/runtime_api_smoke_runner.py b/scripts/runtime_api_smoke_runner.py index 7e69ea5..0570472 100644 --- a/scripts/runtime_api_smoke_runner.py +++ b/scripts/runtime_api_smoke_runner.py @@ -309,7 +309,8 @@ def run_smoke( instance_id=instance_id, team_id=team_id, ) - deadline = time.monotonic() + timeout + create_started = time.monotonic() + deadline = create_started + timeout recovered_after_timeout = False try: accepted = _submit_with_retry( @@ -357,6 +358,7 @@ def run_smoke( runtime_workload_id = create_result.get("runtime_workload_id") if not isinstance(runtime_workload_id, str) or not runtime_workload_id.strip(): raise RuntimeError("Runtime create operation returned an invalid runtime_workload_id") + create_elapsed_seconds = round(time.monotonic() - create_started, 3) delete_request = { "request_id": f"ci-smoke-delete-{create_request['instance_id']}", @@ -366,6 +368,7 @@ def run_smoke( "runtime_workload_id": runtime_workload_id, "delete_reason": "ADMIN_FORCED", } + delete_started = time.monotonic() cleanup_deadline = time.monotonic() + cleanup_timeout deleted = _submit_with_retry( client, @@ -381,15 +384,23 @@ def run_smoke( poll_interval=poll_interval, deadline=cleanup_deadline, ) + delete_elapsed_seconds = round(time.monotonic() - delete_started, 3) return { "challenge_slug": artifact.get("challenge_slug"), "revision": artifact.get("revision"), "target_id": target_id, "instance_id": create_request["instance_id"], "runtime_workload_id": runtime_workload_id, + "images": [ + {"name": container["name"], "image": container["image"]} + for container in create_request["workload"]["containers"] + ], "service_url": create_result.get("service_url"), + "endpoints": create_result.get("endpoints", []), "create_status": created["status"], + "create_elapsed_seconds": create_elapsed_seconds, "delete_status": delete_snapshot["status"], + "delete_elapsed_seconds": delete_elapsed_seconds, "recovered_after_timeout": recovered_after_timeout, } diff --git a/tests/test_runtime_api_smoke_runner.py b/tests/test_runtime_api_smoke_runner.py index 5efe22b..5b723aa 100644 --- a/tests/test_runtime_api_smoke_runner.py +++ b/tests/test_runtime_api_smoke_runner.py @@ -248,6 +248,67 @@ def test_creates_polls_and_always_deletes_runtime_workload(self): self.assertEqual(delete_body["runtime_workload_id"], "aws-k3s-001/ctf-test/challenge") self.assertEqual(delete_body["delete_reason"], "ADMIN_FORCED") + def test_reports_digest_images_and_runtime_endpoints(self): + self.start_server() + RuntimeHandler.create_result = { + "runtime_workload_id": "aws-k3s-001/ctf-test/challenge", + "service_url": "http://203.0.113.10:31042", + "endpoints": [ + { + "container_name": "service", + "port": 8080, + "protocol": "HTTP", + "service_url": "http://203.0.113.10:31042", + } + ], + } + with tempfile.TemporaryDirectory() as directory: + token_file = Path(directory) / "service-token" + token_file.write_text("A" * 43, encoding="utf-8") + result = run_smoke( + ARTIFACT, + api_url=f"http://127.0.0.1:{self.server.server_port}", + token_file=token_file, + target_id="aws-k3s-001", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + poll_interval=0, + timeout=2, + ) + + self.assertEqual( + result["images"], + [ + { + "name": "service", + "image": ARTIFACT["workload"]["containers"][0]["image"], + } + ], + ) + self.assertEqual(result["endpoints"], RuntimeHandler.create_result["endpoints"]) + self.assertNotIn("A" * 43, json.dumps(result)) + + def test_reports_create_and_delete_elapsed_seconds(self): + self.start_server() + with tempfile.TemporaryDirectory() as directory: + token_file = Path(directory) / "service-token" + token_file.write_text("A" * 43, encoding="utf-8") + result = run_smoke( + ARTIFACT, + api_url=f"http://127.0.0.1:{self.server.server_port}", + token_file=token_file, + target_id="aws-k3s-001", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + poll_interval=0, + timeout=2, + ) + + self.assertIsInstance(result["create_elapsed_seconds"], float) + self.assertGreaterEqual(result["create_elapsed_seconds"], 0.0) + self.assertIsInstance(result["delete_elapsed_seconds"], float) + self.assertGreaterEqual(result["delete_elapsed_seconds"], 0.0) + def test_maps_pwn_category_to_pwn_isolation_profile(self): artifact = dict(ARTIFACT, category="pwn") From 771a8373e3981038291e5ebcae0d434ea1b624a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Sat, 29 Aug 2026 02:46:32 +0900 Subject: [PATCH 02/13] Harden runtime smoke evidence validation --- docs/aws-k3s-cd-smoke.md | 9 ++- scripts/runtime_api_smoke_runner.py | 27 ++++++--- tests/test_runtime_api_smoke_runner.py | 78 ++++++++++++++++++++++++-- 3 files changed, 99 insertions(+), 15 deletions(-) diff --git a/docs/aws-k3s-cd-smoke.md b/docs/aws-k3s-cd-smoke.md index 3223e3d..d783cc1 100644 --- a/docs/aws-k3s-cd-smoke.md +++ b/docs/aws-k3s-cd-smoke.md @@ -89,7 +89,14 @@ Smoke instance와 team UUID는 GitHub run 정보로 결정적으로 생성됩니 "image": "ghcr.io/msg-ctf/challenges/example/web@sha256:..." } ], - "endpoints": [], + "endpoints": [ + { + "container_name": "web", + "port": 8080, + "protocol": "HTTP", + "service_url": "http://203.0.113.10:31042" + } + ], "create_status": "SUCCEEDED", "create_elapsed_seconds": 12.345, "delete_status": "SUCCEEDED", diff --git a/scripts/runtime_api_smoke_runner.py b/scripts/runtime_api_smoke_runner.py index 0570472..1d63bbd 100644 --- a/scripts/runtime_api_smoke_runner.py +++ b/scripts/runtime_api_smoke_runner.py @@ -10,7 +10,7 @@ import time import uuid from pathlib import Path -from typing import Any +from typing import Any, Callable from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen @@ -206,7 +206,11 @@ def request(self, method: str, path: str, body: dict[str, Any] | None = None) -> with urlopen(request, timeout=self.timeout) as response: payload = response.read().decode("utf-8") except HTTPError as error: - detail = error.read().decode("utf-8", errors="replace")[:500] + try: + detail = error.read().decode("utf-8", errors="replace") + finally: + error.close() + detail = detail.replace(self.token, "[REDACTED]")[:500] if error.code >= 500: raise RetryableRuntimeError( f"Runtime API {method} {path} returned HTTP {error.code}: {detail}" @@ -300,7 +304,10 @@ def run_smoke( poll_interval: float = 2, timeout: float = 300, cleanup_timeout: float = 300, + evidence_clock: Callable[[], float] | None = None, ) -> dict[str, Any]: + if evidence_clock is None: + evidence_clock = time.monotonic token = token_file.read_text(encoding="utf-8").strip() client = RuntimeClient(api_url, token, timeout=min(max(timeout, cleanup_timeout, 1), 30)) create_request = build_create_request( @@ -309,8 +316,8 @@ def run_smoke( instance_id=instance_id, team_id=team_id, ) - create_started = time.monotonic() - deadline = create_started + timeout + create_started = evidence_clock() + deadline = time.monotonic() + timeout recovered_after_timeout = False try: accepted = _submit_with_retry( @@ -358,7 +365,9 @@ def run_smoke( runtime_workload_id = create_result.get("runtime_workload_id") if not isinstance(runtime_workload_id, str) or not runtime_workload_id.strip(): raise RuntimeError("Runtime create operation returned an invalid runtime_workload_id") - create_elapsed_seconds = round(time.monotonic() - create_started, 3) + endpoints = create_result.get("endpoints") + endpoints_valid = isinstance(endpoints, list) and bool(endpoints) + create_elapsed_seconds = round(evidence_clock() - create_started, 3) delete_request = { "request_id": f"ci-smoke-delete-{create_request['instance_id']}", @@ -368,7 +377,7 @@ def run_smoke( "runtime_workload_id": runtime_workload_id, "delete_reason": "ADMIN_FORCED", } - delete_started = time.monotonic() + delete_started = evidence_clock() cleanup_deadline = time.monotonic() + cleanup_timeout deleted = _submit_with_retry( client, @@ -384,7 +393,9 @@ def run_smoke( poll_interval=poll_interval, deadline=cleanup_deadline, ) - delete_elapsed_seconds = round(time.monotonic() - delete_started, 3) + delete_elapsed_seconds = round(evidence_clock() - delete_started, 3) + if not endpoints_valid: + raise RuntimeError("Runtime create operation did not return public endpoints") return { "challenge_slug": artifact.get("challenge_slug"), "revision": artifact.get("revision"), @@ -396,7 +407,7 @@ def run_smoke( for container in create_request["workload"]["containers"] ], "service_url": create_result.get("service_url"), - "endpoints": create_result.get("endpoints", []), + "endpoints": endpoints, "create_status": created["status"], "create_elapsed_seconds": create_elapsed_seconds, "delete_status": delete_snapshot["status"], diff --git a/tests/test_runtime_api_smoke_runner.py b/tests/test_runtime_api_smoke_runner.py index 5b723aa..7d9c726 100644 --- a/tests/test_runtime_api_smoke_runner.py +++ b/tests/test_runtime_api_smoke_runner.py @@ -47,13 +47,21 @@ class RuntimeHandler(BaseHTTPRequestHandler): create_result = { "runtime_workload_id": "aws-k3s-001/ctf-test/challenge", "service_url": "http://203.0.113.10:31042", - "endpoints": [], + "endpoints": [ + { + "container_name": "service", + "port": 8080, + "protocol": "HTTP", + "service_url": "http://203.0.113.10:31042", + } + ], } drop_create_response_once = False drop_delete_response_once = False omit_create_operation_id_once = False omit_delete_operation_id_once = False omit_create_result_once = False + echo_auth_error = False def log_message(self, _format, *_args): return @@ -74,6 +82,9 @@ def _respond(self, status, body): def do_POST(self): type(self).requests.append(("POST", self.path, self.headers, self._json_body())) + if type(self).echo_auth_error: + self._respond(400, {"error": self.headers.get("Authorization")}) + return if type(self).drop_create_response_once: type(self).drop_create_response_once = False self.connection.shutdown(socket.SHUT_RDWR) @@ -137,13 +148,21 @@ def start_server(self): RuntimeHandler.create_result = { "runtime_workload_id": "aws-k3s-001/ctf-test/challenge", "service_url": "http://203.0.113.10:31042", - "endpoints": [], + "endpoints": [ + { + "container_name": "service", + "port": 8080, + "protocol": "HTTP", + "service_url": "http://203.0.113.10:31042", + } + ], } RuntimeHandler.drop_create_response_once = False RuntimeHandler.drop_delete_response_once = False RuntimeHandler.omit_create_operation_id_once = False RuntimeHandler.omit_delete_operation_id_once = False RuntimeHandler.omit_create_result_once = False + RuntimeHandler.echo_auth_error = False self.server = ThreadingHTTPServer(("127.0.0.1", 0), RuntimeHandler) self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) self.thread.start() @@ -290,6 +309,7 @@ def test_reports_digest_images_and_runtime_endpoints(self): def test_reports_create_and_delete_elapsed_seconds(self): self.start_server() + evidence_times = iter([10.0, 12.5, 20.0, 21.25]) with tempfile.TemporaryDirectory() as directory: token_file = Path(directory) / "service-token" token_file.write_text("A" * 43, encoding="utf-8") @@ -302,12 +322,58 @@ def test_reports_create_and_delete_elapsed_seconds(self): team_id=TEAM_ID, poll_interval=0, timeout=2, + evidence_clock=lambda: next(evidence_times), ) - self.assertIsInstance(result["create_elapsed_seconds"], float) - self.assertGreaterEqual(result["create_elapsed_seconds"], 0.0) - self.assertIsInstance(result["delete_elapsed_seconds"], float) - self.assertGreaterEqual(result["delete_elapsed_seconds"], 0.0) + self.assertEqual(result["create_elapsed_seconds"], 2.5) + self.assertEqual(result["delete_elapsed_seconds"], 1.25) + + def test_rejects_success_without_endpoints_after_cleanup(self): + self.start_server() + RuntimeHandler.create_result = { + "runtime_workload_id": "aws-k3s-001/ctf-test/challenge", + "service_url": None, + "endpoints": [], + } + with tempfile.TemporaryDirectory() as directory: + token_file = Path(directory) / "service-token" + token_file.write_text("A" * 43, encoding="utf-8") + with self.assertRaisesRegex(RuntimeError, "endpoints"): + run_smoke( + ARTIFACT, + api_url=f"http://127.0.0.1:{self.server.server_port}", + token_file=token_file, + target_id="aws-k3s-001", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + poll_interval=0, + timeout=2, + ) + + methods = [(method, path) for method, path, _headers, _body in RuntimeHandler.requests] + self.assertIn(("DELETE", f"/internal/v1/instances/{INSTANCE_ID}"), methods) + + def test_redacts_service_token_from_runtime_error_details(self): + self.start_server() + RuntimeHandler.echo_auth_error = True + service_token = "A" * 43 + with tempfile.TemporaryDirectory() as directory: + token_file = Path(directory) / "service-token" + token_file.write_text(service_token, encoding="utf-8") + with self.assertRaises(RuntimeError) as raised: + run_smoke( + ARTIFACT, + api_url=f"http://127.0.0.1:{self.server.server_port}", + token_file=token_file, + target_id="aws-k3s-001", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + poll_interval=0, + timeout=2, + ) + + self.assertNotIn(service_token, str(raised.exception)) + self.assertIn("[REDACTED]", str(raised.exception)) def test_maps_pwn_category_to_pwn_isolation_profile(self): artifact = dict(ARTIFACT, category="pwn") From c2a139fb3363c08c6c871f9413fa231a9e523ce2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Sat, 29 Aug 2026 02:49:05 +0900 Subject: [PATCH 03/13] Run supply chain checks on pull requests --- .github/workflows/pipeline-self-test.yml | 9 +++++++++ tests/test_workflow_contracts.py | 1 + 2 files changed, 10 insertions(+) diff --git a/.github/workflows/pipeline-self-test.yml b/.github/workflows/pipeline-self-test.yml index 83a286b..36e25b1 100644 --- a/.github/workflows/pipeline-self-test.yml +++ b/.github/workflows/pipeline-self-test.yml @@ -10,6 +10,15 @@ on: - "ci/**" - "scripts/**" - "tests/**" + pull_request: + branches: [main] + paths: + - ".github/workflows/challenge-branch-validation.yml" + - ".github/workflows/challenge-supply-chain.yml" + - ".github/workflows/pipeline-self-test.yml" + - "ci/**" + - "scripts/**" + - "tests/**" workflow_dispatch: permissions: diff --git a/tests/test_workflow_contracts.py b/tests/test_workflow_contracts.py index c2f8147..ab64f41 100644 --- a/tests/test_workflow_contracts.py +++ b/tests/test_workflow_contracts.py @@ -321,6 +321,7 @@ def test_pipeline_self_test_calls_reusable_supply_chain(self): text = path.read_text(encoding="utf-8") self.assertIn("push", workflow["on"]) + self.assertIn("pull_request", workflow["on"]) self.assertIn("workflow_dispatch", workflow["on"]) self.assertEqual(workflow["permissions"], {"contents": "read"}) self.assertIn( From e01fc18abba6779ab767b659387ac578afe0d81b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Tue, 1 Sep 2026 23:00:08 +0900 Subject: [PATCH 04/13] =?UTF-8?q?=EC=B5=9C=EC=8B=A0=20publish=20bundle?= =?UTF-8?q?=EB=A1=9C=20K3s=20smoke=20=EA=B2=80=EC=A6=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/aws-k3s-cd-smoke.md | 6 ++++++ scripts/runtime_api_smoke_runner.py | 23 +++++++++++++++++++- tests/test_runtime_api_smoke_runner.py | 29 +++++++++++++++++++++++++- 3 files changed, 56 insertions(+), 2 deletions(-) diff --git a/docs/aws-k3s-cd-smoke.md b/docs/aws-k3s-cd-smoke.md index d783cc1..d41ed76 100644 --- a/docs/aws-k3s-cd-smoke.md +++ b/docs/aws-k3s-cd-smoke.md @@ -83,6 +83,7 @@ Smoke instance와 team UUID는 GitHub run 정보로 결정적으로 생성됩니 ```json { + "registry_revision": 12, "images": [ { "name": "web", @@ -104,6 +105,11 @@ Smoke instance와 team UUID는 GitHub run 정보로 결정적으로 생성됩니 } ``` +Smoke runner는 `artifact-v2.json`의 `revision`과 `registry_revision`이 같은지, +`isolation_profile`이 문제 category와 일치하는지, `scan_result`가 `PASS`인지 먼저 +확인합니다. `containers[]`의 digest 이미지와 선택형 `internal_connections[]`는 +같은 publish bundle에서 읽어 Runtime 요청에 전달합니다. + `create_elapsed_seconds`는 생성 요청을 처음 제출한 시점부터 생성 Operation이 `SUCCEEDED`가 될 때까지의 시간입니다. 이미지 pull뿐 아니라 Pod와 Service 준비 시간도 포함하므로 순수 네트워크 처리량으로 해석하지 않습니다. diff --git a/scripts/runtime_api_smoke_runner.py b/scripts/runtime_api_smoke_runner.py index 1d63bbd..7d059de 100644 --- a/scripts/runtime_api_smoke_runner.py +++ b/scripts/runtime_api_smoke_runner.py @@ -48,6 +48,22 @@ def _isolation_profile(category: Any) -> str: return "PWN" if category.lower() == "pwn" else "WEB" +def _validate_bundle_contract(artifact: dict[str, Any]) -> tuple[int, int, str]: + revision = _positive_int(artifact.get("revision"), "artifact revision") + registry_revision = _positive_int( + artifact.get("registry_revision"), + "artifact registry_revision", + ) + if registry_revision != revision: + raise ValueError("artifact registry_revision must equal revision") + expected_profile = _isolation_profile(artifact.get("category")) + if artifact.get("isolation_profile") != expected_profile: + raise ValueError("artifact isolation_profile must match the challenge category") + if artifact.get("scan_result") != "PASS": + raise ValueError("artifact scan_result must be PASS") + return revision, registry_revision, expected_profile + + def build_create_request( artifact: dict[str, Any], *, @@ -56,6 +72,9 @@ def build_create_request( team_id: str, ) -> dict[str, Any]: """Translate a publish artifact into the Runtime team's create contract.""" + _revision, _registry_revision, isolation_profile = _validate_bundle_contract( + artifact + ) if artifact.get("runtime_type") != "KUBERNETES": raise ValueError("Runtime smoke deployment requires runtime_type KUBERNETES") if artifact.get("architecture") != "AMD64": @@ -175,7 +194,7 @@ def build_create_request( "request_id": f"ci-smoke-create-{normalized_instance_id}", "instance_id": normalized_instance_id, "team_id": normalized_team_id, - "isolation_profile": _isolation_profile(artifact.get("category")), + "isolation_profile": isolation_profile, "target": {"runtime_type": "KUBERNETES", "target_id": target_id.strip()}, "workload": {**runtime_workload, "resource_limits": resource_limits}, } @@ -308,6 +327,7 @@ def run_smoke( ) -> dict[str, Any]: if evidence_clock is None: evidence_clock = time.monotonic + _revision, registry_revision, _profile = _validate_bundle_contract(artifact) token = token_file.read_text(encoding="utf-8").strip() client = RuntimeClient(api_url, token, timeout=min(max(timeout, cleanup_timeout, 1), 30)) create_request = build_create_request( @@ -399,6 +419,7 @@ def run_smoke( return { "challenge_slug": artifact.get("challenge_slug"), "revision": artifact.get("revision"), + "registry_revision": registry_revision, "target_id": target_id, "instance_id": create_request["instance_id"], "runtime_workload_id": runtime_workload_id, diff --git a/tests/test_runtime_api_smoke_runner.py b/tests/test_runtime_api_smoke_runner.py index 7d9c726..386250c 100644 --- a/tests/test_runtime_api_smoke_runner.py +++ b/tests/test_runtime_api_smoke_runner.py @@ -14,11 +14,15 @@ INSTANCE_ID = "018f3f1e-21b8-7a91-a30b-63b3400fd001" TEAM_ID = "00000000-0000-4000-8000-000000000018" ARTIFACT = { + "schema_version": "2.0", "challenge_slug": "koth-template", "revision": 11, + "registry_revision": 11, "category": "koth", "runtime_type": "KUBERNETES", "architecture": "AMD64", + "isolation_profile": "WEB", + "scan_result": "PASS", "workload": { "containers": [ { @@ -305,8 +309,31 @@ def test_reports_digest_images_and_runtime_endpoints(self): ], ) self.assertEqual(result["endpoints"], RuntimeHandler.create_result["endpoints"]) + self.assertEqual(result["registry_revision"], 11) self.assertNotIn("A" * 43, json.dumps(result)) + def test_rejects_registry_revision_mismatch_before_runtime_request(self): + artifact = dict(ARTIFACT, registry_revision=12) + + with self.assertRaisesRegex(ValueError, "registry_revision"): + build_create_request( + artifact, + target_id="aws-k3s-001", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + ) + + def test_rejects_isolation_profile_mismatch_before_runtime_request(self): + artifact = dict(ARTIFACT, isolation_profile="PWN") + + with self.assertRaisesRegex(ValueError, "isolation_profile"): + build_create_request( + artifact, + target_id="aws-k3s-001", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + ) + def test_reports_create_and_delete_elapsed_seconds(self): self.start_server() evidence_times = iter([10.0, 12.5, 20.0, 21.25]) @@ -376,7 +403,7 @@ def test_redacts_service_token_from_runtime_error_details(self): self.assertIn("[REDACTED]", str(raised.exception)) def test_maps_pwn_category_to_pwn_isolation_profile(self): - artifact = dict(ARTIFACT, category="pwn") + artifact = dict(ARTIFACT, category="pwn", isolation_profile="PWN") request = build_create_request( artifact, From 5d93633bda04a03d8090a9d26bae45f7404a8b00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Mon, 7 Sep 2026 01:44:26 +0900 Subject: [PATCH 05/13] =?UTF-8?q?Runtime=20=ED=8F=AC=ED=8A=B8=20=EA=B3=B5?= =?UTF-8?q?=EA=B0=9C=20=EA=B3=84=EC=95=BD=20=EC=97=B0=EB=8F=99=20=EC=84=A4?= =?UTF-8?q?=EA=B3=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...untime-exposed-ports-integration-design.md | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 docs/superpowers/specs/2026-09-07-runtime-exposed-ports-integration-design.md diff --git a/docs/superpowers/specs/2026-09-07-runtime-exposed-ports-integration-design.md b/docs/superpowers/specs/2026-09-07-runtime-exposed-ports-integration-design.md new file mode 100644 index 0000000..1fd79f8 --- /dev/null +++ b/docs/superpowers/specs/2026-09-07-runtime-exposed-ports-integration-design.md @@ -0,0 +1,92 @@ +# Runtime 포트 공개 계약 연동 설계 + +## 목적 + +DevSecOps가 발행한 `artifact-v2.json`을 Runtime의 최신 인스턴스 생성 API 계약으로 +손실 없이 변환한다. 같은 컨테이너에서 public 포트와 private 포트가 섞여 있어도 +private 포트를 외부에 노출하지 않고, Runtime 응답의 공개 endpoint가 요청과 정확히 +일치하는지 검증한다. + +## 역할 경계 + +- 출제자 입력인 `info.yaml`의 기존 `ports`와 `expose` 형식은 이 변경에서 수정하지 않는다. +- DevSecOps publish bundle은 Backend PR #62가 소비하는 + `ports: [{"port": 8080, "public": true}]` 형식을 유지한다. +- DevSecOps Runtime smoke runner만 bundle의 포트 정보를 Runtime API의 + `ports: [8080, 9000]`, `exposed_ports: [8080]` 형식으로 변환한다. +- Runtime 요청에는 `expose`를 포함하지 않는다. +- Backend의 DB 모델, Scheduler의 DTO, Runtime 구현은 DevSecOps에서 수정하지 않는다. + +## Runtime 요청 변환 + +각 `workload.containers[]`에 다음 규칙을 적용한다. + +1. `ports`에는 bundle에 선언된 전체 포트를 순서대로 넣는다. +2. `exposed_ports`에는 `public: true`인 포트만 넣는다. +3. 모두 private인 컨테이너도 `exposed_ports: []`를 명시한다. +4. `name`, digest 고정 `image`, `ports`, `exposed_ports`, `run_as_user`를 보낸다. +5. workload 전체에 공개 포트가 하나도 없으면 요청 전에 실패한다. +6. `internal_connections`와 `resource_limits`는 기존 검증을 거쳐 보존한다. + +예시: + +```json +{ + "name": "web", + "image": "ghcr.io/msg-ctf/challenges/example/web@sha256:...", + "ports": [8080, 9000], + "exposed_ports": [8080], + "run_as_user": 10001 +} +``` + +## 배포 대상과 인증 + +- 실제 smoke의 `target.target_id`는 workflow 입력을 통해 `aws-k3s-lab`으로 전달한다. +- `target_id`는 release 자체의 속성이 아니므로 `artifact-v2.json`에 저장하지 않는다. +- Runtime API service token은 GitHub Actions secret으로만 전달하며 파일, 로그, bundle에 + 남기지 않는다. +- 현재 token이 준비되지 않았으므로 코드·단위 테스트까지만 수행하고 실제 K3s 결과는 + 미검증으로 기록한다. + +## 응답 검증과 정리 + +- bundle의 모든 `public: true` 포트에서 `(container_name, port)` 예상 집합을 만든다. +- Runtime의 `endpoints[]`는 각 항목의 `container_name`, `port`, `protocol`, + `service_url`을 검증한다. +- 예상 endpoint와 실제 endpoint가 누락, 추가, 중복 없이 정확히 일치해야 성공한다. +- 불일치하거나 생성 결과가 불완전하면 기존 동작대로 workload 삭제를 먼저 요청하고 + 삭제 완료를 확인한 뒤 실패한다. + +## Backend 연동 + +Backend PR #62는 bundle의 `internal_connections`를 검증하고 ChallengeRelease DB와 +등록·조회 응답, Poller 수집 과정에 보존한다. DevSecOps는 실제 +`web -> db:5432/TCP` 연결을 포함한 publish bundle을 발행한다. + +실제 통합 검증은 다음을 확인한다. + +1. 최초 bundle 등록과 DB 왕복 후 `internal_connections` 보존 +2. 같은 `registry_revision` 재수집 시 중복 등록 방지 +3. 새 revision 등록 후 기존 active release 유지 +4. Scheduler 계약 확정 후 Runtime 요청까지 `internal_connections`와 + `exposed_ports` 보존 + +Backend PR #62가 아직 Draft이고 연결이 있는 release 활성화를 차단하므로, 4번과 실제 +Runtime 배포는 Backend·Scheduler 계약이 준비된 뒤 수행한다. + +## 테스트 + +- 혼합 포트를 `exposed_ports`로 변환하고 `expose`를 보내지 않는 단위 테스트 +- 전체 public과 전체 private 컨테이너 변환 테스트 +- 공개 포트가 없는 workload 거절 테스트 +- `web -> db:5432/TCP` 보존 테스트 +- Runtime endpoint 정확 일치와 누락·추가·중복 거절 테스트 +- 전체 Python 단위 테스트, 문법 검사, `git diff --check`, Gitleaks + +## 완료 기준 + +- PR #6의 runner와 테스트가 Runtime PR #39 계약을 따른다. +- PR #7의 publish bundle은 Backend PR #62 입력 계약을 유지한다. +- 실제 배포 전까지 문서와 PR에서 K3s smoke를 완료로 표시하지 않는다. +- Runtime token을 받은 뒤 `aws-k3s-lab`에서 생성·endpoint 확인·삭제 증거를 남긴다. From 801b872731dd35e1fb0b764aa696640e71e994e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Mon, 7 Sep 2026 01:48:18 +0900 Subject: [PATCH 06/13] =?UTF-8?q?Runtime=20=ED=8F=AC=ED=8A=B8=20=EA=B3=84?= =?UTF-8?q?=EC=95=BD=20=EA=B5=AC=ED=98=84=20=EA=B3=84=ED=9A=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...09-07-runtime-exposed-ports-integration.md | 168 ++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md diff --git a/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md b/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md new file mode 100644 index 0000000..036345c --- /dev/null +++ b/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md @@ -0,0 +1,168 @@ +# Runtime Exposed Ports Integration Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** `artifact-v2.json`의 포트별 공개 정보를 Runtime PR #39의 `ports`와 `exposed_ports` 요청 계약으로 손실 없이 변환하고 검증한다. + +**Architecture:** Backend가 소비하는 publish bundle 형식은 변경하지 않는다. `runtime_api_smoke_runner.py`가 bundle 경계에서 전체 포트와 공개 포트를 분리해 Runtime 요청을 만들고, 기존 endpoint 집합 검증과 cleanup을 유지한다. 실제 K3s 호출은 service token을 받은 뒤 별도 실행한다. + +**Tech Stack:** Python 3 표준 라이브러리, `unittest`, GitHub Actions, Secure Provisioner HTTP API. + +**Spec:** `docs/superpowers/specs/2026-09-07-runtime-exposed-ports-integration-design.md` + +## Global Constraints + +- Runtime 요청의 한 컨테이너에는 `expose`와 `exposed_ports`를 함께 보내지 않는다. +- Runtime 요청의 `ports`는 전체 포트이며 `exposed_ports`는 public 포트 부분집합이다. +- `artifact-v2.json`의 `ports[].public` 형식은 유지한다. +- `target_id`는 bundle에 넣지 않고 workflow 입력으로 전달한다. +- Runtime과 Backend 저장소 코드는 수정하지 않는다. +- 실제 service token이 없으므로 K3s 실행을 완료로 표시하지 않는다. + +--- + +### Task 1: Runtime 요청 포트 변환 + +**Files:** +- Modify: `tests/test_runtime_api_smoke_runner.py` +- Modify: `scripts/runtime_api_smoke_runner.py` + +**Interfaces:** +- Consumes: `build_create_request(artifact, target_id, instance_id, team_id)`와 bundle의 `workload.containers[].ports[]`. +- Produces: Runtime 컨테이너 `{name, image, ports, exposed_ports, run_as_user}`. + +- [ ] **Step 1: 혼합 포트와 private 컨테이너의 실패 테스트 작성** + + 기존 request 예상값에서 `expose`를 제거하고 `exposed_ports`를 요구한다. 별도 테스트는 + 같은 컨테이너의 `8080 public`, `9000 private`가 + `ports: [8080, 9000]`, `exposed_ports: [8080]`로 변환되는지 확인한다. private DB는 + `exposed_ports: []`를 확인한다. + +- [ ] **Step 2: 테스트 실패 확인** + + Run: `python3 -m unittest tests.test_runtime_api_smoke_runner.RuntimeApiSmokeRunnerTests.test_builds_runtime_team_multi_container_contract tests.test_runtime_api_smoke_runner.RuntimeApiSmokeRunnerTests.test_builds_mixed_public_private_ports_with_exposed_ports -v` + + Expected: 기존 구현이 `expose`를 반환하고 혼합 포트를 거절해 FAIL. + +- [ ] **Step 3: 최소 변환 구현** + + `public_values`와 혼합 포트 거절을 제거한다. 각 port object를 검증하면서 전체 `ports`와 + `public: true`인 `exposed_ports`를 따로 누적하고 Runtime container에 두 배열을 넣는다. + workload 전체 공개 여부는 `bool(exposed_ports)`로 계산한다. + +- [ ] **Step 4: 대상 테스트 통과 확인** + + Run: `python3 -m unittest tests.test_runtime_api_smoke_runner.RuntimeApiSmokeRunnerTests.test_builds_runtime_team_multi_container_contract tests.test_runtime_api_smoke_runner.RuntimeApiSmokeRunnerTests.test_builds_mixed_public_private_ports_with_exposed_ports -v` + + Expected: PASS. + +- [ ] **Step 5: 포트 변환 변경 커밋** + + ```bash + git add scripts/runtime_api_smoke_runner.py tests/test_runtime_api_smoke_runner.py + git commit -m "Runtime exposed_ports 계약 반영" + ``` + +### Task 2: 연결 정보와 endpoint 회귀 검증 + +**Files:** +- Modify: `tests/test_runtime_api_smoke_runner.py` + +**Interfaces:** +- Consumes: Task 1의 Runtime request와 기존 `run_smoke` endpoint 검증. +- Produces: `web -> db:5432/TCP`가 유지되고 공개 endpoint만 기대하는 회귀 테스트. + +- [ ] **Step 1: web과 db의 실제 계약 테스트 작성** + + web은 `8080 public`, `9000 private`, db는 `5432 private`로 구성하고 + `web -> db:5432/TCP`를 넣는다. 생성 요청에서 `expose`가 어느 컨테이너에도 없고, + web `exposed_ports == [8080]`, db `exposed_ports == []`, 연결 배열이 원형 보존되는지 + 확인한다. + +- [ ] **Step 2: 기존 endpoint 누락·추가·중복 검증 테스트 실행** + + Run: `python3 -m unittest tests.test_runtime_api_smoke_runner -v` + + Expected: 모든 Runtime smoke runner 테스트 PASS. endpoint 불일치 테스트는 내부적으로 + 오류와 cleanup을 기대하므로 테스트 자체는 PASS. + +- [ ] **Step 3: 회귀 테스트 커밋** + + ```bash + git add tests/test_runtime_api_smoke_runner.py + git commit -m "Runtime 멀티 컨테이너 연결 회귀 검증" + ``` + +### Task 3: 운영 문서와 target 계약 정리 + +**Files:** +- Modify: `docs/aws-k3s-cd-smoke.md` +- Modify: PR #6 description after push. + +**Interfaces:** +- Consumes: Runtime PR #39의 `exposed_ports` 계약과 운영 target `aws-k3s-lab`. +- Produces: 토큰 준비 전후를 구분한 실행 안내. + +- [ ] **Step 1: 문서 수정** + + caller 예시의 `runtime_target_id`를 `aws-k3s-lab`으로 바꾼다. 혼합 포트 거절 제약을 + 제거하고 `ports[].public`이 Runtime `exposed_ports`로 변환되며 `expose`를 보내지 + 않는다고 설명한다. service token 미수령으로 실제 K3s smoke가 미실행임을 명시한다. + +- [ ] **Step 2: 문서 계약 검사** + + Run: `rg -n "aws-k3s-lab|exposed_ports|실제 K3s" docs/aws-k3s-cd-smoke.md` + + Expected: 세 계약이 문서에 존재하며 기존 “혼합 포트 거절” 설명은 없음. + +- [ ] **Step 3: 문서 커밋** + + ```bash + git add docs/aws-k3s-cd-smoke.md + git commit -m "Runtime 포트별 공개 smoke 문서화" + ``` + +### Task 4: 전체 검증과 PR #6 갱신 + +**Files:** +- Verify: `scripts/*.py` +- Verify: `tests/` +- Update: `MSG-CTF/msgctf-devsecops` PR #6 metadata. + +**Interfaces:** +- Consumes: Tasks 1-3의 코드·테스트·문서. +- Produces: 검증된 PR #6 커밋과 정확한 미완료 항목. + +- [ ] **Step 1: 전체 단위 테스트 실행** + + Run: `python3 -W error::ResourceWarning -m unittest discover -s tests -v` + + Expected: PASS. + +- [ ] **Step 2: 정적 검증 실행** + + Run: `python3 -m py_compile scripts/*.py` + + Run: `git diff --check` + + Run: `gitleaks detect --source . --no-banner --redact --exit-code 1` + + Expected: 모두 exit code 0. + +- [ ] **Step 3: 브랜치 push** + + Run: `git push msg-ctf runtime-smoke-evidence` + + Expected: PR #6 head가 새 커밋으로 갱신됨. + +- [ ] **Step 4: PR 설명과 댓글 갱신** + + PR #6에 Runtime PR #39 계약 반영, `target_id=aws-k3s-lab`, Backend PR #62 호환, + service token 미수령 때문에 실제 K3s smoke는 남아 있다는 사실을 기록한다. + +- [ ] **Step 5: GitHub Actions 결과 확인** + + Run: `gh pr checks 6 --repo MSG-CTF/msgctf-devsecops --watch` + + Expected: 실행된 check PASS. 실제 K3s smoke는 token과 배포 환경이 없으면 실행하지 + 않았다고 구분해 기록한다. From fb5cc057d58aeee5f523599115f6fa172d694bfc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Mon, 7 Sep 2026 02:12:54 +0900 Subject: [PATCH 07/13] =?UTF-8?q?Runtime=20exposed=5Fports=20=EA=B3=84?= =?UTF-8?q?=EC=95=BD=20=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...09-07-runtime-exposed-ports-integration.md | 25 ++++++--- scripts/runtime_api_smoke_runner.py | 14 ++--- tests/test_runtime_api_smoke_runner.py | 54 ++++++++++++++++++- 3 files changed, 76 insertions(+), 17 deletions(-) diff --git a/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md b/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md index 036345c..9291392 100644 --- a/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md +++ b/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md @@ -31,32 +31,32 @@ - Consumes: `build_create_request(artifact, target_id, instance_id, team_id)`와 bundle의 `workload.containers[].ports[]`. - Produces: Runtime 컨테이너 `{name, image, ports, exposed_ports, run_as_user}`. -- [ ] **Step 1: 혼합 포트와 private 컨테이너의 실패 테스트 작성** +- [x] **Step 1: 혼합 포트와 private 컨테이너의 실패 테스트 작성** 기존 request 예상값에서 `expose`를 제거하고 `exposed_ports`를 요구한다. 별도 테스트는 같은 컨테이너의 `8080 public`, `9000 private`가 `ports: [8080, 9000]`, `exposed_ports: [8080]`로 변환되는지 확인한다. private DB는 `exposed_ports: []`를 확인한다. -- [ ] **Step 2: 테스트 실패 확인** +- [x] **Step 2: 테스트 실패 확인** Run: `python3 -m unittest tests.test_runtime_api_smoke_runner.RuntimeApiSmokeRunnerTests.test_builds_runtime_team_multi_container_contract tests.test_runtime_api_smoke_runner.RuntimeApiSmokeRunnerTests.test_builds_mixed_public_private_ports_with_exposed_ports -v` Expected: 기존 구현이 `expose`를 반환하고 혼합 포트를 거절해 FAIL. -- [ ] **Step 3: 최소 변환 구현** +- [x] **Step 3: 최소 변환 구현** `public_values`와 혼합 포트 거절을 제거한다. 각 port object를 검증하면서 전체 `ports`와 `public: true`인 `exposed_ports`를 따로 누적하고 Runtime container에 두 배열을 넣는다. workload 전체 공개 여부는 `bool(exposed_ports)`로 계산한다. -- [ ] **Step 4: 대상 테스트 통과 확인** +- [x] **Step 4: 대상 테스트 통과 확인** Run: `python3 -m unittest tests.test_runtime_api_smoke_runner.RuntimeApiSmokeRunnerTests.test_builds_runtime_team_multi_container_contract tests.test_runtime_api_smoke_runner.RuntimeApiSmokeRunnerTests.test_builds_mixed_public_private_ports_with_exposed_ports -v` Expected: PASS. -- [ ] **Step 5: 포트 변환 변경 커밋** +- [x] **Step 5: 포트 변환 변경 커밋** ```bash git add scripts/runtime_api_smoke_runner.py tests/test_runtime_api_smoke_runner.py @@ -79,14 +79,25 @@ web `exposed_ports == [8080]`, db `exposed_ports == []`, 연결 배열이 원형 보존되는지 확인한다. -- [ ] **Step 2: 기존 endpoint 누락·추가·중복 검증 테스트 실행** +- [ ] **Step 2: endpoint 누락·추가·중복 실패 테스트 작성** + + 현재 runner가 endpoint 배열이 비어 있지 않은지만 검사하는 반례를 먼저 재현한다. + artifact의 공개 `(container_name, port)` 집합과 Runtime 응답의 집합이 다르거나, + endpoint 항목이 중복되면 cleanup 후 실패하는 테스트를 추가한다. + +- [ ] **Step 3: endpoint 정확 일치 검증 구현** + + request의 `exposed_ports`에서 예상 집합을 만들고 Runtime 응답 각 항목의 필수 필드와 + 중복을 검증한다. 실제 집합이 예상 집합과 다르면 cleanup 후 오류를 반환한다. + +- [ ] **Step 4: Runtime smoke runner 테스트 실행** Run: `python3 -m unittest tests.test_runtime_api_smoke_runner -v` Expected: 모든 Runtime smoke runner 테스트 PASS. endpoint 불일치 테스트는 내부적으로 오류와 cleanup을 기대하므로 테스트 자체는 PASS. -- [ ] **Step 3: 회귀 테스트 커밋** +- [ ] **Step 5: 회귀 테스트 커밋** ```bash git add tests/test_runtime_api_smoke_runner.py diff --git a/scripts/runtime_api_smoke_runner.py b/scripts/runtime_api_smoke_runner.py index 7d059de..8d83a64 100644 --- a/scripts/runtime_api_smoke_runner.py +++ b/scripts/runtime_api_smoke_runner.py @@ -105,7 +105,7 @@ def build_create_request( if not isinstance(artifact_ports, list) or not artifact_ports: raise ValueError("container ports must be a non-empty list") ports = [] - public_values = set() + exposed_ports = [] for port_spec in artifact_ports: if not isinstance(port_spec, dict): raise ValueError("container port must be an object") @@ -116,20 +116,16 @@ def build_create_request( if not isinstance(public, bool): raise ValueError("container port public must be a boolean") ports.append(port) - public_values.add(public) + if public: + exposed_ports.append(port) - if len(public_values) != 1: - raise ValueError( - "Runtime contract exposes ports by container, so one container cannot mix public and private ports" - ) - expose = public_values == {True} - exposed = exposed or expose + exposed = exposed or bool(exposed_ports) runtime_containers.append( { "name": name, "image": image, "ports": ports, - "expose": expose, + "exposed_ports": exposed_ports, "run_as_user": _positive_int(container.get("run_as_user", 10001), "run_as_user"), } ) diff --git a/tests/test_runtime_api_smoke_runner.py b/tests/test_runtime_api_smoke_runner.py index 386250c..dc2ed2a 100644 --- a/tests/test_runtime_api_smoke_runner.py +++ b/tests/test_runtime_api_smoke_runner.py @@ -199,7 +199,7 @@ def test_builds_runtime_team_multi_container_contract(self): "name": "service", "image": ARTIFACT["workload"]["containers"][0]["image"], "ports": [8080, 9090], - "expose": True, + "exposed_ports": [8080, 9090], "run_as_user": 10001, } ], @@ -207,6 +207,58 @@ def test_builds_runtime_team_multi_container_contract(self): }, ) + def test_builds_mixed_public_private_ports_with_exposed_ports(self): + artifact = copy.deepcopy(ARTIFACT) + artifact["workload"]["containers"] = [ + { + "name": "web", + "image": f"ghcr.io/msg-ctf/challenges/web-notebook/web@{DIGEST}", + "ports": [ + {"port": 8080, "public": True}, + {"port": 9000, "public": False}, + ], + }, + { + "name": "db", + "image": f"ghcr.io/msg-ctf/challenges/web-notebook/db@{DIGEST}", + "ports": [{"port": 5432, "public": False}], + }, + ] + + request = build_create_request( + artifact, + target_id="aws-k3s-lab", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + ) + + self.assertEqual(request["target"]["target_id"], "aws-k3s-lab") + self.assertEqual( + request["workload"]["containers"], + [ + { + "name": "web", + "image": artifact["workload"]["containers"][0]["image"], + "ports": [8080, 9000], + "exposed_ports": [8080], + "run_as_user": 10001, + }, + { + "name": "db", + "image": artifact["workload"]["containers"][1]["image"], + "ports": [5432], + "exposed_ports": [], + "run_as_user": 10001, + }, + ], + ) + self.assertTrue( + all( + "expose" not in container + for container in request["workload"]["containers"] + ) + ) + def test_preserves_internal_connections_in_runtime_request(self): artifact = copy.deepcopy(ARTIFACT) artifact["workload"]["containers"].append( From 1964a67867d670e44c544abcdc42b438673de16b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Mon, 7 Sep 2026 02:23:44 +0900 Subject: [PATCH 08/13] =?UTF-8?q?Runtime=20endpoint=20=EA=B3=84=EC=95=BD?= =?UTF-8?q?=20=EA=B2=80=EC=A6=9D=20=EA=B0=95=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...09-07-runtime-exposed-ports-integration.md | 10 +- scripts/runtime_api_smoke_runner.py | 48 ++++++- tests/test_runtime_api_smoke_runner.py | 135 +++++++++++++++++- 3 files changed, 182 insertions(+), 11 deletions(-) diff --git a/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md b/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md index 9291392..91c048e 100644 --- a/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md +++ b/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md @@ -72,32 +72,32 @@ - Consumes: Task 1의 Runtime request와 기존 `run_smoke` endpoint 검증. - Produces: `web -> db:5432/TCP`가 유지되고 공개 endpoint만 기대하는 회귀 테스트. -- [ ] **Step 1: web과 db의 실제 계약 테스트 작성** +- [x] **Step 1: web과 db의 실제 계약 테스트 작성** web은 `8080 public`, `9000 private`, db는 `5432 private`로 구성하고 `web -> db:5432/TCP`를 넣는다. 생성 요청에서 `expose`가 어느 컨테이너에도 없고, web `exposed_ports == [8080]`, db `exposed_ports == []`, 연결 배열이 원형 보존되는지 확인한다. -- [ ] **Step 2: endpoint 누락·추가·중복 실패 테스트 작성** +- [x] **Step 2: endpoint 누락·추가·중복 실패 테스트 작성** 현재 runner가 endpoint 배열이 비어 있지 않은지만 검사하는 반례를 먼저 재현한다. artifact의 공개 `(container_name, port)` 집합과 Runtime 응답의 집합이 다르거나, endpoint 항목이 중복되면 cleanup 후 실패하는 테스트를 추가한다. -- [ ] **Step 3: endpoint 정확 일치 검증 구현** +- [x] **Step 3: endpoint 정확 일치 검증 구현** request의 `exposed_ports`에서 예상 집합을 만들고 Runtime 응답 각 항목의 필수 필드와 중복을 검증한다. 실제 집합이 예상 집합과 다르면 cleanup 후 오류를 반환한다. -- [ ] **Step 4: Runtime smoke runner 테스트 실행** +- [x] **Step 4: Runtime smoke runner 테스트 실행** Run: `python3 -m unittest tests.test_runtime_api_smoke_runner -v` Expected: 모든 Runtime smoke runner 테스트 PASS. endpoint 불일치 테스트는 내부적으로 오류와 cleanup을 기대하므로 테스트 자체는 PASS. -- [ ] **Step 5: 회귀 테스트 커밋** +- [x] **Step 5: 회귀 테스트 커밋** ```bash git add tests/test_runtime_api_smoke_runner.py diff --git a/scripts/runtime_api_smoke_runner.py b/scripts/runtime_api_smoke_runner.py index 8d83a64..ae3686f 100644 --- a/scripts/runtime_api_smoke_runner.py +++ b/scripts/runtime_api_smoke_runner.py @@ -308,6 +308,48 @@ def _poll_operation( raise TimeoutError(f"Runtime operation {operation_id} timed out") +def _runtime_endpoint_error( + create_request: dict[str, Any], + endpoints: Any, +) -> str | None: + expected = { + (container["name"], port) + for container in create_request["workload"]["containers"] + for port in container["exposed_ports"] + } + if not isinstance(endpoints, list) or not endpoints: + return "Runtime create operation did not return public endpoints" + + actual = set() + for endpoint in endpoints: + if not isinstance(endpoint, dict): + return "Runtime endpoints contain an invalid item" + container_name = endpoint.get("container_name") + port = endpoint.get("port") + protocol = endpoint.get("protocol") + service_url = endpoint.get("service_url") + if ( + not isinstance(container_name, str) + or not container_name + or isinstance(port, bool) + or not isinstance(port, int) + or not 1 <= port <= 65535 + or not isinstance(protocol, str) + or not protocol + or not isinstance(service_url, str) + or not service_url + ): + return "Runtime endpoints contain missing or invalid required fields" + key = (container_name, port) + if key in actual: + return "Runtime endpoints contain a duplicate container and port" + actual.add(key) + + if actual != expected: + return "Runtime endpoints do not exactly match requested public ports" + return None + + def run_smoke( artifact: dict[str, Any], *, @@ -382,7 +424,7 @@ def run_smoke( if not isinstance(runtime_workload_id, str) or not runtime_workload_id.strip(): raise RuntimeError("Runtime create operation returned an invalid runtime_workload_id") endpoints = create_result.get("endpoints") - endpoints_valid = isinstance(endpoints, list) and bool(endpoints) + endpoint_error = _runtime_endpoint_error(create_request, endpoints) create_elapsed_seconds = round(evidence_clock() - create_started, 3) delete_request = { @@ -410,8 +452,8 @@ def run_smoke( deadline=cleanup_deadline, ) delete_elapsed_seconds = round(evidence_clock() - delete_started, 3) - if not endpoints_valid: - raise RuntimeError("Runtime create operation did not return public endpoints") + if endpoint_error is not None: + raise RuntimeError(endpoint_error) return { "challenge_slug": artifact.get("challenge_slug"), "revision": artifact.get("revision"), diff --git a/tests/test_runtime_api_smoke_runner.py b/tests/test_runtime_api_smoke_runner.py index dc2ed2a..0cfdf9b 100644 --- a/tests/test_runtime_api_smoke_runner.py +++ b/tests/test_runtime_api_smoke_runner.py @@ -57,7 +57,13 @@ class RuntimeHandler(BaseHTTPRequestHandler): "port": 8080, "protocol": "HTTP", "service_url": "http://203.0.113.10:31042", - } + }, + { + "container_name": "service", + "port": 9090, + "protocol": "HTTP", + "service_url": "http://203.0.113.10:31043", + }, ], } drop_create_response_once = False @@ -158,7 +164,13 @@ def start_server(self): "port": 8080, "protocol": "HTTP", "service_url": "http://203.0.113.10:31042", - } + }, + { + "container_name": "service", + "port": 9090, + "protocol": "HTTP", + "service_url": "http://203.0.113.10:31043", + }, ], } RuntimeHandler.drop_create_response_once = False @@ -224,6 +236,14 @@ def test_builds_mixed_public_private_ports_with_exposed_ports(self): "ports": [{"port": 5432, "public": False}], }, ] + artifact["workload"]["internal_connections"] = [ + { + "source_container": "web", + "destination_container": "db", + "protocol": "TCP", + "port": 5432, + } + ] request = build_create_request( artifact, @@ -258,6 +278,10 @@ def test_builds_mixed_public_private_ports_with_exposed_ports(self): for container in request["workload"]["containers"] ) ) + self.assertEqual( + request["workload"]["internal_connections"], + artifact["workload"]["internal_connections"], + ) def test_preserves_internal_connections_in_runtime_request(self): artifact = copy.deepcopy(ARTIFACT) @@ -334,7 +358,13 @@ def test_reports_digest_images_and_runtime_endpoints(self): "port": 8080, "protocol": "HTTP", "service_url": "http://203.0.113.10:31042", - } + }, + { + "container_name": "service", + "port": 9090, + "protocol": "HTTP", + "service_url": "http://203.0.113.10:31043", + }, ], } with tempfile.TemporaryDirectory() as directory: @@ -432,6 +462,105 @@ def test_rejects_success_without_endpoints_after_cleanup(self): methods = [(method, path) for method, path, _headers, _body in RuntimeHandler.requests] self.assertIn(("DELETE", f"/internal/v1/instances/{INSTANCE_ID}"), methods) + def test_rejects_incomplete_endpoint_set_after_cleanup(self): + self.start_server() + RuntimeHandler.create_result["endpoints"] = [ + RuntimeHandler.create_result["endpoints"][0] + ] + + with tempfile.TemporaryDirectory() as directory: + token_file = Path(directory) / "service-token" + token_file.write_text("A" * 43, encoding="utf-8") + with self.assertRaisesRegex(RuntimeError, "endpoints"): + run_smoke( + ARTIFACT, + api_url=f"http://127.0.0.1:{self.server.server_port}", + token_file=token_file, + target_id="aws-k3s-lab", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + poll_interval=0, + timeout=2, + ) + + methods = [method for method, _path, _headers, _body in RuntimeHandler.requests] + self.assertIn("DELETE", methods) + + def test_rejects_unexpected_endpoint_after_cleanup(self): + self.start_server() + RuntimeHandler.create_result["endpoints"].append( + { + "container_name": "service", + "port": 9000, + "protocol": "HTTP", + "service_url": "http://203.0.113.10:31044", + } + ) + + with tempfile.TemporaryDirectory() as directory: + token_file = Path(directory) / "service-token" + token_file.write_text("A" * 43, encoding="utf-8") + with self.assertRaisesRegex(RuntimeError, "endpoints"): + run_smoke( + ARTIFACT, + api_url=f"http://127.0.0.1:{self.server.server_port}", + token_file=token_file, + target_id="aws-k3s-lab", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + poll_interval=0, + timeout=2, + ) + + methods = [method for method, _path, _headers, _body in RuntimeHandler.requests] + self.assertIn("DELETE", methods) + + def test_rejects_duplicate_endpoint_after_cleanup(self): + self.start_server() + RuntimeHandler.create_result["endpoints"].append( + copy.deepcopy(RuntimeHandler.create_result["endpoints"][0]) + ) + + with tempfile.TemporaryDirectory() as directory: + token_file = Path(directory) / "service-token" + token_file.write_text("A" * 43, encoding="utf-8") + with self.assertRaisesRegex(RuntimeError, "endpoints"): + run_smoke( + ARTIFACT, + api_url=f"http://127.0.0.1:{self.server.server_port}", + token_file=token_file, + target_id="aws-k3s-lab", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + poll_interval=0, + timeout=2, + ) + + methods = [method for method, _path, _headers, _body in RuntimeHandler.requests] + self.assertIn("DELETE", methods) + + def test_rejects_endpoint_missing_required_field_after_cleanup(self): + self.start_server() + del RuntimeHandler.create_result["endpoints"][0]["service_url"] + + with tempfile.TemporaryDirectory() as directory: + token_file = Path(directory) / "service-token" + token_file.write_text("A" * 43, encoding="utf-8") + with self.assertRaisesRegex(RuntimeError, "endpoints"): + run_smoke( + ARTIFACT, + api_url=f"http://127.0.0.1:{self.server.server_port}", + token_file=token_file, + target_id="aws-k3s-lab", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + poll_interval=0, + timeout=2, + ) + + methods = [method for method, _path, _headers, _body in RuntimeHandler.requests] + self.assertIn("DELETE", methods) + def test_redacts_service_token_from_runtime_error_details(self): self.start_server() RuntimeHandler.echo_auth_error = True From 94beffb916d594bc6478c68d464c8fc3b015366d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Mon, 7 Sep 2026 02:26:39 +0900 Subject: [PATCH 09/13] =?UTF-8?q?Runtime=20=ED=8F=AC=ED=8A=B8=EB=B3=84=20?= =?UTF-8?q?=EA=B3=B5=EA=B0=9C=20smoke=20=EB=AC=B8=EC=84=9C=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/aws-k3s-cd-smoke.md | 19 ++++++++++++++++--- ...09-07-runtime-exposed-ports-integration.md | 6 +++--- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/docs/aws-k3s-cd-smoke.md b/docs/aws-k3s-cd-smoke.md index d41ed76..4b006cc 100644 --- a/docs/aws-k3s-cd-smoke.md +++ b/docs/aws-k3s-cd-smoke.md @@ -41,7 +41,7 @@ caller는 다음 입력을 전달합니다. ```yaml with: enable_k3s_smoke_deploy: true - runtime_target_id: aws-k3s-001 + runtime_target_id: aws-k3s-lab secrets: inherit ``` @@ -110,6 +110,18 @@ Smoke runner는 `artifact-v2.json`의 `revision`과 `registry_revision`이 같 확인합니다. `containers[]`의 digest 이미지와 선택형 `internal_connections[]`는 같은 publish bundle에서 읽어 Runtime 요청에 전달합니다. +bundle의 컨테이너 포트는 다음처럼 Runtime PR #39 계약으로 변환합니다. + +- bundle의 전체 `ports[].port`는 Runtime 요청의 `ports`가 됩니다. +- `ports[].public: true`인 포트만 Runtime 요청의 `exposed_ports`가 됩니다. +- 모두 private인 컨테이너는 `exposed_ports: []`를 보냅니다. +- Runtime 요청에는 기존 `expose`를 함께 보내지 않습니다. + +따라서 한 컨테이너에 `8080 public`, `9000 private`가 함께 있어도 8080만 외부 +endpoint로 요청할 수 있습니다. Runtime 응답의 `endpoints[]`는 요청한 모든 +`(container_name, port)`와 누락, 추가, 중복 없이 정확히 일치해야 합니다. endpoint +각 항목의 `container_name`, `port`, `protocol`, `service_url`도 모두 검증합니다. + `create_elapsed_seconds`는 생성 요청을 처음 제출한 시점부터 생성 Operation이 `SUCCEEDED`가 될 때까지의 시간입니다. 이미지 pull뿐 아니라 Pod와 Service 준비 시간도 포함하므로 순수 네트워크 처리량으로 해석하지 않습니다. @@ -141,8 +153,9 @@ S3 staging 파일 또는 API body에 기록하지 않습니다. - Runtime팀 API의 현재 격리 profile에 맞춰 `pwn`은 `PWN`, 나머지는 `WEB`을 사용합니다. - `info.yaml`에 `run_as_user`가 없으면 smoke 요청은 non-root UID `10001`을 사용합니다. -- 한 컨테이너 안에서 public 포트와 private 포트를 섞는 artifact는 Runtime의 현재 - container 단위 `expose` 계약으로 손실 없이 변환할 수 없어 거부합니다. +- 운영 smoke 대상은 Runtime팀에서 전달한 `aws-k3s-lab`을 사용합니다. +- Runtime API service token이 아직 준비되지 않아 실제 K3s 생성·endpoint 확인·삭제는 + 실행하지 않았습니다. 현재 완료 범위는 요청 변환과 cleanup 동작의 단위 테스트입니다. - 운영 참가자 instance 생성은 Backend, Scheduler, Broker, Runtime 경로가 담당합니다. 이 job은 문제 revision 발행 직후의 임시 통합 검증입니다. diff --git a/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md b/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md index 91c048e..c904291 100644 --- a/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md +++ b/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md @@ -114,19 +114,19 @@ - Consumes: Runtime PR #39의 `exposed_ports` 계약과 운영 target `aws-k3s-lab`. - Produces: 토큰 준비 전후를 구분한 실행 안내. -- [ ] **Step 1: 문서 수정** +- [x] **Step 1: 문서 수정** caller 예시의 `runtime_target_id`를 `aws-k3s-lab`으로 바꾼다. 혼합 포트 거절 제약을 제거하고 `ports[].public`이 Runtime `exposed_ports`로 변환되며 `expose`를 보내지 않는다고 설명한다. service token 미수령으로 실제 K3s smoke가 미실행임을 명시한다. -- [ ] **Step 2: 문서 계약 검사** +- [x] **Step 2: 문서 계약 검사** Run: `rg -n "aws-k3s-lab|exposed_ports|실제 K3s" docs/aws-k3s-cd-smoke.md` Expected: 세 계약이 문서에 존재하며 기존 “혼합 포트 거절” 설명은 없음. -- [ ] **Step 3: 문서 커밋** +- [x] **Step 3: 문서 커밋** ```bash git add docs/aws-k3s-cd-smoke.md From 4af2e9b275d73f690c73f9f0bd0221599c2bdf05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Mon, 7 Sep 2026 11:43:34 +0900 Subject: [PATCH 10/13] =?UTF-8?q?Runtime=20=EA=B3=84=EC=95=BD=20=EA=B2=80?= =?UTF-8?q?=EC=A6=9D=20=EB=A6=AC=EB=B7=B0=20=EB=B3=B4=EC=99=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/aws-k3s-cd-smoke.md | 8 +- docs/devsecops-runbook.md | 8 +- ...09-07-runtime-exposed-ports-integration.md | 40 +++- ...untime-exposed-ports-integration-design.md | 17 +- scripts/runtime_api_smoke_runner.py | 112 +++++++++-- scripts/validate_info_spec.py | 6 + tests/test_runtime_api_smoke_runner.py | 180 ++++++++++++++++-- tests/test_validate_info_spec.py | 9 + 8 files changed, 334 insertions(+), 46 deletions(-) diff --git a/docs/aws-k3s-cd-smoke.md b/docs/aws-k3s-cd-smoke.md index 4b006cc..a622d89 100644 --- a/docs/aws-k3s-cd-smoke.md +++ b/docs/aws-k3s-cd-smoke.md @@ -154,8 +154,9 @@ S3 staging 파일 또는 API body에 기록하지 않습니다. - Runtime팀 API의 현재 격리 profile에 맞춰 `pwn`은 `PWN`, 나머지는 `WEB`을 사용합니다. - `info.yaml`에 `run_as_user`가 없으면 smoke 요청은 non-root UID `10001`을 사용합니다. - 운영 smoke 대상은 Runtime팀에서 전달한 `aws-k3s-lab`을 사용합니다. -- Runtime API service token이 아직 준비되지 않아 실제 K3s 생성·endpoint 확인·삭제는 - 실행하지 않았습니다. 현재 완료 범위는 요청 변환과 cleanup 동작의 단위 테스트입니다. +- `aws-k3s-lab` node에서 읽을 Runtime API service token이 아직 준비되지 않아 실제 + K3s 생성·endpoint 확인·삭제는 실행하지 않았습니다. 현재 완료 범위는 요청 변환과 + cleanup 동작의 단위 테스트입니다. - 운영 참가자 instance 생성은 Backend, Scheduler, Broker, Runtime 경로가 담당합니다. 이 job은 문제 revision 발행 직후의 임시 통합 검증입니다. @@ -166,5 +167,8 @@ S3 staging 파일 또는 API body에 기록하지 않습니다. - `PROVISIONER_CLUSTER_REGISTRY`의 target과 K3s kubeconfig가 유효해야 합니다. - K3s/containerd가 private GHCR digest를 pull할 수 있어야 합니다. - 실패 후 Runtime Operation과 Namespace가 남지 않았는지 확인해야 합니다. +- create operation 결과가 불완전하면 runner가 `runtime-status`에서 workload ID를 + cleanup 제한 시간까지 재시도해 복구하고 삭제합니다. status 조회에서도 ID를 얻지 + 못하면 Runtime팀이 해당 instance의 잔존 리소스를 확인해야 합니다. - cold pull 검증은 다른 workload가 없는 전용 target에서 Runtime팀이 image cache 상태를 확인한 뒤 실행해야 합니다. diff --git a/docs/devsecops-runbook.md b/docs/devsecops-runbook.md index 4ca3689..4c5d7e8 100644 --- a/docs/devsecops-runbook.md +++ b/docs/devsecops-runbook.md @@ -107,7 +107,7 @@ Backend PR #26 기능 브랜치에는 Challenge Registry 등록·조회 API와 r ```yaml with: enable_k3s_smoke_deploy: true - runtime_target_id: aws-k3s-001 + runtime_target_id: aws-k3s-lab secrets: inherit ``` @@ -177,8 +177,10 @@ cold pull, 인증 실패, `ImagePullBackOff`, 실행 digest 일치 항목은 Run ### Scheduler와 Runtime -- Secure Provisioner `dev`는 멀티 컨테이너, digest image, port, `expose`, - resource limit와 `WEB | PWN` 격리 profile을 수용합니다. +- Secure Provisioner PR #39는 멀티 컨테이너, digest image, `ports`, + `exposed_ports`, resource limit와 `WEB | PWN` 격리 profile을 수용합니다. +- DevSecOps smoke 요청은 `ports[].public`을 `exposed_ports`로 변환하고 `expose`를 + 함께 보내지 않습니다. PWN의 공개 컨테이너는 전체 포트가 정확히 1개여야 합니다. - Scheduler `feature/live-e2e-contract`도 멀티 컨테이너 Runtime DTO를 반영했지만 아직 `dev` 병합 전입니다. - DevSecOps smoke runner는 현재 Runtime API 계약으로 변환하되 CI가 Kubernetes diff --git a/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md b/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md index c904291..5099e69 100644 --- a/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md +++ b/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md @@ -144,13 +144,13 @@ - Consumes: Tasks 1-3의 코드·테스트·문서. - Produces: 검증된 PR #6 커밋과 정확한 미완료 항목. -- [ ] **Step 1: 전체 단위 테스트 실행** +- [x] **Step 1: 전체 단위 테스트 실행** Run: `python3 -W error::ResourceWarning -m unittest discover -s tests -v` Expected: PASS. -- [ ] **Step 2: 정적 검증 실행** +- [x] **Step 2: 정적 검증 실행** Run: `python3 -m py_compile scripts/*.py` @@ -177,3 +177,39 @@ Expected: 실행된 check PASS. 실제 K3s smoke는 token과 배포 환경이 없으면 실행하지 않았다고 구분해 기록한다. + +### Task 5: 독립 코드리뷰 보완 + +**Files:** +- Modify: `scripts/runtime_api_smoke_runner.py` +- Modify: `scripts/validate_info_spec.py` +- Modify: `tests/test_runtime_api_smoke_runner.py` +- Modify: `tests/test_validate_info_spec.py` +- Modify: `docs/aws-k3s-cd-smoke.md` +- Modify: `docs/devsecops-runbook.md` +- Modify: `docs/superpowers/specs/2026-09-07-runtime-exposed-ports-integration-design.md` + +**Interfaces:** +- Consumes: Runtime PR #39 OpenAPI의 endpoint schema, PWN 포트 제한, runtime-status 조회. +- Produces: 잘못된 Runtime 응답 차단, PWN 조기 차단, 불완전 create 결과 cleanup 복구. + +- [x] **Step 1: 실패 테스트 작성과 RED 확인** + + 잘못된 endpoint protocol·URI·추가 필드, 공개 PWN 컨테이너 다중 포트, + runtime-status를 통한 `runtime_workload_id` 복구 후 cleanup 완료를 테스트한다. + +- [x] **Step 2: 최소 구현과 GREEN 확인** + + endpoint의 정확한 키·`HTTP|TCP`·URI를 검사한다. PWN 공개 컨테이너는 전체 포트가 + 정확히 하나인지 info 검증과 Runtime 변환 경계에서 확인한다. create operation 결과가 + 불완전하면 runtime-status에서 workload ID를 복구해 삭제한다. + +- [x] **Step 3: cleanup 완료와 token 문서 계약 보완** + + endpoint 오류 테스트에서 delete operation 조회 완료까지 확인한다. service token은 + GitHub Secret이 아니라 Runtime node의 `/etc/secure-provisioner/service-token`에서만 + 읽는 것으로 설계·운영 문서를 통일하고 기존 `expose` 설명을 갱신한다. + +- [x] **Step 4: 전체 검증과 커밋** + + 76개 이상의 전체 테스트, Python 문법, diff, Gitleaks 검사를 통과한 뒤 커밋한다. diff --git a/docs/superpowers/specs/2026-09-07-runtime-exposed-ports-integration-design.md b/docs/superpowers/specs/2026-09-07-runtime-exposed-ports-integration-design.md index 1fd79f8..4c35059 100644 --- a/docs/superpowers/specs/2026-09-07-runtime-exposed-ports-integration-design.md +++ b/docs/superpowers/specs/2026-09-07-runtime-exposed-ports-integration-design.md @@ -44,10 +44,11 @@ private 포트를 외부에 노출하지 않고, Runtime 응답의 공개 endpoi - 실제 smoke의 `target.target_id`는 workflow 입력을 통해 `aws-k3s-lab`으로 전달한다. - `target_id`는 release 자체의 속성이 아니므로 `artifact-v2.json`에 저장하지 않는다. -- Runtime API service token은 GitHub Actions secret으로만 전달하며 파일, 로그, bundle에 - 남기지 않는다. -- 현재 token이 준비되지 않았으므로 코드·단위 테스트까지만 수행하고 실제 K3s 결과는 - 미검증으로 기록한다. +- Runtime API service token은 GitHub Actions에 전달하지 않고 Runtime node의 + `/etc/secure-provisioner/service-token`에서만 읽는다. token은 로그, S3 staging, + bundle에 남기지 않는다. +- 현재 node에 사용할 service token이 준비되지 않았으므로 코드·단위 테스트까지만 + 수행하고 실제 K3s 결과는 미검증으로 기록한다. ## 응답 검증과 정리 @@ -55,8 +56,12 @@ private 포트를 외부에 노출하지 않고, Runtime 응답의 공개 endpoi - Runtime의 `endpoints[]`는 각 항목의 `container_name`, `port`, `protocol`, `service_url`을 검증한다. - 예상 endpoint와 실제 endpoint가 누락, 추가, 중복 없이 정확히 일치해야 성공한다. -- 불일치하거나 생성 결과가 불완전하면 기존 동작대로 workload 삭제를 먼저 요청하고 - 삭제 완료를 확인한 뒤 실패한다. +- endpoint가 불일치하면 workload 삭제를 먼저 요청하고 삭제 완료를 확인한 뒤 실패한다. +- create operation 결과에 `runtime_workload_id`가 누락되면 + `GET /internal/v1/instances/{instance_id}/runtime-status`를 cleanup 제한 시간까지 + 재시도해 ID를 복구한 뒤 삭제한다. + status 조회에서도 ID를 복구할 수 없으면 유효한 삭제 요청을 만들 수 없으므로 오류와 + 수동 확인 필요 상태를 남긴다. ## Backend 연동 diff --git a/scripts/runtime_api_smoke_runner.py b/scripts/runtime_api_smoke_runner.py index ae3686f..039e04f 100644 --- a/scripts/runtime_api_smoke_runner.py +++ b/scripts/runtime_api_smoke_runner.py @@ -12,12 +12,15 @@ from pathlib import Path from typing import Any, Callable from urllib.error import HTTPError, URLError +from urllib.parse import urlsplit from urllib.request import Request, urlopen DIGEST_IMAGE = re.compile(r"^.+@sha256:[0-9a-f]{64}$") SERVICE_TOKEN = re.compile(r"^[A-Za-z0-9_-]{43,128}$") FINAL_OPERATION_STATES = {"SUCCEEDED", "FAILED"} +ENDPOINT_FIELDS = {"container_name", "port", "protocol", "service_url"} +ENDPOINT_PROTOCOLS = {"HTTP", "TCP"} class RetryableRuntimeError(RuntimeError): @@ -120,6 +123,8 @@ def build_create_request( exposed_ports.append(port) exposed = exposed or bool(exposed_ports) + if isolation_profile == "PWN" and exposed_ports and len(ports) != 1: + raise ValueError("PWN exposed container must declare exactly one port") runtime_containers.append( { "name": name, @@ -324,6 +329,8 @@ def _runtime_endpoint_error( for endpoint in endpoints: if not isinstance(endpoint, dict): return "Runtime endpoints contain an invalid item" + if set(endpoint) != ENDPOINT_FIELDS: + return "Runtime endpoints contain missing or unknown fields" container_name = endpoint.get("container_name") port = endpoint.get("port") protocol = endpoint.get("protocol") @@ -334,12 +341,25 @@ def _runtime_endpoint_error( or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535 - or not isinstance(protocol, str) - or not protocol + or protocol not in ENDPOINT_PROTOCOLS or not isinstance(service_url, str) or not service_url ): return "Runtime endpoints contain missing or invalid required fields" + if any(character.isspace() for character in service_url): + return "Runtime endpoints contain an invalid service_url" + try: + parsed_service_url = urlsplit(service_url) + hostname = parsed_service_url.hostname + parsed_service_url.port + except ValueError: + return "Runtime endpoints contain an invalid service_url" + if ( + not parsed_service_url.scheme + or not parsed_service_url.netloc + or not hostname + ): + return "Runtime endpoints contain an invalid service_url" key = (container_name, port) if key in actual: return "Runtime endpoints contain a duplicate container and port" @@ -350,6 +370,39 @@ def _runtime_endpoint_error( return None +def _recover_runtime_workload_id( + client: RuntimeClient, + create_request: dict[str, Any], + *, + poll_interval: float, + deadline: float, +) -> str: + instance_id = create_request["instance_id"] + path = f"/internal/v1/instances/{instance_id}/runtime-status" + while True: + try: + status = client.request("GET", path) + break + except RetryableRuntimeError as error: + if time.monotonic() >= deadline: + raise TimeoutError( + "Runtime status recovery timed out before cleanup" + ) from error + time.sleep(poll_interval) + if status.get("instance_id") != instance_id: + raise IncompleteOperationResult( + "Runtime status returned a different instance_id" + ) + if status.get("target_id") != create_request["target"]["target_id"]: + raise IncompleteOperationResult("Runtime status returned a different target_id") + runtime_workload_id = status.get("runtime_workload_id") + if not isinstance(runtime_workload_id, str) or not runtime_workload_id.strip(): + raise IncompleteOperationResult( + "Runtime status did not return a runtime_workload_id" + ) + return runtime_workload_id + + def run_smoke( artifact: dict[str, Any], *, @@ -398,6 +451,7 @@ def run_smoke( poll_interval=poll_interval, deadline=create_poll_deadline, ) + created = None try: created = _poll_operation( client, @@ -406,23 +460,45 @@ def run_smoke( deadline=create_poll_deadline, require_create_result=True, ) - except (TimeoutError, IncompleteOperationResult): + except (TimeoutError, IncompleteOperationResult) as error: if recovered_after_timeout: - raise - recovered_after_timeout = True - created = _poll_operation( - client, - accepted.get("operation_id"), - poll_interval=poll_interval, - deadline=time.monotonic() + cleanup_timeout, - require_create_result=True, - ) - create_result = created.get("result") - if not isinstance(create_result, dict): - raise RuntimeError("Runtime create operation did not return a result") - runtime_workload_id = create_result.get("runtime_workload_id") - if not isinstance(runtime_workload_id, str) or not runtime_workload_id.strip(): - raise RuntimeError("Runtime create operation returned an invalid runtime_workload_id") + if isinstance(error, IncompleteOperationResult): + runtime_workload_id = _recover_runtime_workload_id( + client, + create_request, + poll_interval=poll_interval, + deadline=time.monotonic() + cleanup_timeout, + ) + else: + raise + else: + recovered_after_timeout = True + try: + created = _poll_operation( + client, + accepted.get("operation_id"), + poll_interval=poll_interval, + deadline=time.monotonic() + cleanup_timeout, + require_create_result=True, + ) + except IncompleteOperationResult: + runtime_workload_id = _recover_runtime_workload_id( + client, + create_request, + poll_interval=poll_interval, + deadline=time.monotonic() + cleanup_timeout, + ) + + if created is None: + create_result = {"runtime_workload_id": runtime_workload_id, "endpoints": []} + created = {"status": "SUCCEEDED", "result": create_result} + else: + create_result = created.get("result") + if not isinstance(create_result, dict): + raise RuntimeError("Runtime create operation did not return a result") + runtime_workload_id = create_result.get("runtime_workload_id") + if not isinstance(runtime_workload_id, str) or not runtime_workload_id.strip(): + raise RuntimeError("Runtime create operation returned an invalid runtime_workload_id") endpoints = create_result.get("endpoints") endpoint_error = _runtime_endpoint_error(create_request, endpoints) create_elapsed_seconds = round(evidence_clock() - create_started, 3) diff --git a/scripts/validate_info_spec.py b/scripts/validate_info_spec.py index e9fdd50..6375a80 100644 --- a/scripts/validate_info_spec.py +++ b/scripts/validate_info_spec.py @@ -235,6 +235,12 @@ def validate_spec(challenge_path): names = [container["name"] for container in containers] if len(names) != len(set(names)): raise ValueError("container name values must be unique") + if category == "pwn": + for container in containers: + if container["expose"] and len(container["ports"]) != 1: + raise ValueError( + "PWN exposed container must declare exactly one port" + ) raw_profile = deployment.get("resource_profile") if not isinstance(raw_profile, dict): diff --git a/tests/test_runtime_api_smoke_runner.py b/tests/test_runtime_api_smoke_runner.py index 0cfdf9b..c1a8cf7 100644 --- a/tests/test_runtime_api_smoke_runner.py +++ b/tests/test_runtime_api_smoke_runner.py @@ -72,6 +72,12 @@ class RuntimeHandler(BaseHTTPRequestHandler): omit_delete_operation_id_once = False omit_create_result_once = False echo_auth_error = False + fail_runtime_status_once = False + runtime_status_result = { + "instance_id": INSTANCE_ID, + "target_id": "aws-k3s-lab", + "runtime_workload_id": "aws-k3s-lab/ctf-test/challenge", + } def log_message(self, _format, *_args): return @@ -121,6 +127,13 @@ def do_DELETE(self): def do_GET(self): type(self).requests.append(("GET", self.path, self.headers, None)) + if self.path.endswith("/runtime-status"): + if type(self).fail_runtime_status_once: + type(self).fail_runtime_status_once = False + self._respond(503, {"error": "temporary unavailable"}) + return + self._respond(200, type(self).runtime_status_result) + return if self.path.endswith("op-create"): type(self).create_polls += 1 result = type(self).create_result @@ -179,6 +192,12 @@ def start_server(self): RuntimeHandler.omit_delete_operation_id_once = False RuntimeHandler.omit_create_result_once = False RuntimeHandler.echo_auth_error = False + RuntimeHandler.fail_runtime_status_once = False + RuntimeHandler.runtime_status_result = { + "instance_id": INSTANCE_ID, + "target_id": "aws-k3s-lab", + "runtime_workload_id": "aws-k3s-lab/ctf-test/challenge", + } self.server = ThreadingHTTPServer(("127.0.0.1", 0), RuntimeHandler) self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) self.thread.start() @@ -190,6 +209,40 @@ def tearDown(self): self.server.server_close() self.thread.join(timeout=5) + def assert_endpoint_response_rejected(self, endpoint): + self.start_server() + RuntimeHandler.create_result["endpoints"][0] = endpoint + with tempfile.TemporaryDirectory() as directory: + token_file = Path(directory) / "service-token" + token_file.write_text("A" * 43, encoding="utf-8") + with self.assertRaisesRegex(RuntimeError, "endpoints"): + run_smoke( + ARTIFACT, + api_url=f"http://127.0.0.1:{self.server.server_port}", + token_file=token_file, + target_id="aws-k3s-lab", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + poll_interval=0, + timeout=2, + ) + methods = [ + (method, path) + for method, path, _headers, _body in RuntimeHandler.requests + ] + self.assertIn(("DELETE", f"/internal/v1/instances/{INSTANCE_ID}"), methods) + self.assertIn(("GET", "/internal/v1/operations/op-delete"), methods) + self.assertGreater(RuntimeHandler.delete_polls, 0) + + @staticmethod + def valid_service_endpoint(): + return { + "container_name": "service", + "port": 8080, + "protocol": "HTTP", + "service_url": "http://203.0.113.10:31042", + } + def test_builds_runtime_team_multi_container_contract(self): request = build_create_request( ARTIFACT, @@ -452,7 +505,7 @@ def test_rejects_success_without_endpoints_after_cleanup(self): ARTIFACT, api_url=f"http://127.0.0.1:{self.server.server_port}", token_file=token_file, - target_id="aws-k3s-001", + target_id="aws-k3s-lab", instance_id=INSTANCE_ID, team_id=TEAM_ID, poll_interval=0, @@ -483,8 +536,13 @@ def test_rejects_incomplete_endpoint_set_after_cleanup(self): timeout=2, ) - methods = [method for method, _path, _headers, _body in RuntimeHandler.requests] - self.assertIn("DELETE", methods) + methods = [ + (method, path) + for method, path, _headers, _body in RuntimeHandler.requests + ] + self.assertIn(("DELETE", f"/internal/v1/instances/{INSTANCE_ID}"), methods) + self.assertIn(("GET", "/internal/v1/operations/op-delete"), methods) + self.assertGreater(RuntimeHandler.delete_polls, 0) def test_rejects_unexpected_endpoint_after_cleanup(self): self.start_server() @@ -512,8 +570,13 @@ def test_rejects_unexpected_endpoint_after_cleanup(self): timeout=2, ) - methods = [method for method, _path, _headers, _body in RuntimeHandler.requests] - self.assertIn("DELETE", methods) + methods = [ + (method, path) + for method, path, _headers, _body in RuntimeHandler.requests + ] + self.assertIn(("DELETE", f"/internal/v1/instances/{INSTANCE_ID}"), methods) + self.assertIn(("GET", "/internal/v1/operations/op-delete"), methods) + self.assertGreater(RuntimeHandler.delete_polls, 0) def test_rejects_duplicate_endpoint_after_cleanup(self): self.start_server() @@ -536,8 +599,13 @@ def test_rejects_duplicate_endpoint_after_cleanup(self): timeout=2, ) - methods = [method for method, _path, _headers, _body in RuntimeHandler.requests] - self.assertIn("DELETE", methods) + methods = [ + (method, path) + for method, path, _headers, _body in RuntimeHandler.requests + ] + self.assertIn(("DELETE", f"/internal/v1/instances/{INSTANCE_ID}"), methods) + self.assertIn(("GET", "/internal/v1/operations/op-delete"), methods) + self.assertGreater(RuntimeHandler.delete_polls, 0) def test_rejects_endpoint_missing_required_field_after_cleanup(self): self.start_server() @@ -558,8 +626,31 @@ def test_rejects_endpoint_missing_required_field_after_cleanup(self): timeout=2, ) - methods = [method for method, _path, _headers, _body in RuntimeHandler.requests] - self.assertIn("DELETE", methods) + methods = [ + (method, path) + for method, path, _headers, _body in RuntimeHandler.requests + ] + self.assertIn(("DELETE", f"/internal/v1/instances/{INSTANCE_ID}"), methods) + self.assertIn(("GET", "/internal/v1/operations/op-delete"), methods) + self.assertGreater(RuntimeHandler.delete_polls, 0) + + def test_rejects_endpoint_with_unsupported_protocol_after_cleanup(self): + endpoint = self.valid_service_endpoint() + endpoint["protocol"] = "SMTP" + + self.assert_endpoint_response_rejected(endpoint) + + def test_rejects_endpoint_with_invalid_service_url_after_cleanup(self): + endpoint = self.valid_service_endpoint() + endpoint["service_url"] = "http://bad host/path" + + self.assert_endpoint_response_rejected(endpoint) + + def test_rejects_endpoint_with_unknown_field_after_cleanup(self): + endpoint = self.valid_service_endpoint() + endpoint["unexpected"] = True + + self.assert_endpoint_response_rejected(endpoint) def test_redacts_service_token_from_runtime_error_details(self): self.start_server() @@ -584,7 +675,12 @@ def test_redacts_service_token_from_runtime_error_details(self): self.assertIn("[REDACTED]", str(raised.exception)) def test_maps_pwn_category_to_pwn_isolation_profile(self): - artifact = dict(ARTIFACT, category="pwn", isolation_profile="PWN") + artifact = copy.deepcopy(ARTIFACT) + artifact["category"] = "pwn" + artifact["isolation_profile"] = "PWN" + artifact["workload"]["containers"][0]["ports"] = [ + {"port": 31337, "public": True} + ] request = build_create_request( artifact, @@ -595,28 +691,82 @@ def test_maps_pwn_category_to_pwn_isolation_profile(self): self.assertEqual(request["isolation_profile"], "PWN") - def test_rejects_malformed_create_result_without_invalid_delete_request(self): + def test_rejects_public_pwn_container_with_multiple_ports(self): + artifact = copy.deepcopy(ARTIFACT) + artifact["category"] = "pwn" + artifact["isolation_profile"] = "PWN" + artifact["workload"]["containers"][0]["ports"] = [ + {"port": 31337, "public": True}, + {"port": 9000, "public": False}, + ] + + with self.assertRaisesRegex(ValueError, "PWN.*one port"): + build_create_request( + artifact, + target_id="aws-k3s-lab", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + ) + + def test_recovers_workload_id_and_cleans_up_incomplete_create_result(self): self.start_server() RuntimeHandler.create_result = None with tempfile.TemporaryDirectory() as directory: token_file = Path(directory) / "service-token" token_file.write_text("A" * 43, encoding="utf-8") - with self.assertRaisesRegex(RuntimeError, "did not return a result"): + with self.assertRaisesRegex(RuntimeError, "endpoints"): run_smoke( ARTIFACT, api_url=f"http://127.0.0.1:{self.server.server_port}", token_file=token_file, - target_id="aws-k3s-001", + target_id="aws-k3s-lab", instance_id=INSTANCE_ID, team_id=TEAM_ID, poll_interval=0, timeout=0.01, - cleanup_timeout=0.01, + cleanup_timeout=0.05, ) methods = [(method, path) for method, path, _headers, _body in RuntimeHandler.requests] - self.assertNotIn(("DELETE", f"/internal/v1/instances/{INSTANCE_ID}"), methods) + self.assertIn( + ("GET", f"/internal/v1/instances/{INSTANCE_ID}/runtime-status"), + methods, + ) + self.assertIn(("DELETE", f"/internal/v1/instances/{INSTANCE_ID}"), methods) + self.assertIn(("GET", "/internal/v1/operations/op-delete"), methods) + self.assertGreater(RuntimeHandler.delete_polls, 0) + + def test_retries_runtime_status_recovery_before_cleanup(self): + self.start_server() + RuntimeHandler.create_result = None + RuntimeHandler.fail_runtime_status_once = True + with tempfile.TemporaryDirectory() as directory: + token_file = Path(directory) / "service-token" + token_file.write_text("A" * 43, encoding="utf-8") + + with self.assertRaisesRegex(RuntimeError, "endpoints"): + run_smoke( + ARTIFACT, + api_url=f"http://127.0.0.1:{self.server.server_port}", + token_file=token_file, + target_id="aws-k3s-lab", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + poll_interval=0, + timeout=0.01, + cleanup_timeout=0.1, + ) + + status_path = f"/internal/v1/instances/{INSTANCE_ID}/runtime-status" + methods = [ + (method, path) + for method, path, _headers, _body in RuntimeHandler.requests + ] + self.assertEqual(methods.count(("GET", status_path)), 2) + self.assertIn(("DELETE", f"/internal/v1/instances/{INSTANCE_ID}"), methods) + self.assertIn(("GET", "/internal/v1/operations/op-delete"), methods) + self.assertGreater(RuntimeHandler.delete_polls, 0) def test_recovers_timed_out_create_operation_and_deletes_workload(self): self.start_server() diff --git a/tests/test_validate_info_spec.py b/tests/test_validate_info_spec.py index 487547f..75e1f56 100644 --- a/tests/test_validate_info_spec.py +++ b/tests/test_validate_info_spec.py @@ -64,11 +64,20 @@ def test_server_challenge_is_marked_as_server(self): def test_pwn_server_uses_pwn_isolation_profile(self): raw = self._raw_fixture() raw["category"] = "pwn" + raw["deployment"]["containers"][0]["ports"] = [8080] + raw["deployment"]["healthcheck"]["port"] = 8080 metadata = self._validate_raw(raw) self.assertEqual(metadata["isolation_profile"], "PWN") + def test_rejects_public_pwn_container_with_multiple_ports(self): + raw = self._raw_fixture() + raw["category"] = "pwn" + + with self.assertRaisesRegex(ValueError, "PWN.*one port"): + self._validate_raw(raw) + def test_accepts_declared_internal_connection(self): raw = self._raw_fixture() raw["deployment"]["internal_connections"] = [ From 3f580d5ec1578bdc9d26957a60fc8fdef011710d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Mon, 7 Sep 2026 12:16:27 +0900 Subject: [PATCH 11/13] =?UTF-8?q?Runtime=20=EC=97=B0=EB=8F=99=20=EA=B2=80?= =?UTF-8?q?=EC=A6=9D=20=EA=B2=B0=EA=B3=BC=20=EA=B8=B0=EB=A1=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plans/2026-09-07-runtime-exposed-ports-integration.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md b/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md index 5099e69..19158e7 100644 --- a/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md +++ b/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md @@ -160,18 +160,18 @@ Expected: 모두 exit code 0. -- [ ] **Step 3: 브랜치 push** +- [x] **Step 3: 브랜치 push** Run: `git push msg-ctf runtime-smoke-evidence` Expected: PR #6 head가 새 커밋으로 갱신됨. -- [ ] **Step 4: PR 설명과 댓글 갱신** +- [x] **Step 4: PR 설명과 댓글 갱신** PR #6에 Runtime PR #39 계약 반영, `target_id=aws-k3s-lab`, Backend PR #62 호환, service token 미수령 때문에 실제 K3s smoke는 남아 있다는 사실을 기록한다. -- [ ] **Step 5: GitHub Actions 결과 확인** +- [x] **Step 5: GitHub Actions 결과 확인** Run: `gh pr checks 6 --repo MSG-CTF/msgctf-devsecops --watch` From 7a7d3636620f21c73f368bd57f81d66c90b18890 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Mon, 7 Sep 2026 14:05:10 +0900 Subject: [PATCH 12/13] =?UTF-8?q?Runtime=20=EC=9D=91=EB=8B=B5=20=EC=A0=95?= =?UTF-8?q?=EB=A6=AC=EC=99=80=20PWN=20=EA=B3=84=EC=95=BD=20=EA=B2=80?= =?UTF-8?q?=EC=A6=9D=20=EA=B0=95=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/aws-k3s-cd-smoke.md | 2 ++ docs/devsecops-runbook.md | 3 ++- scripts/runtime_api_smoke_runner.py | 8 +++++- scripts/validate_info_spec.py | 10 ++++---- tests/test_runtime_api_smoke_runner.py | 35 +++++++++++++++++++++++++- tests/test_validate_info_spec.py | 10 ++++++++ 6 files changed, 60 insertions(+), 8 deletions(-) diff --git a/docs/aws-k3s-cd-smoke.md b/docs/aws-k3s-cd-smoke.md index a622d89..7163be7 100644 --- a/docs/aws-k3s-cd-smoke.md +++ b/docs/aws-k3s-cd-smoke.md @@ -115,6 +115,8 @@ bundle의 컨테이너 포트는 다음처럼 Runtime PR #39 계약으로 변환 - bundle의 전체 `ports[].port`는 Runtime 요청의 `ports`가 됩니다. - `ports[].public: true`인 포트만 Runtime 요청의 `exposed_ports`가 됩니다. - 모두 private인 컨테이너는 `exposed_ports: []`를 보냅니다. +- PWN은 공개 컨테이너가 정확히 1개여야 하며, 해당 컨테이너의 전체 포트도 + 정확히 1개여야 합니다. - Runtime 요청에는 기존 `expose`를 함께 보내지 않습니다. 따라서 한 컨테이너에 `8080 public`, `9000 private`가 함께 있어도 8080만 외부 diff --git a/docs/devsecops-runbook.md b/docs/devsecops-runbook.md index 4c5d7e8..6e6ed0b 100644 --- a/docs/devsecops-runbook.md +++ b/docs/devsecops-runbook.md @@ -180,7 +180,8 @@ cold pull, 인증 실패, `ImagePullBackOff`, 실행 digest 일치 항목은 Run - Secure Provisioner PR #39는 멀티 컨테이너, digest image, `ports`, `exposed_ports`, resource limit와 `WEB | PWN` 격리 profile을 수용합니다. - DevSecOps smoke 요청은 `ports[].public`을 `exposed_ports`로 변환하고 `expose`를 - 함께 보내지 않습니다. PWN의 공개 컨테이너는 전체 포트가 정확히 1개여야 합니다. + 함께 보내지 않습니다. PWN은 공개 컨테이너가 정확히 1개여야 하며, 해당 + 컨테이너의 전체 포트도 정확히 1개여야 합니다. - Scheduler `feature/live-e2e-contract`도 멀티 컨테이너 Runtime DTO를 반영했지만 아직 `dev` 병합 전입니다. - DevSecOps smoke runner는 현재 Runtime API 계약으로 변환하되 CI가 Kubernetes diff --git a/scripts/runtime_api_smoke_runner.py b/scripts/runtime_api_smoke_runner.py index 039e04f..4c8887a 100644 --- a/scripts/runtime_api_smoke_runner.py +++ b/scripts/runtime_api_smoke_runner.py @@ -94,6 +94,7 @@ def build_create_request( runtime_containers = [] exposed = False + exposed_container_count = 0 for container in artifact_containers: if not isinstance(container, dict): raise ValueError("artifact container must be an object") @@ -122,7 +123,9 @@ def build_create_request( if public: exposed_ports.append(port) - exposed = exposed or bool(exposed_ports) + if exposed_ports: + exposed = True + exposed_container_count += 1 if isolation_profile == "PWN" and exposed_ports and len(ports) != 1: raise ValueError("PWN exposed container must declare exactly one port") runtime_containers.append( @@ -137,6 +140,8 @@ def build_create_request( if not exposed: raise ValueError("Runtime smoke deployment requires at least one exposed container") + if isolation_profile == "PWN" and exposed_container_count != 1: + raise ValueError("PWN workload must declare exactly one exposed container") runtime_workload = {"containers": runtime_containers} internal_connections = workload.get("internal_connections") @@ -341,6 +346,7 @@ def _runtime_endpoint_error( or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535 + or not isinstance(protocol, str) or protocol not in ENDPOINT_PROTOCOLS or not isinstance(service_url, str) or not service_url diff --git a/scripts/validate_info_spec.py b/scripts/validate_info_spec.py index 6375a80..90f259a 100644 --- a/scripts/validate_info_spec.py +++ b/scripts/validate_info_spec.py @@ -236,11 +236,11 @@ def validate_spec(challenge_path): if len(names) != len(set(names)): raise ValueError("container name values must be unique") if category == "pwn": - for container in containers: - if container["expose"] and len(container["ports"]) != 1: - raise ValueError( - "PWN exposed container must declare exactly one port" - ) + exposed_containers = [container for container in containers if container["expose"]] + if len(exposed_containers) != 1: + raise ValueError("PWN workload must declare exactly one exposed container") + if len(exposed_containers[0]["ports"]) != 1: + raise ValueError("PWN exposed container must declare exactly one port") raw_profile = deployment.get("resource_profile") if not isinstance(raw_profile, dict): diff --git a/tests/test_runtime_api_smoke_runner.py b/tests/test_runtime_api_smoke_runner.py index c1a8cf7..6be274c 100644 --- a/tests/test_runtime_api_smoke_runner.py +++ b/tests/test_runtime_api_smoke_runner.py @@ -640,6 +640,12 @@ def test_rejects_endpoint_with_unsupported_protocol_after_cleanup(self): self.assert_endpoint_response_rejected(endpoint) + def test_rejects_non_string_endpoint_protocol_after_cleanup(self): + endpoint = self.valid_service_endpoint() + endpoint["protocol"] = ["HTTP"] + + self.assert_endpoint_response_rejected(endpoint) + def test_rejects_endpoint_with_invalid_service_url_after_cleanup(self): endpoint = self.valid_service_endpoint() endpoint["service_url"] = "http://bad host/path" @@ -708,6 +714,33 @@ def test_rejects_public_pwn_container_with_multiple_ports(self): team_id=TEAM_ID, ) + def test_rejects_multiple_public_pwn_containers(self): + artifact = copy.deepcopy(ARTIFACT) + artifact["category"] = "pwn" + artifact["isolation_profile"] = "PWN" + artifact["workload"]["containers"] = [ + { + "name": "pwn-a", + "image": "ghcr.io/msg-ctf/pwn-a@sha256:" + "a" * 64, + "ports": [{"port": 31337, "public": True}], + "run_as_user": 10001, + }, + { + "name": "pwn-b", + "image": "ghcr.io/msg-ctf/pwn-b@sha256:" + "b" * 64, + "ports": [{"port": 31338, "public": True}], + "run_as_user": 10002, + }, + ] + + with self.assertRaisesRegex(ValueError, "PWN.*one exposed container"): + build_create_request( + artifact, + target_id="aws-k3s-lab", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + ) + def test_recovers_workload_id_and_cleans_up_incomplete_create_result(self): self.start_server() RuntimeHandler.create_result = None @@ -725,7 +758,7 @@ def test_recovers_workload_id_and_cleans_up_incomplete_create_result(self): team_id=TEAM_ID, poll_interval=0, timeout=0.01, - cleanup_timeout=0.05, + cleanup_timeout=1, ) methods = [(method, path) for method, path, _headers, _body in RuntimeHandler.requests] diff --git a/tests/test_validate_info_spec.py b/tests/test_validate_info_spec.py index 75e1f56..6317189 100644 --- a/tests/test_validate_info_spec.py +++ b/tests/test_validate_info_spec.py @@ -78,6 +78,16 @@ def test_rejects_public_pwn_container_with_multiple_ports(self): with self.assertRaisesRegex(ValueError, "PWN.*one port"): self._validate_raw(raw) + def test_rejects_multiple_public_pwn_containers(self): + raw = self._raw_fixture() + raw["category"] = "pwn" + raw["deployment"]["containers"][0]["ports"] = [8080] + raw["deployment"]["healthcheck"]["port"] = 8080 + raw["deployment"]["containers"][1]["expose"] = True + + with self.assertRaisesRegex(ValueError, "PWN.*one exposed container"): + self._validate_raw(raw) + def test_accepts_declared_internal_connection(self): raw = self._raw_fixture() raw["deployment"]["internal_connections"] = [ From f5679bfe1ac55931885480117fed35188a245a97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Mon, 14 Sep 2026 00:36:37 +0900 Subject: [PATCH 13/13] =?UTF-8?q?=ED=8F=90=EA=B8=B0=EB=90=9C=20Runtime=20?= =?UTF-8?q?=EC=97=B0=EB=8F=99=20=EA=B3=84=ED=9A=8D=20=EB=AC=B8=EC=84=9C=20?= =?UTF-8?q?=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...09-07-runtime-exposed-ports-integration.md | 215 ------------------ 1 file changed, 215 deletions(-) delete mode 100644 docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md diff --git a/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md b/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md deleted file mode 100644 index 19158e7..0000000 --- a/docs/superpowers/plans/2026-09-07-runtime-exposed-ports-integration.md +++ /dev/null @@ -1,215 +0,0 @@ -# Runtime Exposed Ports Integration Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** `artifact-v2.json`의 포트별 공개 정보를 Runtime PR #39의 `ports`와 `exposed_ports` 요청 계약으로 손실 없이 변환하고 검증한다. - -**Architecture:** Backend가 소비하는 publish bundle 형식은 변경하지 않는다. `runtime_api_smoke_runner.py`가 bundle 경계에서 전체 포트와 공개 포트를 분리해 Runtime 요청을 만들고, 기존 endpoint 집합 검증과 cleanup을 유지한다. 실제 K3s 호출은 service token을 받은 뒤 별도 실행한다. - -**Tech Stack:** Python 3 표준 라이브러리, `unittest`, GitHub Actions, Secure Provisioner HTTP API. - -**Spec:** `docs/superpowers/specs/2026-09-07-runtime-exposed-ports-integration-design.md` - -## Global Constraints - -- Runtime 요청의 한 컨테이너에는 `expose`와 `exposed_ports`를 함께 보내지 않는다. -- Runtime 요청의 `ports`는 전체 포트이며 `exposed_ports`는 public 포트 부분집합이다. -- `artifact-v2.json`의 `ports[].public` 형식은 유지한다. -- `target_id`는 bundle에 넣지 않고 workflow 입력으로 전달한다. -- Runtime과 Backend 저장소 코드는 수정하지 않는다. -- 실제 service token이 없으므로 K3s 실행을 완료로 표시하지 않는다. - ---- - -### Task 1: Runtime 요청 포트 변환 - -**Files:** -- Modify: `tests/test_runtime_api_smoke_runner.py` -- Modify: `scripts/runtime_api_smoke_runner.py` - -**Interfaces:** -- Consumes: `build_create_request(artifact, target_id, instance_id, team_id)`와 bundle의 `workload.containers[].ports[]`. -- Produces: Runtime 컨테이너 `{name, image, ports, exposed_ports, run_as_user}`. - -- [x] **Step 1: 혼합 포트와 private 컨테이너의 실패 테스트 작성** - - 기존 request 예상값에서 `expose`를 제거하고 `exposed_ports`를 요구한다. 별도 테스트는 - 같은 컨테이너의 `8080 public`, `9000 private`가 - `ports: [8080, 9000]`, `exposed_ports: [8080]`로 변환되는지 확인한다. private DB는 - `exposed_ports: []`를 확인한다. - -- [x] **Step 2: 테스트 실패 확인** - - Run: `python3 -m unittest tests.test_runtime_api_smoke_runner.RuntimeApiSmokeRunnerTests.test_builds_runtime_team_multi_container_contract tests.test_runtime_api_smoke_runner.RuntimeApiSmokeRunnerTests.test_builds_mixed_public_private_ports_with_exposed_ports -v` - - Expected: 기존 구현이 `expose`를 반환하고 혼합 포트를 거절해 FAIL. - -- [x] **Step 3: 최소 변환 구현** - - `public_values`와 혼합 포트 거절을 제거한다. 각 port object를 검증하면서 전체 `ports`와 - `public: true`인 `exposed_ports`를 따로 누적하고 Runtime container에 두 배열을 넣는다. - workload 전체 공개 여부는 `bool(exposed_ports)`로 계산한다. - -- [x] **Step 4: 대상 테스트 통과 확인** - - Run: `python3 -m unittest tests.test_runtime_api_smoke_runner.RuntimeApiSmokeRunnerTests.test_builds_runtime_team_multi_container_contract tests.test_runtime_api_smoke_runner.RuntimeApiSmokeRunnerTests.test_builds_mixed_public_private_ports_with_exposed_ports -v` - - Expected: PASS. - -- [x] **Step 5: 포트 변환 변경 커밋** - - ```bash - git add scripts/runtime_api_smoke_runner.py tests/test_runtime_api_smoke_runner.py - git commit -m "Runtime exposed_ports 계약 반영" - ``` - -### Task 2: 연결 정보와 endpoint 회귀 검증 - -**Files:** -- Modify: `tests/test_runtime_api_smoke_runner.py` - -**Interfaces:** -- Consumes: Task 1의 Runtime request와 기존 `run_smoke` endpoint 검증. -- Produces: `web -> db:5432/TCP`가 유지되고 공개 endpoint만 기대하는 회귀 테스트. - -- [x] **Step 1: web과 db의 실제 계약 테스트 작성** - - web은 `8080 public`, `9000 private`, db는 `5432 private`로 구성하고 - `web -> db:5432/TCP`를 넣는다. 생성 요청에서 `expose`가 어느 컨테이너에도 없고, - web `exposed_ports == [8080]`, db `exposed_ports == []`, 연결 배열이 원형 보존되는지 - 확인한다. - -- [x] **Step 2: endpoint 누락·추가·중복 실패 테스트 작성** - - 현재 runner가 endpoint 배열이 비어 있지 않은지만 검사하는 반례를 먼저 재현한다. - artifact의 공개 `(container_name, port)` 집합과 Runtime 응답의 집합이 다르거나, - endpoint 항목이 중복되면 cleanup 후 실패하는 테스트를 추가한다. - -- [x] **Step 3: endpoint 정확 일치 검증 구현** - - request의 `exposed_ports`에서 예상 집합을 만들고 Runtime 응답 각 항목의 필수 필드와 - 중복을 검증한다. 실제 집합이 예상 집합과 다르면 cleanup 후 오류를 반환한다. - -- [x] **Step 4: Runtime smoke runner 테스트 실행** - - Run: `python3 -m unittest tests.test_runtime_api_smoke_runner -v` - - Expected: 모든 Runtime smoke runner 테스트 PASS. endpoint 불일치 테스트는 내부적으로 - 오류와 cleanup을 기대하므로 테스트 자체는 PASS. - -- [x] **Step 5: 회귀 테스트 커밋** - - ```bash - git add tests/test_runtime_api_smoke_runner.py - git commit -m "Runtime 멀티 컨테이너 연결 회귀 검증" - ``` - -### Task 3: 운영 문서와 target 계약 정리 - -**Files:** -- Modify: `docs/aws-k3s-cd-smoke.md` -- Modify: PR #6 description after push. - -**Interfaces:** -- Consumes: Runtime PR #39의 `exposed_ports` 계약과 운영 target `aws-k3s-lab`. -- Produces: 토큰 준비 전후를 구분한 실행 안내. - -- [x] **Step 1: 문서 수정** - - caller 예시의 `runtime_target_id`를 `aws-k3s-lab`으로 바꾼다. 혼합 포트 거절 제약을 - 제거하고 `ports[].public`이 Runtime `exposed_ports`로 변환되며 `expose`를 보내지 - 않는다고 설명한다. service token 미수령으로 실제 K3s smoke가 미실행임을 명시한다. - -- [x] **Step 2: 문서 계약 검사** - - Run: `rg -n "aws-k3s-lab|exposed_ports|실제 K3s" docs/aws-k3s-cd-smoke.md` - - Expected: 세 계약이 문서에 존재하며 기존 “혼합 포트 거절” 설명은 없음. - -- [x] **Step 3: 문서 커밋** - - ```bash - git add docs/aws-k3s-cd-smoke.md - git commit -m "Runtime 포트별 공개 smoke 문서화" - ``` - -### Task 4: 전체 검증과 PR #6 갱신 - -**Files:** -- Verify: `scripts/*.py` -- Verify: `tests/` -- Update: `MSG-CTF/msgctf-devsecops` PR #6 metadata. - -**Interfaces:** -- Consumes: Tasks 1-3의 코드·테스트·문서. -- Produces: 검증된 PR #6 커밋과 정확한 미완료 항목. - -- [x] **Step 1: 전체 단위 테스트 실행** - - Run: `python3 -W error::ResourceWarning -m unittest discover -s tests -v` - - Expected: PASS. - -- [x] **Step 2: 정적 검증 실행** - - Run: `python3 -m py_compile scripts/*.py` - - Run: `git diff --check` - - Run: `gitleaks detect --source . --no-banner --redact --exit-code 1` - - Expected: 모두 exit code 0. - -- [x] **Step 3: 브랜치 push** - - Run: `git push msg-ctf runtime-smoke-evidence` - - Expected: PR #6 head가 새 커밋으로 갱신됨. - -- [x] **Step 4: PR 설명과 댓글 갱신** - - PR #6에 Runtime PR #39 계약 반영, `target_id=aws-k3s-lab`, Backend PR #62 호환, - service token 미수령 때문에 실제 K3s smoke는 남아 있다는 사실을 기록한다. - -- [x] **Step 5: GitHub Actions 결과 확인** - - Run: `gh pr checks 6 --repo MSG-CTF/msgctf-devsecops --watch` - - Expected: 실행된 check PASS. 실제 K3s smoke는 token과 배포 환경이 없으면 실행하지 - 않았다고 구분해 기록한다. - -### Task 5: 독립 코드리뷰 보완 - -**Files:** -- Modify: `scripts/runtime_api_smoke_runner.py` -- Modify: `scripts/validate_info_spec.py` -- Modify: `tests/test_runtime_api_smoke_runner.py` -- Modify: `tests/test_validate_info_spec.py` -- Modify: `docs/aws-k3s-cd-smoke.md` -- Modify: `docs/devsecops-runbook.md` -- Modify: `docs/superpowers/specs/2026-09-07-runtime-exposed-ports-integration-design.md` - -**Interfaces:** -- Consumes: Runtime PR #39 OpenAPI의 endpoint schema, PWN 포트 제한, runtime-status 조회. -- Produces: 잘못된 Runtime 응답 차단, PWN 조기 차단, 불완전 create 결과 cleanup 복구. - -- [x] **Step 1: 실패 테스트 작성과 RED 확인** - - 잘못된 endpoint protocol·URI·추가 필드, 공개 PWN 컨테이너 다중 포트, - runtime-status를 통한 `runtime_workload_id` 복구 후 cleanup 완료를 테스트한다. - -- [x] **Step 2: 최소 구현과 GREEN 확인** - - endpoint의 정확한 키·`HTTP|TCP`·URI를 검사한다. PWN 공개 컨테이너는 전체 포트가 - 정확히 하나인지 info 검증과 Runtime 변환 경계에서 확인한다. create operation 결과가 - 불완전하면 runtime-status에서 workload ID를 복구해 삭제한다. - -- [x] **Step 3: cleanup 완료와 token 문서 계약 보완** - - endpoint 오류 테스트에서 delete operation 조회 완료까지 확인한다. service token은 - GitHub Secret이 아니라 Runtime node의 `/etc/secure-provisioner/service-token`에서만 - 읽는 것으로 설계·운영 문서를 통일하고 기존 `expose` 설명을 갱신한다. - -- [x] **Step 4: 전체 검증과 커밋** - - 76개 이상의 전체 테스트, Python 문법, diff, Gitleaks 검사를 통과한 뒤 커밋한다.