From 107fc642a51e99f2c1769a69df97bec8c72237d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Fri, 23 Oct 2026 21:40:35 +0900 Subject: [PATCH 1/3] =?UTF-8?q?=EB=AC=B8=EC=A0=9C=20=EC=9D=B4=EB=AF=B8?= =?UTF-8?q?=EC=A7=80=20=EC=82=AC=EC=A0=84=20=EB=8B=A4=EC=9A=B4=EB=A1=9C?= =?UTF-8?q?=EB=93=9C=20=EB=AA=A9=EB=A1=9D=EA=B3=BC=20=EC=88=98=EC=A7=91?= =?UTF-8?q?=C2=B7=EC=A0=81=EC=9A=A9=20=EC=97=B0=EB=8F=99=20=EA=B8=B0?= =?UTF-8?q?=EC=A4=80=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/challenge-supply-chain.yml | 9 + README.md | 12 + docs/README.md | 1 + docs/node-image-prefetch.md | 158 ++++++++++ scripts/README.md | 7 + scripts/generate_node_image_plan.py | 149 +++++++++ tests/README.md | 7 + tests/test_generate_node_image_plan.py | 312 +++++++++++++++++++ 8 files changed, 655 insertions(+) create mode 100644 docs/node-image-prefetch.md create mode 100644 scripts/generate_node_image_plan.py create mode 100644 tests/test_generate_node_image_plan.py diff --git a/.github/workflows/challenge-supply-chain.yml b/.github/workflows/challenge-supply-chain.yml index 48db8f5..3315921 100644 --- a/.github/workflows/challenge-supply-chain.yml +++ b/.github/workflows/challenge-supply-chain.yml @@ -589,6 +589,15 @@ jobs: --artifact-output dist/artifact-v2.json \ --registry-output dist/registry-publish.json + - name: 노드 이미지 사전 다운로드 목록 생성 + if: >- + github.ref == 'refs/heads/main' && + (github.event_name == 'push' || github.event_name == 'workflow_dispatch') + run: | + python3 .msgctf-ci/scripts/generate_node_image_plan.py \ + --artifact dist/artifact-v2.json \ + --output-dir dist/node-prefetch + - name: GHCR digest 발행 결과 요약 id: summary env: diff --git a/README.md b/README.md index 042d5f9..8055ffb 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,11 @@ Scheduler가 Challenge Registry의 active revision 조회 CI는 Kubernetes manifest, Namespace, Service, NetworkPolicy 또는 cleanup을 소유하지 않습니다. 해당 영역은 Runtime 및 격리보안팀의 책임입니다. +일반 K3s 문제의 main 발행 bundle에는 노드 사전 다운로드용 digest 목록도 +포함합니다. 실제 노드 다운로드와 수집·적용 버튼 연결은 아직 구현 전이며, +[노드 이미지 사전 다운로드 연동](docs/node-image-prefetch.md)에 담당별 연결과 +기존 참가자 인스턴스를 유지하는 전환 순서를 정리했습니다. + GHCR 이미지 버전은 [삭제 없는 정리 후보 조회](docs/ghcr-cleanup.md)로 관리합니다. active release·실행 중 digest와 KOTH의 별도 사용 목록을 확인하기 전에는 실제 이미지를 삭제하지 않습니다. @@ -191,6 +196,9 @@ GHCR push, publish bundle 생성과 Runtime smoke는 승인된 `main` 실행에 --publish-bundle/ ├ artifact-v2.json ├ registry-publish.json +├ node-prefetch/ # 일반 K3s 문제의 main 발행만 해당 +│ ├ plan.json +│ └ images.txt ├ input/metadata.json └ results// ├ timing.json @@ -325,6 +333,10 @@ K3s는 향후 containerd mirror 설정을 통해 내부 OCI mirror를 사용할 사전 pull, mirror 또는 별도 Registry 도입은 MVP 이후 결정하며, 이 경우에도 Runtime에는 digest 고정 reference만 전달합니다. +2026-10-23 추가 요구에 따라 노드 사전 다운로드를 준비하고 있습니다. 위 MVP의 +on-demand pull 설명은 기존 동작이며, 이번 보조 목록 발행만으로 노드 자동 +다운로드나 기존 인스턴스의 무중단 교체가 활성화되지는 않습니다. + 신규 아키텍처 기준 공급망은 `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에서 처리하지 않습니다. diff --git a/docs/README.md b/docs/README.md index a14b1a9..f51a58a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,5 +1,6 @@ # 문서 +- [노드 이미지 사전 다운로드 연동](node-image-prefetch.md): publish bundle의 digest 목록과 수집·다운로드·적용의 책임 경계, 기존 인스턴스를 유지하는 전환 제안 - [발행본 독립 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 시험과 수집 계약 구분 diff --git a/docs/node-image-prefetch.md b/docs/node-image-prefetch.md new file mode 100644 index 0000000..c43a650 --- /dev/null +++ b/docs/node-image-prefetch.md @@ -0,0 +1,158 @@ +# 노드 이미지 사전 다운로드 연동 + +## 목표와 현재 범위 + +관리자가 Backend에서 문제를 수집하면 새 릴리스를 등록하고, 해당 릴리스의 +이미지를 실행 가능한 K3s 노드에 미리 받는 흐름을 목표로 합니다. 이미지가 +준비된 뒤 관리자가 적용하면 이후 새 인스턴스가 해당 버전을 사용합니다. + +이 변경에서 구현한 것은 검사를 통과한 publish bundle에 다운로드 목록을 +추가하는 부분입니다. Backend 수집 버튼 연결, 노드 작업 실행, 준비 상태 저장과 +활성화 제한은 아직 구현된 기능이 아닙니다. 이 문서의 상태·처리 순서는 담당자와 +합의할 연동 제안이며, 현재 Runtime API 계약이 아닙니다. + +현재 확인한 Backend Poller는 등록만 수행하고, 활성화 API는 현재 release 포인터를 +전환합니다. Runtime의 공개 OpenAPI에는 사전 다운로드 API가 없습니다. Broker +Node Agent는 Kubernetes 관측용이며 containerd socket이나 workload 변경 권한이 +없습니다. 기존 수집 버튼이나 Node Agent에 이미 다운로드 기능이 있다고 보지 않습니다. + +## 수집과 적용 흐름 + +```text +문제 main 발행 성공 + -> GHCR digest 이미지 + publish bundle + -> 관리자 수집 또는 Backend Poller + -> 출처 검증과 새 release 등록 (기존 active 유지) + -> 승인된 실행 노드별 사전 다운로드 작업 요청 [추가 연동 필요] + -> 노드 아키텍처와 전체 컨테이너 digest 확인 [추가 연동 필요] + -> 노드별 준비 완료 기록 [추가 연동 필요] + -> 관리자가 적용: 준비된 release만 active 전환 [추가 연동 필요] + -> 새 인스턴스는 해당 release와 노드 캐시 사용 +``` + +수집 자체를 이미지 실행이나 자동 활성화로 해석하지 않습니다. 자동 다운로드는 +위 연동 구현 후 수집에 연결하며, 참가자 문제 인스턴스를 미리 전부 생성하는 +기능이 아닙니다. 파일 생성이나 작업 접수만으로 준비 완료를 표시하지 않습니다. + +## DevSecOps 발행 자료 + +`artifact-v2.json`의 기존 JSON과 `info.yaml` 형식은 바꾸지 않습니다. main의 성공한 +일반 `KUBERNETES` 문제 발행에 다음 보조 파일을 함께 업로드합니다. + +```text +--publish-bundle/ +├── artifact-v2.json +├── registry-publish.json +└── node-prefetch/ + ├── plan.json + └── images.txt +``` + +`plan.json`에는 `plan_only: true`, 문제 slug, revision, source ref/SHA, +아키텍처, 컨테이너별 digest reference와 원본 artifact 및 목록의 SHA-256이 +들어갑니다. 다운로드 성공이나 Runtime 이미지 승인 상태를 뜻하지 않습니다. +환경변수, FLAG, 인증 토큰이나 실행 명령은 담지 않습니다. + +`images.txt`에는 공개 여부와 관계없이 해당 문제의 **모든 컨테이너** 이미지를 +한 줄에 하나씩 기록합니다. 다른 문제·다른 컨테이너 경로, tag-only reference, +`latest`, 검사 실패 또는 컨테이너별 증거 불일치는 거절합니다. + +KOTH와 VM은 이번 실행 범위에서 제외하며 보조 목록을 만들지 않습니다. 정적 +문제는 기존대로 이미지 발행 자체가 없습니다. PWN 목록 생성은 실행 승인이 +아니며 Runtime의 격리 조건을 별도로 만족해야 합니다. + +기존 성공 bundle에서도 목록을 만들 수 있습니다. + +```bash +python3 scripts/generate_node_image_plan.py \ + --artifact /absolute/path/to/artifact-v2.json \ + --output-dir /absolute/path/to/new-node-prefetch +``` + +기존 출력 디렉터리는 덮어쓰지 않습니다. 이 도구는 네트워크 호출이나 이미지 +다운로드를 하지 않습니다. 원본 파일 hash는 파일 연결 확인용이지 신뢰를 +발급하는 서명이 아닙니다. 소비자는 기존 Backend 출처 검사대로 성공 workflow, +공식 main, 저장소, run/artifact와 commit을 검증하고, 검증한 원본에서 목록을 +다시 계산·대조해야 합니다. `plan_only`를 지우거나 보조 JSON을 수정해도 실행 +승인으로 인정하지 않습니다. + +## 노드 저장 방식 + +K3s의 실행 이미지는 노드의 containerd 저장소에 들어가야 합니다. VM에서 별도 +Docker daemon으로 `docker pull`한 것만으로 K3s의 이미지 준비를 판정하지 않습니다. +K3s는 `/var/lib/rancher/k3s/agent/images` 아래에 한 줄당 이미지 하나인 텍스트 +파일을 놓거나 갱신하면 CRI로 사전 다운로드하는 기능을 제공합니다. +실제 배포 버전의 지원 여부와 GHCR 인증을 먼저 확인해야 합니다. + +- [K3s 이미지 가져오기 공식 문서](https://docs.k3s.io/add-ons/import-images) +- [K3s private registry 인증](https://docs.k3s.io/installation/private-registry) + +이는 사용할 수 있는 노드 내부 구현 방식이지 CI가 직접 해당 경로에 쓰도록 +허용한 것이 아닙니다. 노드 담당자가 작업 실행 경로를 정해야 합니다. Pod의 +`imagePullSecrets`만으로 노드 사전 다운로드 인증이 된다고 가정하지 않습니다. +CI에 SSH·root 권한, kubeconfig 또는 GHCR pull 토큰을 새로 전달하지 않습니다. + +## 업데이트와 기존 인스턴스 유지 + +1. digest A가 실행 중이어도 새 digest B는 별도 release로 등록합니다. +2. B를 허용된 노드에 먼저 받고 전체 컨테이너를 확인합니다. +3. 관리자가 B를 적용하면 새로 생성하는 인스턴스만 B를 참조합니다. +4. 기존 인스턴스와 reset은 원래 release 계약을 유지합니다. 강제 재시작하지 않습니다. +5. A는 실행 중 인스턴스와 승인된 롤백이 참조하는 동안 삭제하지 않습니다. + +이 방식은 기존 참가자 세션을 유지하는 버전 전환입니다. 이미 실행 중인 +인스턴스까지 새 이미지로 실시간 교체하는 무중단 배포를 보장하지 않습니다. +그 요구는 상태·스토리지, TCP 세션, readiness와 트래픽 전환 계약을 별도로 +정한 뒤 다뤄야 합니다. 사전 다운로드만으로 해결되지 않습니다. + +## 담당별 후속 연결 + +| 담당 | 추가할 작업 | +|---|---| +| DevSecOps | 이번 보조 목록 발행, digest·아키텍처·출처 대조, 승인된 단일 문제 연동 증거 | +| Backend | 수집 후 release별 작업 접수, 상태 조회, 준비되지 않은 release 적용 차단, 기존 active 보존 | +| Runtime·노드 담당 | 노드별 containerd 다운로드와 실제 digest 확인, 인증·디스크·재시도·캐시 상태 처리 | +| Broker | 실행 가능한 target·노드·아키텍처 목록 제공, 새 노드와 준비 실패 노드의 후보 처리 합의 | + +아래 항목을 합의한 뒤 호출 코드를 연결합니다. 다른 팀의 API나 privileged +에이전트를 DevSecOps 저장소에서 임의로 만들지 않습니다. + +- 사전 다운로드 실행 주체와 요청·조회 인터페이스, 인증 방법 +- 대상 target/node 목록의 공급자와 갱신 주기 +- 아키텍처별 승인된 실행 노드 전체 준비를 적용 조건으로 사용할지 +- 노드가 일부 실패했을 때 적용을 보류할지, 준비 노드에만 한정할지 +- 새 노드·재생성 노드의 초기 동기화와 캐시 삭제 후 재확인 +- 작업 중복 키: release 식별자 + target/node 식별자 + image digest +- 반환 정보: 작업 식별자, node, 요청 image, 실제 digest/아키텍처, + 관측 시각, 성공·실패, 소요 시간, 재시도 가능 여부 +- 동시 다운로드 제한, 디스크 여유 기준과 중단·재시도 기준 + +문제 전체 이미지를 미리 받더라도 모든 과거 GHCR 버전을 받지 않습니다. +대상은 일반 동적 문제의 승인된 현재 release와 별도로 승인한 롤백 버전입니다. +최신판이라는 tag를 노드에서 해석하지 않고 정확한 digest 목록을 사용합니다. + +## 검증 순서 + +1. 승인된 단일 WEB의 노드 이미지 미보유 상태를 먼저 확인합니다. +2. 수집으로 사전 다운로드를 요청하고 요청 전후 캐시·pull 증거·시간을 기록합니다. +3. 모든 컨테이너의 digest와 아키텍처를 확인한 뒤 적용합니다. +4. 생성·실제 HTTP 접속·실행 imageID·삭제를 확인합니다. +5. 캐시가 있는 상태의 생성 시간과 비교합니다. 전체 생성 시간을 pull 시간으로 기록하지 않습니다. +6. 새 revision을 수집할 때 기존 active와 실행 인스턴스가 유지되는지 확인합니다. +7. 인증 실패·디스크 부족·부분 실패·새 노드에서도 거짓 준비 완료가 나오지 않는지 확인합니다. + +현재는 위 노드 다운로드·자동 적용 연동을 수행한 상태가 아닙니다. 기존 +Open House 생성·삭제 성공 기록은 cold pull이나 이번 자동화 검증으로 재사용하지 않습니다. + +## 이번 변경의 확인 결과 + +- 기존 테스트 237개와 새 목록 검사 21개를 합쳐 로컬 테스트 258개 통과 +- 기존 Open House main 발행 run `37349840954`, revision `461`의 실제 + `artifact-v2.json`으로 이미지 목록 생성 확인 +- 출력의 이미지가 원본 bundle의 정확한 digest와 일치하고 원본 파일 hash가 보존됨 +- 실제 workflow의 목록 생성 셸 실행과 기존 Poller의 파일 선택 방식 호환 확인 + +이 결과는 목록 생성 검증입니다. 실제 Backend 수집, 노드 다운로드, 캐시 hit, +Runtime HTTP 접속이나 무중단 교체 성공을 의미하지 않습니다. +PR 병합 후 문제 저장소가 참조하는 reusable workflow와 `devsecops_ref`를 같은 +병합 SHA로 갱신해야 새 발행에 이 목록이 포함됩니다. 기존 bundle은 자동 변경되지 않습니다. diff --git a/scripts/README.md b/scripts/README.md index b2563cf..830f89a 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -9,6 +9,13 @@ Provisioner API 요청으로 변환합니다. 생성 Operation을 조회한 뒤 ## 파일 +### `generate_node_image_plan.py` + +성공한 main 발행 bundle에서 일반 Linux K3s 문제의 모든 컨테이너 digest 목록과 +출처·아키텍처·파일 checksum을 생성합니다. 기존 artifact JSON은 수정하지 않으며 +노드 접근·다운로드·릴리스 활성화·기존 인스턴스 교체는 하지 않습니다. +KOTH·VM은 제외합니다. [사전 다운로드 연동 제안](../docs/node-image-prefetch.md)을 참고합니다. + ### `validate_runtime_smoke_source.py` 독립 Runtime 시험에서 성공한 main 발행 run과 전체 artifact 페이지를 대조합니다. diff --git a/scripts/generate_node_image_plan.py b/scripts/generate_node_image_plan.py new file mode 100644 index 0000000..76a2c5a --- /dev/null +++ b/scripts/generate_node_image_plan.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""발행 bundle에서 노드 사전 다운로드용 목록만 생성합니다. 노드는 변경하지 않습니다.""" + +import argparse +import hashlib +import json +from pathlib import Path +import re +import sys + +if __package__: + from .generate_publish_bundle import COMMIT_SHA, MSGCTF_GHCR_DIGEST_IMAGE +else: + from generate_publish_bundle import COMMIT_SHA, MSGCTF_GHCR_DIGEST_IMAGE + + +NAME = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$") +MAX_ARTIFACT_BYTES = 1024 * 1024 + + +def generate_plan(artifact, artifact_sha256): + if not isinstance(artifact, dict): + raise ValueError("발행 자료는 JSON 객체여야 합니다") + if artifact.get("schema_version") not in ("2.0", "2.1"): + raise ValueError("지원하는 발행 자료 버전이 아닙니다") + if not isinstance(artifact_sha256, str) or not re.fullmatch(r"[0-9a-f]{64}", artifact_sha256): + raise ValueError("원본 발행 자료의 SHA-256이 필요합니다") + + category = artifact.get("category") + if not isinstance(category, str) or not category: + raise ValueError("문제 분야가 필요합니다") + if category.lower() == "koth" or artifact.get("runtime_type") != "KUBERNETES": + return None + + slug = artifact.get("challenge_slug") + if not isinstance(slug, str) or not NAME.fullmatch(slug) or slug.startswith("koth-"): + raise ValueError("일반 문제 식별자가 올바르지 않습니다") + architecture = artifact.get("architecture") + if architecture not in ("AMD64", "ARM64"): + raise ValueError("지원하는 Linux 아키텍처가 아닙니다") + revision = artifact.get("registry_revision") + if type(revision) is not int or revision <= 0: + raise ValueError("registry_revision은 양의 정수여야 합니다") + if type(artifact.get("revision")) is not int or artifact["revision"] != revision: + raise ValueError("revision과 registry_revision이 일치해야 합니다") + if artifact.get("source_ref") != "refs/heads/main": + raise ValueError("main 발행 자료만 목록으로 만들 수 있습니다") + source_sha = artifact.get("source_sha") + if not isinstance(source_sha, str) or not COMMIT_SHA.fullmatch(source_sha): + raise ValueError("원본 커밋 SHA가 올바르지 않습니다") + if artifact.get("scan_result") != "PASS": + raise ValueError("검사를 통과한 발행 자료가 아닙니다") + + workload = artifact.get("workload") + containers = workload.get("containers") if isinstance(workload, dict) else None + if not isinstance(containers, list) or not containers: + raise ValueError("전체 컨테이너 목록이 필요합니다") + images = {} + for container in containers: + if not isinstance(container, dict): + raise ValueError("컨테이너 정보가 올바르지 않습니다") + name = container.get("name") + if not isinstance(name, str) or not NAME.fullmatch(name) or name in images: + raise ValueError("컨테이너 이름이 올바르지 않거나 중복됩니다") + image = container.get("image") + expected = f"ghcr.io/msg-ctf/challenges/{slug}/{name}@sha256:" + if (not isinstance(image, str) or not MSGCTF_GHCR_DIGEST_IMAGE.fullmatch(image) + or not image.startswith(expected)): + raise ValueError("문제와 컨테이너에 해당하는 GHCR digest 이미지가 필요합니다") + images[name] = image + + evidence = artifact.get("evidence") + scanned = evidence.get("containers") if isinstance(evidence, dict) else None + if not isinstance(scanned, list) or len(scanned) != len(images): + raise ValueError("전체 컨테이너의 검사 증거가 필요합니다") + seen = set() + for item in scanned: + if not isinstance(item, dict): + raise ValueError("컨테이너 검사 증거가 올바르지 않습니다") + name = item.get("name") + if not isinstance(name, str) or name not in images or name in seen: + raise ValueError("검사 증거의 컨테이너 목록이 일치하지 않습니다") + if (item.get("published_image") != images[name] + or item.get("vulnerability_scan") != "PASS" + or item.get("secret_scan") != "PASS"): + raise ValueError("발행 이미지와 검사 증거가 일치하지 않습니다") + seen.add(name) + + ordered = [{"name": name, "image": images[name]} for name in sorted(images)] + image_list = ("\n".join(item["image"] for item in ordered) + "\n").encode("utf-8") + plan = { + "schema_version": "1.0", + "plan_only": True, + "challenge_slug": slug, + "registry_revision": revision, + "runtime_type": "KUBERNETES", + "architecture": architecture, + "source_ref": artifact["source_ref"], + "source_sha": source_sha, + "artifact_sha256": artifact_sha256, + "containers": ordered, + "image_list": { + "file": "images.txt", + "sha256": hashlib.sha256(image_list).hexdigest(), + }, + } + return plan, image_list + + +def write_plan(artifact_path, output_dir): + artifact_path, output_dir = Path(artifact_path), Path(output_dir) + if (artifact_path.is_symlink() or not artifact_path.is_file() + or artifact_path.stat().st_size > MAX_ARTIFACT_BYTES): + raise ValueError("원본 발행 자료의 경로와 크기를 확인하세요") + with artifact_path.open("rb") as stream: + raw = stream.read(MAX_ARTIFACT_BYTES + 1) + if len(raw) > MAX_ARTIFACT_BYTES: + raise ValueError("원본 발행 자료 크기가 제한을 넘었습니다") + result = generate_plan(json.loads(raw), hashlib.sha256(raw).hexdigest()) + if result is None: + return False + plan, images = result + output_dir.mkdir(parents=True, exist_ok=False) + (output_dir / "images.txt").write_bytes(images) + (output_dir / "plan.json").write_text( + json.dumps(plan, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + return True + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--artifact", required=True, type=Path) + parser.add_argument("--output-dir", required=True, type=Path) + args = parser.parse_args() + try: + generated = write_plan(args.artifact, args.output_dir) + except (ValueError, OSError, TypeError, RecursionError): + print("사전 다운로드 목록 생성 실패: 발행 자료와 출력 경로를 확인하세요", file=sys.stderr) + return 2 + if generated: + print("사전 다운로드 목록을 생성했습니다. 실제 노드 다운로드와 활성화는 실행하지 않았습니다") + else: + print("일반 Linux K3s 문제 범위가 아니므로 사전 다운로드 목록을 생성하지 않았습니다") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/README.md b/tests/README.md index f8c6acf..c73067d 100644 --- a/tests/README.md +++ b/tests/README.md @@ -5,6 +5,13 @@ ## 테스트 구성 +### `test_generate_node_image_plan.py` + +기존 발행 자료에서 공개·비공개 컨테이너 전체의 digest와 아키텍처가 보존되는지, +tag·다른 문제 이미지·검사 증거 불일치·잘못된 출처가 차단되는지 확인합니다. +기존 bundle 불변, 출력 덮어쓰기 거절, 비밀값 비포함, 실제 workflow 명령과 +KOTH·VM 제외도 검증합니다. 노드 다운로드나 무중단 교체를 시험한 것은 아닙니다. + ### `test_validate_runtime_smoke_source.py` 공식 main 성공 실행·전체 artifact pagination·시도 번호·만료·출처·SHA·revision과 diff --git a/tests/test_generate_node_image_plan.py b/tests/test_generate_node_image_plan.py new file mode 100644 index 0000000..b849900 --- /dev/null +++ b/tests/test_generate_node_image_plan.py @@ -0,0 +1,312 @@ +import copy +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +import zipfile + +import yaml + +from scripts.generate_node_image_plan import generate_plan, write_plan +from scripts.generate_publish_bundle import generate_bundle + + +ROOT = Path(__file__).resolve().parents[1] +ARTIFACT_SHA = "c" * 64 + + +def sample_artifact(): + containers = [ + {"name": name, "image": f"ghcr.io/msg-ctf/challenges/web-notebook/{name}@sha256:{digest * 64}", + "ports": [{"port": port, "public": public}]} + for name, digest, port, public in (("web", "a", 8080, True), ("db", "b", 5432, False)) + ] + return { + "schema_version": "2.0", + "challenge_slug": "web-notebook", + "registry_revision": 5, + "revision": 5, + "runtime_type": "KUBERNETES", + "architecture": "AMD64", + "category": "web", + "source_ref": "refs/heads/main", + "source_sha": "1" * 40, + "scan_result": "PASS", + "workload": {"containers": containers}, + "evidence": {"containers": [ + {"name": item["name"], "published_image": item["image"], + "vulnerability_scan": "PASS", "secret_scan": "PASS"} + for item in containers + ]}, + } + + +class GenerateNodeImagePlanTests(unittest.TestCase): + def test_includes_public_and_private_containers_without_changing_artifact(self): + artifact = sample_artifact() + before = copy.deepcopy(artifact) + plan, images = generate_plan(artifact, ARTIFACT_SHA) + self.assertEqual(artifact, before) + self.assertEqual([item["name"] for item in plan["containers"]], ["db", "web"]) + self.assertEqual(images.decode().splitlines(), [item["image"] for item in plan["containers"]]) + self.assertEqual(plan["artifact_sha256"], ARTIFACT_SHA) + self.assertEqual(plan["image_list"]["sha256"], hashlib.sha256(images).hexdigest()) + self.assertIs(plan["plan_only"], True) + self.assertEqual(plan["registry_revision"], 5) + self.assertEqual(plan["architecture"], "AMD64") + self.assertNotIn("ready", plan) + + def test_reordering_containers_does_not_change_the_image_list(self): + artifact = sample_artifact() + expected = generate_plan(artifact, ARTIFACT_SHA) + artifact["workload"]["containers"].reverse() + artifact["evidence"]["containers"].reverse() + self.assertEqual(generate_plan(artifact, ARTIFACT_SHA), expected) + + def test_keeps_revisions_separate_and_does_not_overwrite_the_old_plan(self): + previous = sample_artifact() + updated = copy.deepcopy(previous) + updated.update(registry_revision=6, revision=6, source_sha="2" * 40) + updated["workload"]["containers"][0]["image"] = ( + "ghcr.io/msg-ctf/challenges/web-notebook/web@sha256:" + "d" * 64 + ) + updated["evidence"]["containers"][0]["published_image"] = updated["workload"]["containers"][0]["image"] + old_plan, old_images = generate_plan(previous, ARTIFACT_SHA) + new_plan, new_images = generate_plan(updated, "d" * 64) + self.assertEqual(old_plan["registry_revision"], 5) + self.assertEqual(new_plan["registry_revision"], 6) + self.assertNotEqual(old_images, new_images) + self.assertIn(("a" * 64).encode(), old_images) + + def test_supports_arm64_and_schema_21_without_exporting_execution_settings(self): + artifact = sample_artifact() + artifact.update(architecture="ARM64", schema_version="2.1") + artifact["workload"]["containers"][0].update( + env={"APP_MODE": "not-for-image-plan"}, secret_env={"FLAG": "secret-binding"} + ) + plan, _ = generate_plan(artifact, ARTIFACT_SHA) + self.assertEqual(plan["architecture"], "ARM64") + self.assertEqual(set(plan["containers"][0]), {"name", "image"}) + for forbidden in ("not-for-image-plan", "secret-binding", "secret_env", "FLAG"): + self.assertNotIn(forbidden, json.dumps(plan)) + + def test_pwn_image_list_is_not_an_execution_approval(self): + artifact = sample_artifact() + artifact["category"] = "pwn" + plan, _ = generate_plan(artifact, ARTIFACT_SHA) + self.assertIs(plan["plan_only"], True) + self.assertNotIn("create_enabled", plan) + + def test_excludes_koth_vm_and_non_kubernetes_payloads(self): + for change in ({"category": "koth"}, {"runtime_type": "VM"}, {"runtime_type": "DOCKER"}): + with self.subTest(change=change): + self.assertIsNone(generate_plan(dict(sample_artifact(), **change), ARTIFACT_SHA)) + + def test_rejects_wrong_source_schema_architecture_revision_and_scan(self): + cases = ( + {"schema_version": "3.0"}, {"source_ref": "refs/heads/feature/example"}, + {"source_sha": "invalid"}, {"source_sha": 1}, {"scan_result": "FAIL"}, + {"architecture": "WINDOWS"}, {"registry_revision": True}, + {"registry_revision": 0}, {"registry_revision": 6}, {"revision": True}, + {"challenge_slug": "../outside"}, {"challenge_slug": "koth-example"}, + ) + for change in cases: + with self.subTest(change=change), self.assertRaises(ValueError): + generate_plan(dict(sample_artifact(), **change), ARTIFACT_SHA) + + def test_rejects_unpinned_cross_repository_or_injected_images(self): + for image in ( + "ghcr.io/msg-ctf/challenges/web-notebook/web:latest", + "ghcr.io/msg-ctf/challenges/web-notebook/web:v1.0.0", + "ghcr.io/msg-ctf/challenges/other-problem/web@sha256:" + "a" * 64, + "ghcr.io/msg-ctf/challenges/web-notebook/other@sha256:" + "a" * 64, + "evil.example/web@sha256:" + "a" * 64, + sample_artifact()["workload"]["containers"][0]["image"] + "\nmalicious-command", + 1, + ): + with self.subTest(image=image), self.assertRaises(ValueError): + artifact = sample_artifact() + artifact["workload"]["containers"][0]["image"] = image + generate_plan(artifact, ARTIFACT_SHA) + + def test_rejects_missing_duplicate_and_invalid_containers(self): + for value in ([], {}, [None], [dict(sample_artifact()["workload"]["containers"][0])] * 2, + [{"name": "web\ncommand", "image": "invalid"}]): + with self.subTest(value=value), self.assertRaises(ValueError): + artifact = sample_artifact() + artifact["workload"]["containers"] = value + generate_plan(artifact, ARTIFACT_SHA) + + def test_rejects_missing_mismatched_duplicate_or_failed_scan_evidence(self): + cases = [None, [], [None, None]] + cases.append(sample_artifact()["evidence"]["containers"][:1] * 2) + for field, value in (("published_image", "wrong"), ("vulnerability_scan", "FAIL"), + ("secret_scan", "Not scanned"), ("name", "another-container")): + evidence = copy.deepcopy(sample_artifact()["evidence"]["containers"]) + evidence[0][field] = value + cases.append(evidence) + for evidence in cases: + with self.subTest(evidence=evidence), self.assertRaises(ValueError): + artifact = sample_artifact() + artifact["evidence"]["containers"] = evidence + generate_plan(artifact, ARTIFACT_SHA) + + def test_rejects_non_objects_and_invalid_artifact_hashes(self): + for value in (None, [], "not-json-object"): + with self.subTest(value=value), self.assertRaises(ValueError): + generate_plan(value, ARTIFACT_SHA) + for value in (None, "", "not-sha256", "a" * 63, "A" * 64): + with self.subTest(value=value), self.assertRaises(ValueError): + generate_plan(sample_artifact(), value) + + def test_cli_writes_exact_artifact_hash_and_only_two_output_files(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + raw = (json.dumps(sample_artifact()) + "\n").encode() + artifact = root / "artifact-v2.json" + artifact.write_bytes(raw) + output = root / "node-prefetch" + result = subprocess.run( + [sys.executable, "-B", str(ROOT / "scripts/generate_node_image_plan.py"), + "--artifact", str(artifact), "--output-dir", str(output)], + capture_output=True, text=True, timeout=10, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(artifact.read_bytes(), raw) + self.assertEqual({path.name for path in output.iterdir()}, {"plan.json", "images.txt"}) + plan = json.loads((output / "plan.json").read_text()) + self.assertEqual(plan["artifact_sha256"], hashlib.sha256(raw).hexdigest()) + self.assertIn("실제 노드 다운로드와 활성화는 실행하지 않았습니다", result.stdout) + + def test_existing_output_is_not_overwritten(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + artifact = root / "artifact-v2.json" + artifact.write_text(json.dumps(sample_artifact())) + output = root / "node-prefetch" + self.assertTrue(write_plan(artifact, output)) + previous = (output / "plan.json").read_bytes() + with self.assertRaises(FileExistsError): + write_plan(artifact, output) + self.assertEqual((output / "plan.json").read_bytes(), previous) + + def test_invalid_input_does_not_create_an_output_directory(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + artifact = root / "artifact-v2.json" + artifact.write_text(json.dumps(dict(sample_artifact(), scan_result="FAIL"))) + output = root / "node-prefetch" + with self.assertRaises(ValueError): + write_plan(artifact, output) + self.assertFalse(output.exists()) + artifact.write_bytes(b"x" * (1024 * 1024 + 1)) + with self.assertRaises(ValueError): + write_plan(artifact, output) + self.assertFalse(output.exists()) + + def test_symlinked_artifact_is_rejected(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + original = root / "original.json" + original.write_text(json.dumps(sample_artifact())) + link = root / "artifact-v2.json" + link.symlink_to(original) + with self.assertRaises(ValueError): + write_plan(link, root / "node-prefetch") + + def test_koth_scope_does_not_emit_files(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + artifact = root / "artifact-v2.json" + artifact.write_text(json.dumps(dict(sample_artifact(), category="koth"))) + self.assertFalse(write_plan(artifact, root / "node-prefetch")) + self.assertFalse((root / "node-prefetch").exists()) + + def test_validation_failure_does_not_print_artifact_contents(self): + with tempfile.TemporaryDirectory() as temporary: + artifact = Path(temporary) / "artifact-v2.json" + artifact.write_text(json.dumps({"private": "do-not-print-this", "schema_version": "bad"})) + result = subprocess.run( + [sys.executable, "-B", "-m", "scripts.generate_node_image_plan", "--artifact", str(artifact), + "--output-dir", str(Path(temporary) / "output")], + cwd=ROOT, capture_output=True, text=True, timeout=10, + ) + self.assertEqual(result.returncode, 2) + self.assertNotIn("do-not-print-this", result.stdout + result.stderr) + self.assertNotIn("Traceback", result.stderr) + + def test_workflow_generates_plan_before_existing_bundle_upload(self): + workflow = yaml.load((ROOT / ".github/workflows/challenge-supply-chain.yml").read_text(), Loader=yaml.BaseLoader) + aggregate = workflow["jobs"]["aggregate"] + steps = aggregate["steps"] + plan_index = next(index for index, step in enumerate(steps) if step.get("name") == "노드 이미지 사전 다운로드 목록 생성") + artifact_index = next(index for index, step in enumerate(steps) if step.get("name") == "Runtime artifact와 Registry publish document 생성") + upload_index = next(index for index, step in enumerate(steps) if step.get("name") == "Atomic Publish bundle 업로드") + self.assertLess(artifact_index, plan_index) + self.assertLess(plan_index, upload_index) + self.assertIn("github.ref == 'refs/heads/main'", steps[plan_index]["if"]) + self.assertIn("workflow_dispatch", steps[plan_index]["if"]) + self.assertIn("--output-dir dist/node-prefetch", steps[plan_index]["run"]) + self.assertEqual(steps[upload_index]["with"]["path"], "dist/") + self.assertEqual(aggregate["permissions"], {"contents": "read"}) + for forbidden in ("ssh ", "kubectl ", "docker pull", "k3s ", "RUNTIME_API_TOKEN", "curl "): + self.assertNotIn(forbidden, steps[plan_index]["run"]) + + def test_actual_workflow_command_generates_plan_without_network_or_node_access(self): + workflow = yaml.load((ROOT / ".github/workflows/challenge-supply-chain.yml").read_text(), Loader=yaml.BaseLoader) + step = next(step for step in workflow["jobs"]["aggregate"]["steps"] + if step.get("name") == "노드 이미지 사전 다운로드 목록 생성") + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + (root / ".msgctf-ci").symlink_to(ROOT, target_is_directory=True) + (root / "dist").mkdir() + artifact_path = root / "dist/artifact-v2.json" + artifact_path.write_text(json.dumps(sample_artifact())) + result = subprocess.run(["bash", "-eu", "-c", step["run"]], cwd=root, + env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}, + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue((root / "dist/node-prefetch/plan.json").is_file()) + + def test_existing_poller_file_selection_still_reads_original_artifact(self): + artifact = sample_artifact() + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + artifact_path = root / "artifact-v2.json" + artifact_path.write_text(json.dumps(artifact)) + write_plan(artifact_path, root / "node-prefetch") + archive_path = root / "bundle.zip" + with zipfile.ZipFile(archive_path, "w") as archive: + for path in (artifact_path, *(root / "node-prefetch").iterdir()): + archive.write(path, path.relative_to(root)) + with zipfile.ZipFile(archive_path) as archive: + # 현재 Backend Poller의 파일 선택에서 원본 bundle이 유지됩니다. + selected = next(name for name in archive.namelist() if name.split("/")[-1] == "artifact-v2.json") + self.assertEqual(json.loads(archive.read(selected)), artifact) + + def test_bundle_generator_output_is_supported_without_changing_schema(self): + artifact = sample_artifact() + metadata = {key: artifact[key] for key in ("challenge_slug", "category", "runtime_type", "architecture")} + metadata.update(name="Web Notebook", containers=[ + {"name": "web", "ports": [8080], "expose": True}, + {"name": "db", "ports": [5432], "expose": False}, + ], resource_profile={"cpu_millicores": 700, "memory_mib": 768, "ephemeral_storage_mib": 1024}) + results = [{"name": item["name"], "image": item["image"], + "source_digest": item["image"].split("@", 1)[1], + "sbom": f"results/{item['name']}/sbom/{item['name']}.cdx.json", "scan_result": "PASS", + "timing": {"build_seconds": 1, "scan_seconds": 1, "push_seconds": 1, "total_seconds": 3}} + for item in artifact["workload"]["containers"]] + generated = generate_bundle(metadata, results, "refs/heads/main", "1" * 40, 5, + ROOT / "tests/fixtures/publish-evidence")["artifact"] + plan, _ = generate_plan(generated, ARTIFACT_SHA) + self.assertEqual(generated["schema_version"], "2.0") + self.assertEqual(len(plan["containers"]), 2) + self.assertNotIn("node-prefetch", generated) + + +if __name__ == "__main__": + unittest.main() From 5a72124bc7c976ccc13f9788d2d93a2ac934d05e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Fri, 23 Oct 2026 21:43:40 +0900 Subject: [PATCH 2/3] =?UTF-8?q?=EC=82=AC=EC=A0=84=20=EB=8B=A4=EC=9A=B4?= =?UTF-8?q?=EB=A1=9C=EB=93=9C=20=EB=8C=80=EA=B8=B0=20=EB=B2=84=EC=A0=84?= =?UTF-8?q?=EC=9D=98=20=EB=B3=B4=EC=A1=B4=EA=B3=BC=20=EC=BA=90=EC=8B=9C=20?= =?UTF-8?q?=EC=9E=AC=ED=99=95=EC=9D=B8=20=EA=B8=B0=EC=A4=80=20=EB=AA=85?= =?UTF-8?q?=EC=8B=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/node-image-prefetch.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/node-image-prefetch.md b/docs/node-image-prefetch.md index c43a650..809a3ca 100644 --- a/docs/node-image-prefetch.md +++ b/docs/node-image-prefetch.md @@ -126,10 +126,15 @@ CI에 SSH·root 권한, kubeconfig 또는 GHCR pull 토큰을 새로 전달하 - 반환 정보: 작업 식별자, node, 요청 image, 실제 digest/아키텍처, 관측 시각, 성공·실패, 소요 시간, 재시도 가능 여부 - 동시 다운로드 제한, 디스크 여유 기준과 중단·재시도 기준 +- 노드 캐시가 정리됐을 때 준비 상태를 다시 확인하고, Runtime의 실제 + imagePullPolicy와 GHCR 인증 동작을 함께 검증하는 기준 문제 전체 이미지를 미리 받더라도 모든 과거 GHCR 버전을 받지 않습니다. -대상은 일반 동적 문제의 승인된 현재 release와 별도로 승인한 롤백 버전입니다. +대상은 일반 동적 문제의 승인된 현재 release, 새로 수집해 사전 다운로드·적용을 +준비 중인 승인된 release와 별도로 승인한 롤백 버전입니다. 최신판이라는 tag를 노드에서 해석하지 않고 정확한 digest 목록을 사용합니다. +다운로드 작업 중이거나 다운로드 후 적용 대기 중인 digest도 GHCR 정리 보호 +목록에 포함해야 합니다. 노드 캐시가 있다는 이유로 GHCR 원본을 지우지 않습니다. ## 검증 순서 From 1aacb04e7e9c6add503ec479321aa23b865a5106 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A7=80=EC=9C=A4?= Date: Sat, 24 Oct 2026 01:25:51 +0900 Subject: [PATCH 3/3] =?UTF-8?q?=EC=9D=BC=EB=B0=98=20=EB=AC=B8=EC=A0=9C=20?= =?UTF-8?q?=EC=9D=B4=EB=AF=B8=EC=A7=80=20=EC=A0=84=EC=B2=B4=20=EC=B7=A8?= =?UTF-8?q?=ED=95=A9=EA=B3=BC=20=EB=B3=80=EA=B2=BD=EB=B6=84=C2=B7=EB=88=84?= =?UTF-8?q?=EB=9D=BD=20=EA=B2=80=EC=A6=9D=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/README.md | 8 + .../workflows/node-image-prefetch-plan.yml | 83 +++++ .github/workflows/pipeline-self-test.yml | 2 + README.md | 4 + docs/README.md | 2 +- docs/node-image-prefetch-caller-example.yml | 28 ++ docs/node-image-prefetch.md | 72 +++- scripts/README.md | 7 + scripts/collect_node_image_plans.py | 336 +++++++++++++++++ tests/README.md | 6 + tests/test_collect_node_image_plans.py | 342 ++++++++++++++++++ tests/test_workflow_contracts.py | 1 + 12 files changed, 888 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/node-image-prefetch-plan.yml create mode 100644 docs/node-image-prefetch-caller-example.yml create mode 100644 scripts/collect_node_image_plans.py create mode 100644 tests/test_collect_node_image_plans.py diff --git a/.github/workflows/README.md b/.github/workflows/README.md index b9b45a2..747eb62 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -5,6 +5,14 @@ workflow를 관리합니다. ## 파일 +### `node-image-prefetch-plan.yml` + +문제 저장소의 수동 main caller에서 호출하는 읽기 전용 reusable workflow입니다. +현재 문제와 성공한 bundle 전체를 대조해 아키텍처별 이미지 목록, 이전 목록과의 +변경분과 Actions Summary를 보관합니다. 누락·조회·입력 실패는 전체 취합 실패로 +처리하며 노드 다운로드, release 활성화나 이미지 삭제는 수행하지 않습니다. +[연동 기준과 caller 예시](../../docs/node-image-prefetch.md)를 확인합니다. + ### `published-runtime-smoke.yml` 성공한 main 발행본을 선택하는 별도 수동 caller용 reusable workflow입니다. diff --git a/.github/workflows/node-image-prefetch-plan.yml b/.github/workflows/node-image-prefetch-plan.yml new file mode 100644 index 0000000..6f40685 --- /dev/null +++ b/.github/workflows/node-image-prefetch-plan.yml @@ -0,0 +1,83 @@ +name: 일반 문제 이미지 사전 다운로드 목록 취합 + +on: + workflow_call: + inputs: + devsecops_ref: + description: 리뷰한 공급망 도구 commit SHA + type: string + required: true + previous_artifact_id: + description: 이전 완료 취합 artifact ID, 최초 취합은 생략 + type: string + required: false + default: "" + +permissions: + contents: read + actions: read + +jobs: + plan: + name: 노드 변경 없는 전체 목록·변경분 생성 + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: 공식 저장소의 수동 main 요청 확인 + env: + DEVSECOPS_REF: ${{ inputs.devsecops_ref }} + PREVIOUS_ARTIFACT_ID: ${{ inputs.previous_artifact_id }} + run: | + set -euo pipefail + test "$GITHUB_REPOSITORY" = MSG-CTF/2026_MSG_CTF || { echo "공식 문제 저장소에서 호출하세요" >&2; exit 1; } + test "$GITHUB_EVENT_NAME" = workflow_dispatch || { echo "수동 실행만 허용합니다" >&2; exit 1; } + test "$GITHUB_REF" = refs/heads/main || { echo "main 실행만 허용합니다" >&2; exit 1; } + [[ "$DEVSECOPS_REF" =~ ^[0-9a-f]{40}$ ]] || { echo "검토한 도구 SHA가 필요합니다" >&2; exit 1; } + if [ -n "$PREVIOUS_ARTIFACT_ID" ]; then + [[ "$PREVIOUS_ARTIFACT_ID" =~ ^[1-9][0-9]{0,18}$ ]] || { echo "이전 artifact ID 형식을 확인하세요" >&2; exit 1; } + fi + + - name: 검토한 공급망 도구 가져오기 + uses: actions/checkout@v4 + with: + repository: MSG-CTF/msgctf-devsecops + ref: ${{ inputs.devsecops_ref }} + persist-credentials: false + + - name: Python 설정 + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: 검증 의존성 설치 + run: python3 -m pip install -r ci/requirements.txt + + - name: 전체 성공 발행본 취합과 변경분 계산 + env: + GH_TOKEN: ${{ github.token }} + PREVIOUS_ARTIFACT_ID: ${{ inputs.previous_artifact_id }} + run: | + set -euo pipefail + args=() + if [ -n "$PREVIOUS_ARTIFACT_ID" ]; then + args+=(--previous-artifact-id "$PREVIOUS_ARTIFACT_ID") + fi + python3 -B -m scripts.collect_node_image_plans \ + --expected-source-sha "$GITHUB_SHA" \ + --output-dir dist/node-prefetch "${args[@]}" + + - name: 취합 결과 보관 + if: always() && hashFiles('dist/node-prefetch/summary.md') != '' + uses: actions/upload-artifact@v4 + with: + name: node-image-prefetch-${{ github.run_id }}-${{ github.run_attempt }} + path: dist/node-prefetch/ + retention-days: 90 + if-no-files-found: error + + - name: 취합·실패 결과 요약 + if: always() + run: | + if [ -f dist/node-prefetch/summary.md ]; then + cat dist/node-prefetch/summary.md >> "$GITHUB_STEP_SUMMARY" + fi diff --git a/.github/workflows/pipeline-self-test.yml b/.github/workflows/pipeline-self-test.yml index 32ccc36..e4d33ed 100644 --- a/.github/workflows/pipeline-self-test.yml +++ b/.github/workflows/pipeline-self-test.yml @@ -9,6 +9,7 @@ on: - ".github/workflows/published-runtime-smoke.yml" - ".github/workflows/pipeline-self-test.yml" - ".github/workflows/ghcr-cleanup-dry-run.yml" + - ".github/workflows/node-image-prefetch-plan.yml" - "ci/**" - "scripts/**" - "tests/**" @@ -20,6 +21,7 @@ on: - ".github/workflows/published-runtime-smoke.yml" - ".github/workflows/pipeline-self-test.yml" - ".github/workflows/ghcr-cleanup-dry-run.yml" + - ".github/workflows/node-image-prefetch-plan.yml" - "ci/**" - "scripts/**" - "tests/**" diff --git a/README.md b/README.md index 8055ffb..734fad6 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,10 @@ CI는 Kubernetes manifest, Namespace, Service, NetworkPolicy 또는 cleanup을 [노드 이미지 사전 다운로드 연동](docs/node-image-prefetch.md)에 담당별 연결과 기존 참가자 인스턴스를 유지하는 전환 순서를 정리했습니다. +전체 대상 취합과 이전 목록 비교는 `scripts/collect_node_image_plans.py` 및 +읽기 전용 `node-image-prefetch-plan.yml`로 준비합니다. 문제 저장소의 수동 caller +예시를 제공하며 실제 노드 연결이나 caller 적용은 이번 변경에서 하지 않습니다. + GHCR 이미지 버전은 [삭제 없는 정리 후보 조회](docs/ghcr-cleanup.md)로 관리합니다. active release·실행 중 digest와 KOTH의 별도 사용 목록을 확인하기 전에는 실제 이미지를 삭제하지 않습니다. diff --git a/docs/README.md b/docs/README.md index f51a58a..7a2b603 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,6 @@ # 문서 -- [노드 이미지 사전 다운로드 연동](node-image-prefetch.md): publish bundle의 digest 목록과 수집·다운로드·적용의 책임 경계, 기존 인스턴스를 유지하는 전환 제안 +- [노드 이미지 사전 다운로드 연동](node-image-prefetch.md): 문제별·전체 이미지 목록과 변경분 취합, 읽기 전용 Actions와 수집·다운로드·적용의 책임 경계 - [발행본 독립 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 시험과 수집 계약 구분 diff --git a/docs/node-image-prefetch-caller-example.yml b/docs/node-image-prefetch-caller-example.yml new file mode 100644 index 0000000..5a078db --- /dev/null +++ b/docs/node-image-prefetch-caller-example.yml @@ -0,0 +1,28 @@ +# 문제 저장소의 .github/workflows/node-image-prefetch.yml 예시입니다. +# 0으로 된 두 SHA를 PR 리뷰·병합 후 동일한 실제 병합 SHA로 교체해야 합니다. +# 자동 활성화·노드 호출·이미지 삭제는 하지 않습니다. +name: 일반 문제 이미지 사전 다운로드 목록 준비 + +on: + workflow_dispatch: + inputs: + previous_artifact_id: + description: 이전 성공 취합 artifact ID, 처음에는 생략 + type: string + required: false + default: "" + +concurrency: + group: node-image-prefetch-${{ github.repository }} + cancel-in-progress: false + +permissions: + contents: read + actions: read + +jobs: + plan: + uses: MSG-CTF/msgctf-devsecops/.github/workflows/node-image-prefetch-plan.yml@0000000000000000000000000000000000000000 + with: + devsecops_ref: "0000000000000000000000000000000000000000" + previous_artifact_id: ${{ inputs.previous_artifact_id }} diff --git a/docs/node-image-prefetch.md b/docs/node-image-prefetch.md index 809a3ca..ef80025 100644 --- a/docs/node-image-prefetch.md +++ b/docs/node-image-prefetch.md @@ -76,7 +76,67 @@ python3 scripts/generate_node_image_plan.py \ 다시 계산·대조해야 합니다. `plan_only`를 지우거나 보조 JSON을 수정해도 실행 승인으로 인정하지 않습니다. -## 노드 저장 방식 +## 전체 목록과 업데이트 변경분 + +`scripts/collect_node_image_plans.py`는 현재 main 문제 전체와 성공 발행본을 새로 +대조한 뒤 일반 동적 문제의 원본 `artifact-v2.json`을 가져옵니다. 저장소·공식 +workflow·main·성공 여부·run·revision·commit과 문제 폴더 일치, 전체 컨테이너 +검사 증거를 확인하고 기존 문제별 생성기를 재사용합니다. + +출력 예: + +```text +node-prefetch/ +├── prefetch-inventory.json +├── changes.json +├── images-amd64.txt +├── images-arm64.txt # 해당 아키텍처가 있을 때만 생성 +└── summary.md +``` + +아키텍처별 목록은 서로 섞지 않습니다. 전체 대상 중 하나라도 조회·출처·검사에 +실패하면 이미지 목록과 완료 inventory는 발행하지 않습니다. 대신 실패 문제와 +고정된 오류 분류를 담은 `failure-report.json`, `summary.md`만 남기고 종료 코드 +2로 실패합니다. API 응답 본문이나 인증 원문을 오류 보고서에 복사하지 않습니다. +파일 저장도 임시 디렉터리에 완료한 뒤 이동하므로 중간 저장 실패를 완료로 +취급하지 않습니다. 취합 도중 main이 바뀌어도 실패합니다. + +```bash +python3 -B -m scripts.collect_node_image_plans \ + --output-dir /absolute/path/to/new-node-prefetch + +python3 -B -m scripts.collect_node_image_plans \ + --previous-plan /absolute/path/to/previous/prefetch-inventory.json \ + --output-dir /absolute/path/to/next-node-prefetch +``` + +`changes.json`은 문제·컨테이너 단위의 신규, digest/아키텍처 변경, 유지와 +현재 목록에서 제외된 항목을 구분합니다. 최초 취합은 비교 기준 없음으로 +표시합니다. 지정한 이전 파일이 없거나 손상됐으면 최초 취합으로 대체하지 +않고 실패합니다. 이전 목록의 문제·컨테이너 경로와 checksum도 검증합니다. +**현재 목록 제외는 삭제 승인이 아닙니다.** 이전 이미지의 실행·롤백·적용 대기 +여부는 별도로 보호해야 하며 `deletion_authorized`는 항상 `false`입니다. + +### Actions 연결 + +새 reusable workflow는 `.github/workflows/node-image-prefetch-plan.yml`입니다. +문제 저장소에서 `.github/workflows/node-image-prefetch.yml`이라는 수동 caller로 +호출하는 예시는 [caller 예시](node-image-prefetch-caller-example.yml)에 있습니다. +두 SHA placeholder는 리뷰·병합된 동일한 실제 commit으로 교체해야 합니다. +이번 PR은 예시만 제공하며 실제 문제 저장소의 caller를 수정하지 않습니다. + +공식 문제 저장소의 수동 main 호출만 허용하고, source 저장소 자신의 +`GITHUB_TOKEN`에 `contents: read`, `actions: read`만 사용합니다. 별도 PAT, +Backend 서비스 토큰, Runtime 토큰이나 SSH 권한을 추가하지 않습니다. +실행 commit과 조회한 main이 다르면 실패합니다. Summary와 90일 보관 artifact를 +남기며, 실패한 실행에는 실패 보고서만 보관합니다. + +다음 호출에서 `previous_artifact_id`로 이전 성공 취합 artifact를 지정할 수 있습니다. +이전 artifact도 동일 저장소·공식 caller·main 성공 실행인지 확인합니다. 로컬 +이전 JSON 파일은 구조·checksum 검사만 수행하므로 승인된 원본을 직접 선택해야 +하며, 파일 자체를 서명된 신뢰 근거로 사용하지 않습니다. + +## 실제 노드 저장 방식 K3s의 실행 이미지는 노드의 containerd 저장소에 들어가야 합니다. VM에서 별도 Docker daemon으로 `docker pull`한 것만으로 K3s의 이미지 준비를 판정하지 않습니다. @@ -151,11 +211,19 @@ Open House 생성·삭제 성공 기록은 cold pull이나 이번 자동화 검 ## 이번 변경의 확인 결과 -- 기존 테스트 237개와 새 목록 검사 21개를 합쳐 로컬 테스트 258개 통과 +- 전체 로컬 단위 테스트 286개 통과 - 기존 Open House main 발행 run `37349840954`, revision `461`의 실제 `artifact-v2.json`으로 이미지 목록 생성 확인 - 출력의 이미지가 원본 bundle의 정확한 digest와 일치하고 원본 파일 hash가 보존됨 - 실제 workflow의 목록 생성 셸 실행과 기존 Poller의 파일 선택 방식 호환 확인 +- 실제 일반 동적 문제 18개 중 K3s 지원 15개·컨테이너 이미지 22개 취합 +- `misc-reqr`, `pwn-ghost-file`, `pwn-random6`는 현재 `DOCKER` 선언이므로 + K3s 목록에서 별도 분류하며 실행 방식을 임의로 바꾸지 않음 +- 전체 일반 문제 30개와 정적 12개, KOTH·Windows 제외를 구분해 보고 + +새 취합 workflow는 reusable 코드와 caller 예시만 준비한 상태입니다. 실제 문제 +저장소의 수동 caller 적용과 해당 경로의 Actions 실행은 리뷰·병합 후 진행합니다. +PR 자체 CI와 로컬 실제 bundle 취합 성공을 새 caller의 운영 실행 성공으로 기록하지 않습니다. 이 결과는 목록 생성 검증입니다. 실제 Backend 수집, 노드 다운로드, 캐시 hit, Runtime HTTP 접속이나 무중단 교체 성공을 의미하지 않습니다. diff --git a/scripts/README.md b/scripts/README.md index 830f89a..2ba21d4 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -9,6 +9,13 @@ Provisioner API 요청으로 변환합니다. 생성 Operation을 조회한 뒤 ## 파일 +### `collect_node_image_plans.py` + +현재 main과 성공한 실제 bundle을 대조해 일반 Linux K3s 문제의 전체 다운로드 +목록을 아키텍처별로 취합합니다. 이전 완료 목록과 신규·변경·유지·현재 목록 +제외를 비교하되 삭제는 하지 않습니다. 일부 실패는 전체 취합 실패이며 부분 +목록을 발행하지 않습니다. [취합·Actions 연결](../docs/node-image-prefetch.md)을 참고합니다. + ### `generate_node_image_plan.py` 성공한 main 발행 bundle에서 일반 Linux K3s 문제의 모든 컨테이너 digest 목록과 diff --git a/scripts/collect_node_image_plans.py b/scripts/collect_node_image_plans.py new file mode 100644 index 0000000..07df620 --- /dev/null +++ b/scripts/collect_node_image_plans.py @@ -0,0 +1,336 @@ +#!/usr/bin/env python3 +"""성공한 일반 문제 발행본을 취합합니다. 노드·Registry·release는 변경하지 않습니다.""" + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import zipfile + +if __package__: + from . import audit_publication_state as publication + from .generate_node_image_plan import generate_plan, NAME, MAX_ARTIFACT_BYTES + from .generate_publish_bundle import COMMIT_SHA, MSGCTF_GHCR_DIGEST_IMAGE +else: + import audit_publication_state as publication + from generate_node_image_plan import generate_plan, NAME, MAX_ARTIFACT_BYTES + from generate_publish_bundle import COMMIT_SHA, MSGCTF_GHCR_DIGEST_IMAGE + + +SCOPE = "GENERAL_LINUX_KUBERNETES" +MAX_ARCHIVE_BYTES = 16 * 1024 * 1024 +EXCLUDED = {"pwn-msgdriver"} + + +class CollectionFailure(ValueError): + def __init__(self, failures): + super().__init__("전체 목록 취합을 완료하지 못했습니다") + self.failures = failures + + +class UnsupportedWorkload(ValueError): + def __init__(self, runtime_type): + super().__init__("K3s 취합 범위 밖의 실행 방식입니다") + self.runtime_type = runtime_type if runtime_type in ("KUBERNETES", "DOCKER", "VM") else "UNSUPPORTED" + + +def positive(value): + return type(value) is int and value > 0 + + +def download_json(artifact_id, filename): + if not positive(artifact_id): + raise ValueError("artifact 식별자가 올바르지 않습니다") + # ZIP은 추출하지 않고 제한된 JSON 하나만 읽습니다. 인증 원문은 gh가 관리합니다. + with tempfile.TemporaryFile() as stream: + result = subprocess.run( + ["gh", "api", f"repos/{publication.REPOSITORY}/actions/artifacts/{artifact_id}/zip"], + stdout=stream, stderr=subprocess.PIPE, timeout=180, + ) + if result.returncode or stream.tell() > MAX_ARCHIVE_BYTES: + raise ValueError("artifact 다운로드를 확인하지 못했습니다") + stream.seek(0) + with zipfile.ZipFile(stream) as archive: + if archive.namelist().count(filename) != 1: + raise ValueError("artifact에 필요한 JSON이 정확히 하나 있어야 합니다") + item = archive.getinfo(filename) + if item.file_size > MAX_ARTIFACT_BYTES or item.flag_bits & 1: + raise ValueError("JSON 크기 또는 ZIP 형식을 확인하세요") + raw = archive.read(item) + return json.loads(raw), raw + + +def checked_origin(meta, run): + origin = meta.get("workflow_run") + if (not positive(meta.get("id")) or meta.get("expired") is not False + or not positive(meta.get("size_in_bytes")) or meta["size_in_bytes"] > MAX_ARCHIVE_BYTES + or not isinstance(origin, dict) or not positive(run.get("id")) + or origin.get("id") != run["id"] or origin.get("head_sha") != run.get("head_sha") + or origin.get("head_branch") != "main" or run.get("head_branch") != "main" + or run.get("status") != "completed" or run.get("conclusion") != "success" + or run.get("event") not in ("push", "workflow_dispatch")): + raise ValueError("성공한 공식 main artifact가 아닙니다") + sha = run.get("head_sha") + if not isinstance(sha, str) or not COMMIT_SHA.fullmatch(sha): + raise ValueError("발행 커밋이 올바르지 않습니다") + for key in ("repository", "head_repository"): + if not isinstance(run.get(key), dict) or run[key].get("full_name") != publication.REPOSITORY: + raise ValueError("공식 문제 저장소의 실행이 아닙니다") + + +def fetch_plan(slug, selected, *, api=publication.github, download=download_json): + if not isinstance(selected, dict) or not positive(selected.get("id")) or not positive(selected.get("run_id")): + raise ValueError("발행 bundle이 누락됐습니다") + meta = api(f"actions/artifacts/{selected['id']}") + run = api(f"actions/runs/{selected['run_id']}") + checked_origin(meta, run) + if (meta["id"] != selected["id"] or meta.get("name") != selected.get("name") + or run.get("path") != ".github/workflows/challenge-validation.yml" + or not positive(run.get("run_number")) or run["run_number"] != selected.get("registry_revision") + or run["head_sha"] != selected.get("source_sha") + or not isinstance(meta.get("name"), str) + or not re.fullmatch(re.escape(f"{slug}-{run['id']}-") + r"[1-9][0-9]*-[0-9a-f]+-publish-bundle", meta["name"])): + raise ValueError("문제·run·revision과 artifact가 일치하지 않습니다") + artifact, raw = download(selected["id"], "artifact-v2.json") + if (not isinstance(artifact, dict) or artifact.get("challenge_slug") != slug + or artifact.get("registry_revision") != run["run_number"] or artifact.get("source_sha") != run["head_sha"]): + raise ValueError("발행 JSON 출처가 일치하지 않습니다") + result = generate_plan(artifact, hashlib.sha256(raw).hexdigest()) + if result is None: + raise UnsupportedWorkload(artifact.get("runtime_type")) + plan, _ = result + return {**plan, "publish_run_id": run["id"], "publish_artifact_id": meta["id"]} + + +def flatten(report): + if (not isinstance(report, dict) or report.get("schema_version") != "1.0" + or report.get("scope") != SCOPE or report.get("repository") != publication.REPOSITORY + or report.get("complete") is not True or report.get("plan_only") is not True + or report.get("source_ref") != "refs/heads/main" + or not isinstance(report.get("source_sha"), str) or not COMMIT_SHA.fullmatch(report["source_sha"]) + or not isinstance(report.get("plans"), list) or not report["plans"]): + raise ValueError("완료된 동일 범위의 취합 목록이 필요합니다") + indexed, slugs = {}, set() + for plan in report["plans"]: + if not isinstance(plan, dict): + raise ValueError("문제별 목록 형식이 올바르지 않습니다") + slug, arch = plan.get("challenge_slug"), plan.get("architecture") + if (not isinstance(slug, str) or not NAME.fullmatch(slug) or slug in slugs + or slug.startswith("koth-") or slug in EXCLUDED or arch not in ("AMD64", "ARM64") + or plan.get("schema_version") != "1.0" or plan.get("plan_only") is not True + or plan.get("runtime_type") != "KUBERNETES" or plan.get("source_ref") != "refs/heads/main" + or not positive(plan.get("registry_revision")) or not positive(plan.get("publish_run_id")) + or not positive(plan.get("publish_artifact_id")) + or not isinstance(plan.get("source_sha"), str) or not COMMIT_SHA.fullmatch(plan["source_sha"]) + or not isinstance(plan.get("artifact_sha256"), str) or not re.fullmatch(r"[0-9a-f]{64}", plan["artifact_sha256"]) + or not isinstance(plan.get("containers"), list) or not plan["containers"]): + raise ValueError("문제별 목록의 출처·범위가 올바르지 않습니다") + slugs.add(slug) + names = set() + for item in plan["containers"]: + if not isinstance(item, dict) or set(item) != {"name", "image"}: + raise ValueError("컨테이너 목록에는 이름과 이미지만 허용합니다") + name, image = item["name"], item["image"] + if (not isinstance(name, str) or not NAME.fullmatch(name) or name in names + or not isinstance(image, str) or not MSGCTF_GHCR_DIGEST_IMAGE.fullmatch(image) + or not image.startswith(f"ghcr.io/msg-ctf/challenges/{slug}/{name}@sha256:")): + raise ValueError("컨테이너 digest 경로가 일치하지 않습니다") + names.add(name) + indexed[(slug, name)] = {"challenge_slug": slug, "name": name, "architecture": arch, "image": image} + raw = ("\n".join(item["image"] for item in sorted(plan["containers"], key=lambda item: item["name"])) + "\n").encode() + if plan.get("image_list") != {"file": "images.txt", "sha256": hashlib.sha256(raw).hexdigest()}: + raise ValueError("문제별 이미지 목록 checksum이 일치하지 않습니다") + return indexed + + +def compare(current, previous=None): + new = flatten(current) + old = flatten(previous) if previous is not None else {} + added, changed, unchanged = [], [], [] + for key, row in sorted(new.items()): + if key not in old: + added.append(row) + elif old[key] == row: + unchanged.append(row) + else: + changed.append({**row, "previous_image": old[key]["image"], "previous_architecture": old[key]["architecture"]}) + return {"baseline_present": previous is not None, "added": added, "changed": changed, + "unchanged": unchanged, "no_longer_listed": [old[key] for key in sorted(old.keys() - new.keys())], + "deletion_authorized": False} + + +def collect(catalog=None, previous=None, *, fetch=fetch_plan, expected_sha=None, head=None): + catalog = publication.collect() if catalog is None else catalog + if (not isinstance(catalog, dict) or catalog.get("repository") != publication.REPOSITORY + or catalog.get("source_ref") != "refs/heads/main" or not isinstance(catalog.get("source_sha"), str) + or not COMMIT_SHA.fullmatch(catalog["source_sha"]) or not isinstance(catalog.get("problems"), list) + or not catalog["problems"]): + raise ValueError("공식 main 문제 전체 목록이 필요합니다") + if expected_sha is not None and catalog["source_sha"] != expected_sha: + raise ValueError("실행 커밋과 현재 문제 main이 다릅니다") + counts = catalog.get("counts") + if not isinstance(counts, dict) or type(counts.get("total")) is not int or counts["total"] != len(catalog["problems"]): + raise ValueError("전체 문제 개수가 일치하지 않습니다") + plans, excluded, seen, failures = [], [], set(), [] + general_problems, general_dynamic = 0, 0 + for item in catalog["problems"]: + slug = item.get("challenge_slug") if isinstance(item, dict) else None + if not isinstance(slug, str) or not NAME.fullmatch(slug) or slug in seen: + raise ValueError("문제 목록에 잘못된 이름이나 중복이 있습니다") + seen.add(slug) + if slug.startswith("koth-") or slug in EXCLUDED: + excluded.append({"challenge_slug": slug, "reason": "OUTSIDE_GENERAL_SCOPE"}) + continue + if type(item.get("runtime_required")) is not bool: + raise ValueError("정적·동적 분류가 올바르지 않습니다") + general_problems += 1 + if not item["runtime_required"]: + excluded.append({"challenge_slug": slug, "reason": "STATIC_PROBLEM"}) + continue + general_dynamic += 1 + if item.get("status") != "ARTIFACTS_MATCH_PROBLEM_TREE": + failures.append({"challenge_slug": slug, "error_code": "PUBLISH_NOT_CURRENT"}) + continue + selected = item.get("artifacts", {}).get("publish") + if not isinstance(selected, dict) or selected.get("problem_tree_matches") is not True: + failures.append({"challenge_slug": slug, "error_code": "PUBLISH_TREE_UNCONFIRMED"}) + continue + try: + plan = fetch(slug, selected) + except UnsupportedWorkload as error: + excluded.append({"challenge_slug": slug, "reason": "UNSUPPORTED_WORKLOAD_SCOPE", "runtime_type": error.runtime_type}) + continue + except (OSError, ValueError, KeyError, TypeError, RuntimeError, subprocess.SubprocessError, zipfile.BadZipFile): + failures.append({"challenge_slug": slug, "error_code": "PUBLISH_FETCH_OR_VALIDATION_FAILED"}) + continue + if plan is None: + excluded.append({"challenge_slug": slug, "reason": "UNSUPPORTED_WORKLOAD_SCOPE"}) + else: + if plan.get("challenge_slug") != slug: + raise ValueError("선택한 문제와 목록이 일치하지 않습니다") + plans.append(plan) + if failures: + raise CollectionFailure(failures) + report = {"schema_version": "1.0", "plan_only": True, "complete": True, "scope": SCOPE, + "repository": publication.REPOSITORY, "source_ref": "refs/heads/main", "source_sha": catalog["source_sha"], + "generated_at": datetime.now(timezone.utc).isoformat(), "plans": sorted(plans, key=lambda row: row["challenge_slug"]), + "excluded": sorted(excluded, key=lambda row: row["challenge_slug"])} + indexed = flatten(report) + changes = compare(report, previous) + report["counts"] = {"general_problems": general_problems, "general_dynamic": general_dynamic, + "unsupported_dynamic": general_dynamic - len(plans), + "selected_problems": len(plans), "images": len(indexed), "excluded_problems": len(excluded), + **{key: len(changes[key]) for key in ("added", "changed", "unchanged", "no_longer_listed")}} + files = {} + for arch in ("AMD64", "ARM64"): + images = sorted({row["image"] for row in indexed.values() if row["architecture"] == arch}) + if images: + files[f"images-{arch.lower()}.txt"] = ("\n".join(images) + "\n").encode() + report["image_lists"] = {name: {"sha256": hashlib.sha256(raw).hexdigest(), "image_count": len(raw.splitlines())} + for name, raw in files.items()} + if head is not None and head() != catalog["source_sha"]: + raise ValueError("조회 도중 문제 main이 변경됐습니다") + return report, changes, files + + +def fetch_previous(artifact_id, *, api=publication.github, download=download_json): + meta = api(f"actions/artifacts/{artifact_id}") + origin = meta.get("workflow_run") + if not isinstance(origin, dict) or not positive(origin.get("id")): + raise ValueError("이전 목록 출처가 없습니다") + run = api(f"actions/runs/{origin['id']}") + checked_origin(meta, run) + if (meta["id"] != artifact_id or run.get("path") != ".github/workflows/node-image-prefetch.yml" + or not isinstance(meta.get("name"), str) + or not re.fullmatch(re.escape(f"node-image-prefetch-{run['id']}-") + r"[1-9][0-9]*", meta["name"])): + raise ValueError("공식 취합 workflow의 이전 목록이 아닙니다") + report, _ = download(artifact_id, "prefetch-inventory.json") + flatten(report) + if report["source_sha"] != run["head_sha"]: + raise ValueError("이전 목록의 커밋이 일치하지 않습니다") + return report + + +def summary(report, changes): + counts = report["counts"] + lines = ["# 노드 이미지 사전 다운로드 준비", "", "목록 생성 완료이며 노드 다운로드·실행 승인이 아닙니다.", "", + f"- 일반 문제 {counts['general_problems']}개 / 동적 {counts['general_dynamic']}개 / 이 중 지원 범위 밖 {counts['unsupported_dynamic']}개", + f"- 문제: {counts['selected_problems']}개 / 컨테이너 이미지: {counts['images']}개", + f"- 비교 기준: {'이전 완료 목록' if changes['baseline_present'] else '최초 목록 (비교 기준 없음)'}", + f"- 신규 {counts['added']} / 변경 {counts['changed']} / 유지 {counts['unchanged']} / 현재 목록 제외 {counts['no_longer_listed']}", + "- 현재 목록에서 제외된 이미지도 자동 삭제하지 않습니다.", "", + "| 문제 | 아키텍처 | revision | 이미지 수 |", "|---|---|---:|---:|"] + for plan in report["plans"]: + lines.append(f"| {plan['challenge_slug']} | {plan['architecture']} | {plan['registry_revision']} | {len(plan['containers'])} |") + unsupported = [item for item in report["excluded"] if item["reason"] == "UNSUPPORTED_WORKLOAD_SCOPE"] + if unsupported: + lines += ["", "## 별도 실행 계약이 필요한 동적 문제", "", "| 문제 | 현재 실행 방식 |", "|---|---|"] + lines += [f"| {item['challenge_slug']} | {item.get('runtime_type', '미확인')} |" for item in unsupported] + lines += ["", "실제 노드 캐시·pull·HTTP 응답·Runtime 정책·Backend 등록은 별도 확인이 필요합니다.", ""] + return "\n".join(lines) + + +def write_result(output, report, changes, files): + output = Path(output) + if output.exists() or output.is_symlink(): + raise FileExistsError("기존 출력 경로는 덮어쓰지 않습니다") + output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix=".node-prefetch-", dir=output.parent) as temporary: + staging = Path(temporary) / "result" + staging.mkdir() + for name, raw in files.items(): + (staging / name).write_bytes(raw) + for name, value in (("prefetch-inventory.json", report), ("changes.json", changes)): + (staging / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + (staging / "summary.md").write_text(summary(report, changes), encoding="utf-8") + staging.rename(output) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", required=True, type=Path) + baseline = parser.add_mutually_exclusive_group() + baseline.add_argument("--previous-plan", type=Path) + baseline.add_argument("--previous-artifact-id", type=int) + parser.add_argument("--expected-source-sha") + args = parser.parse_args() + if args.output_dir.exists() or args.output_dir.is_symlink(): + print("기존 출력 경로는 덮어쓰지 않습니다", file=sys.stderr) + return 2 + try: + previous = None + if args.previous_plan: + if args.previous_plan.is_symlink() or args.previous_plan.stat().st_size > MAX_ARTIFACT_BYTES: + raise ValueError("이전 목록 경로·크기를 확인하세요") + previous = json.loads(args.previous_plan.read_text(encoding="utf-8")) + elif args.previous_artifact_id is not None: + if not positive(args.previous_artifact_id): + raise ValueError("이전 artifact 식별자를 확인하세요") + previous = fetch_previous(args.previous_artifact_id) + report, changes, files = collect(previous=previous, expected_sha=args.expected_source_sha, + head=lambda: publication.github("git/ref/heads/main")["object"]["sha"]) + write_result(args.output_dir, report, changes, files) + print(json.dumps({"complete": True, "plan_only": True, "counts": report["counts"]})) + return 0 + except (OSError, ValueError, KeyError, TypeError, RuntimeError, RecursionError, subprocess.SubprocessError, zipfile.BadZipFile) as error: + # 인증·입력·API 본문과 환경변수는 실패 보고서에 복사하지 않습니다. + args.output_dir.mkdir(parents=True, exist_ok=False) + failures = error.failures if isinstance(error, CollectionFailure) else [{"error_code": "SOURCE_OR_INPUT_INVALID"}] + (args.output_dir / "failure-report.json").write_text( + json.dumps({"complete": False, "plan_only": True, "status": "BLOCKED", + "error_code": "PREFETCH_COLLECTION_FAILED", "failures": failures}) + "\n") + (args.output_dir / "summary.md").write_text( + "# 사전 다운로드 목록 취합 실패\n\n완료 이미지 목록은 발행하지 않습니다.\n\n" + + "\n".join(f"- {item.get('challenge_slug', '전체 조회')}: `{item['error_code']}`" for item in failures) + + "\n", encoding="utf-8") + print("목록 취합 실패: 인증·전체 발행본·비교 기준을 확인하세요", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/README.md b/tests/README.md index c73067d..f57397c 100644 --- a/tests/README.md +++ b/tests/README.md @@ -5,6 +5,12 @@ ## 테스트 구성 +### `test_collect_node_image_plans.py` + +전체 대상과 아키텍처별 취합, 신규·변경·유지 비교, 누락·중복·출처·이전 목록 +검증과 부분 저장 방지를 검사합니다. 공식 문제 저장소·수동 main·도구 SHA의 +실제 셸 경계, 최소 읽기 권한과 Actions 요약도 확인합니다. 노드 배포 시험은 아닙니다. + ### `test_generate_node_image_plan.py` 기존 발행 자료에서 공개·비공개 컨테이너 전체의 digest와 아키텍처가 보존되는지, diff --git a/tests/test_collect_node_image_plans.py b/tests/test_collect_node_image_plans.py new file mode 100644 index 0000000..829cfc7 --- /dev/null +++ b/tests/test_collect_node_image_plans.py @@ -0,0 +1,342 @@ +import copy +import hashlib +import io +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +import warnings +import zipfile +from unittest.mock import patch + +import yaml + +from scripts import collect_node_image_plans as collector +from scripts.generate_node_image_plan import generate_plan + + +ROOT = Path(__file__).resolve().parents[1] +SHA = "1" * 40 + + +def artifact(slug="web-one", digest="a", arch="AMD64"): + image = f"ghcr.io/msg-ctf/challenges/{slug}/web@sha256:{digest * 64}" + return {"schema_version": "2.0", "category": "web", "challenge_slug": slug, + "registry_revision": 1, "revision": 1, "architecture": arch, "runtime_type": "KUBERNETES", + "source_sha": SHA, "source_ref": "refs/heads/main", "scan_result": "PASS", + "workload": {"containers": [{"name": "web", "image": image}]}, + "evidence": {"containers": [{"name": "web", "published_image": image, + "secret_scan": "PASS", "vulnerability_scan": "PASS"}]}} + + +def plan(slug="web-one", digest="a", arch="AMD64"): + value, _ = generate_plan(artifact(slug, digest, arch), "c" * 64) + return {**value, "publish_run_id": 100, "publish_artifact_id": 200} + + +def selected(): + return {"id": 200, "run_id": 100, "registry_revision": 1, "source_sha": SHA, + "name": "web-one-100-1-abcdef-publish-bundle", "problem_tree_matches": True} + + +def catalog(*slugs): + return {"repository": collector.publication.REPOSITORY, "source_ref": "refs/heads/main", "source_sha": SHA, + "counts": {"total": len(slugs)}, "problems": [ + {"challenge_slug": slug, "runtime_required": True, + "status": "ARTIFACTS_MATCH_PROBLEM_TREE", "artifacts": {"publish": selected()}} + for slug in slugs]} + + +def make_report(*values): + values = values or (plan(),) + return collector.collect(catalog(*(value["challenge_slug"] for value in values)), + fetch=lambda slug, _: next(value for value in values if value["challenge_slug"] == slug)) + + +def origin(): + meta = {"id": 200, "size_in_bytes": 1000, "expired": False, + "name": selected()["name"], "workflow_run": {"id": 100, "head_sha": SHA, "head_branch": "main"}} + run = {"id": 100, "status": "completed", "conclusion": "success", "event": "push", + "head_sha": SHA, "head_branch": "main", "run_number": 1, + "path": ".github/workflows/challenge-validation.yml", + "repository": {"full_name": collector.publication.REPOSITORY}, + "head_repository": {"full_name": collector.publication.REPOSITORY}} + return meta, run + + +class CollectNodeImagePlansTests(unittest.TestCase): + def test_groups_complete_lists_by_architecture(self): + report, changes, files = make_report(plan(), plan("web-two", "b", "ARM64")) + self.assertEqual(report["counts"]["selected_problems"], 2) + self.assertEqual(set(files), {"images-amd64.txt", "images-arm64.txt"}) + self.assertTrue(report["complete"]) + self.assertTrue(report["plan_only"]) + self.assertFalse(changes["deletion_authorized"]) + for name, raw in files.items(): + self.assertEqual(report["image_lists"][name]["sha256"], hashlib.sha256(raw).hexdigest()) + + def test_initial_plan_does_not_pretend_to_have_a_previous_baseline(self): + report, changes, _ = make_report() + self.assertFalse(changes["baseline_present"]) + self.assertEqual(len(changes["added"]), 1) + self.assertIn("최초 목록", collector.summary(report, changes)) + + def test_diffs_added_changed_unchanged_and_no_longer_listed(self): + old, _, _ = make_report(plan(), plan("web-keep", "b"), plan("web-old", "c")) + new, _, _ = make_report(plan(digest="d"), plan("web-keep", "b"), plan("web-new", "e")) + diff = collector.compare(new, old) + for key in ("added", "changed", "unchanged", "no_longer_listed"): + self.assertEqual(len(diff[key]), 1) + self.assertEqual(diff["changed"][0]["previous_image"], old["plans"][2]["containers"][0]["image"]) + self.assertFalse(diff["deletion_authorized"]) + + def test_architecture_change_is_a_change_even_for_the_same_digest(self): + old, _, _ = make_report(plan()) + new, _, _ = make_report(plan(arch="ARM64")) + self.assertEqual(len(collector.compare(new, old)["changed"]), 1) + + def test_excludes_static_koth_windows_and_non_kubernetes(self): + source = catalog("web-one", "rev-static", "koth-real", "pwn-msgdriver", "web-vm") + source["problems"][1]["runtime_required"] = False + fetched = [] + def fetch(slug, _): + fetched.append(slug) + return None if slug == "web-vm" else plan(slug) + report, _, _ = collector.collect(source, fetch=fetch) + self.assertEqual(fetched, ["web-one", "web-vm"]) + self.assertEqual(len(report["excluded"]), 4) + + def test_no_eligible_image_cannot_be_reported_as_complete(self): + source = catalog("rev-static") + source["problems"][0]["runtime_required"] = False + with self.assertRaises(ValueError): + collector.collect(source) + + def test_unsupported_runtime_stays_visible_and_is_not_silently_converted(self): + source = catalog("web-one", "pwn-docker") + def fetch(slug, _): + if slug == "pwn-docker": + raise collector.UnsupportedWorkload("DOCKER") + return plan(slug) + report, changes, _ = collector.collect(source, fetch=fetch) + self.assertEqual(report["counts"]["general_dynamic"], 2) + self.assertEqual(report["counts"]["selected_problems"], 1) + self.assertEqual(report["counts"]["unsupported_dynamic"], 1) + self.assertIn("DOCKER", collector.summary(report, changes)) + self.assertEqual(report["excluded"][0]["runtime_type"], "DOCKER") + + def test_reports_every_missing_or_failed_problem_without_partial_success(self): + source = catalog("web-one", "web-missing", "web-broken") + source["problems"][1]["status"] = "MISSING_SUCCESSFUL_ARTIFACT" + def fetch(slug, _): + if slug == "web-broken": + raise RuntimeError("do-not-print-secret") + return plan(slug) + with self.assertRaises(collector.CollectionFailure) as caught: + collector.collect(source, fetch=fetch) + self.assertEqual({row["challenge_slug"] for row in caught.exception.failures}, {"web-missing", "web-broken"}) + self.assertNotIn("do-not-print-secret", str(caught.exception.failures)) + + def test_unconfirmed_problem_tree_is_rejected(self): + source = catalog("web-one") + source["problems"][0]["artifacts"]["publish"]["problem_tree_matches"] = False + with self.assertRaises(collector.CollectionFailure): + collector.collect(source) + + def test_detects_duplicate_or_truncated_catalogs(self): + for source in (catalog("web-one", "web-one"), dict(catalog("web-one"), counts={"total": 2})): + with self.subTest(source=source), self.assertRaises(ValueError): + collector.collect(source, fetch=lambda slug, _: plan(slug)) + + def test_expected_commit_and_mid_collection_main_change_are_rejected(self): + with self.assertRaises(ValueError): + collector.collect(catalog("web-one"), expected_sha="2" * 40) + with self.assertRaises(ValueError): + collector.collect(catalog("web-one"), fetch=lambda slug, _: plan(slug), head=lambda: "2" * 40) + + def test_fetches_and_checks_real_publication_shape_before_generating(self): + meta, run = origin() + data = artifact() + result = collector.fetch_plan("web-one", selected(), api=lambda path: meta if "artifacts/" in path else run, + download=lambda *_: (data, json.dumps(data).encode())) + self.assertEqual(result["publish_artifact_id"], 200) + self.assertEqual(result["artifact_sha256"], hashlib.sha256(json.dumps(data).encode()).hexdigest()) + + def test_failed_expired_foreign_or_misbound_sources_are_rejected(self): + mutations = (lambda m, r: m.update(expired=True), lambda m, r: r.update(conclusion="failure"), + lambda m, r: r.update(head_branch="feature/example"), lambda m, r: r.update(run_number=2), + lambda m, r: r.update(repository={"full_name": "outside/repo"}), + lambda m, r: r.update(path="other.yml"), lambda m, r: m.update(name="other-bundle"), + lambda m, r: m["workflow_run"].update(head_sha="2" * 40)) + for mutate in mutations: + meta, run = origin() + mutate(meta, run) + with self.subTest(mutate=mutate), self.assertRaises(ValueError): + collector.fetch_plan("web-one", selected(), api=lambda path: meta if "artifacts/" in path else run) + + def test_wrong_payload_slug_revision_digest_or_scan_is_rejected(self): + for mutation in ({"challenge_slug": "web-two"}, {"registry_revision": 2}, {"scan_result": "FAIL"}): + data = dict(artifact(), **mutation) + meta, run = origin() + with self.subTest(mutation=mutation), self.assertRaises(ValueError): + collector.fetch_plan("web-one", selected(), api=lambda path: meta if "artifacts/" in path else run, + download=lambda *_: (data, json.dumps(data).encode())) + + def test_invalid_baselines_fail_instead_of_becoming_initial_lists(self): + valid, _, _ = make_report() + for update in ({"complete": False}, {"scope": "OTHER"}, {"repository": "other/repo"}, + {"plans": []}, {"source_sha": "invalid"}, {"plan_only": False}): + with self.subTest(update=update), self.assertRaises(ValueError): + collector.compare(valid, dict(valid, **update)) + + def test_baseline_rejects_tag_paths_duplicates_and_mismatched_checksum(self): + valid, _, _ = make_report() + for mode in ("tag", "checksum", "duplicate", "outside"): + old = copy.deepcopy(valid) + if mode == "tag": + old["plans"][0]["containers"][0]["image"] = "ghcr.io/msg-ctf/challenges/web-one/web:latest" + elif mode == "checksum": + old["plans"][0]["image_list"]["sha256"] = "0" * 64 + elif mode == "duplicate": + old["plans"].append(old["plans"][0]) + else: + old["plans"][0]["challenge_slug"] = "koth-real" + with self.subTest(mode=mode), self.assertRaises(ValueError): + collector.compare(valid, old) + + def test_previous_artifact_requires_successful_official_collector_run(self): + meta, run = origin() + meta["name"] = "node-image-prefetch-100-1" + run["path"] = ".github/workflows/node-image-prefetch.yml" + previous, _, _ = make_report() + api = lambda path: meta if "artifacts/" in path else run + self.assertEqual(collector.fetch_previous(200, api=api, download=lambda *_: (previous, b"")), previous) + run["conclusion"] = "failure" + with self.assertRaises(ValueError): + collector.fetch_previous(200, api=api, download=lambda *_: (previous, b"")) + + def test_previous_artifact_commit_mismatch_is_rejected(self): + meta, run = origin() + meta["name"] = "node-image-prefetch-100-1" + run["path"] = ".github/workflows/node-image-prefetch.yml" + previous, _, _ = make_report() + previous["source_sha"] = "2" * 40 + with self.assertRaises(ValueError): + collector.fetch_previous(200, api=lambda path: meta if "artifacts/" in path else run, + download=lambda *_: (previous, b"")) + + def test_success_output_is_atomic_and_does_not_overwrite(self): + report, diff, files = make_report() + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "result" + collector.write_result(output, report, diff, files) + self.assertTrue((output / "images-amd64.txt").is_file()) + with self.assertRaises(FileExistsError): + collector.write_result(output, report, diff, files) + self.assertEqual(json.loads((output / "prefetch-inventory.json").read_text()), report) + + def test_write_failure_leaves_no_partial_image_list(self): + report, diff, files = make_report() + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "result" + with patch.object(Path, "write_bytes", side_effect=OSError("disk-full")), self.assertRaises(OSError): + collector.write_result(output, report, diff, files) + self.assertFalse(output.exists()) + self.assertEqual(list(Path(temporary).iterdir()), []) + + def test_cli_failure_only_publishes_sanitized_failure_report(self): + error = collector.CollectionFailure([{"challenge_slug": "web-one", "error_code": "PUBLISH_NOT_CURRENT"}]) + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "result" + with patch.object(collector, "collect", side_effect=error), patch.object(collector.sys, "argv", ["tool", "--output-dir", str(output)]): + self.assertEqual(collector.main(), 2) + self.assertEqual({path.name for path in output.iterdir()}, {"failure-report.json", "summary.md"}) + self.assertFalse(json.loads((output / "failure-report.json").read_text())["complete"]) + + def test_cli_missing_baseline_is_a_failure_not_an_initial_run(self): + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "result" + with patch.object(collector.sys, "argv", ["tool", "--output-dir", str(output), "--previous-plan", str(Path(temporary) / "missing.json")]): + self.assertEqual(collector.main(), 2) + self.assertFalse((output / "prefetch-inventory.json").exists()) + + def test_success_cli_keeps_existing_node_and_runtime_out_of_scope(self): + report, diff, files = make_report() + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "result" + with patch.object(collector, "collect", return_value=(report, diff, files)), patch.object(collector.sys, "argv", ["tool", "--output-dir", str(output)]): + self.assertEqual(collector.main(), 0) + self.assertTrue((output / "summary.md").exists()) + self.assertNotIn("token", (output / "prefetch-inventory.json").read_text()) + + def test_workflow_is_read_only_and_has_no_backend_or_runtime_credentials(self): + workflow = yaml.load((ROOT / ".github/workflows/node-image-prefetch-plan.yml").read_text(), Loader=yaml.BaseLoader) + self.assertEqual(set(workflow["on"]), {"workflow_call"}) + self.assertEqual(workflow["permissions"], {"contents": "read", "actions": "read"}) + self.assertNotIn("secrets", workflow["on"]["workflow_call"]) + text = str(workflow) + for forbidden in ("RUNTIME_API_TOKEN", "packages: write", "id-token: write", "docker pull", "kubectl", "ssh ", "--method DELETE"): + self.assertNotIn(forbidden, text) + self.assertIn("github.token", text) + self.assertIn("GITHUB_STEP_SUMMARY", text) + self.assertIn("--expected-source-sha", text) + + def test_guard_executes_event_repository_branch_and_sha_checks(self): + workflow = yaml.load((ROOT / ".github/workflows/node-image-prefetch-plan.yml").read_text(), Loader=yaml.BaseLoader) + guard = workflow["jobs"]["plan"]["steps"][0]["run"] + cases = ({}, {"GITHUB_EVENT_NAME": "push"}, {"GITHUB_REPOSITORY": "outside/repo"}, + {"GITHUB_REF": "refs/heads/feature/test"}, {"DEVSECOPS_REF": "main"}, {"PREVIOUS_ARTIFACT_ID": "0"}) + for change in cases: + env = {**os.environ, "GITHUB_REPOSITORY": collector.publication.REPOSITORY, + "GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REF": "refs/heads/main", + "DEVSECOPS_REF": SHA, "PREVIOUS_ARTIFACT_ID": "", **change} + result = subprocess.run(["bash", "-c", guard], env=env, capture_output=True, timeout=10) + with self.subTest(change=change): + self.assertEqual(result.returncode == 0, not change) + + def test_new_workflow_changes_trigger_self_test_and_caller_uses_no_secrets(self): + workflow = yaml.load((ROOT / ".github/workflows/pipeline-self-test.yml").read_text(), Loader=yaml.BaseLoader) + for event in ("push", "pull_request"): + self.assertIn(".github/workflows/node-image-prefetch-plan.yml", workflow["on"][event]["paths"]) + caller = yaml.load((ROOT / "docs/node-image-prefetch-caller-example.yml").read_text(), Loader=yaml.BaseLoader) + self.assertEqual(set(caller["on"]), {"workflow_dispatch"}) + self.assertNotIn("secrets", caller["jobs"]["plan"]) + self.assertIn("previous_artifact_id", caller["jobs"]["plan"]["with"]) + + def test_download_reads_only_one_bounded_json_without_extracting_zip(self): + raw = io.BytesIO() + with zipfile.ZipFile(raw, "w") as archive: + archive.writestr("artifact-v2.json", json.dumps(artifact())) + archive.writestr("../not-extracted", "unused") + def run(*_, **kwargs): + kwargs["stdout"].write(raw.getvalue()) + return subprocess.CompletedProcess([], 0) + with patch.object(collector.subprocess, "run", side_effect=run): + data, original = collector.download_json(200, "artifact-v2.json") + self.assertEqual(data, artifact()) + self.assertEqual(json.loads(original), artifact()) + + def test_corrupt_duplicate_and_oversized_manifest_are_rejected(self): + archives = [b"not-a-zip"] + for duplicate in (False, True): + raw = io.BytesIO() + with warnings.catch_warnings(), zipfile.ZipFile(raw, "w") as archive: + warnings.simplefilter("ignore") + archive.writestr("artifact-v2.json", "x" * 100) + if duplicate: + archive.writestr("artifact-v2.json", "{}") + archives.append(raw.getvalue()) + for raw in archives: + def run(*_, **kwargs): + kwargs["stdout"].write(raw) + return subprocess.CompletedProcess([], 0) + with self.subTest(size=len(raw)), patch.object(collector.subprocess, "run", side_effect=run), \ + patch.object(collector, "MAX_ARTIFACT_BYTES", 32), \ + self.assertRaises((ValueError, zipfile.BadZipFile)): + collector.download_json(200, "artifact-v2.json") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_workflow_contracts.py b/tests/test_workflow_contracts.py index 1c500df..6362cdb 100644 --- a/tests/test_workflow_contracts.py +++ b/tests/test_workflow_contracts.py @@ -463,6 +463,7 @@ def test_repository_only_exposes_challenge_validation_workflows(self): "pipeline-self-test.yml", "ghcr-cleanup-dry-run.yml", "published-runtime-smoke.yml", + "node-image-prefetch-plan.yml", }, )