From a66e7e5d0cdaca2d1acaddd0ea3911f4fc8e3840 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Tue, 1 Sep 2026 18:13:14 +0900 Subject: [PATCH 1/8] =?UTF-8?q?Challenge=20Registry=20publish=20bundle=20?= =?UTF-8?q?=EA=B3=84=EC=95=BD=20=EA=B0=95=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 19 ++++- ci/README.md | 17 +++- docs/README.md | 5 ++ docs/challenge-registry-integration.md | 92 ++++++++++++++++++++++ docs/devsecops-runbook.md | 9 ++- scripts/README.md | 10 ++- scripts/generate_publish_bundle.py | 31 +++++++- scripts/render_publish_summary.py | 33 +++++++- scripts/runtime_api_smoke_runner.py | 45 ++++++++++- scripts/validate_info_spec.py | 70 +++++++++++++++++ tests/test_generate_publish_bundle.py | 74 ++++++++++++++--- tests/test_render_publish_summary.py | 71 +++++++++++++++++ tests/test_runtime_api_smoke_runner.py | 31 ++++++++ tests/test_validate_info_spec.py | 105 +++++++++++++++++++++++++ 14 files changed, 577 insertions(+), 35 deletions(-) create mode 100644 docs/challenge-registry-integration.md diff --git a/README.md b/README.md index 0a946a5..75b49f8 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,11 @@ deployment: image: postgres:16 ports: [5432] expose: false + internal_connections: + - source_container: web + destination_container: db + protocol: TCP + port: 5432 healthcheck: container: web port: 9090 @@ -103,6 +108,11 @@ deployment: - `build`는 문제 디렉터리 내부의 Docker build context만 가리킬 수 있습니다. - 외부 `image`는 `latest`나 암묵적 tag를 사용할 수 없으며 명시적 non-latest tag 또는 digest가 필요합니다. - `expose: true`인 컨테이너의 포트만 참가자에게 공개합니다. +- 컨테이너 간 통신은 `internal_connections`에 TCP 방향과 목적지 포트를 + 명시합니다. 선언하지 않은 통신은 Runtime NetworkPolicy가 차단합니다. +- 출제자는 raw Kubernetes `NetworkPolicy`를 입력하지 않습니다. CI는 문제 + category를 `WEB` 또는 `PWN` `isolation_profile`로 정규화하고 Runtime이 + 승인된 정책을 생성합니다. - `resource_profile`은 문제의 모든 컨테이너를 합산한 값입니다. - `flag`는 존재 여부만 검증하며 로그, output, artifact에 기록하지 않습니다. - `deployment`가 없는 정적 문제는 Docker build와 image 발행을 수행하지 않습니다. @@ -182,7 +192,7 @@ GitHub runner 대기 시간과 job 준비 시간은 포함하지 않습니다. 최종 image 경로: ```text -ghcr.io//challenges//@sha256: +ghcr.io/msg-ctf/challenges//@sha256: ``` `latest`는 생성하지 않습니다. @@ -196,7 +206,7 @@ ghcr.io//challenges//@sha256: healthcheck 포트와 `resource_profile`을 검증한 뒤 다음 경로로 발행합니다. ```text -ghcr.io//challenges//service@sha256: +ghcr.io/msg-ctf/challenges//service@sha256: ``` `prob/for_organizer/docker-compose.yml`은 출제자 로컬 테스트용입니다. GHCR에는 @@ -207,6 +217,11 @@ ghcr.io//challenges//service@sha256: `artifact-v2.json`은 Runtime이 읽을 digest workload입니다. `registry-publish.json`은 Challenge Registry의 원자적 revision 등록 API가 소비할 자료입니다. +두 파일에는 `revision`과 같은 값인 `registry_revision`, `isolation_profile`, +`workload.containers[]`가 포함됩니다. 모든 최종 image는 +`ghcr.io/msg-ctf/challenges//@sha256:` 형식만 허용하며 +tag와 `latest`는 발행 자료 생성 단계에서 거절합니다. + 발행 조건: - 모든 container image가 존재합니다. diff --git a/ci/README.md b/ci/README.md index a4079e5..6fbb531 100644 --- a/ci/README.md +++ b/ci/README.md @@ -31,6 +31,9 @@ DevSecOps는 참가자 instance scheduling, target 선택, Kubernetes manifest - Dockerfile 존재 여부 - port 범위 - healthcheck container·port·path +- 문제 category에서 결정한 `WEB | PWN` isolation profile +- `internal_connections`의 source·destination·TCP 목적지 포트 +- raw Kubernetes NetworkPolicy 입력 금지 - CPU, memory, ephemeral storage 값 검증 결과에는 `flag`가 포함되지 않습니다. @@ -65,13 +68,13 @@ Git 이력에서 secret이 발견되면 해당 credential을 폐기·회전하 검사 통과 image만 다음 경로로 push합니다. ```text -ghcr.io//challenges//:-- +ghcr.io/msg-ctf/challenges//:-- ``` Runtime에 전달하는 값은 다음과 같습니다. ```text -ghcr.io//challenges//@sha256: +ghcr.io/msg-ctf/challenges//@sha256: ``` commit tag는 추적과 발행을 위한 입력이고 Runtime 계약은 digest입니다. `latest`는 만들지 않습니다. @@ -90,6 +93,11 @@ KOTH 문제도 같은 규칙을 사용합니다. `info.yaml`의 `deployment.cont - `artifact-v2.json`: Runtime과 Scheduler가 읽을 immutable workload - `registry-publish.json`: Challenge Registry가 한 transaction으로 revision을 추가하고 active를 전환할 요청 +두 파일은 같은 `registry_revision`, `isolation_profile`과 +`workload.containers[]`를 보존합니다. `workload.internal_connections[]`가 있으면 +Runtime은 선언된 방향과 포트만 허용하는 NetworkPolicy를 생성합니다. CI는 raw +NetworkPolicy를 생성하거나 전달하지 않습니다. + Registry는 기존 active revision을 먼저 해제한 뒤 새 row를 쓰는 방식으로 처리하면 안 됩니다. 새 revision 저장과 active 전환이 하나의 transaction에서 성공해야 합니다. 실패하면 기존 active revision을 유지해야 합니다. 실행 중 instance가 참조하는 revision은 active가 아니더라도 보존합니다. @@ -122,7 +130,10 @@ DevSecOps가 검증한 다음 필드를 그대로 사용합니다. ### Runtime 및 격리보안 -DevSecOps는 `workload.containers[]`, `ports[].public`, `healthcheck`, `resource_profile`을 전달합니다. Runtime은 이를 이용해 Namespace, Pod, Service, Gateway, NetworkPolicy, SecurityContext와 cleanup을 구현합니다. +DevSecOps는 `isolation_profile`, `workload.containers[]`, `ports[].public`, +`workload.internal_connections[]`, `healthcheck`, `resource_profile`을 전달합니다. +Runtime은 이를 이용해 Namespace, Pod, Service, Gateway, NetworkPolicy, +SecurityContext와 cleanup을 구현합니다. 발행 후 smoke test는 SSM으로 Runtime node 안의 Secure Provisioner API를 호출해 생성과 삭제 Operation이 모두 성공하는지만 확인합니다. diff --git a/docs/README.md b/docs/README.md index 677dc8b..686ce5f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,3 +18,8 @@ Monitoring 팀과 맞춰야 할 계약도 포함합니다. 현재 GitHub 기준의 문제 저장소, Broker, Scheduler, Runtime, Monitoring 연동 상태와 미확정 항목도 기록합니다. + +### `challenge-registry-integration.md` + +실제 GitHub Actions publish bundle을 백엔드 Challenge Registry 기능 브랜치에 +등록한 통합 검증 증거와 운영 연결 전 남은 조건을 기록합니다. diff --git a/docs/challenge-registry-integration.md b/docs/challenge-registry-integration.md new file mode 100644 index 0000000..8e6d97c --- /dev/null +++ b/docs/challenge-registry-integration.md @@ -0,0 +1,92 @@ +# Challenge Registry 통합 검증 + +## 검증 범위 + +2026년 8월 31일, 실제 GitHub Actions 성공 실행의 이미지 발행 결과를 입력으로 +이번 브랜치의 generator가 publish bundle 후보를 다시 생성했고, 이를 백엔드 +PR #26의 Challenge Registry API에 등록했습니다. 운영 서버와 운영 DB는 사용하지 +않았으며 PR #26 commit `fdba92d`를 SQLite 데모 설정으로 실행했습니다. + +## 입력 증거 + +- DevSecOps Actions run: `32959545593` +- source commit: `8cf8892588ca43fab2fd57c16d32b8791cac6b8b` +- 원본 artifact: `info-valid-32959545593-1-96109d17d15a4df6b2d1db5a4f4921be-publish-bundle` +- `challenge_slug`: `info-valid` +- 원본 `revision`: `19` +- `scan_result`: `PASS` + +원본 Actions artifact는 현재 `main` 코드로 생성돼 `registry_revision`과 +`isolation_profile`이 없었습니다. 이번 브랜치의 generator로 원본 metadata, +container results, SBOM과 동일한 image digest를 사용해 후보 bundle을 재생성했고, +그 후보에 `registry_revision: 19`와 `isolation_profile: WEB`이 추가됐습니다. +따라서 아래 등록 결과는 새 계약의 로컬 호환성 증거이며 새 계약이 Actions +`main`에서 이미 발행됐다는 뜻은 아닙니다. + +컨테이너는 다음 digest로 고정됐습니다. + +```text +ghcr.io/msg-ctf/challenges/info-valid/web@sha256:3f9a465ff4ca0d25db1a415f384576b1b0832ca681fbf03e2b575f24859b3ef0 +ghcr.io/msg-ctf/challenges/info-valid/helper@sha256:dcb7908ca45b38f72f3f3a41023a52ef6972be007b793dd2606b97018c017f1e +``` + +두 이미지는 GHCR push를 성공한 Actions publish 결과입니다. 로컬 GitHub token은 +private package read 권한이 없어 별도 manifest 재조회는 HTTP 401로 거절됐으며, +이 검증은 K3s cold pull 성공 증거로 사용하지 않습니다. + +## 등록 결과 + +PR #26의 현재 등록 endpoint는 최종 `registry-publish.json` 계약보다 오래된 +`{"artifact": , "note": ...}` 요청 형식을 사용합니다. 따라서 로컬 +호환성 검증에서는 재생성한 후보의 `artifact-v2`를 이 wrapper에 넣어 등록했습니다. +현재 workflow가 전송하는 `registry-publish.json` 전체 요청은 백엔드 최종 endpoint가 +병합·배포된 뒤 별도로 검증해야 합니다. + +로컬 Registry API는 다음 결과를 반환했습니다. + +```json +{ + "code": "SUCCESS", + "release_id": "1107b1f1-90e9-4467-9605-b45b86920412", + "version": 1, + "registry_revision": 19, + "challenge_slug": "info-valid", + "container_count": 2, + "is_current": false, + "is_deployable": false +} +``` + +조회 API와 DB를 다시 확인한 결과 `challenge_releases`에 revision 한 행, +`release_containers`에 `web`과 `helper` 두 행이 저장됐습니다. 각 컨테이너의 +digest와 `ports[].public`도 입력 bundle과 일치했습니다. + +`is_deployable: false`는 등록 실패가 아닙니다. PR #26의 기존 Scheduler 게이트가 +멀티 컨테이너 또는 여러 public 포트를 활성화하지 못하도록 제한하기 때문입니다. + +## NetworkPolicy 경계 + +publish bundle은 raw Kubernetes NetworkPolicy를 포함하지 않습니다. 다음 의도만 +전달합니다. + +- `isolation_profile`: `WEB | PWN` +- `workload.containers[]` +- `ports[].public` +- 선택형 `workload.internal_connections[]` + +Runtime/Secure Provisioner는 이 값으로 default-deny, DNS, public ingress와 선언된 +컨테이너 간 TCP 통신 정책을 생성합니다. 출제자와 CI는 임의 egress 또는 Kubernetes +NetworkPolicy를 주입할 수 없습니다. + +## 운영 연결 전 남은 조건 + +- 백엔드 Registry 구현의 `main` 병합과 배포 +- DevSecOps service Bearer token 발급 +- `registry-publish.json` 전체 요청과 `Idempotency-Key` 계약 반영 +- revision 등록과 active 전환의 단일 transaction 처리 +- 멀티 컨테이너 Scheduler 계약과 Registry 모델 통합 +- 운영 endpoint에서 GitHub Actions 실제 전송 재검증 + +따라서 이번 결과는 실제 Actions 이미지 발행 결과로 재생성한 publish bundle +후보의 **로컬 Challenge Registry 등록 성공** 증거이며, 운영 Challenge Registry +연결 완료 증거는 아닙니다. diff --git a/docs/devsecops-runbook.md b/docs/devsecops-runbook.md index 983269b..4ca3689 100644 --- a/docs/devsecops-runbook.md +++ b/docs/devsecops-runbook.md @@ -94,10 +94,11 @@ Backend API는 `registry-publish.json` 전체를 요청 body로 받고, Bearer t 하나의 transaction으로 처리해야 합니다. API URL 또는 token이 없거나 API가 오류를 반환하면 Registry 등록 job이 실패합니다. -Backend `main`에는 아직 Challenge Registry 등록 API와 revision 모델이 없습니다. -endpoint, Bearer token과 transaction 구현이 들어오기 전에는 -`publish_registry: false`를 유지합니다. 이 상태에서도 GHCR push, digest 추출, -SBOM과 publish bundle 생성은 정상 수행됩니다. +Backend PR #26 기능 브랜치에는 Challenge Registry 등록·조회 API와 revision +모델이 있으며 실제 Actions bundle의 로컬 등록을 확인했습니다. 다만 `main` +병합과 운영 배포, service Bearer token, `Idempotency-Key`, 원자적 active 전환 +계약은 아직 완료되지 않았으므로 운영 caller는 `publish_registry: false`를 +유지합니다. 검증 증거는 `docs/challenge-registry-integration.md`에 기록합니다. ## Secure Provisioner K3s 연결 diff --git a/scripts/README.md b/scripts/README.md index d8524a2..cab1fe2 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -17,8 +17,10 @@ Git 변경 내역에서 `info.yaml`이 있는 문제 디렉터리를 찾아 검 ### `validate_info_spec.py` `info.yaml`, 컨테이너 정의, Docker build context, architecture, port, -healthcheck, resource profile을 검증합니다. 검증 결과에서는 flag를 -제거하고 build matrix와 정규화된 metadata를 생성합니다. +healthcheck, resource profile과 `internal_connections`를 검증합니다. 문제 +category는 신뢰된 `WEB | PWN` isolation profile로 정규화하며 raw Kubernetes +NetworkPolicy 입력은 거절합니다. 검증 결과에서는 flag를 제거하고 build +matrix와 정규화된 metadata를 생성합니다. ### `generate_publish_bundle.py` @@ -28,6 +30,10 @@ healthcheck, resource profile을 검증합니다. 검증 결과에서는 flag를 - `artifact-v2.json`: Runtime과 Scheduler가 사용할 immutable workload - `registry-publish.json`: Challenge Registry revision 등록 요청 자료 +두 자료에는 같은 `registry_revision`, digest 고정 `workload.containers[]`와 +`isolation_profile`이 포함됩니다. tag, `latest`, MSG-CTF GHCR 밖의 최종 image는 +거절합니다. 선언된 `internal_connections`는 workload에 그대로 보존합니다. + 컨테이너별 공급망 소요 시간을 검증해 `artifact-v2.json`의 `evidence.containers[].timing`에 보존합니다. diff --git a/scripts/generate_publish_bundle.py b/scripts/generate_publish_bundle.py index 6a41021..bf0bff7 100644 --- a/scripts/generate_publish_bundle.py +++ b/scripts/generate_publish_bundle.py @@ -6,8 +6,10 @@ DIGEST = re.compile(r"^sha256:[0-9a-f]{64}$") -DIGEST_IMAGE = re.compile( - r"^[a-z0-9][a-z0-9._:-]*(?:/[a-z0-9][a-z0-9._-]*)+" +MSGCTF_GHCR_DIGEST_IMAGE = re.compile( + r"^ghcr\.io/msg-ctf/challenges/" + r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/" + r"[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?" r"@sha256:[0-9a-f]{64}$" ) TIMING_FIELDS = ( @@ -87,8 +89,17 @@ def _validated_results(metadata, results, evidence_root): for name in expected: result = by_name[name] image = _clean_string(result.get("image"), f"{name}.image") - if not DIGEST_IMAGE.fullmatch(image): - raise ValueError(f"{name}.image must be digest-pinned") + if not MSGCTF_GHCR_DIGEST_IMAGE.fullmatch(image): + raise ValueError( + f"{name}.image must be a digest-pinned MSG-CTF GHCR digest image" + ) + expected_repository = ( + f"ghcr.io/msg-ctf/challenges/{metadata['challenge_slug']}/{name}" + ) + if not image.startswith(f"{expected_repository}@sha256:"): + raise ValueError( + f"{name}.image must use expected GHCR repository {expected_repository}" + ) source_digest = _clean_string( result.get("source_digest"), f"{name}.source_digest", @@ -122,6 +133,10 @@ def generate_bundle(metadata, results, source_ref, revision, evidence_root): raise ValueError("revision must be a positive integer") source_ref = _clean_string(source_ref, "source_ref") validated_results = _validated_results(metadata, results, evidence_root) + expected_profile = "PWN" if metadata.get("category") == "pwn" else "WEB" + isolation_profile = metadata.get("isolation_profile", expected_profile) + if isolation_profile != expected_profile: + raise ValueError("isolation_profile must match the challenge category") workload_containers = [] evidence_containers = [] @@ -150,6 +165,8 @@ def generate_bundle(metadata, results, source_ref, revision, evidence_root): ) workload = {"containers": workload_containers} + if metadata.get("internal_connections"): + workload["internal_connections"] = metadata["internal_connections"] if "healthcheck" in metadata: workload["healthcheck"] = metadata["healthcheck"] @@ -157,10 +174,12 @@ def generate_bundle(metadata, results, source_ref, revision, evidence_root): "schema_version": "2.0", "challenge_slug": metadata["challenge_slug"], "revision": revision, + "registry_revision": revision, "name": metadata["name"], "category": metadata["category"], "runtime_type": metadata["runtime_type"], "architecture": metadata["architecture"], + "isolation_profile": isolation_profile, "workload": workload, "resource_profile": metadata["resource_profile"], "source_ref": source_ref, @@ -172,11 +191,13 @@ def generate_bundle(metadata, results, source_ref, revision, evidence_root): "operation": "publish_revision", "challenge_slug": metadata["challenge_slug"], "revision": revision, + "registry_revision": revision, "activate": True, "name": metadata["name"], "category": metadata["category"], "runtime_type": metadata["runtime_type"], "architecture": metadata["architecture"], + "isolation_profile": isolation_profile, "workload": workload, "resource_profile": metadata["resource_profile"], "source_ref": source_ref, @@ -234,6 +255,8 @@ def main(): { "challenge_slug": bundle["artifact"]["challenge_slug"], "revision": bundle["artifact"]["revision"], + "registry_revision": bundle["artifact"]["registry_revision"], + "isolation_profile": bundle["artifact"]["isolation_profile"], "container_count": len( bundle["artifact"]["workload"]["containers"] ), diff --git a/scripts/render_publish_summary.py b/scripts/render_publish_summary.py index c489f20..40e76a5 100644 --- a/scripts/render_publish_summary.py +++ b/scripts/render_publish_summary.py @@ -5,8 +5,10 @@ from pathlib import Path -DIGEST_IMAGE = re.compile( - r"^[a-z0-9][a-z0-9._:-]*(?:/[a-z0-9][a-z0-9._-]*)+" +MSGCTF_GHCR_DIGEST_IMAGE = re.compile( + r"^ghcr\.io/msg-ctf/challenges/" + r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/" + r"[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?" r"@sha256:[0-9a-f]{64}$" ) @@ -50,6 +52,20 @@ def render_summary(artifact, bundle_name): revision = artifact.get("revision") if isinstance(revision, bool) or not isinstance(revision, int) or revision <= 0: raise ValueError("revision must be a positive integer") + registry_revision = artifact.get("registry_revision") + if ( + isinstance(registry_revision, bool) + or not isinstance(registry_revision, int) + or registry_revision <= 0 + ): + raise ValueError("registry_revision must be a positive integer") + if registry_revision != revision: + raise ValueError("registry_revision must equal revision") + category = _required_string(artifact.get("category"), "category").lower() + expected_profile = "PWN" if category == "pwn" else "WEB" + isolation_profile = artifact.get("isolation_profile") + if isolation_profile != expected_profile: + raise ValueError("isolation_profile must match the challenge category") if artifact.get("scan_result") != "PASS": raise ValueError("scan_result must be PASS") @@ -65,8 +81,15 @@ def render_summary(artifact, bundle_name): raise ValueError("each container must be an object") name = _required_string(container.get("name"), "container.name") image = _required_string(container.get("image"), f"{name}.image") - if not DIGEST_IMAGE.fullmatch(image): - raise ValueError(f"{name}.image must be digest-pinned") + if not MSGCTF_GHCR_DIGEST_IMAGE.fullmatch(image): + raise ValueError( + f"{name}.image must be a digest-pinned MSG-CTF GHCR image" + ) + expected_repository = f"ghcr.io/msg-ctf/challenges/{challenge_slug}/{name}" + if not image.startswith(f"{expected_repository}@sha256:"): + raise ValueError( + f"{name}.image must use expected GHCR repository {expected_repository}" + ) repository, digest = image.rsplit("@", 1) container_names.append(name) rows.append(f"| {name} | `{repository}` | `{digest}` |") @@ -82,6 +105,8 @@ def render_summary(artifact, bundle_name): "", f"- 문제: `{challenge_slug}`", f"- revision: `{revision}`", + f"- registry revision: `{registry_revision}`", + f"- 격리 프로파일: `{isolation_profile}`", "- 보안 검사: `PASS`", f"- Actions artifact: `{bundle_name}` (90일 보관)", "", diff --git a/scripts/runtime_api_smoke_runner.py b/scripts/runtime_api_smoke_runner.py index a9367fe..7e69ea5 100644 --- a/scripts/runtime_api_smoke_runner.py +++ b/scripts/runtime_api_smoke_runner.py @@ -118,6 +118,46 @@ def build_create_request( if not exposed: raise ValueError("Runtime smoke deployment requires at least one exposed container") + runtime_workload = {"containers": runtime_containers} + internal_connections = workload.get("internal_connections") + if internal_connections is not None: + if not isinstance(internal_connections, list): + raise ValueError("workload.internal_connections must be a list") + ports_by_container = { + container["name"]: set(container["ports"]) + for container in runtime_containers + } + normalized_connections = [] + seen_connections = set() + for connection in internal_connections: + if not isinstance(connection, dict): + raise ValueError("each internal connection must be an object") + source = connection.get("source_container") + destination = connection.get("destination_container") + protocol = connection.get("protocol") + port = _positive_int(connection.get("port"), "internal connection port") + if source not in ports_by_container or destination not in ports_by_container: + raise ValueError("internal connection must reference declared containers") + if source == destination: + raise ValueError("internal connection containers must be different") + if protocol != "TCP": + raise ValueError("internal connection protocol must be TCP") + if port not in ports_by_container[destination]: + raise ValueError("internal connection port must be declared by destination") + key = (source, destination, protocol, port) + if key in seen_connections: + raise ValueError("internal connections must be unique") + seen_connections.add(key) + normalized_connections.append( + { + "source_container": source, + "destination_container": destination, + "protocol": protocol, + "port": port, + } + ) + runtime_workload["internal_connections"] = normalized_connections + resource_profile = artifact.get("resource_profile") if not isinstance(resource_profile, dict): raise ValueError("artifact resource_profile must be an object") @@ -137,10 +177,7 @@ def build_create_request( "team_id": normalized_team_id, "isolation_profile": _isolation_profile(artifact.get("category")), "target": {"runtime_type": "KUBERNETES", "target_id": target_id.strip()}, - "workload": { - "containers": runtime_containers, - "resource_limits": resource_limits, - }, + "workload": {**runtime_workload, "resource_limits": resource_limits}, } diff --git a/scripts/validate_info_spec.py b/scripts/validate_info_spec.py index 4a45e29..e9fdd50 100644 --- a/scripts/validate_info_spec.py +++ b/scripts/validate_info_spec.py @@ -122,6 +122,52 @@ def _validate_healthcheck(raw, containers): return {"container": container_name, "port": port, "path": path} +def _validate_internal_connections(raw, containers): + if raw is None: + return [] + if not isinstance(raw, list): + raise ValueError("deployment.internal_connections must be a list") + + by_name = {container["name"]: container for container in containers} + connections = [] + seen = set() + for entry in raw: + if not isinstance(entry, dict): + raise ValueError("each internal connection must be an object") + source = _required_string( + entry.get("source_container"), + "internal_connections.source_container", + ) + destination = _required_string( + entry.get("destination_container"), + "internal_connections.destination_container", + ) + if source not in by_name or destination not in by_name: + raise ValueError("internal connection must reference declared containers") + if source == destination: + raise ValueError("internal connection containers must be different") + if entry.get("protocol") != "TCP": + raise ValueError("internal connection protocol must be TCP") + port = _positive_int(entry.get("port"), "internal_connections.port") + if port > 65535 or port not in by_name[destination]["ports"]: + raise ValueError( + "internal connection port must reference a destination container port" + ) + key = (source, destination, "TCP", port) + if key in seen: + raise ValueError("internal connections must not contain duplicates") + seen.add(key) + connections.append( + { + "source_container": source, + "destination_container": destination, + "protocol": "TCP", + "port": port, + } + ) + return connections + + def validate_spec(challenge_path): challenge_path = Path(challenge_path).resolve() if not challenge_path.is_dir(): @@ -155,6 +201,23 @@ def validate_spec(challenge_path): return metadata if not isinstance(deployment, dict): raise ValueError("deployment must be an object") + allowed_deployment_fields = { + "runtime_type", + "architecture", + "containers", + "resource_profile", + "healthcheck", + "internal_connections", + } + unsupported_fields = sorted(set(deployment) - allowed_deployment_fields) + if "network_policy" in deployment: + raise ValueError( + "raw Kubernetes NetworkPolicy is Runtime-owned and must not be declared" + ) + if unsupported_fields: + raise ValueError( + "deployment contains unsupported fields: " + ", ".join(unsupported_fields) + ) runtime_type = deployment.get("runtime_type") if runtime_type not in RUNTIME_TYPES: raise ValueError("deployment.runtime_type is not supported") @@ -184,9 +247,16 @@ def validate_spec(challenge_path): metadata.update({ "runtime_type": runtime_type, "architecture": architecture, + "isolation_profile": "PWN" if category == "pwn" else "WEB", "containers": containers, "resource_profile": resource_profile, }) + internal_connections = _validate_internal_connections( + deployment.get("internal_connections"), + containers, + ) + if internal_connections: + metadata["internal_connections"] = internal_connections healthcheck = _validate_healthcheck(deployment.get("healthcheck"), containers) if healthcheck: metadata["healthcheck"] = healthcheck diff --git a/tests/test_generate_publish_bundle.py b/tests/test_generate_publish_bundle.py index 6f35854..c46a7d1 100644 --- a/tests/test_generate_publish_bundle.py +++ b/tests/test_generate_publish_bundle.py @@ -75,6 +75,8 @@ def test_generates_runtime_artifact_and_registry_publish_document(self): publish = bundle["registry_publish"] self.assertEqual(artifact["schema_version"], "2.0") self.assertEqual(artifact["revision"], 3) + self.assertEqual(artifact["registry_revision"], 3) + self.assertEqual(artifact["isolation_profile"], "WEB") self.assertEqual( artifact["workload"]["containers"][0]["ports"], [ @@ -91,8 +93,42 @@ def test_generates_runtime_artifact_and_registry_publish_document(self): self.assertEqual(publish["operation"], "publish_revision") self.assertTrue(publish["activate"]) self.assertEqual(publish["revision"], 3) + self.assertEqual(publish["registry_revision"], 3) + self.assertEqual(publish["isolation_profile"], "WEB") self.assertEqual(publish["workload"], artifact["workload"]) + def test_preserves_declared_internal_connections(self): + metadata = dict( + METADATA, + internal_connections=[ + { + "source_container": "web", + "destination_container": "db", + "protocol": "TCP", + "port": 5432, + } + ], + ) + + bundle = generate_bundle(metadata, RESULTS, "abc123", 1, EVIDENCE_ROOT) + + self.assertEqual( + bundle["artifact"]["workload"]["internal_connections"], + metadata["internal_connections"], + ) + self.assertEqual( + bundle["registry_publish"]["workload"]["internal_connections"], + metadata["internal_connections"], + ) + + def test_maps_pwn_category_to_pwn_isolation_profile(self): + metadata = dict(METADATA, category="pwn") + + bundle = generate_bundle(metadata, RESULTS, "abc123", 1, EVIDENCE_ROOT) + + self.assertEqual(bundle["artifact"]["isolation_profile"], "PWN") + self.assertEqual(bundle["registry_publish"]["isolation_profile"], "PWN") + def test_preserves_healthcheck_and_sbom_evidence(self): bundle = generate_bundle(METADATA, RESULTS, "abc123", 1, EVIDENCE_ROOT) @@ -135,7 +171,7 @@ def test_rejects_tag_only_image(self): with self.assertRaisesRegex(ValueError, "digest-pinned"): generate_bundle(METADATA, results, "abc123", 1, EVIDENCE_ROOT) - def test_accepts_digest_image_from_registry_with_port(self): + def test_rejects_digest_image_outside_msg_ctf_ghcr(self): results = [ dict( RESULTS[0], @@ -144,18 +180,32 @@ def test_accepts_digest_image_from_registry_with_port(self): RESULTS[1], ] - bundle = generate_bundle( - METADATA, - results, - "abc123", - 1, - EVIDENCE_ROOT, - ) + with self.assertRaisesRegex(ValueError, "MSG-CTF GHCR digest"): + generate_bundle(METADATA, results, "abc123", 1, EVIDENCE_ROOT) - self.assertEqual( - bundle["artifact"]["workload"]["containers"][0]["image"], - results[0]["image"], - ) + def test_rejects_image_from_another_challenge_repository(self): + results = [ + dict( + RESULTS[0], + image=f"ghcr.io/msg-ctf/challenges/other-challenge/web@{DIGEST_A}", + ), + RESULTS[1], + ] + + with self.assertRaisesRegex(ValueError, "expected GHCR repository"): + generate_bundle(METADATA, results, "abc123", 1, EVIDENCE_ROOT) + + def test_rejects_image_from_another_container_repository(self): + results = [ + dict( + RESULTS[0], + image=f"ghcr.io/msg-ctf/challenges/web-notebook/admin@{DIGEST_A}", + ), + RESULTS[1], + ] + + with self.assertRaisesRegex(ValueError, "expected GHCR repository"): + generate_bundle(METADATA, results, "abc123", 1, EVIDENCE_ROOT) def test_rejects_missing_container_result(self): with self.assertRaisesRegex(ValueError, "result set"): diff --git a/tests/test_render_publish_summary.py b/tests/test_render_publish_summary.py index 104f08d..5af27b4 100644 --- a/tests/test_render_publish_summary.py +++ b/tests/test_render_publish_summary.py @@ -11,7 +11,10 @@ class RenderPublishSummaryTests(unittest.TestCase): def test_renders_digest_images_and_bundle_name(self): artifact = { "challenge_slug": "web-notebook", + "category": "web", "revision": 7, + "registry_revision": 7, + "isolation_profile": "WEB", "scan_result": "PASS", "evidence": { "containers": [ @@ -53,6 +56,8 @@ def test_renders_digest_images_and_bundle_name(self): self.assertIn("# 문제 이미지 발행 결과", summary) self.assertIn("`web-notebook-publish-bundle`", summary) + self.assertIn("registry revision: `7`", summary) + self.assertIn("격리 프로파일: `WEB`", summary) self.assertIn("| web |", summary) self.assertIn(DIGEST_A, summary) self.assertIn("| db |", summary) @@ -63,7 +68,10 @@ def test_renders_digest_images_and_bundle_name(self): def test_rejects_tag_only_image(self): artifact = { "challenge_slug": "web-notebook", + "category": "web", "revision": 7, + "registry_revision": 7, + "isolation_profile": "WEB", "scan_result": "PASS", "workload": { "containers": [ @@ -78,6 +86,69 @@ def test_rejects_tag_only_image(self): with self.assertRaisesRegex(ValueError, "digest-pinned"): render_summary(artifact, "web-notebook-publish-bundle") + def test_rejects_digest_image_outside_msg_ctf_ghcr(self): + artifact = { + "challenge_slug": "web-notebook", + "category": "web", + "revision": 7, + "registry_revision": 7, + "isolation_profile": "WEB", + "scan_result": "PASS", + "workload": { + "containers": [ + { + "name": "web", + "image": f"registry.internal/challenges/web@{DIGEST_A}", + } + ] + }, + } + + with self.assertRaisesRegex(ValueError, "MSG-CTF GHCR"): + render_summary(artifact, "web-notebook-publish-bundle") + + def test_rejects_registry_revision_mismatch(self): + artifact = { + "challenge_slug": "web-notebook", + "category": "web", + "revision": 7, + "registry_revision": 8, + "isolation_profile": "WEB", + "scan_result": "PASS", + "workload": {"containers": []}, + } + + with self.assertRaisesRegex(ValueError, "registry_revision"): + render_summary(artifact, "web-notebook-publish-bundle") + + def test_rejects_boolean_registry_revision(self): + artifact = { + "challenge_slug": "web-notebook", + "category": "web", + "revision": 1, + "registry_revision": True, + "isolation_profile": "WEB", + "scan_result": "PASS", + "workload": {"containers": []}, + } + + with self.assertRaisesRegex(ValueError, "registry_revision"): + render_summary(artifact, "web-notebook-publish-bundle") + + def test_rejects_isolation_profile_that_does_not_match_category(self): + artifact = { + "challenge_slug": "pwn-example", + "category": "pwn", + "revision": 1, + "registry_revision": 1, + "isolation_profile": "WEB", + "scan_result": "PASS", + "workload": {"containers": []}, + } + + with self.assertRaisesRegex(ValueError, "challenge category"): + render_summary(artifact, "pwn-example-publish-bundle") + if __name__ == "__main__": unittest.main() diff --git a/tests/test_runtime_api_smoke_runner.py b/tests/test_runtime_api_smoke_runner.py index 66501b5..5efe22b 100644 --- a/tests/test_runtime_api_smoke_runner.py +++ b/tests/test_runtime_api_smoke_runner.py @@ -1,4 +1,5 @@ import json +import copy import socket import tempfile import threading @@ -183,6 +184,36 @@ def test_builds_runtime_team_multi_container_contract(self): }, ) + def test_preserves_internal_connections_in_runtime_request(self): + artifact = copy.deepcopy(ARTIFACT) + artifact["workload"]["containers"].append( + { + "name": "db", + "image": f"ghcr.io/msg-ctf/challenges/koth-template/db@{DIGEST}", + "ports": [{"port": 5432, "public": False}], + } + ) + artifact["workload"]["internal_connections"] = [ + { + "source_container": "service", + "destination_container": "db", + "protocol": "TCP", + "port": 5432, + } + ] + + request = build_create_request( + artifact, + target_id="aws-k3s-001", + instance_id=INSTANCE_ID, + team_id=TEAM_ID, + ) + + self.assertEqual( + request["workload"]["internal_connections"], + artifact["workload"]["internal_connections"], + ) + def test_creates_polls_and_always_deletes_runtime_workload(self): self.start_server() with tempfile.TemporaryDirectory() as directory: diff --git a/tests/test_validate_info_spec.py b/tests/test_validate_info_spec.py index 70fd34c..487547f 100644 --- a/tests/test_validate_info_spec.py +++ b/tests/test_validate_info_spec.py @@ -59,6 +59,111 @@ def test_server_challenge_is_marked_as_server(self): metadata = validate_spec(FIXTURE) self.assertTrue(metadata["is_server"]) + self.assertEqual(metadata["isolation_profile"], "WEB") + + def test_pwn_server_uses_pwn_isolation_profile(self): + raw = self._raw_fixture() + raw["category"] = "pwn" + + metadata = self._validate_raw(raw) + + self.assertEqual(metadata["isolation_profile"], "PWN") + + def test_accepts_declared_internal_connection(self): + raw = self._raw_fixture() + raw["deployment"]["internal_connections"] = [ + { + "source_container": "web", + "destination_container": "helper", + "protocol": "TCP", + "port": 9091, + } + ] + + metadata = self._validate_raw(raw) + + self.assertEqual( + metadata["internal_connections"], + raw["deployment"]["internal_connections"], + ) + + def test_rejects_internal_connection_to_undeclared_port(self): + raw = self._raw_fixture() + raw["deployment"]["internal_connections"] = [ + { + "source_container": "web", + "destination_container": "helper", + "protocol": "TCP", + "port": 9999, + } + ] + + with self.assertRaisesRegex(ValueError, "destination container port"): + self._validate_raw(raw) + + def test_rejects_invalid_internal_connection_contracts(self): + invalid_connections = [ + ( + { + "source_container": "unknown", + "destination_container": "helper", + "protocol": "TCP", + "port": 9091, + }, + "declared containers", + ), + ( + { + "source_container": "web", + "destination_container": "web", + "protocol": "TCP", + "port": 8080, + }, + "must be different", + ), + ( + { + "source_container": "web", + "destination_container": "helper", + "protocol": "UDP", + "port": 9091, + }, + "must be TCP", + ), + ] + for connection, message in invalid_connections: + with self.subTest(connection=connection): + raw = self._raw_fixture() + raw["deployment"]["internal_connections"] = [connection] + with self.assertRaisesRegex(ValueError, message): + self._validate_raw(raw) + + def test_rejects_duplicate_internal_connections(self): + raw = self._raw_fixture() + connection = { + "source_container": "web", + "destination_container": "helper", + "protocol": "TCP", + "port": 9091, + } + raw["deployment"]["internal_connections"] = [connection, connection] + + with self.assertRaisesRegex(ValueError, "duplicates"): + self._validate_raw(raw) + + def test_rejects_raw_network_policy(self): + raw = self._raw_fixture() + raw["deployment"]["network_policy"] = {"egress": [{"to": "0.0.0.0/0"}]} + + with self.assertRaisesRegex(ValueError, "NetworkPolicy"): + self._validate_raw(raw) + + def test_rejects_unknown_deployment_field(self): + raw = self._raw_fixture() + raw["deployment"]["networkPolicy"] = {"egress": []} + + with self.assertRaisesRegex(ValueError, "unsupported fields"): + self._validate_raw(raw) def test_accepts_backend_team_koth_template_contract(self): metadata = validate_spec(KOTH_FIXTURE) From 51f5f9857333923e9a94b29a5b83207065ae796d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Thu, 3 Sep 2026 11:00:29 +0900 Subject: [PATCH 2/8] =?UTF-8?q?Backend=20poller=20=EA=B8=B0=EB=B0=98=20Reg?= =?UTF-8?q?istry=20=EB=93=B1=EB=A1=9D=20=EC=84=A4=EA=B3=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...26-09-03-backend-poller-registry-design.md | 147 ++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 docs/superpowers/specs/2026-09-03-backend-poller-registry-design.md diff --git a/docs/superpowers/specs/2026-09-03-backend-poller-registry-design.md b/docs/superpowers/specs/2026-09-03-backend-poller-registry-design.md new file mode 100644 index 0000000..1424f77 --- /dev/null +++ b/docs/superpowers/specs/2026-09-03-backend-poller-registry-design.md @@ -0,0 +1,147 @@ +# Backend Poller 기반 Challenge Release 등록 설계 + +## 배경 + +DevSecOps 공급망은 문제 image를 검사해 GHCR에 digest로 고정하고 +`artifact-v2.json`을 포함한 publish bundle을 GitHub Actions artifact로 발행한다. +Backend PR #26은 이 artifact를 주기적으로 수집해 Challenge Release로 등록하는 +poller를 제공한다. + +기존 PR #7에는 GitHub Actions가 Backend API를 직접 호출하는 push 방식도 +포함되어 있었다. 이 방식은 Backend UUID `challenge_id`, API base URL, +관리자 또는 service token과 POST 재전송 규칙을 CI가 알아야 한다. 문제 저장소의 +`info.yaml`에는 Backend UUID가 없으므로 현재 계약으로는 안전하게 URL을 만들 수 +없다. + +MVP에서는 Backend poller를 단일 등록 경로로 사용한다. + +## 결정 + +Challenge Release 등록 흐름은 다음과 같다. + +```text +문제 저장소 push +→ GitHub Actions 검증 및 image build +→ Gitleaks와 Trivy 통과 +→ GHCR digest image 발행 +→ artifact-v2.json과 SBOM을 publish bundle로 업로드 +→ Backend poller가 GitHub Actions artifact 수집 +→ Backend가 challenge를 매핑하고 release 등록 +→ 관리자 또는 Backend가 별도 API로 active release 전환 +``` + +GitHub Actions는 Backend Release API를 직접 호출하지 않는다. 따라서 +`CHALLENGE_REGISTRY_URL`, `CHALLENGE_REGISTRY_TOKEN`, `challenge_id`, +`Idempotency-Key`는 DevSecOps publish workflow의 입력이나 secret으로 사용하지 +않는다. + +## Publish Bundle 계약 + +Backend poller가 읽는 공식 파일은 `artifact-v2.json`이다. 파일에는 다음 값이 +포함된다. + +- `schema_version: "2.0"` +- `challenge_slug` +- `revision`과 `registry_revision` +- `runtime_type`과 `architecture` +- `isolation_profile` +- `workload.containers[]` +- 각 컨테이너의 GHCR digest image와 `ports[].public` +- 선택형 `workload.healthcheck` +- 선택형 `workload.internal_connections[]` +- `resource_profile` +- `source_ref` +- `scan_result: "PASS"` +- 컨테이너별 scan, SBOM과 timing evidence + +Actions artifact 이름은 Backend poller가 식별할 수 있도록 +`--publish-bundle` 형식을 유지한다. + +`registry-publish.json`은 자동 전송에 사용하지 않고 수동 API 검증 자료로 +유지한다. Backend PR #26의 요청 형식인 아래 wrapper만 담는다. + +```json +{ + "artifact": {} +} +``` + +wrapper의 `artifact` 값은 같은 bundle의 `artifact-v2.json`과 정확히 같아야 한다. +`activate`, `operation`, `preconditions`, `retention` 같은 Backend 요청 계약 밖의 +필드는 넣지 않는다. + +## 책임 경계 + +DevSecOps는 다음을 담당한다. + +- `info.yaml` 검증 +- image build 또는 외부 image pull +- Gitleaks와 Trivy 차단 검사 +- SBOM 생성 +- GHCR digest image 발행 +- `artifact-v2.json` 생성과 Actions artifact 업로드 + +Backend는 다음을 담당한다. + +- GitHub Actions artifact 조회 인증 token 관리 +- publish bundle 수집 +- `challenge_slug`와 Backend `challenge_id` 매핑 +- release 등록과 기존 revision 보존 +- 같은 `challenge_id`와 `registry_revision`의 중복 수집 처리 +- active release 전환과 롤백 + +Runtime과 Secure Provisioner는 다음을 담당한다. + +- active release workload를 실제 K3s 자원으로 변환 +- Service endpoint 생성 +- NetworkPolicy와 격리 정책 생성 +- workload cleanup + +## 중복과 실패 처리 + +Backend poller가 이미 등록한 `registry_revision`을 다시 수집하면 중복으로 +기록하고 전체 poll을 실패시키지 않는다. API를 이용한 수동 등록에서 +`409 RELEASE_DUPLICATED`가 반환되는 경우에도 이미 등록된 revision으로 본다. +다른 409 code는 성공으로 처리하지 않는다. + +CI가 실패하면 publish bundle을 만들지 않는다. Backend poller가 bundle 형식 오류, +challenge 매핑 실패 또는 GitHub API 통신 오류를 만나면 해당 bundle을 등록하지 +않고 Backend 로그와 poll 결과에 원인을 남긴다. + +Release 등록은 active release를 변경하지 않는다. 활성화와 롤백은 관리자 또는 +Backend가 별도 API와 권한으로 수행한다. + +## 혼합 포트 경계 + +Registry artifact는 포트별 `public` 값을 보존한다. 현재 Runtime `dev` 계약은 +`ports: [int]`와 컨테이너 단위 `expose`를 사용하므로 한 컨테이너 안에서 public과 +private 포트가 섞인 workload를 손실 없이 변환할 수 없다. + +이 변경에서는 Runtime DTO를 임의로 확장하거나 포트를 누락하지 않는다. 혼합 포트 +지원은 Runtime 팀이 확정한 DTO를 받은 뒤 별도 계약 변경으로 구현한다. 그전까지 +DevSecOps smoke runner는 표현할 수 없는 혼합 노출 workload를 명시적으로 거절한다. + +## 테스트 + +PR #7은 다음 자동 테스트를 만족해야 한다. + +1. 생성된 `artifact-v2.json`이 Backend PR #26 validator 입력으로 유효하다. +2. `registry-publish.json`의 `artifact` wrapper가 + `artifact-v2.json`과 정확히 일치한다. +3. workflow에 Backend 직접 API 호출, `Idempotency-Key`, 자동 활성화가 없다. +4. publish bundle 이름이 Backend poller suffix 규칙을 만족한다. +5. digest가 아닌 GHCR image와 `scan_result` 실패 상태는 bundle로 발행되지 않는다. +6. 기존 단일·멀티 컨테이너 생성 테스트와 전체 unit test가 통과한다. + +실제 통합 검증에서는 Backend poller가 Actions artifact를 내려받아 release를 한 번 +등록하고, 같은 bundle을 다시 읽었을 때 duplicate로 처리하며 active release는 +변하지 않는지 확인한다. + +## 범위 밖 + +- active release 자동 전환 +- Backend API base URL 배포와 service token 발급 +- Runtime 혼합 public/private 포트 DTO 변경 +- 실제 K3s cold pull, 인증 실패와 ImagePullBackOff 재현 + +위 항목은 각각 Backend 운영 연결과 PR #6 Runtime/K3s smoke 검증에서 처리한다. From 14a6ca46fb56f861a4eb558e99d98c581f7942bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Thu, 3 Sep 2026 11:11:01 +0900 Subject: [PATCH 3/8] =?UTF-8?q?Backend=20poller=20=ED=86=B5=ED=95=A9=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20=EA=B3=84=ED=9A=8D=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...-backend-poller-registry-implementation.md | 460 ++++++++++++++++++ 1 file changed, 460 insertions(+) create mode 100644 docs/superpowers/plans/2026-09-03-backend-poller-registry-implementation.md diff --git a/docs/superpowers/plans/2026-09-03-backend-poller-registry-implementation.md b/docs/superpowers/plans/2026-09-03-backend-poller-registry-implementation.md new file mode 100644 index 0000000..2cf742f --- /dev/null +++ b/docs/superpowers/plans/2026-09-03-backend-poller-registry-implementation.md @@ -0,0 +1,460 @@ +# Backend Poller Registry 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:** DevSecOps 공급망이 Backend API를 직접 호출하지 않고, Backend poller가 소비할 `artifact-v2.json` publish bundle을 정확히 발행하도록 PR #7을 수정한다. + +**Architecture:** 문제 저장소의 GitHub Actions는 검증된 image를 GHCR digest로 고정하고 `artifact-v2.json`, `registry-publish.json`, SBOM과 검사 증거를 Actions artifact로 업로드한다. Backend poller가 이름이 `-publish-bundle`로 끝나는 artifact를 내려받아 release를 등록하며, 중복 처리와 active release 전환은 Backend가 소유한다. + +**Tech Stack:** GitHub Actions reusable workflow, Python 3 표준 라이브러리, `unittest`, Docker/Buildx, GHCR, Gitleaks, Trivy, CycloneDX SBOM + +**Spec:** `docs/superpowers/specs/2026-09-03-backend-poller-registry-design.md` + +## Global Constraints + +- `artifact-v2.json`의 `schema_version`, `registry_revision`, `containers`, digest image, `scan_result` 계약을 유지한다. +- GitHub Actions에서 Backend Release API를 직접 호출하지 않는다. +- `registry-publish.json`은 수동 호환성 검증용 `{"artifact": }` wrapper만 제공한다. +- CI는 release를 활성화하지 않는다. active release 전환과 롤백은 Backend 또는 관리자가 담당한다. +- Runtime, Scheduler, Resource Broker 저장소의 코드는 수정하지 않는다. +- 포트별 `public` 정보는 artifact에서 손실 없이 보존한다. 현재 Runtime이 표현하지 못하는 혼합 노출 포트는 임의 변환하지 않는다. +- 기존 GHCR build-once, scan, push와 K3s smoke 경로는 직접 Registry API 제거 때문에 깨지지 않아야 한다. + +--- + +## Task 1: Backend poller용 publish 문서 생성 + +**Files:** +- Modify: `tests/test_generate_publish_bundle.py` +- Modify: `scripts/generate_publish_bundle.py` + +**Interface:** + +```python +def generate_bundle( + metadata: dict, + results: list[dict], + source_ref: str, + revision: int, + evidence_root: Path, +) -> dict: + """Return artifact-v2 and its Backend request wrapper.""" +``` + +반환값은 아래 관계를 만족해야 한다. + +```python +bundle["registry_publish"] == {"artifact": bundle["artifact"]} +``` + +- [ ] **Step 1: 기존 flat publish 문서를 거절하는 테스트 작성** + +`test_generates_runtime_artifact_and_registry_publish_document`를 다음 계약으로 바꾼다. + +```python +artifact = bundle["artifact"] +publish = bundle["registry_publish"] +self.assertEqual(publish, {"artifact": artifact}) +for forbidden in ("activate", "operation", "preconditions", "retention"): + self.assertNotIn(forbidden, publish) +``` + +`internal_connections`와 `isolation_profile` 테스트도 `registry_publish["artifact"]`를 통해 같은 artifact를 검사하게 변경한다. + +- [ ] **Step 2: 변경한 테스트가 기존 구현에서 실패하는지 확인** + +Run: + +```bash +python3 -m unittest tests.test_generate_publish_bundle -v +``` + +Expected: 기존 `registry_publish`가 flat object이고 `operation`, `activate`를 포함하므로 FAIL. + +- [ ] **Step 3: generator를 최소 변경으로 수정** + +`artifact`를 한 번만 만든 뒤 아래처럼 wrapper를 생성한다. + +```python +registry_publish = {"artifact": artifact} +return {"artifact": artifact, "registry_publish": registry_publish} +``` + +기존 digest, SBOM, timing, scan 검증은 변경하지 않는다. + +- [ ] **Step 4: generator 테스트 통과 확인** + +Run: + +```bash +python3 -m unittest tests.test_generate_publish_bundle -v +``` + +Expected: 모든 generator 테스트 PASS. + +- [ ] **Step 5: 변경 커밋** + +```bash +git add scripts/generate_publish_bundle.py tests/test_generate_publish_bundle.py +git commit -m "Backend poller publish wrapper 계약 반영" +``` + +--- + +## Task 2: reusable workflow에서 Backend 직접 호출 제거 + +**Files:** +- Modify: `tests/test_workflow_contracts.py` +- Modify: `.github/workflows/challenge-supply-chain.yml` + +**Workflow contract:** + +- 입력에는 `challenge_path`, `revision`, `devsecops_ref`, `publish_images`, `enable_k3s_smoke_deploy`, `runtime_target_id`만 사용한다. +- `workflow_call.secrets`에는 Runtime/K3s smoke에 필요한 AWS secret과 기존 caller 호환용 `GHCR_PULL_SECRET_ARN`만 남긴다. +- job은 검증, build/scan/push, bundle 집계, 선택형 K3s smoke로 구성한다. +- bundle artifact 이름은 `${challenge_slug}-${artifact_scope}-publish-bundle` 형식을 유지한다. + +- [ ] **Step 1: 직접 API 호출이 없어야 한다는 계약 테스트 작성** + +`test_challenge_supply_chain_has_required_contract`에서 아래를 검증하도록 변경한다. + +```python +self.assertNotIn("publish_registry", workflow["on"]["workflow_call"]["inputs"]) +self.assertNotIn("publish-registry", workflow["jobs"]) +self.assertNotIn("CHALLENGE_REGISTRY_TOKEN", workflow["on"]["workflow_call"].get("secrets", {})) +self.assertNotIn("CHALLENGE_REGISTRY_URL", workflow["on"]["workflow_call"].get("secrets", {})) +for forbidden in ("Authorization: Bearer", "Idempotency-Key:", "curl --fail-with-body"): + self.assertNotIn(forbidden, text) +self.assertIn("${{ needs.validate.outputs.artifact_scope }}-publish-bundle", text) +``` + +branch validation 조건 테스트의 job 목록은 `aggregate`, `k3s-smoke-deploy`만 검사하게 수정한다. + +- [ ] **Step 2: 변경한 workflow 계약 테스트가 실패하는지 확인** + +Run: + +```bash +python3 -m unittest tests.test_workflow_contracts.WorkflowContractTests.test_challenge_supply_chain_has_required_contract -v +python3 -m unittest tests.test_workflow_contracts.WorkflowContractTests.test_branch_validation_can_disable_all_publish_and_deploy_steps -v +``` + +Expected: `publish_registry`, Registry secret, `publish-registry` job이 남아 있어 FAIL. + +- [ ] **Step 3: reusable workflow 최소 수정** + +`.github/workflows/challenge-supply-chain.yml`에서 다음을 제거한다. + +- `publish_registry` input +- `CHALLENGE_REGISTRY_TOKEN`, `CHALLENGE_REGISTRY_URL` secrets +- `publish-registry` job 전체 +- `Authorization`, `Idempotency-Key`, `curl` 기반 Backend 전송 코드 + +`aggregate` job의 publish bundle 업로드와 `k3s-smoke-deploy` job은 유지한다. + +- [ ] **Step 4: workflow 계약 테스트 통과 확인** + +Run: + +```bash +python3 -m unittest tests.test_workflow_contracts -v +``` + +Expected: workflow 계약 테스트 PASS. + +- [ ] **Step 5: 변경 커밋** + +```bash +git add .github/workflows/challenge-supply-chain.yml tests/test_workflow_contracts.py +git commit -m "Backend poller 중심 release 등록 흐름 적용" +``` + +--- + +## Task 3: 문제 저장소 caller 예시에서 Registry push 설정 제거 + +**Files:** +- Modify: `docs/challenge-caller-example.yml` +- Modify: `.github/workflows/pipeline-self-test.yml` +- Modify: `tests/test_workflow_contracts.py` + +- [ ] **Step 1: caller와 self-test의 새 계약을 테스트에 반영** + +caller 테스트에서 `publish-main.with`에 `publish_registry`가 없고 secret mapping에 Registry URL/token이 없음을 검증한다. + +```python +self.assertNotIn("publish_registry", publish["with"]) +self.assertEqual( + set(publish["secrets"]), + { + "AWS_ROLE_TO_ASSUME", + "AWS_REGION", + "AWS_K3S_INSTANCE_ID", + "AWS_CD_ARTIFACT_BUCKET", + }, +) +``` + +self-test 테스트에서는 `publish_registry: false` 문자열 요구를 제거하고, self-test workflow에도 해당 입력이 없음을 검증한다. + +- [ ] **Step 2: caller 계약 테스트 실패 확인** + +Run: + +```bash +python3 -m unittest tests.test_workflow_contracts.WorkflowContractTests.test_caller_example_separates_branch_validation_from_main_publish -v +python3 -m unittest tests.test_workflow_contracts.WorkflowContractTests.test_pipeline_self_test_calls_reusable_supply_chain -v +``` + +Expected: 예시와 self-test에 기존 `publish_registry` 설정이 남아 있어 FAIL. + +- [ ] **Step 3: caller 예시와 self-test 수정** + +`docs/challenge-caller-example.yml`에서 아래 항목을 제거한다. + +```yaml +publish_registry: ${{ vars.ENABLE_CHALLENGE_REGISTRY == 'true' }} +CHALLENGE_REGISTRY_TOKEN: ${{ secrets.CHALLENGE_REGISTRY_TOKEN }} +CHALLENGE_REGISTRY_URL: ${{ secrets.CHALLENGE_REGISTRY_URL }} +``` + +`.github/workflows/pipeline-self-test.yml`의 reusable workflow 호출에서 `publish_registry: false`를 제거한다. + +- [ ] **Step 4: caller와 전체 workflow 테스트 통과 확인** + +Run: + +```bash +python3 -m unittest tests.test_workflow_contracts -v +``` + +Expected: 모든 workflow 계약 테스트 PASS. + +- [ ] **Step 5: 변경 커밋** + +```bash +git add docs/challenge-caller-example.yml .github/workflows/pipeline-self-test.yml tests/test_workflow_contracts.py +git commit -m "문제 저장소 caller를 poller 방식으로 정리" +``` + +--- + +## Task 4: 문서에서 파트 간 책임과 운영 절차 정리 + +**Files:** +- Create: `tests/test_backend_poller_documentation.py` +- Modify: `README.md` +- Modify: `.github/workflows/README.md` +- Modify: `ci/README.md` +- Modify: `docs/README.md` +- Modify: `docs/challenge-registry-integration.md` +- Modify: `docs/devsecops-runbook.md` +- Modify: `scripts/README.md` + +**Documented ownership:** + +```text +DevSecOps: artifact-v2.json과 GHCR digest image 발행 +Backend poller: Actions artifact 수집, challenge 매핑, release 등록, duplicate 처리 +Backend/admin: active release 전환과 롤백 +Runtime/Secure Provisioner: active workload의 K3s 배포와 cleanup +``` + +- [ ] **Step 1: 오래된 직접 push 안내를 탐지하는 문서 테스트 작성** + +`tests/test_backend_poller_documentation.py`를 추가한다. + +```python +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +DOCUMENTS = ( + ROOT / "README.md", + ROOT / ".github/workflows/README.md", + ROOT / "ci/README.md", + ROOT / "docs/README.md", + ROOT / "docs/challenge-registry-integration.md", + ROOT / "docs/devsecops-runbook.md", + ROOT / "scripts/README.md", +) + + +class BackendPollerDocumentationTests(unittest.TestCase): + def test_documents_poller_without_direct_registry_push_settings(self): + text = "\n".join(path.read_text(encoding="utf-8") for path in DOCUMENTS) + self.assertIn("Backend poller", text) + self.assertIn("artifact-v2.json", text) + for forbidden in ( + "publish_registry: true", + "CHALLENGE_REGISTRY_URL", + "CHALLENGE_REGISTRY_TOKEN", + "Idempotency-Key", + ): + self.assertNotIn(forbidden, text) + + +if __name__ == "__main__": + unittest.main() +``` + +- [ ] **Step 2: 문서 테스트 실패 확인** + +Run: + +```bash +python3 -m unittest tests.test_backend_poller_documentation -v +``` + +Expected: 기존 문서에 직접 API 전송용 URL, token, `Idempotency-Key` 안내가 있어 FAIL. + +- [ ] **Step 3: 문서를 Backend poller 방식으로 갱신** + +문서에 다음 내용을 일관되게 반영한다. + +- `artifact-v2.json`이 자동 수집의 공식 입력이다. +- `registry-publish.json`은 동일 artifact를 감싼 수동 API 검증용 wrapper다. +- DevSecOps workflow에는 Backend base URL 또는 service token이 필요하지 않다. +- Backend 운영 환경의 `RELEASE_POLL_REPO`, `RELEASE_POLL_GITHUB_TOKEN`은 Backend 팀이 관리한다. +- 동일 `registry_revision`의 중복 수집과 active release 전환은 Backend가 처리한다. +- 혼합 public/private 포트는 Runtime DTO 확정 전까지 손실 변환하지 않는다. +- 실제 poller 통합 완료 증거는 Actions artifact 수집, 최초 등록, 중복 재수집, active 미변경을 함께 확인해야 한다. + +`docs/challenge-registry-integration.md`의 과거 직접 API 연결 전제와 service token 대기 항목을 poller 기반 통합 상태로 교체한다. 과거 로컬 등록 결과는 호환성 증거로 남기되 운영 연결 완료로 표현하지 않는다. + +- [ ] **Step 4: 문서 테스트와 전체 테스트 통과 확인** + +Run: + +```bash +python3 -m unittest tests.test_backend_poller_documentation -v +python3 -m unittest discover -s tests -v +``` + +Expected: 문서 계약과 전체 unit test PASS. + +- [ ] **Step 5: 변경 커밋** + +```bash +git add README.md .github/workflows/README.md ci/README.md docs/README.md docs/challenge-registry-integration.md docs/devsecops-runbook.md scripts/README.md tests/test_backend_poller_documentation.py +git commit -m "Backend poller 운영 계약 문서화" +``` + +--- + +## Task 5: 전체 검증과 PR #7 갱신 + +**Files:** +- Verify: `.github/workflows/challenge-supply-chain.yml` +- Verify: `scripts/generate_publish_bundle.py` +- Verify: `tests/` +- Verify: documentation files from Task 4 + +- [ ] **Step 1: Python 전체 테스트 실행** + +Run: + +```bash +python3 -W error::ResourceWarning -m unittest discover -s tests -v +``` + +Expected: 모든 테스트 PASS, warning 없음. + +- [ ] **Step 2: Python 문법과 diff 검사** + +Run: + +```bash +python3 -m py_compile scripts/*.py +git diff --check +``` + +Expected: 출력 없이 exit code 0. + +- [ ] **Step 3: repository secret scan 실행** + +Run: + +```bash +gitleaks detect --source . --no-banner --redact --exit-code 1 +``` + +Expected: leak 없음, exit code 0. + +- [ ] **Step 4: 운영 workflow와 문서의 오래된 설정 잔존 여부 확인** + +Run: + +```bash +rg -n "publish_registry|CHALLENGE_REGISTRY_URL|CHALLENGE_REGISTRY_TOKEN|Idempotency-Key|activate: true" \ + .github README.md ci docs scripts tests \ + -g '!docs/superpowers/**' +``` + +Expected: 운영 workflow와 사용자 문서에서는 결과가 없어야 한다. 테스트의 금지 문자열 목록만 결과에 나타날 수 있다. + +- [ ] **Step 5: 생성 결과의 wrapper 관계 확인** + +테스트 fixture로 bundle을 생성하는 계약 테스트를 단독 실행한다. + +Run: + +```bash +python3 -m unittest tests.test_generate_publish_bundle.GeneratePublishBundleTests.test_generates_runtime_artifact_and_registry_publish_document -v +``` + +이 테스트는 아래 조건을 검사한다. + +```python +registry_publish == {"artifact": artifact_v2} +artifact_v2["scan_result"] == "PASS" +all("@sha256:" in item["image"] for item in artifact_v2["workload"]["containers"]) +``` + +Expected: wrapper 동일성, PASS gate, digest 고정 모두 충족. + +- [ ] **Step 6: 최종 수정 커밋과 원격 branch push** + +검증이 실패하면 해당 Task로 돌아가 수정, targeted test와 전체 검증을 다시 통과시킨 뒤 그 Task의 파일 목록으로 커밋한다. 모든 검증이 통과하면 작업 상태를 확인하고 branch를 push한다. + +```bash +git status --short +git push -u msg-ctf registry-integration +``` + +- [ ] **Step 7: PR #7에 검증 결과 공유** + +PR comment에 아래 내용을 기록한다. + +- Backend 직접 API push 제거 +- `artifact-v2.json` publish bundle이 poller의 공식 입력임 +- `registry-publish.json`은 `{"artifact": ...}` wrapper임 +- 실행한 테스트와 결과 +- active 전환은 Backend 소유임 +- 혼합 포트는 Runtime 계약 확정이 필요한 별도 항목임 + +PR은 리뷰 전 자동 merge하지 않는다. + +--- + +## 완료 기준 + +- reusable workflow가 Backend URL/token 없이 publish bundle을 발행한다. +- publish bundle artifact 이름이 `-publish-bundle`로 끝난다. +- `artifact-v2.json`에 `registry_revision`, 전체 `containers`, digest 고정 GHCR image가 포함된다. +- `registry-publish.json`이 Backend PR #26 요청 wrapper와 일치한다. +- release 자동 활성화와 직접 API 호출 코드가 없다. +- 전체 unit test, Python 문법 검사, diff 검사, Gitleaks가 통과한다. +- PR #7에 변경 이유와 검증 결과가 남고 리뷰 가능한 상태가 된다. + +## 후속 통합 검증 + +Backend PR #26이 poller 포함 상태로 배포된 환경에서 Backend 팀과 다음 네 가지를 공동 확인한다. + +1. 실제 Actions publish bundle 한 건이 자동 수집되어 release로 등록된다. +2. 같은 bundle을 다시 수집하면 duplicate로 처리되고 poll 전체는 실패하지 않는다. +3. 등록 직후 active release는 자동 변경되지 않는다. +4. Backend/admin이 활성화한 release의 `release_id`와 digest가 인스턴스 생성 요청까지 동일하게 전달된다. + +Runtime 팀이 포트별 공개 여부를 표현하는 DTO를 확정하면 PR #6에서 exact `(container_name, port)` endpoint set 검증과 실제 K3s cold pull, 인증 실패, `ImagePullBackOff`, cleanup 증거를 별도로 수행한다. From 5330319660c096988d557540f10420b447eed41b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Thu, 3 Sep 2026 21:34:58 +0900 Subject: [PATCH 4/8] =?UTF-8?q?Backend=20poller=20publish=20wrapper=20?= =?UTF-8?q?=EA=B3=84=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 --- scripts/generate_publish_bundle.py | 23 +---------------------- tests/test_generate_publish_bundle.py | 13 +++++-------- 2 files changed, 6 insertions(+), 30 deletions(-) diff --git a/scripts/generate_publish_bundle.py b/scripts/generate_publish_bundle.py index bf0bff7..f101b4c 100644 --- a/scripts/generate_publish_bundle.py +++ b/scripts/generate_publish_bundle.py @@ -186,28 +186,7 @@ def generate_bundle(metadata, results, source_ref, revision, evidence_root): "scan_result": "PASS", "evidence": {"containers": evidence_containers}, } - registry_publish = { - "schema_version": "1.0", - "operation": "publish_revision", - "challenge_slug": metadata["challenge_slug"], - "revision": revision, - "registry_revision": revision, - "activate": True, - "name": metadata["name"], - "category": metadata["category"], - "runtime_type": metadata["runtime_type"], - "architecture": metadata["architecture"], - "isolation_profile": isolation_profile, - "workload": workload, - "resource_profile": metadata["resource_profile"], - "source_ref": source_ref, - "preconditions": { - "all_images_digest_pinned": True, - "all_scans_passed": True, - "all_sboms_present": True, - }, - "retention": {"protect_running_revisions": True}, - } + registry_publish = {"artifact": artifact} return {"artifact": artifact, "registry_publish": registry_publish} diff --git a/tests/test_generate_publish_bundle.py b/tests/test_generate_publish_bundle.py index c46a7d1..db986eb 100644 --- a/tests/test_generate_publish_bundle.py +++ b/tests/test_generate_publish_bundle.py @@ -90,12 +90,9 @@ def test_generates_runtime_artifact_and_registry_publish_document(self): for container in artifact["workload"]["containers"] ) ) - self.assertEqual(publish["operation"], "publish_revision") - self.assertTrue(publish["activate"]) - self.assertEqual(publish["revision"], 3) - self.assertEqual(publish["registry_revision"], 3) - self.assertEqual(publish["isolation_profile"], "WEB") - self.assertEqual(publish["workload"], artifact["workload"]) + self.assertEqual(publish, {"artifact": artifact}) + for forbidden in ("activate", "operation", "preconditions", "retention"): + self.assertNotIn(forbidden, publish) def test_preserves_declared_internal_connections(self): metadata = dict( @@ -117,7 +114,7 @@ def test_preserves_declared_internal_connections(self): metadata["internal_connections"], ) self.assertEqual( - bundle["registry_publish"]["workload"]["internal_connections"], + bundle["registry_publish"]["artifact"]["workload"]["internal_connections"], metadata["internal_connections"], ) @@ -127,7 +124,7 @@ def test_maps_pwn_category_to_pwn_isolation_profile(self): bundle = generate_bundle(metadata, RESULTS, "abc123", 1, EVIDENCE_ROOT) self.assertEqual(bundle["artifact"]["isolation_profile"], "PWN") - self.assertEqual(bundle["registry_publish"]["isolation_profile"], "PWN") + self.assertEqual(bundle["registry_publish"]["artifact"]["isolation_profile"], "PWN") def test_preserves_healthcheck_and_sbom_evidence(self): bundle = generate_bundle(METADATA, RESULTS, "abc123", 1, EVIDENCE_ROOT) From 839c86264db01b642cfe4e89af968435bdd53c37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Thu, 3 Sep 2026 21:40:18 +0900 Subject: [PATCH 5/8] =?UTF-8?q?Backend=20poller=20=EC=A4=91=EC=8B=AC=20rel?= =?UTF-8?q?ease=20=EB=93=B1=EB=A1=9D=20=ED=9D=90=EB=A6=84=20=EC=A0=81?= =?UTF-8?q?=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/challenge-supply-chain.yml | 73 -------------------- tests/test_workflow_contracts.py | 46 ++++-------- 2 files changed, 13 insertions(+), 106 deletions(-) diff --git a/.github/workflows/challenge-supply-chain.yml b/.github/workflows/challenge-supply-chain.yml index e76d121..d873949 100644 --- a/.github/workflows/challenge-supply-chain.yml +++ b/.github/workflows/challenge-supply-chain.yml @@ -21,11 +21,6 @@ on: required: false default: true type: boolean - publish_registry: - description: 검증된 revision을 Challenge Registry API에 등록할지 여부 - required: false - default: false - type: boolean enable_k3s_smoke_deploy: description: Secure Provisioner API를 통한 AWS K3s 임시 배포 검증 실행 여부 required: false @@ -55,10 +50,6 @@ on: # 이전 caller 호환용입니다. Runtime smoke에서는 사용하지 않습니다. GHCR_PULL_SECRET_ARN: required: false - CHALLENGE_REGISTRY_TOKEN: - required: false - CHALLENGE_REGISTRY_URL: - required: false permissions: contents: read @@ -414,70 +405,6 @@ jobs: if-no-files-found: error retention-days: 90 - publish-registry: - needs: - - aggregate - if: >- - inputs.publish_images && - inputs.publish_registry && - needs.aggregate.result == 'success' - runs-on: ubuntu-latest - permissions: - contents: read - steps: - - name: 발행 bundle 가져오기 - uses: actions/download-artifact@v4 - with: - name: ${{ needs.aggregate.outputs.publish_bundle_name }} - path: dist - - - name: Challenge Registry 연결 설정 검증 - env: - REGISTRY_API_URL: ${{ secrets.CHALLENGE_REGISTRY_URL }} - REGISTRY_TOKEN: ${{ secrets.CHALLENGE_REGISTRY_TOKEN }} - run: | - case "$REGISTRY_API_URL" in - https://*) ;; - *) echo "registry_api_url은 HTTPS URL이어야 합니다" >&2; exit 1 ;; - esac - if [ -z "$REGISTRY_TOKEN" ]; then - echo "CHALLENGE_REGISTRY_TOKEN이 필요합니다" >&2 - exit 1 - fi - if [[ "$REGISTRY_TOKEN" == *$'\n'* || "$REGISTRY_TOKEN" == *$'\r'* ]]; then - echo "CHALLENGE_REGISTRY_TOKEN에 줄바꿈을 사용할 수 없습니다" >&2 - exit 1 - fi - - - name: Challenge Registry revision 등록 - env: - REGISTRY_API_URL: ${{ secrets.CHALLENGE_REGISTRY_URL }} - REGISTRY_TOKEN: ${{ secrets.CHALLENGE_REGISTRY_TOKEN }} - run: | - challenge_slug="$(jq -r '.challenge_slug' dist/registry-publish.json)" - revision="$(jq -r '.revision' dist/registry-publish.json)" - payload_sha256="$(sha256sum dist/registry-publish.json | cut -d ' ' -f 1)" - idempotency_key="${GITHUB_REPOSITORY_ID}:${challenge_slug}:${revision}:${payload_sha256}" - curl --fail-with-body \ - --retry 3 \ - --retry-all-errors \ - --connect-timeout 5 \ - --max-time 30 \ - --request POST \ - --header "Authorization: Bearer ${REGISTRY_TOKEN}" \ - --header "Content-Type: application/json" \ - --header "Idempotency-Key: ${idempotency_key}" \ - --data-binary @dist/registry-publish.json \ - --output dist/registry-response.txt \ - "$REGISTRY_API_URL" - { - echo "## Challenge Registry 등록 결과" - echo - echo "- 문제: \`${challenge_slug}\`" - echo "- revision: \`${revision}\`" - echo "- 상태: \`ACCEPTED\`" - } >> "$GITHUB_STEP_SUMMARY" - k3s-smoke-deploy: needs: - validate diff --git a/tests/test_workflow_contracts.py b/tests/test_workflow_contracts.py index c2f8147..8198763 100644 --- a/tests/test_workflow_contracts.py +++ b/tests/test_workflow_contracts.py @@ -57,7 +57,6 @@ def test_challenge_supply_chain_has_required_contract(self): "revision", "devsecops_ref", "publish_images", - "publish_registry", "enable_k3s_smoke_deploy", "runtime_target_id", }, @@ -67,8 +66,6 @@ def test_challenge_supply_chain_has_required_contract(self): self.assertEqual(inputs["devsecops_ref"]["default"], "main") self.assertEqual(inputs["publish_images"]["type"], "boolean") self.assertEqual(inputs["publish_images"]["default"], "true") - self.assertEqual(inputs["publish_registry"]["type"], "boolean") - self.assertEqual(inputs["publish_registry"]["default"], "false") self.assertEqual(inputs["enable_k3s_smoke_deploy"]["type"], "boolean") self.assertEqual(inputs["runtime_target_id"]["type"], "string") outputs = workflow["on"]["workflow_call"]["outputs"] @@ -117,7 +114,6 @@ def test_challenge_supply_chain_has_required_contract(self): "validate", "build-scan-push", "aggregate", - "publish-registry", "k3s-smoke-deploy", }, ) @@ -171,6 +167,18 @@ def test_challenge_supply_chain_has_required_contract(self): "${{ needs.validate.outputs.artifact_scope }}-publish-bundle", text, ) + self.assertNotIn("publish_registry", workflow["on"]["workflow_call"]["inputs"]) + self.assertNotIn("publish-registry", workflow["jobs"]) + self.assertNotIn( + "CHALLENGE_REGISTRY_TOKEN", + workflow["on"]["workflow_call"].get("secrets", {}), + ) + self.assertNotIn( + "CHALLENGE_REGISTRY_URL", + workflow["on"]["workflow_call"].get("secrets", {}), + ) + for forbidden in ("Authorization: Bearer", "Idempotency-Key:", "curl --fail-with-body"): + self.assertNotIn(forbidden, text) k3s_download = next( step for step in workflow["jobs"]["k3s-smoke-deploy"]["steps"] @@ -188,34 +196,6 @@ def test_challenge_supply_chain_has_required_contract(self): ): self.assertIn(required, text) - publish = workflow["jobs"]["publish-registry"] - self.assertEqual(publish["needs"], ["aggregate"]) - self.assertIn("inputs.publish_registry", publish["if"]) - self.assertEqual(publish["permissions"], {"contents": "read"}) - self.assertIn("CHALLENGE_REGISTRY_TOKEN", workflow["on"]["workflow_call"]["secrets"]) - self.assertIn("CHALLENGE_REGISTRY_URL", workflow["on"]["workflow_call"]["secrets"]) - - publish_run = next( - step["run"] - for step in publish["steps"] - if step.get("name") == "Challenge Registry revision 등록" - ) - validation_run = next( - step["run"] - for step in publish["steps"] - if step.get("name") == "Challenge Registry 연결 설정 검증" - ) - self.assertIn("https://", validation_run) - for required in ( - "registry-publish.json", - "Authorization: Bearer", - "Idempotency-Key:", - "sha256sum dist/registry-publish.json", - "--fail-with-body", - "--retry 3", - ): - self.assertIn(required, publish_run) - def test_branch_validation_can_disable_all_publish_and_deploy_steps(self): path = ROOT / ".github/workflows/challenge-supply-chain.yml" workflow = load_workflow(path) @@ -236,7 +216,7 @@ def test_branch_validation_can_disable_all_publish_and_deploy_steps(self): self.assertIn("inputs.publish_images", step.get("if", "")) self.assertEqual(found_steps, protected_steps) - for job_name in ("aggregate", "publish-registry", "k3s-smoke-deploy"): + for job_name in ("aggregate", "k3s-smoke-deploy"): self.assertIn( "inputs.publish_images", workflow["jobs"][job_name].get("if", ""), From f7addf53dcaaa7981844e8003af16d40b753956c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Thu, 3 Sep 2026 21:48:42 +0900 Subject: [PATCH 6/8] =?UTF-8?q?=EB=AC=B8=EC=A0=9C=20=EC=A0=80=EC=9E=A5?= =?UTF-8?q?=EC=86=8C=20caller=EB=A5=BC=20poller=20=EB=B0=A9=EC=8B=9D?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/pipeline-self-test.yml | 2 -- docs/challenge-caller-example.yml | 3 --- tests/test_workflow_contracts.py | 11 ++++------- 3 files changed, 4 insertions(+), 12 deletions(-) diff --git a/.github/workflows/pipeline-self-test.yml b/.github/workflows/pipeline-self-test.yml index 83a286b..a7b2218 100644 --- a/.github/workflows/pipeline-self-test.yml +++ b/.github/workflows/pipeline-self-test.yml @@ -51,7 +51,6 @@ jobs: challenge_path: tests/fixtures/info-valid revision: ${{ github.run_number }} devsecops_ref: ${{ github.sha }} - publish_registry: false enable_k3s_smoke_deploy: false secrets: inherit @@ -80,6 +79,5 @@ jobs: challenge_path: tests/fixtures/koth-template revision: ${{ github.run_number }} devsecops_ref: ${{ github.sha }} - publish_registry: false enable_k3s_smoke_deploy: false secrets: inherit diff --git a/docs/challenge-caller-example.yml b/docs/challenge-caller-example.yml index f340cbf..6a6f26b 100644 --- a/docs/challenge-caller-example.yml +++ b/docs/challenge-caller-example.yml @@ -118,7 +118,6 @@ jobs: revision: ${{ github.run_number }} devsecops_ref: 64a8d9267b2e7ea6a3eea5c92070d09ab1d76d8d publish_images: true - publish_registry: ${{ vars.ENABLE_CHALLENGE_REGISTRY == 'true' }} enable_k3s_smoke_deploy: ${{ vars.ENABLE_RUNTIME_SMOKE == 'true' }} runtime_target_id: ${{ vars.RUNTIME_TARGET_ID }} secrets: @@ -126,5 +125,3 @@ jobs: AWS_REGION: ${{ secrets.AWS_REGION }} AWS_K3S_INSTANCE_ID: ${{ secrets.AWS_K3S_INSTANCE_ID }} AWS_CD_ARTIFACT_BUCKET: ${{ secrets.AWS_CD_ARTIFACT_BUCKET }} - CHALLENGE_REGISTRY_TOKEN: ${{ secrets.CHALLENGE_REGISTRY_TOKEN }} - CHALLENGE_REGISTRY_URL: ${{ secrets.CHALLENGE_REGISTRY_URL }} diff --git a/tests/test_workflow_contracts.py b/tests/test_workflow_contracts.py index 8198763..2852c6d 100644 --- a/tests/test_workflow_contracts.py +++ b/tests/test_workflow_contracts.py @@ -314,9 +314,11 @@ def test_pipeline_self_test_calls_reusable_supply_chain(self): self.assertIn("tests/fixtures/info-valid", text) self.assertIn("tests/fixtures/koth-template", text) self.assertEqual(text.count("devsecops_ref: ${{ github.sha }}"), 3) - self.assertIn("publish_registry: false", text) + self.assertNotIn("publish_registry", text) self.assertIn("enable_k3s_smoke_deploy: false", text) self.assertIn("id-token: write", text) + for job_name in ("sample-server-challenge", "koth-challenge"): + self.assertNotIn("publish_registry", workflow["jobs"][job_name]["with"]) branch_validation = workflow["jobs"]["branch-validation"] self.assertEqual(branch_validation["permissions"], {"contents": "read"}) self.assertNotIn("secrets", branch_validation) @@ -387,10 +389,7 @@ def test_caller_example_separates_branch_validation_from_main_publish(self): inputs = publish["with"] self.assertEqual(inputs["publish_images"], "true") - self.assertEqual( - inputs["publish_registry"], - "${{ vars.ENABLE_CHALLENGE_REGISTRY == 'true' }}", - ) + self.assertNotIn("publish_registry", inputs) self.assertEqual( inputs["enable_k3s_smoke_deploy"], "${{ vars.ENABLE_RUNTIME_SMOKE == 'true' }}", @@ -408,8 +407,6 @@ def test_caller_example_separates_branch_validation_from_main_publish(self): "AWS_REGION", "AWS_K3S_INSTANCE_ID", "AWS_CD_ARTIFACT_BUCKET", - "CHALLENGE_REGISTRY_TOKEN", - "CHALLENGE_REGISTRY_URL", }, ) From 1de4efff463b056c415f52aad3b9897bd5ebd58a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Fri, 4 Sep 2026 04:41:34 +0900 Subject: [PATCH 7/8] =?UTF-8?q?Backend=20poller=20=EC=9A=B4=EC=98=81=20?= =?UTF-8?q?=EB=AC=B8=EC=84=9C=20=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/README.md | 16 +++---- README.md | 40 ++++++++-------- ci/README.md | 25 +++++----- docs/README.md | 4 +- docs/challenge-registry-integration.md | 49 ++++++++++++-------- docs/devsecops-runbook.md | 54 ++++++++-------------- scripts/README.md | 7 ++- tests/test_backend_poller_documentation.py | 32 +++++++++++++ 8 files changed, 132 insertions(+), 95 deletions(-) create mode 100644 tests/test_backend_poller_documentation.py diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 1d8d402..3118603 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -29,22 +29,22 @@ caller는 자동 실행에서 `source_ref: ${{ github.sha }}`를 전달합니다 - Trivy 취약점·image secret 검사 - CycloneDX SBOM 생성 - GHCR push와 image digest 추출 -- Runtime artifact와 Challenge Registry publish document 생성 +- `artifact-v2.json`과 수동 검증용 `registry-publish.json` 생성 - Actions Summary에 컨테이너별 GHCR digest 표시 - Build/Pull, Trivy Scan, GHCR Push와 합계 시간 측정 - publish bundle을 90일 보관하고 artifact 이름을 caller output으로 제공 -- 설정된 경우 publish document를 Challenge Registry HTTPS API에 등록 - 설정된 경우 SSM을 통해 Secure Provisioner API로 K3s 생성·삭제 smoke test 승인된 `main` 실행만 이 workflow를 호출해 image와 publish bundle을 발행합니다. 출제자 branch와 PR은 `challenge-branch-validation.yml`을 호출합니다. -Challenge Registry 등록은 `publish_registry: true`, -`CHALLENGE_REGISTRY_URL`, `CHALLENGE_REGISTRY_TOKEN`이 모두 설정된 경우에만 -실행합니다. URL과 token은 임의 실행 입력이 아닌 GitHub Secret으로 관리합니다. -기본값은 비활성화이며 Backend DB, Scheduler와 Broker를 workflow가 직접 -조작하지 않습니다. K3s smoke test도 Runtime API를 거치며 Kubernetes resource를 -직접 생성하지 않습니다. +성공한 실행은 `-publish-bundle` suffix의 Actions artifact를 남깁니다. +`artifact-v2.json`은 Backend poller가 자동 수집하는 공식 입력이고, +`registry-publish.json`은 같은 artifact를 감싼 수동 API 검증용 wrapper입니다. +workflow와 caller는 Backend base URL 또는 service token을 사용하지 않으며, +Backend poller가 수집, challenge 매핑, release 등록, 중복 처리를 수행합니다. +Backend/admin이 active release 전환과 롤백을 수행합니다. K3s smoke test는 +Runtime API를 거치며 Kubernetes resource를 직접 생성하지 않습니다. ### `pipeline-self-test.yml` diff --git a/README.md b/README.md index 75b49f8..86aa6e3 100644 --- a/README.md +++ b/README.md @@ -31,8 +31,9 @@ Challenge Repo → CycloneDX SBOM 생성 → OCI Registry에 commit SHA tag로 push → OCI digest 추출 -→ Runtime artifact + Registry publish document 생성 -→ 선택적으로 Challenge Registry API에 revision 등록 +→ `artifact-v2.json`과 수동 검증용 `registry-publish.json` 생성 +→ `-publish-bundle` Actions artifact 보관 +→ Backend poller가 artifact를 수집해 release 등록 ``` Platform 실행 흐름은 다음과 같습니다. @@ -151,7 +152,6 @@ Docker build context와 secret을 검사하고 image를 build한 뒤 Trivy와 Cy - `revision`: 새 Challenge Registry revision - `devsecops_ref`: 공급망 도구 version, 기본값 `main` - `publish_images`: 검사한 image를 GHCR에 발행하고 publish bundle을 생성할지 여부, 기본값 `true` -- `publish_registry`: Challenge Registry API 등록 여부, 기본값 `false` - `enable_k3s_smoke_deploy`: Secure Provisioner API 경유 임시 K3s 배포 검증 여부, 기본값 `false` - `runtime_target_id`: Secure Provisioner Registry의 K3s target ID @@ -161,8 +161,10 @@ Docker build context와 secret을 검사하고 image를 build한 뒤 Trivy와 Cy 출제자 branch와 PR 검증에서는 `publish_images: false`를 사용하고 Secret을 전달하지 않습니다. 이 모드는 Docker build, Gitleaks, Trivy와 SBOM 생성까지만 수행합니다. -GHCR push, Challenge Registry 등록과 Runtime smoke는 승인된 `main` 실행에서만 -활성화합니다. +GHCR push, publish bundle 생성과 Runtime smoke는 승인된 `main` 실행에서만 +활성화합니다. release 등록은 Backend poller가 성공한 Actions artifact를 수집해 +처리하므로 caller와 reusable workflow에 Backend URL 또는 service token을 두지 +않습니다. 출력 artifact: @@ -213,9 +215,11 @@ ghcr.io/msg-ctf/challenges//service@sha256: `info.yaml`의 `deployment.containers`에 선언된 컨테이너만 발행하므로 Compose의 보조 `checker`는 자동 발행하지 않습니다. -## Atomic Publish +## Publish Bundle과 Backend poller -`artifact-v2.json`은 Runtime이 읽을 digest workload입니다. `registry-publish.json`은 Challenge Registry의 원자적 revision 등록 API가 소비할 자료입니다. +`artifact-v2.json`은 Backend poller의 자동 수집과 Runtime이 공통으로 사용하는 +공식 입력이며, digest 고정 workload입니다. `registry-publish.json`은 같은 +artifact를 감싼 수동 API 검증용 wrapper로만 보관합니다. 두 파일에는 `revision`과 같은 값인 `registry_revision`, `isolation_profile`, `workload.containers[]`가 포함됩니다. 모든 최종 image는 @@ -228,18 +232,18 @@ tag와 `latest`는 발행 자료 생성 단계에서 거절합니다. - 모든 image가 digest로 고정돼 있습니다. - Gitleaks와 Trivy 검사가 통과했습니다. - 모든 container의 CycloneDX SBOM이 생성됐습니다. -- 위 조건을 모두 만족해야 active revision 전환을 요청합니다. +- 위 조건을 모두 만족한 bundle만 Backend poller 수집 대상입니다. -`publish_registry: true`이면 workflow가 검증된 `registry-publish.json`을 -`CHALLENGE_REGISTRY_URL` secret에 설정된 HTTPS API로 `POST`합니다. 인증에는 -`CHALLENGE_REGISTRY_TOKEN` secret을 사용하고, 문제, revision, 요청 body SHA-256을 -조합한 `Idempotency-Key`를 전달합니다. API 오류는 성공으로 처리하지 않으며 -Registry 등록 job이 실패합니다. +DevSecOps는 `artifact-v2.json`과 GHCR digest image를 발행하고, Backend poller는 +`-publish-bundle` artifact 수집, challenge 매핑, release 등록, 동일 +`registry_revision`의 중복 처리를 소유합니다. Backend/admin은 active release +전환과 롤백을 소유합니다. Runtime/Secure Provisioner는 active workload의 K3s +배포와 정리를 소유합니다. 혼합 public/private port는 Runtime DTO가 확정될 +때까지 손실 변환하지 않습니다. -이 기능은 Backend의 등록 API가 준비될 때까지 기본적으로 비활성화합니다. CI는 -Backend DB를 직접 수정하지 않고 API 계약만 사용합니다. 선택형 K3s smoke job만 -SSM을 통해 Secure Provisioner API를 호출하며 Scheduler와 Broker의 운영 흐름은 -직접 호출하지 않습니다. +Backend 운영 환경의 `RELEASE_POLL_REPO`와 `RELEASE_POLL_GITHUB_TOKEN`은 Backend +팀이 관리합니다. CI는 Backend DB, Scheduler 또는 Broker를 직접 조작하지 않으며, +선택형 K3s smoke job만 SSM으로 Secure Provisioner API를 호출합니다. ## Runtime K3s Smoke @@ -277,7 +281,7 @@ K3s는 향후 containerd mirror 설정을 통해 내부 OCI mirror를 사용할 사전 pull, mirror 또는 별도 Registry 도입은 MVP 이후 결정하며, 이 경우에도 Runtime에는 digest 고정 reference만 전달합니다. -신규 아키텍처 기준 공급망은 `info.yaml`, 멀티 컨테이너, digest, SBOM, publish bundle을 지원합니다. Challenge Registry API는 Backend endpoint가 준비된 뒤 활성화하고, Runtime 배포 smoke는 Secure Provisioner API를 경유합니다. OCI mirror와 Terraform/Ansible 인프라는 각 담당 팀의 계약에 맞춰 통합 테스트합니다. +신규 아키텍처 기준 공급망은 `info.yaml`, 멀티 컨테이너, digest, SBOM, publish bundle을 지원합니다. Backend poller가 Actions artifact를 수집해 release를 등록하고, Runtime 배포 smoke는 Secure Provisioner API를 경유합니다. OCI mirror와 Terraform/Ansible 인프라는 각 담당 팀의 계약에 맞춰 통합 테스트합니다. Windows container는 Linux image와 같은 build job에서 처리하지 않습니다. Windows runner, node pool, Runtime 및 Registry 계약이 확정된 뒤 별도 workflow로 diff --git a/ci/README.md b/ci/README.md index 6fbb531..ba60682 100644 --- a/ci/README.md +++ b/ci/README.md @@ -86,35 +86,34 @@ commit tag는 추적과 발행을 위한 입력이고 Runtime 계약은 digest KOTH 문제도 같은 규칙을 사용합니다. `info.yaml`의 `deployment.containers`에 선언된 `service`를 발행하며 로컬 Compose 전용 `checker`는 발행 대상이 아닙니다. -### 5. Atomic Publish 자료 +### 5. Publish Bundle 자료 `scripts/generate_publish_bundle.py`가 두 파일을 생성합니다. -- `artifact-v2.json`: Runtime과 Scheduler가 읽을 immutable workload -- `registry-publish.json`: Challenge Registry가 한 transaction으로 revision을 추가하고 active를 전환할 요청 +- `artifact-v2.json`: Backend poller 자동 수집과 Runtime이 읽을 immutable workload +- `registry-publish.json`: 같은 artifact를 감싼 수동 API 검증용 wrapper 두 파일은 같은 `registry_revision`, `isolation_profile`과 `workload.containers[]`를 보존합니다. `workload.internal_connections[]`가 있으면 Runtime은 선언된 방향과 포트만 허용하는 NetworkPolicy를 생성합니다. CI는 raw NetworkPolicy를 생성하거나 전달하지 않습니다. -Registry는 기존 active revision을 먼저 해제한 뒤 새 row를 쓰는 방식으로 처리하면 안 됩니다. 새 revision 저장과 active 전환이 하나의 transaction에서 성공해야 합니다. 실패하면 기존 active revision을 유지해야 합니다. - 실행 중 instance가 참조하는 revision은 active가 아니더라도 보존합니다. -Backend가 등록 API를 제공하면 reusable workflow의 `publish_registry`를 켜서 -`registry-publish.json`을 HTTPS로 전달합니다. API는 `Idempotency-Key`를 기준으로 -같은 문제와 revision의 중복 요청을 안전하게 처리해야 합니다. Registry 등록이 -실패하면 새 revision을 배포 가능 상태로 간주하지 않습니다. +성공한 `-publish-bundle` Actions artifact의 `artifact-v2.json`이 자동 수집의 +공식 입력입니다. Backend poller가 challenge 매핑, release 등록과 같은 +`registry_revision`의 중복 처리를 소유하며, Backend/admin이 active release 전환과 +롤백을 소유합니다. DevSecOps workflow에는 Backend base URL 또는 service token이 +필요하지 않습니다. ## 팀 계약 ### Challenge Registry -- DevSecOps: 검증된 revision publish +- DevSecOps: `artifact-v2.json`과 GHCR digest image 발행 +- Backend poller: Actions artifact 수집, challenge 매핑, release 등록, duplicate 처리 - Scheduler: active revision read-only 조회 -- Backend/Registry: slug와 `challenge_id` 매핑 및 transaction 제공 -- DevSecOps와 Backend: `registry-publish.json` 요청 및 인증 계약 유지 +- Backend/admin: active release 전환과 롤백 ### Resource Broker @@ -134,6 +133,8 @@ DevSecOps는 `isolation_profile`, `workload.containers[]`, `ports[].public`, `workload.internal_connections[]`, `healthcheck`, `resource_profile`을 전달합니다. Runtime은 이를 이용해 Namespace, Pod, Service, Gateway, NetworkPolicy, SecurityContext와 cleanup을 구현합니다. +혼합 public/private port는 Runtime DTO가 확정될 때까지 손실 변환하지 않고 +`artifact-v2.json`에 보존합니다. 발행 후 smoke test는 SSM으로 Runtime node 안의 Secure Provisioner API를 호출해 생성과 삭제 Operation이 모두 성공하는지만 확인합니다. diff --git a/docs/README.md b/docs/README.md index 686ce5f..4c62807 100644 --- a/docs/README.md +++ b/docs/README.md @@ -21,5 +21,5 @@ Monitoring 팀과 맞춰야 할 계약도 포함합니다. ### `challenge-registry-integration.md` -실제 GitHub Actions publish bundle을 백엔드 Challenge Registry 기능 브랜치에 -등록한 통합 검증 증거와 운영 연결 전 남은 조건을 기록합니다. +Backend poller의 Actions artifact 수집 기반 release 등록 운영 계약과, 과거 로컬 +Registry 등록의 호환성 증거를 기록합니다. diff --git a/docs/challenge-registry-integration.md b/docs/challenge-registry-integration.md index 8e6d97c..3bb6c15 100644 --- a/docs/challenge-registry-integration.md +++ b/docs/challenge-registry-integration.md @@ -2,10 +2,17 @@ ## 검증 범위 -2026년 8월 31일, 실제 GitHub Actions 성공 실행의 이미지 발행 결과를 입력으로 -이번 브랜치의 generator가 publish bundle 후보를 다시 생성했고, 이를 백엔드 -PR #26의 Challenge Registry API에 등록했습니다. 운영 서버와 운영 DB는 사용하지 -않았으며 PR #26 commit `fdba92d`를 SQLite 데모 설정으로 실행했습니다. +Backend poller 운영 계약에서 `artifact-v2.json`은 성공한 +`-publish-bundle` Actions artifact에서 수집하는 공식 입력입니다. DevSecOps는 +GHCR digest image와 bundle만 발행하며, Backend poller가 수집, challenge 매핑, +release 등록과 같은 `registry_revision`의 중복 처리를 소유합니다. +Backend/admin은 active release 전환과 롤백을 소유하고, Runtime/Secure +Provisioner는 active workload의 K3s 배포와 정리를 소유합니다. + +아래 2026년 8월 31일 결과는 실제 GitHub Actions 성공 실행의 image 발행 자료를 +후보 bundle으로 재생성해 백엔드 PR #26의 로컬 Registry에 등록한 호환성 증거입니다. +운영 서버와 운영 DB는 사용하지 않았으며 PR #26 commit `fdba92d`를 SQLite 데모 +설정으로 실행했습니다. ## 입력 증거 @@ -36,11 +43,11 @@ private package read 권한이 없어 별도 manifest 재조회는 HTTP 401로 ## 등록 결과 -PR #26의 현재 등록 endpoint는 최종 `registry-publish.json` 계약보다 오래된 -`{"artifact": , "note": ...}` 요청 형식을 사용합니다. 따라서 로컬 -호환성 검증에서는 재생성한 후보의 `artifact-v2`를 이 wrapper에 넣어 등록했습니다. -현재 workflow가 전송하는 `registry-publish.json` 전체 요청은 백엔드 최종 endpoint가 -병합·배포된 뒤 별도로 검증해야 합니다. +PR #26의 현재 등록 endpoint는 수동 API 검증용 `registry-publish.json` +wrapper보다도 오래된 `{"artifact": , "note": ...}` 요청 형식을 +사용합니다. 따라서 로컬 호환성 검증에서는 재생성한 후보의 `artifact-v2`를 이 +wrapper에 넣어 등록했습니다. +이 결과는 poller 수집 경로가 아니라 과거 API 호환성을 확인한 것입니다. 로컬 Registry API는 다음 결과를 반환했습니다. @@ -77,16 +84,20 @@ publish bundle은 raw Kubernetes NetworkPolicy를 포함하지 않습니다. 다 Runtime/Secure Provisioner는 이 값으로 default-deny, DNS, public ingress와 선언된 컨테이너 간 TCP 통신 정책을 생성합니다. 출제자와 CI는 임의 egress 또는 Kubernetes NetworkPolicy를 주입할 수 없습니다. +혼합 public/private port는 Runtime DTO가 확정될 때까지 손실 변환하지 않고 보존합니다. -## 운영 연결 전 남은 조건 +## poller 운영 연결 -- 백엔드 Registry 구현의 `main` 병합과 배포 -- DevSecOps service Bearer token 발급 -- `registry-publish.json` 전체 요청과 `Idempotency-Key` 계약 반영 -- revision 등록과 active 전환의 단일 transaction 처리 -- 멀티 컨테이너 Scheduler 계약과 Registry 모델 통합 -- 운영 endpoint에서 GitHub Actions 실제 전송 재검증 +Backend 운영 환경의 `RELEASE_POLL_REPO`와 `RELEASE_POLL_GITHUB_TOKEN`은 Backend +팀이 관리합니다. reusable workflow와 caller에는 Backend base URL, service token, +직접 전송이 없습니다. -따라서 이번 결과는 실제 Actions 이미지 발행 결과로 재생성한 publish bundle -후보의 **로컬 Challenge Registry 등록 성공** 증거이며, 운영 Challenge Registry -연결 완료 증거는 아닙니다. +실제 poller 통합 완료 증거는 다음을 함께 확인해야 합니다. + +- 성공한 Actions artifact 수집 +- 최초 release 등록 +- 같은 `registry_revision`의 중복 재수집 +- active release가 변하지 않음 + +따라서 위의 로컬 Registry 등록 결과는 **호환성 증거**일 뿐, 운영 poller E2E +완료 증거가 아닙니다. diff --git a/docs/devsecops-runbook.md b/docs/devsecops-runbook.md index 4ca3689..c941881 100644 --- a/docs/devsecops-runbook.md +++ b/docs/devsecops-runbook.md @@ -9,7 +9,7 @@ 5. 컨테이너별 CycloneDX SBOM 생성을 확인합니다. 6. Actions Summary에서 GHCR 경로와 컨테이너별 digest를 확인합니다. 7. 90일 보관되는 `--publish-bundle`을 내려받아 `artifact-v2.json`과 `registry-publish.json`을 검토합니다. -8. Challenge Registry API 연동이 활성화돼 있으면 workflow가 publish document를 한 transaction으로 등록하도록 요청합니다. +8. Backend poller가 성공한 Actions artifact의 `artifact-v2.json`을 수집했는지 확인합니다. 9. Runtime smoke가 활성화돼 있으면 SSM을 통해 Secure Provisioner API로 digest workload를 생성하고 즉시 삭제합니다. ## 발행 전 검수 @@ -51,14 +51,14 @@ - 동일 commit image를 다시 build하지 않고 검사를 통과한 job을 재실행합니다. - 부분적으로 push된 tag는 Runtime에 전달하지 않습니다. -### Registry publish 실패 +### Backend poller 수집 실패 - 기존 active revision을 유지합니다. -- OCI image가 존재하더라도 publish document 처리 전에는 배포 가능 상태로 표시하지 않습니다. -- Registry API 복구 후 같은 revision과 digest로 idempotent하게 재시도합니다. +- OCI image가 존재하더라도 poller 등록 전에는 배포 가능 상태로 표시하지 않습니다. +- Backend가 같은 `registry_revision`과 digest를 재수집해 중복 처리를 확인합니다. - 실행 중 revision을 정리 대상으로 표시하지 않습니다. -## Challenge Registry API 연결 +## Backend poller 연결 출제자 branch와 PR 검증은 `challenge-branch-validation.yml`을 호출하고 `secrets: inherit`를 사용하지 않습니다. @@ -71,34 +71,19 @@ with: devsecops_ref: ``` -GHCR 발행과 외부 연동은 승인된 `main` 실행으로 제한합니다. +GHCR 발행과 Actions artifact 보관은 승인된 `main` 실행으로 제한합니다. +`artifact-v2.json`이 Backend poller 자동 수집의 공식 입력이며, +`registry-publish.json`은 같은 artifact를 감싼 수동 API 검증용 wrapper입니다. -Backend가 revision 등록 API를 제공한 뒤 문제 저장소에 다음 값을 설정합니다. +문제 저장소 caller와 reusable workflow에는 Backend base URL 또는 service token을 +설정하지 않습니다. Backend 팀은 운영 환경에서 `RELEASE_POLL_REPO`와 +`RELEASE_POLL_GITHUB_TOKEN`을 관리하고, poller가 artifact 수집, challenge 매핑, +release 등록 및 동일 `registry_revision` 중복 처리를 수행합니다. -- Repository 또는 Organization Secret `CHALLENGE_REGISTRY_URL`: HTTPS 등록 URL -- Repository 또는 Organization Secret `CHALLENGE_REGISTRY_TOKEN`: 서비스 인증 token - -caller workflow의 reusable workflow 입력은 다음과 같이 설정합니다. - -```yaml -with: - challenge_path: ${{ matrix.challenge_path }} - revision: ${{ github.run_number }} - publish_registry: true -secrets: inherit -``` - -Backend API는 `registry-publish.json` 전체를 요청 body로 받고, Bearer token을 -검증하며, 문제, revision, 요청 body SHA-256으로 구성된 `Idempotency-Key`가 같은 -재시도를 중복 revision으로 만들지 않아야 합니다. 새 revision 저장과 active 전환은 -하나의 transaction으로 처리해야 합니다. -API URL 또는 token이 없거나 API가 오류를 반환하면 Registry 등록 job이 실패합니다. - -Backend PR #26 기능 브랜치에는 Challenge Registry 등록·조회 API와 revision -모델이 있으며 실제 Actions bundle의 로컬 등록을 확인했습니다. 다만 `main` -병합과 운영 배포, service Bearer token, `Idempotency-Key`, 원자적 active 전환 -계약은 아직 완료되지 않았으므로 운영 caller는 `publish_registry: false`를 -유지합니다. 검증 증거는 `docs/challenge-registry-integration.md`에 기록합니다. +Backend/admin만 active release 전환과 롤백을 수행합니다. 실제 poller 통합은 +Actions artifact 수집, 최초 등록, 중복 재수집, active release 미변경을 함께 +확인해야 합니다. 과거 로컬 Registry 등록은 호환성 증거이며 운영 E2E 완료 증거가 +아닙니다. 상세 증거는 `docs/challenge-registry-integration.md`에 기록합니다. ## Secure Provisioner K3s 연결 @@ -127,10 +112,10 @@ GitHub에 저장하지 않고 node의 `/etc/secure-provisioner/service-token`을 1. 기존 revision을 수정하지 않고 새 revision을 만듭니다. 2. 전체 validation, build, scan, SBOM, publish 과정을 다시 실행합니다. -3. Challenge Registry에서 새 revision을 active로 전환합니다. +3. Backend poller가 새 revision을 등록한 뒤 Backend/admin이 active release로 전환합니다. 4. 기존 instance가 참조하는 revision과 digest는 유지합니다. 5. 신규 instance부터 새 active revision을 사용합니다. -6. rollback이 필요하면 이전 revision을 다시 active로 전환합니다. +6. 롤백이 필요하면 Backend/admin이 이전 revision을 다시 active release로 전환합니다. ## 대회 전 점검 @@ -192,7 +177,8 @@ cold pull, 인증 실패, `ImagePullBackOff`, 실행 digest 일치 항목은 Run Challenge Pod의 readiness, image pull 실패, healthcheck 실패 지표와 알림 규칙은 Runtime·Monitoring 팀이 별도로 확정해야 합니다. - GitHub Actions는 검증, GHCR 발행, publish bundle 생성까지 담당합니다. - Backend API가 준비되면 선택형 Registry publish job까지 담당합니다. + Backend poller는 Actions artifact 수집, challenge 매핑, release 등록과 중복 + 처리를 담당하고, Backend/admin은 active release 전환과 롤백을 담당합니다. 참가자 요청에 따른 Namespace, Pod, Service, TTL cleanup은 Runtime과 Scheduler의 운영 책임입니다. diff --git a/scripts/README.md b/scripts/README.md index cab1fe2..8b6785d 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -27,8 +27,8 @@ matrix와 정규화된 metadata를 생성합니다. 검사와 발행을 통과한 컨테이너별 digest 및 SBOM을 모아 다음 자료를 생성합니다. -- `artifact-v2.json`: Runtime과 Scheduler가 사용할 immutable workload -- `registry-publish.json`: Challenge Registry revision 등록 요청 자료 +- `artifact-v2.json`: Backend poller 자동 수집과 Runtime이 사용할 immutable workload +- `registry-publish.json`: 같은 artifact를 감싼 수동 API 검증용 wrapper 두 자료에는 같은 `registry_revision`, digest 고정 `workload.containers[]`와 `isolation_profile`이 포함됩니다. tag, `latest`, MSG-CTF GHCR 밖의 최종 image는 @@ -36,6 +36,9 @@ matrix와 정규화된 metadata를 생성합니다. 컨테이너별 공급망 소요 시간을 검증해 `artifact-v2.json`의 `evidence.containers[].timing`에 보존합니다. +Backend poller는 성공한 `-publish-bundle` artifact에서 이 파일을 수집해 challenge +매핑, release 등록과 같은 `registry_revision`의 중복 처리를 수행합니다. 혼합 +public/private port는 Runtime DTO가 확정될 때까지 변환하지 않고 보존합니다. ### `pipeline_timing.py` diff --git a/tests/test_backend_poller_documentation.py b/tests/test_backend_poller_documentation.py new file mode 100644 index 0000000..c7fdd9f --- /dev/null +++ b/tests/test_backend_poller_documentation.py @@ -0,0 +1,32 @@ +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +DOCUMENTS = ( + ROOT / "README.md", + ROOT / ".github/workflows/README.md", + ROOT / "ci/README.md", + ROOT / "docs/README.md", + ROOT / "docs/challenge-registry-integration.md", + ROOT / "docs/devsecops-runbook.md", + ROOT / "scripts/README.md", +) + + +class BackendPollerDocumentationTests(unittest.TestCase): + def test_documents_poller_without_direct_registry_push_settings(self): + text = "\n".join(path.read_text(encoding="utf-8") for path in DOCUMENTS) + self.assertIn("Backend poller", text) + self.assertIn("artifact-v2.json", text) + for forbidden in ( + "publish_registry: true", + "CHALLENGE_REGISTRY_URL", + "CHALLENGE_REGISTRY_TOKEN", + "Idempotency-Key", + ): + self.assertNotIn(forbidden, text) + + +if __name__ == "__main__": + unittest.main() From 9163902b05b924f44e34262744a9b364795d195f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Fri, 4 Sep 2026 13:53:38 +0900 Subject: [PATCH 8/8] =?UTF-8?q?Backend=20poller=20=EB=AC=B8=EC=84=9C=20?= =?UTF-8?q?=EA=B3=84=EC=95=BD=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EA=B0=95?= =?UTF-8?q?=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_backend_poller_documentation.py | 27 ++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/tests/test_backend_poller_documentation.py b/tests/test_backend_poller_documentation.py index c7fdd9f..4a57f44 100644 --- a/tests/test_backend_poller_documentation.py +++ b/tests/test_backend_poller_documentation.py @@ -12,13 +12,12 @@ ROOT / "docs/devsecops-runbook.md", ROOT / "scripts/README.md", ) +POLLER_CONTRACT_DOCUMENT = ROOT / "docs/challenge-registry-integration.md" class BackendPollerDocumentationTests(unittest.TestCase): def test_documents_poller_without_direct_registry_push_settings(self): text = "\n".join(path.read_text(encoding="utf-8") for path in DOCUMENTS) - self.assertIn("Backend poller", text) - self.assertIn("artifact-v2.json", text) for forbidden in ( "publish_registry: true", "CHALLENGE_REGISTRY_URL", @@ -27,6 +26,30 @@ def test_documents_poller_without_direct_registry_push_settings(self): ): self.assertNotIn(forbidden, text) + def test_challenge_registry_document_records_backend_poller_contracts(self): + text = " ".join(POLLER_CONTRACT_DOCUMENT.read_text(encoding="utf-8").split()) + + self.assertIn( + "`artifact-v2.json`은 성공한 `-publish-bundle` Actions artifact에서 수집하는 공식 입력입니다.", + text, + ) + self.assertIn("수동 API 검증용 `registry-publish.json` wrapper", text) + self.assertIn( + "reusable workflow와 caller에는 Backend base URL, service token, 직접 전송이 없습니다.", + text, + ) + self.assertIn( + "Backend 운영 환경의 `RELEASE_POLL_REPO`와 `RELEASE_POLL_GITHUB_TOKEN`은 Backend 팀이 관리합니다.", + text, + ) + self.assertIn("`registry_revision`의 중복 처리를 소유합니다.", text) + self.assertIn("Backend/admin은 active release 전환과 롤백을 소유하고", text) + self.assertIn("혼합 public/private port는 Runtime DTO가 확정될 때까지 손실 변환하지 않고 보존합니다.", text) + self.assertIn("성공한 Actions artifact 수집", text) + self.assertIn("최초 release 등록", text) + self.assertIn("같은 `registry_revision`의 중복 재수집", text) + self.assertIn("active release가 변하지 않음", text) + if __name__ == "__main__": unittest.main()