diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 30b2280..b9b45a2 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -5,6 +5,14 @@ workflow를 관리합니다. ## 파일 +### `published-runtime-smoke.yml` + +성공한 main 발행본을 선택하는 별도 수동 caller용 reusable workflow입니다. +선택한 실행·artifact·bundle의 출처를 검증한 뒤 승인된 단일 WEB 문제의 Runtime +생성·삭제를 시험합니다. 이미지 재발행이나 Backend 등록은 하지 않으며, 시험이 +실패해도 원래 발행 실행의 상태에는 영향을 주지 않습니다. +[실행 조건과 검증 범위](../../docs/published-runtime-smoke.md)를 확인합니다. + ### `ghcr-cleanup-dry-run.yml` 수동 실행하는 GHCR 이미지 정리 후보 조회입니다. package 읽기 권한만 사용하고 diff --git a/.github/workflows/pipeline-self-test.yml b/.github/workflows/pipeline-self-test.yml index fda92ea..32ccc36 100644 --- a/.github/workflows/pipeline-self-test.yml +++ b/.github/workflows/pipeline-self-test.yml @@ -6,6 +6,7 @@ on: paths: - ".github/workflows/challenge-branch-validation.yml" - ".github/workflows/challenge-supply-chain.yml" + - ".github/workflows/published-runtime-smoke.yml" - ".github/workflows/pipeline-self-test.yml" - ".github/workflows/ghcr-cleanup-dry-run.yml" - "ci/**" @@ -16,6 +17,7 @@ on: paths: - ".github/workflows/challenge-branch-validation.yml" - ".github/workflows/challenge-supply-chain.yml" + - ".github/workflows/published-runtime-smoke.yml" - ".github/workflows/pipeline-self-test.yml" - ".github/workflows/ghcr-cleanup-dry-run.yml" - "ci/**" diff --git a/.github/workflows/published-runtime-smoke.yml b/.github/workflows/published-runtime-smoke.yml new file mode 100644 index 0000000..727324a --- /dev/null +++ b/.github/workflows/published-runtime-smoke.yml @@ -0,0 +1,160 @@ +name: 발행 bundle 독립 Runtime 검증 + +on: + workflow_call: + inputs: + source_run_id: + description: 성공한 main 출제 문제 검증 run ID + required: true + type: string + challenge_slug: + description: Runtime 정책에서 승인한 단일 WEB 문제 slug + required: true + type: string + confirm_deploy: + description: 승인한 CI 대상에 임시 생성·삭제를 실행할지 확인 + required: false + default: false + type: boolean + devsecops_ref: + description: 검토한 공급망 도구 commit SHA + required: true + type: string + runtime_api_url: + required: true + type: string + runtime_ci_team_id: + required: true + type: string + runtime_target_id: + required: true + type: string + secrets: + RUNTIME_API_TOKEN: + required: true + +permissions: + contents: read + actions: read + +jobs: + smoke: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: 수동 main 실행과 승인 확인 + env: + CONFIRM_DEPLOY: ${{ inputs.confirm_deploy }} + SOURCE_RUN_ID: ${{ inputs.source_run_id }} + CHALLENGE_SLUG: ${{ inputs.challenge_slug }} + DEVSECOPS_REF: ${{ inputs.devsecops_ref }} + run: | + set -euo pipefail + test "$GITHUB_EVENT_NAME" = workflow_dispatch || { echo "Runtime 시험은 수동 실행만 허용합니다" >&2; exit 1; } + test "$GITHUB_REF" = refs/heads/main || { echo "Runtime 시험은 main 실행만 허용합니다" >&2; exit 1; } + test "$CONFIRM_DEPLOY" = true || { echo "임시 생성·삭제 승인 확인이 필요합니다" >&2; exit 1; } + [[ "$SOURCE_RUN_ID" =~ ^[1-9][0-9]{0,18}$ ]] || { echo "run ID 형식을 확인하세요" >&2; exit 1; } + [[ "$CHALLENGE_SLUG" =~ ^[a-z0-9][a-z0-9-]{0,62}$ ]] || { echo "문제 slug 형식을 확인하세요" >&2; exit 1; } + [[ "$DEVSECOPS_REF" =~ ^[0-9a-f]{40}$ ]] || { echo "검토한 도구 SHA가 필요합니다" >&2; exit 1; } + + - name: 검토한 Runtime 도구 가져오기 + uses: actions/checkout@v4 + with: + repository: MSG-CTF/msgctf-devsecops + ref: ${{ inputs.devsecops_ref }} + path: .msgctf-ci + persist-credentials: false + + - name: Python 설정 + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: 성공한 발행 실행과 전체 artifact 목록 조회 + env: + GH_TOKEN: ${{ github.token }} + SOURCE_RUN_ID: ${{ inputs.source_run_id }} + run: | + set -euo pipefail + mkdir -p evidence + gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${SOURCE_RUN_ID}" > evidence/run.json + gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/actions/runs/${SOURCE_RUN_ID}/artifacts?per_page=100" > evidence/pages.json + + - name: 발행 출처와 bundle 선택 검증 + id: source + env: + SOURCE_RUN_ID: ${{ inputs.source_run_id }} + CHALLENGE_SLUG: ${{ inputs.challenge_slug }} + run: | + python3 .msgctf-ci/scripts/validate_runtime_smoke_source.py select \ + --run evidence/run.json --pages evidence/pages.json \ + --repository "$GITHUB_REPOSITORY" --run-id "$SOURCE_RUN_ID" \ + --challenge-slug "$CHALLENGE_SLUG" \ + --output evidence/selection.json --github-output "$GITHUB_OUTPUT" + + - name: 검증한 발행 bundle만 가져오기 + uses: actions/download-artifact@v4 + with: + artifact-ids: ${{ steps.source.outputs.artifact_id }} + run-id: ${{ inputs.source_run_id }} + repository: ${{ github.repository }} + github-token: ${{ github.token }} + merge-multiple: true + path: dist/publish-bundle + + - name: CI 전용 대상과 bundle 계약 확인 + env: + RUNTIME_API_URL: ${{ inputs.runtime_api_url }} + RUNTIME_CI_TEAM_ID: ${{ inputs.runtime_ci_team_id }} + RUNTIME_TARGET_ID: ${{ inputs.runtime_target_id }} + SMOKE_KEY: ${{ github.repository_id }}:${{ github.run_id }}:${{ github.run_attempt }} + run: | + set -euo pipefail + case "$RUNTIME_API_URL" in https://*) ;; *) echo "Runtime HTTPS URL이 필요합니다" >&2; exit 1 ;; esac + test -n "$RUNTIME_CI_TEAM_ID" || { echo "CI 전용 team ID가 필요합니다" >&2; exit 1; } + test -n "$RUNTIME_TARGET_ID" || { echo "target ID가 필요합니다" >&2; exit 1; } + instance_id="$(python3 -c 'import os, uuid; print(uuid.uuid5(uuid.NAMESPACE_URL, os.environ["SMOKE_KEY"]))')" + jq -n --arg team_id "$RUNTIME_CI_TEAM_ID" --arg target_id "$RUNTIME_TARGET_ID" --arg instance_id "$instance_id" \ + '{team_id:$team_id,target_id:$target_id,instance_id:$instance_id}' > evidence/runtime-config.json + python3 .msgctf-ci/scripts/validate_runtime_smoke_source.py verify \ + --artifact dist/publish-bundle/artifact-v2.json \ + --selection evidence/selection.json --config evidence/runtime-config.json + + - name: 독립 Runtime HTTPS 생성·삭제 검증 + env: + RUNTIME_API_URL: ${{ inputs.runtime_api_url }} + RUNTIME_API_TOKEN: ${{ secrets.RUNTIME_API_TOKEN }} + run: | + set -euo pipefail + test -n "$RUNTIME_API_TOKEN" || { echo "RUNTIME_API_TOKEN Secret이 필요합니다" >&2; exit 1; } + umask 077 + token_file="$(mktemp)" + trap 'rm -f "$token_file"' EXIT INT TERM + printf '%s' "$RUNTIME_API_TOKEN" > "$token_file" + python3 .msgctf-ci/scripts/runtime_api_smoke_runner.py \ + --artifact dist/publish-bundle/artifact-v2.json \ + --config evidence/runtime-config.json --api-url "$RUNTIME_API_URL" \ + --token-file "$token_file" --timeout 300 --cleanup-timeout 300 \ + | tee evidence/runtime-smoke-result.txt + result="$(sed -n 's/^MSGCTF_RUNTIME_SMOKE_RESULT=//p' evidence/runtime-smoke-result.txt | tail -n 1)" + test -n "$result" + printf '%s\n' "$result" | jq -e '.create_status == "SUCCEEDED" and .delete_status == "SUCCEEDED"' >/dev/null + { + echo "## 발행본 독립 Runtime 검증" + echo '출처·결과는 아래 증거에 기록하며 Backend 등록·활성화는 수행하지 않습니다.' + echo '```json' + cat evidence/selection.json + printf '%s\n' "$result" | jq + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + + - name: 출처와 Runtime 시험 결과 보관 + if: always() + uses: actions/upload-artifact@v4 + with: + name: runtime-verification-${{ github.run_id }}-${{ github.run_attempt }} + path: | + evidence/selection.json + evidence/runtime-smoke-result.txt + if-no-files-found: warn + retention-days: 14 diff --git a/docs/README.md b/docs/README.md index 0a38fed..a14b1a9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,5 +1,6 @@ # 문서 +- [발행본 독립 Runtime 검증](published-runtime-smoke.md): 성공한 main 발행본의 출처 검증과 발행 실행에 영향을 주지 않는 단일 WEB 생성·삭제 시험 - [2026-10-21 Backend 개발 서버 전달 자료](reports/2026-10-21-backend-handoff/README.md): 최신 37개 발행 대조와 문제별 revision·run·artifact, 배포 성공 기록 및 서버 확인 요청 - [2026-10-20 최신 발행 대조](reports/2026-10-20-release-readiness/README.md): 37개 문제 폴더와 성공 산출물 일치, 실패한 Runtime 시험과 수집 계약 구분 - [2026-10-19 병합 후 연동 점검](reports/2026-10-19-release-readiness/README.md): 실제 main 산출물 대조, Notebook revision 529·정책 확인과 남은 배포 검증 diff --git a/docs/published-runtime-smoke.md b/docs/published-runtime-smoke.md new file mode 100644 index 0000000..8ae182c --- /dev/null +++ b/docs/published-runtime-smoke.md @@ -0,0 +1,91 @@ +# 발행본 독립 Runtime 검증 + +## 목적과 책임 + +문제 발행과 실제 서버 시험을 서로 다른 GitHub Actions 실행으로 나눕니다. +이미지 검사·GHCR 발행·bundle 생성이 성공했다면 Backend Poller는 해당 성공 실행의 +산출물을 수집할 수 있습니다. 이후 별도 Runtime 시험이 실패하더라도 원래 발행 +실행의 성공 여부는 바뀌지 않습니다. Runtime 시험 자체의 실패는 그대로 실패로 +기록하며 `continue-on-error`로 감추지 않습니다. + +Backend의 `completed`·`success` 실행만 수집하는 기준은 유지합니다. 기존 실패 실행에 +이미 bundle이 있더라도 수집 대상으로 억지로 인정하지 않습니다. + +## 지원 범위 + +- 이미 완료·성공한 문제 저장소 `main` 발행 실행을 수동으로 선택합니다. +- Runtime 운영자가 정확한 GHCR digest를 승인한 일반 WEB 문제만 시험합니다. +- 첫 경로는 단일 컨테이너, `KUBERNETES`, `AMD64`, `WEB`으로 제한합니다. +- 기존 Runtime API 요청 변환기와 HTTPS·인증서 검사, 응답 검사, 삭제 확인을 재사용합니다. +- 새 이미지 빌드·push, Backend API 호출, release 활성화는 하지 않습니다. +- KOTH, PWN, 멀티 컨테이너, 전용 VM 및 Windows 배포를 자동 지원하지 않습니다. + +Afterimage의 전용 VM 배포는 Runtime·Scheduler·Broker가 연결한 별도 경로입니다. +이 단일 WEB smoke의 성공을 해당 경로 또는 전체 격리 검증의 성공으로 기록하지 않습니다. + +## 실행 계약 + +문제 저장소의 별도 수동 caller가 다음 reusable workflow를 호출합니다. + +`.github/workflows/published-runtime-smoke.yml` + +| 입력 | 설명 | +| --- | --- | +| `source_run_id` | 성공한 `challenge-validation.yml` 실행 ID | +| `challenge_slug` | 해당 실행에서 발행한 승인 WEB 문제 | +| `confirm_deploy` | 임시 생성·삭제를 명시적으로 승인, 기본 `false` | +| `devsecops_ref` | 검토한 DevSecOps 도구의 전체 commit SHA | +| `runtime_api_url` | 인증서가 유효한 Runtime HTTPS API 주소 | +| `runtime_ci_team_id` | 서버 측 제한 토큰에 허용된 CI 전용 팀 UUID | +| `runtime_target_id` | 서버 측 제한 토큰에 허용된 현재 target | + +Secret은 `RUNTIME_API_TOKEN`만 사용합니다. GHCR pull 인증은 Runtime 노드가 관리하며 +API 토큰과 혼용하지 않습니다. 토큰은 로그·산출물에 저장하지 않고, 임시 파일은 +접근 권한을 제한해 사용 후 삭제합니다. + +실제 시험 전 Runtime팀과 현재 배포 SHA, 정확한 이미지 digest·UID·쓰기 경로·포트 +승인, 제한된 CI 토큰, target 사용 가능 여부 및 이전 잔여 리소스를 확인해야 합니다. +선택한 bundle의 자원 요구량도 해당 target에 승인된 범위인지 확인합니다. + +## 출처 검증과 흐름 + +1. 수동 실행이며 caller의 실행 ref가 `refs/heads/main`인지 확인합니다. +2. 선택한 원본 실행이 같은 저장소의 공식 `challenge-validation.yml`, `main`, + `push` 또는 `workflow_dispatch`, 완료·성공 상태인지 확인합니다. +3. artifact 전체 페이지를 조회하고 현재 run attempt의 문제별 publish bundle이 + 정확히 하나인지 확인합니다. 만료되거나 16 MiB를 초과하는 압축본은 거절합니다. +4. 검증한 artifact ID만 다운로드합니다. 다른 문제·이전 시도의 산출물을 섞지 않습니다. +5. `artifact-v2.json`의 source SHA, main ref, slug, revision과 원본 실행의 출처가 + 일치하는지 확인합니다. `PASS`, GHCR digest, 자원·포트·healthcheck 계약도 검사합니다. +6. CI 실행·재시도별 instance UUID를 만들어 기존 Runtime runner로 생성·조회·삭제합니다. + 생성 실패나 응답 오류가 나도 기존 runner의 삭제 확인 절차를 유지합니다. +7. 별도 실행에 출처 목록과 정제된 생성·삭제 결과를 보관합니다. + +caller는 같은 CI target을 쓰는 smoke를 직렬 실행하고 `cancel-in-progress: false`로 +설정해야 합니다. 자동 취소로 삭제 절차를 끊지 않도록 합니다. 수동 강제 취소나 +러너 종료까지 정리를 보장하는 것은 아니므로 이 경우 Runtime 리소스를 별도 확인합니다. + +## 실패 job만 재실행한 발행본의 제한 + +`Re-run failed jobs`로 원본 발행 run이 최종 성공했더라도, publish job을 재실행하지 +않았다면 bundle 이름에는 이전 attempt 번호가 남을 수 있습니다. 이 workflow는 +원본 run의 현재 `run_attempt`와 artifact 이름의 attempt가 같은 경우만 선택하므로, +이전 attempt의 bundle만 남아 있으면 다운로드·Runtime 호출 전에 거절합니다. + +이전 attempt를 자동으로 대신 선택하지 않습니다. 같은 승인 소스의 다른 성공 run을 +사용하거나, 문제 저장소 main의 수동 발행에서 해당 문제 하나를 새로 발행한 뒤 +새 성공 run ID를 선택합니다. 새 발행은 비용과 revision 증가가 있으므로 운영 승인에 +따라 진행하며, 이 제한을 해소하려고 실패 실행을 성공으로 표시하지 않습니다. + +## 결과 해석 + +발행 run ID, artifact ID·이름, SHA, slug, revision을 `selection.json`에 남기고 +정제된 Runtime 결과와 함께 14일 보관합니다. 원본 bundle과 token 파일은 재업로드하지 않습니다. + +성공은 기존 runner가 확인한 Runtime 생성 성공, endpoint 응답 계약과 삭제 완료를 뜻합니다. +실제 공개 URL의 HTTP 응답, 노드의 cold pull 시간·실행 digest, 다른 인스턴스와의 격리, +reset, 정상·실패 probe 및 운영 부하는 별도 연동 시험으로 확인해야 합니다. + +이 workflow의 단위 테스트 통과만으로 실제 배포 성공을 선언하지 않습니다. +중앙 reusable workflow를 병합한 뒤 caller의 workflow SHA와 `devsecops_ref`를 같은 +병합 SHA로 갱신하고, 승인한 단일 WEB 발행본으로 최초 실제 실행을 진행합니다. diff --git a/scripts/README.md b/scripts/README.md index bdc708d..b2563cf 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -9,6 +9,13 @@ Provisioner API 요청으로 변환합니다. 생성 Operation을 조회한 뒤 ## 파일 +### `validate_runtime_smoke_source.py` + +독립 Runtime 시험에서 성공한 main 발행 run과 전체 artifact 페이지를 대조합니다. +문제·시도별 bundle 하나만 선택하고 source SHA·revision·GHCR digest를 검증합니다. +단일 WEB·KUBERNETES·AMD64 범위에서 기존 요청 변환기를 재사용하며 Runtime은 호출하지 않습니다. +[독립 시험 운영 절차](../docs/published-runtime-smoke.md)를 참고합니다. + ### `audit_publication_state.py` GitHub CLI의 기존 인증으로 문제 저장소 main의 37개 문제 명세와 실행별 artifact diff --git a/scripts/validate_runtime_smoke_source.py b/scripts/validate_runtime_smoke_source.py new file mode 100644 index 0000000..6de8a07 --- /dev/null +++ b/scripts/validate_runtime_smoke_source.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""성공한 main 발행본의 출처를 확인하며 네트워크나 Runtime은 호출하지 않습니다.""" + +import argparse +import json +from pathlib import Path +import re +import sys + +if __package__: + from .runtime_api_smoke_runner import build_create_request +else: + from runtime_api_smoke_runner import build_create_request + + +SLUG = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$") +SHA = re.compile(r"^[0-9a-f]{40}$") +MAX_JSON_BYTES = 1024 * 1024 +MAX_ARCHIVE_BYTES = 16 * 1024 * 1024 + + +def positive(value): + return type(value) is int and value > 0 + + +def select_source(run, pages, repository, run_id, slug): + if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository) or not SLUG.fullmatch(slug): + raise ValueError("저장소 또는 문제 식별자 형식이 잘못됐습니다") + if not positive(run_id) or not isinstance(run, dict) or run.get("id") != run_id or type(run.get("id")) is not int: + raise ValueError("발행 run ID가 일치하지 않습니다") + if run.get("status") != "completed" or run.get("conclusion") != "success": + raise ValueError("완료·성공한 발행 workflow만 사용할 수 있습니다") + if run.get("path") != ".github/workflows/challenge-validation.yml" or run.get("head_branch") != "main": + raise ValueError("공식 main 발행 workflow가 아닙니다") + if not isinstance(run.get("event"), str) or run["event"] not in {"push", "workflow_dispatch"}: + raise ValueError("발행 이벤트가 허용되지 않습니다") + for field in ("repository", "head_repository"): + full_name = run[field].get("full_name") if isinstance(run.get(field), dict) else None + if not isinstance(full_name, str) or full_name.lower() != repository.lower(): + raise ValueError("외부 저장소의 발행본은 사용할 수 없습니다") + if not isinstance(run.get("head_sha"), str) or not SHA.fullmatch(run["head_sha"]): + raise ValueError("발행 commit SHA가 올바르지 않습니다") + if not positive(run.get("run_number")) or not positive(run.get("run_attempt")): + raise ValueError("발행 revision 또는 시도 번호가 올바르지 않습니다") + if not isinstance(pages, list) or not pages: + raise ValueError("전체 artifact 페이지가 필요합니다") + artifacts = [] + total = pages[0].get("total_count") if isinstance(pages[0], dict) else None + if type(total) is not int or total < 0: + raise ValueError("artifact 목록 크기가 올바르지 않습니다") + for page in pages: + if (not isinstance(page, dict) or type(page.get("total_count")) is not int + or page["total_count"] != total or not isinstance(page.get("artifacts"), list)): + raise ValueError("artifact 페이지가 일치하지 않습니다") + artifacts.extend(page["artifacts"]) + if len(artifacts) != total or any(not isinstance(item, dict) or not positive(item.get("id")) for item in artifacts): + raise ValueError("artifact 전체 목록을 확인하지 못했습니다") + if len({item["id"] for item in artifacts}) != len(artifacts): + raise ValueError("artifact 페이지에 중복이 있습니다") + name = re.compile(re.escape(f"{slug}-{run_id}-{run['run_attempt']}-") + r"[0-9a-f]+-publish-bundle$") + matches = [item for item in artifacts if isinstance(item.get("name"), str) and name.fullmatch(item["name"])] + if len(matches) != 1: + raise ValueError("선택한 문제·현재 시도의 publish bundle이 정확히 하나여야 합니다") + artifact = matches[0] + if artifact.get("expired") is not False or not positive(artifact.get("size_in_bytes")) or artifact["size_in_bytes"] > MAX_ARCHIVE_BYTES: + raise ValueError("만료되었거나 크기 제한을 넘긴 bundle입니다") + origin = artifact.get("workflow_run") + if not isinstance(origin, dict) or type(origin.get("id")) is not int or origin["id"] != run_id or origin.get("head_sha") != run["head_sha"] or origin.get("head_branch") != "main": + raise ValueError("artifact와 발행 run 출처가 일치하지 않습니다") + return {"repository": repository, "run_id": run_id, "artifact_id": artifact["id"], + "artifact_name": artifact["name"], "challenge_slug": slug, "source_sha": run["head_sha"], + "registry_revision": run["run_number"]} + + +def verify_bundle(artifact, selection, config): + if not isinstance(artifact, dict) or not isinstance(selection, dict) or not isinstance(config, dict): + raise ValueError("bundle·출처·설정은 JSON 객체여야 합니다") + if artifact.get("schema_version") != "2.0" or artifact.get("source_ref") != "refs/heads/main": + raise ValueError("지원하는 main 발행 bundle이 아닙니다") + if not isinstance(selection.get("challenge_slug"), str) or not SLUG.fullmatch(selection["challenge_slug"]) or not isinstance(selection.get("source_sha"), str) or not SHA.fullmatch(selection["source_sha"]) or not positive(selection.get("registry_revision")): + raise ValueError("검증된 출처 정보가 올바르지 않습니다") + for field in ("challenge_slug", "source_sha", "registry_revision"): + if artifact.get(field) != selection.get(field) or field not in selection: + raise ValueError("bundle과 검증된 출처가 일치하지 않습니다") + category = artifact.get("category") + if not isinstance(category, str) or category.lower() == "koth" or artifact.get("isolation_profile") != "WEB": + raise ValueError("이 시험은 승인된 일반 WEB 문제만 지원합니다") + containers = artifact.get("workload", {}).get("containers") if isinstance(artifact.get("workload"), dict) else None + if not isinstance(containers, list) or len(containers) != 1 or not isinstance(containers[0], dict): + raise ValueError("이 시험은 승인된 단일 컨테이너만 지원합니다") + container = containers[0] + name = container.get("name") + if not isinstance(name, str) or not SLUG.fullmatch(name): + raise ValueError("컨테이너 이름이 올바르지 않습니다") + expected = f"ghcr.io/msg-ctf/challenges/{selection['challenge_slug']}/{name}@sha256:" + if not isinstance(container.get("image"), str) or not re.fullmatch(re.escape(expected) + r"[0-9a-f]{64}", container["image"]): + raise ValueError("문제·컨테이너의 GHCR digest 고정 이미지가 아닙니다") + # 기존 계약 변환기를 재사용해 PASS·revision·포트·자원·healthcheck도 확인합니다. + build_create_request(artifact, target_id=config.get("target_id"), instance_id=config.get("instance_id"), team_id=config.get("team_id")) + + +def read_json(path): + path = Path(path) + if path.is_symlink() or not path.is_file() or path.stat().st_size > MAX_JSON_BYTES: + raise ValueError("JSON 파일 경로나 크기를 확인하세요") + return json.loads(path.read_text(encoding="utf-8")) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + select = sub.add_parser("select") + select.add_argument("--run", required=True, type=Path) + select.add_argument("--pages", required=True, type=Path) + select.add_argument("--repository", required=True) + select.add_argument("--run-id", required=True, type=int) + select.add_argument("--challenge-slug", required=True) + select.add_argument("--output", required=True, type=Path) + select.add_argument("--github-output", type=Path) + verify = sub.add_parser("verify") + verify.add_argument("--artifact", required=True, type=Path) + verify.add_argument("--selection", required=True, type=Path) + verify.add_argument("--config", required=True, type=Path) + args = parser.parse_args() + try: + if args.command == "select": + selection = select_source(read_json(args.run), read_json(args.pages), args.repository, args.run_id, args.challenge_slug) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(selection, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + if args.github_output: + with args.github_output.open("a", encoding="utf-8") as stream: + stream.write(f"artifact_id={selection['artifact_id']}\n") + print("성공한 main publish bundle의 출처를 확인했습니다") + else: + verify_bundle(read_json(args.artifact), read_json(args.selection), read_json(args.config)) + print("발행 bundle 출처·digest·기존 Runtime 요청 계약을 확인했습니다") + except (ValueError, OSError, TypeError, KeyError, RecursionError): + print("Runtime 시험 입력 검증 실패: 성공한 main 발행본·출처·지원 범위를 확인하세요", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/README.md b/tests/README.md index 94a36bb..f8c6acf 100644 --- a/tests/README.md +++ b/tests/README.md @@ -5,6 +5,15 @@ ## 테스트 구성 +### `test_validate_runtime_smoke_source.py` + +공식 main 성공 실행·전체 artifact pagination·시도 번호·만료·출처·SHA·revision과 +digest 검증을 확인합니다. KOTH·PWN·VM·멀티 컨테이너의 암묵적 승인과 비밀값 노출을 +차단하고, 독립 workflow가 발행·권한 확대·실패 무시를 하지 않는지 검사합니다. +첫 승인 step의 실제 셸을 이벤트·ref 28개 조합과 승인 누락 입력으로 실행합니다. +독립 workflow만 바뀌어도 push·PR 자체 검사가 실행되는지 확인하고, +실패 job만 재실행한 run의 이전 attempt bundle은 자동 재사용하지 않도록 검증합니다. + ### `test_audit_publication_state.py` 정적·동적 문제의 필수 산출물, 실패·실행 중·만료된 artifact 제외, revision 우선순위, diff --git a/tests/test_validate_runtime_smoke_source.py b/tests/test_validate_runtime_smoke_source.py new file mode 100644 index 0000000..be4fcad --- /dev/null +++ b/tests/test_validate_runtime_smoke_source.py @@ -0,0 +1,206 @@ +import copy +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +import yaml + +from scripts.validate_runtime_smoke_source import read_json, select_source, verify_bundle + + +ROOT = Path(__file__).resolve().parents[1] +REPOSITORY = "MSG-CTF/2026_MSG_CTF" + + +class PublishedRuntimeSmokeTests(unittest.TestCase): + def setUp(self): + self.run = {"id": 100, "run_number": 5, "run_attempt": 1, "status": "completed", "conclusion": "success", + "path": ".github/workflows/challenge-validation.yml", "head_branch": "main", "head_sha": "a" * 40, + "event": "push", "repository": {"full_name": REPOSITORY}, "head_repository": {"full_name": REPOSITORY}} + self.artifact = {"id": 200, "name": "web-test-100-1-abc123-publish-bundle", "expired": False, "size_in_bytes": 1000, + "workflow_run": {"id": 100, "head_sha": "a" * 40, "head_branch": "main"}} + self.pages = [{"total_count": 1, "artifacts": [self.artifact]}] + self.config = {"target_id": "ci-target", "instance_id": "11111111-1111-4111-8111-111111111111", + "team_id": "22222222-2222-4222-8222-222222222222"} + self.bundle = {"schema_version": "2.0", "challenge_slug": "web-test", "source_ref": "refs/heads/main", "source_sha": "a" * 40, + "revision": 5, "registry_revision": 5, "category": "web", "scan_result": "PASS", "isolation_profile": "WEB", + "runtime_type": "KUBERNETES", "architecture": "AMD64", "resource_profile": { + "cpu_millicores": 500, "memory_mib": 512, "ephemeral_storage_mib": 1024}, + "workload": {"containers": [{"name": "web", "image": "ghcr.io/msg-ctf/challenges/web-test/web@sha256:" + "b" * 64, + "ports": [{"port": 8080, "public": True}]}]}} + + def select(self): + return select_source(self.run, self.pages, REPOSITORY, 100, "web-test") + + def test_valid_source_and_bundle_are_not_mutated_or_deployed(self): + before = copy.deepcopy((self.run, self.pages, self.bundle)) + selection = self.select() + verify_bundle(self.bundle, selection, self.config) + self.assertEqual(selection["artifact_id"], 200) + self.assertEqual(selection["registry_revision"], 5) + self.assertEqual(before, (self.run, self.pages, self.bundle)) + + def test_failed_running_cancelled_or_wrong_workflow_cannot_be_selected(self): + for patch in ({"status": "in_progress"}, {"conclusion": "failure"}, {"conclusion": "cancelled"}, + {"path": ".github/workflows/runtime-published-bundle-smoke.yml"}, {"head_branch": "feature"}, + {"event": "pull_request"}, {"event": []}, {"head_sha": "../bad"}, {"run_number": True}, {"run_attempt": 0}): + with self.subTest(patch=patch), self.assertRaises(ValueError): + select_source({**self.run, **patch}, self.pages, REPOSITORY, 100, "web-test") + + def test_other_repository_or_fork_and_bad_metadata_type_are_rejected(self): + for field in ("repository", "head_repository"): + for value in ({"full_name": "other/repository"}, {"full_name": []}, []): + with self.subTest(field=field, value=value), self.assertRaises(ValueError): + select_source({**self.run, field: value}, self.pages, REPOSITORY, 100, "web-test") + + def test_other_slug_attempt_expired_and_unbounded_size_are_rejected(self): + for patch in ({"name": "other-100-1-abc123-publish-bundle"}, {"name": "web-test-100-2-abc123-publish-bundle"}, + {"name": "web-test-100-1-abc123-user-files-bundle"}, {"expired": True}, {"expired": "false"}, + {"size_in_bytes": 17 * 1024 * 1024}, {"size_in_bytes": True}, {"id": True}, + {"workflow_run": {"id": 101}}, {"workflow_run": {"id": 100, "head_sha": "c" * 40, "head_branch": "main"}}): + with self.subTest(patch=patch), self.assertRaises(ValueError): + select_source(self.run, [{"total_count": 1, "artifacts": [{**self.artifact, **patch}]}], REPOSITORY, 100, "web-test") + + def test_all_pages_are_considered_but_missing_and_duplicate_pages_are_rejected(self): + unrelated = {**self.artifact, "id": 201, "name": "unrelated"} + pages = [{"total_count": 2, "artifacts": [unrelated]}, {"total_count": 2, "artifacts": [self.artifact]}] + self.assertEqual(select_source(self.run, pages, REPOSITORY, 100, "web-test")["artifact_id"], 200) + for invalid in (pages[:1], [pages[0], pages[0]], [{"total_count": 2, "artifacts": [self.artifact, {**self.artifact, "id": 201}]}]): + with self.subTest(invalid=invalid), self.assertRaises(ValueError): + select_source(self.run, invalid, REPOSITORY, 100, "web-test") + + def test_failed_jobs_rerun_does_not_reuse_an_earlier_attempt_bundle(self): + run = {**self.run, "run_attempt": 2} + with self.assertRaisesRegex(ValueError, "현재 시도"): + select_source(run, self.pages, REPOSITORY, 100, "web-test") + current = {**self.artifact, "id": 201, "name": "web-test-100-2-abc123-publish-bundle"} + pages = [{"total_count": 2, "artifacts": [self.artifact, current]}] + self.assertEqual(select_source(run, pages, REPOSITORY, 100, "web-test")["artifact_id"], 201) + + def test_manifest_sha_revision_slug_ref_and_scan_gate_must_match(self): + selection = self.select() + for patch in ({"source_sha": "c" * 40}, {"registry_revision": 6}, {"revision": 6}, {"challenge_slug": "web-other"}, + {"source_ref": "refs/heads/feature"}, {"scan_result": "FAIL"}, {"schema_version": "2.1"}): + with self.subTest(patch=patch), self.assertRaises(ValueError): + verify_bundle({**self.bundle, **patch}, selection, self.config) + + def test_koth_pwn_vm_and_multiple_containers_are_not_implicitly_approved(self): + for patch in ({"category": "koth"}, {"category": "KOTH"}, {"category": []}, + {"isolation_profile": "PWN"}, {"runtime_type": "VM"}, {"architecture": "ARM64"}, + {"workload": {"containers": self.bundle["workload"]["containers"] * 2}}): + with self.subTest(patch=patch), self.assertRaises(ValueError): + verify_bundle({**self.bundle, **patch}, self.select(), self.config) + + def test_only_the_problem_container_ghcr_digest_is_allowed(self): + for image in ("ghcr.io/msg-ctf/challenges/web-other/web@sha256:" + "b" * 64, + "ghcr.io/msg-ctf/challenges/web-test/web:latest", "example.org/image@sha256:" + "b" * 64): + bundle = copy.deepcopy(self.bundle) + bundle["workload"]["containers"][0]["image"] = image + with self.subTest(image=image), self.assertRaises(ValueError): + verify_bundle(bundle, self.select(), self.config) + + def test_private_healthcheck_ports_and_resource_validation_reuse_existing_contract(self): + bundle = copy.deepcopy(self.bundle) + bundle["workload"]["containers"][0]["ports"].append({"port": 9090, "public": False}) + bundle["workload"]["healthcheck"] = {"container": "web", "port": 9090, "path": "/health"} + verify_bundle(bundle, self.select(), self.config) + bundle["resource_profile"]["cpu_millicores"] = 0 + with self.assertRaises(ValueError): + verify_bundle(bundle, self.select(), self.config) + + def test_bad_json_and_symlinks_fail_without_echoing_secret_or_traceback(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = root / "run.json" + source.write_text('{"SECRET-CONTENT": [', encoding="utf-8") + linked = root / "linked.json" + linked.symlink_to(source) + with self.assertRaises(ValueError): + read_json(linked) + result = subprocess.run([sys.executable, "-B", str(ROOT / "scripts/validate_runtime_smoke_source.py"), "select", + "--run", str(source), "--pages", str(source), "--repository", REPOSITORY, + "--run-id", "100", "--challenge-slug", "web-test", "--output", str(root / "result.json")], + capture_output=True, text=True) + self.assertEqual(result.returncode, 2) + self.assertNotIn("SECRET-CONTENT", result.stdout + result.stderr) + self.assertNotIn("Traceback", result.stderr) + + def test_cli_outputs_only_validated_selection_fields(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self.run["untrusted_extra"] = "DO-NOT-EXPORT" + for name, value in (("run", self.run), ("pages", self.pages)): + (root / f"{name}.json").write_text(json.dumps(value), encoding="utf-8") + output = root / "selection.json" + github_output = root / "github-output" + result = subprocess.run([sys.executable, "-B", str(ROOT / "scripts/validate_runtime_smoke_source.py"), "select", + "--run", str(root / "run.json"), "--pages", str(root / "pages.json"), + "--repository", REPOSITORY, "--run-id", "100", "--challenge-slug", "web-test", + "--output", str(output), "--github-output", str(github_output)], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(output.read_text(encoding="utf-8")), self.select()) + self.assertEqual(github_output.read_text(encoding="utf-8"), "artifact_id=200\n") + self.assertNotIn("DO-NOT-EXPORT", output.read_text(encoding="utf-8") + result.stdout + result.stderr) + + def test_independent_workflow_never_builds_publishes_or_softens_failures(self): + path = ROOT / ".github/workflows/published-runtime-smoke.yml" + raw = path.read_text(encoding="utf-8") + workflow = yaml.load(raw, Loader=yaml.BaseLoader) + self.assertEqual(set(workflow["on"]), {"workflow_call"}) + self.assertEqual(workflow["permissions"], {"contents": "read", "actions": "read"}) + steps = workflow["jobs"]["smoke"]["steps"] + download = next(step for step in steps if step.get("uses") == "actions/download-artifact@v4") + self.assertIn("steps.source.outputs.artifact_id", download["with"]["artifact-ids"]) + self.assertEqual(download["with"]["merge-multiple"], "true") + self.assertFalse(any("continue-on-error" in step for step in steps)) + self.assertNotIn("docker/build-push-action", raw) + self.assertNotIn("packages: write", raw) + self.assertNotIn("aws-actions", raw) + for step in steps: + if "run" in step: + self.assertNotIn("${{ inputs.", step["run"]) + result = subprocess.run(["bash", "-n"], input=step["run"], text=True, capture_output=True) + self.assertEqual(result.returncode, 0, result.stderr) + + def run_approval_step(self, event, ref, confirm="true"): + workflow = yaml.load((ROOT / ".github/workflows/published-runtime-smoke.yml").read_text(encoding="utf-8"), Loader=yaml.BaseLoader) + step = workflow["jobs"]["smoke"]["steps"][0] + env = dict(os.environ, GITHUB_EVENT_NAME=event, GITHUB_REF=ref, CONFIRM_DEPLOY=confirm, + SOURCE_RUN_ID="100", CHALLENGE_SLUG="web-test", DEVSECOPS_REF="a" * 40) + return subprocess.run(["bash", "-e", "-c", step["run"] + "\nprintf 'GATE_PASSED\\n'\n"], + env=env, text=True, capture_output=True, timeout=5) + + def test_approval_shell_rejects_non_manual_events_and_non_main_refs(self): + events = ("workflow_dispatch", "push", "schedule", "pull_request", "workflow_call", "repository_dispatch", "") + refs = ("refs/heads/main", "refs/heads/feature", "refs/tags/main", "") + for event in events: + for ref in refs: + with self.subTest(event=event, ref=ref): + result = self.run_approval_step(event, ref) + allowed = event == "workflow_dispatch" and ref == "refs/heads/main" + self.assertEqual(result.returncode, 0 if allowed else 1, result.stderr) + self.assertEqual("GATE_PASSED" in result.stdout, allowed) + if not allowed: + self.assertIn("수동 실행" if event != "workflow_dispatch" else "main 실행", result.stderr) + + def test_approval_shell_requires_explicit_deployment_consent(self): + for confirm in ("false", "", "True", "1"): + with self.subTest(confirm=confirm): + result = self.run_approval_step("workflow_dispatch", "refs/heads/main", confirm) + self.assertEqual(result.returncode, 1) + self.assertNotIn("GATE_PASSED", result.stdout) + self.assertIn("승인 확인", result.stderr) + + def test_self_test_runs_when_only_the_runtime_workflow_changes(self): + workflow = yaml.load((ROOT / ".github/workflows/pipeline-self-test.yml").read_text(encoding="utf-8"), Loader=yaml.BaseLoader) + for event in ("push", "pull_request"): + with self.subTest(event=event): + self.assertIn(".github/workflows/published-runtime-smoke.yml", workflow["on"][event]["paths"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_workflow_contracts.py b/tests/test_workflow_contracts.py index b8f74f5..1c500df 100644 --- a/tests/test_workflow_contracts.py +++ b/tests/test_workflow_contracts.py @@ -462,6 +462,7 @@ def test_repository_only_exposes_challenge_validation_workflows(self): "challenge-supply-chain.yml", "pipeline-self-test.yml", "ghcr-cleanup-dry-run.yml", + "published-runtime-smoke.yml", }, )