Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/challenge-supply-chain.yml
Original file line number Diff line number Diff line change
Expand Up @@ -694,6 +694,7 @@ jobs:
aws s3 cp dist/runtime-smoke-config.json "s3://${BUCKET}/${prefix}/runtime-smoke-config.json"
aws s3 cp .msgctf-ci/scripts/runtime_api_smoke_runner.py "s3://${BUCKET}/${prefix}/runtime_api_smoke_runner.py"
aws s3 cp .msgctf-ci/scripts/healthcheck_contract.py "s3://${BUCKET}/${prefix}/healthcheck_contract.py"
aws s3 cp .msgctf-ci/scripts/execution_settings_contract.py "s3://${BUCKET}/${prefix}/execution_settings_contract.py"

- name: SSM으로 Secure Provisioner smoke test 실행
env:
Expand All @@ -706,7 +707,7 @@ jobs:
--instance-ids "$INSTANCE_ID" \
--document-name AWS-RunShellScript \
--comment "MSGCTF Secure Provisioner runtime smoke deployment" \
--parameters "commands=[\"set -euo pipefail\",\"install -d -m 0700 ${remote_dir}\",\"trap 'rm -rf ${remote_dir}' EXIT\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/artifact-v2.json ${remote_dir}/artifact-v2.json\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/runtime-smoke-config.json ${remote_dir}/runtime-smoke-config.json\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/runtime_api_smoke_runner.py ${remote_dir}/runtime_api_smoke_runner.py\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/healthcheck_contract.py ${remote_dir}/healthcheck_contract.py\",\"python3 ${remote_dir}/runtime_api_smoke_runner.py --artifact ${remote_dir}/artifact-v2.json --config ${remote_dir}/runtime-smoke-config.json --timeout 180 --cleanup-timeout 180\"]" \
--parameters "commands=[\"set -euo pipefail\",\"install -d -m 0700 ${remote_dir}\",\"trap 'rm -rf ${remote_dir}' EXIT\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/artifact-v2.json ${remote_dir}/artifact-v2.json\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/runtime-smoke-config.json ${remote_dir}/runtime-smoke-config.json\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/runtime_api_smoke_runner.py ${remote_dir}/runtime_api_smoke_runner.py\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/healthcheck_contract.py ${remote_dir}/healthcheck_contract.py\",\"aws s3 cp s3://${BUCKET}/${PREFIX}/execution_settings_contract.py ${remote_dir}/execution_settings_contract.py\",\"python3 ${remote_dir}/runtime_api_smoke_runner.py --artifact ${remote_dir}/artifact-v2.json --config ${remote_dir}/runtime-smoke-config.json --timeout 180 --cleanup-timeout 180\"]" \
--query 'Command.CommandId' --output text)"
for _ in $(seq 1 150); do
status="$(aws ssm get-command-invocation --command-id "$command_id" --instance-id "$INSTANCE_ID" --query Status --output text 2>/dev/null || true)"
Expand Down
337 changes: 102 additions & 235 deletions docs/challenge-execution-settings.md

Large diffs are not rendered by default.

9 changes: 9 additions & 0 deletions docs/challenge-registry-integration.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# Challenge Registry 통합 검증

## 실행 설정 계약

env·secret_env가 있으면 schema 2.1로 발행하며 기존 설정은 2.0을 유지합니다
백엔드는 문제별 비밀값 이름을 불변 버전으로 고정하고 런타임 조회용 UUID를 발급합니다
CI는 비밀값 원문을 발행하지 않습니다
백엔드는 같은 커밋의 컨테이너별 .env 기본값에 발행본의 명시 설정을 합칩니다
일부 env만 선언해도 나머지 필수 비밀값이 빠지지 않아야 하며 소비자 배포를 먼저 확인합니다
계약과 검수표: [문제 실행 설정](challenge-execution-settings.md)

## 검증 범위

Backend poller 운영 계약에서 `artifact-v2.json`은 성공한
Expand Down
51 changes: 51 additions & 0 deletions docs/testing/2026-10-08-execution-settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"started_at": "2026-10-08T08:34:22.947717+00:00",
"scope": "local synthetic fixture, actual Backend/Scheduler/Broker/Runtime/PostgreSQL/K3s",
"supply_chain_scans": "synthetic unit fixture, not a Trivy/Gitleaks/registry verification",
"checks": [
"CI generator schema 2.1 -> Backend registration/activation with encrypted secret versions",
"participant cannot set execution settings/create secrets; scheduler v2 and resolver require service authentication",
"real app gets ordinary env literally, FLAG and INTERNAL_TOKEN",
"immutable Secret only exposes app-specific keys; helper has no secretKeyRef",
"same-instance helper communication works",
"private helper has no NodePort; only app port is public",
"new team uses active revision 2 and new secret version",
"same-instance communication allowed; cross-instance private helper blocked",
"reset preserves original revision/env/secret version after activation changed",
"public metadata and local logs contain no secret plaintext",
"delete/reset cleanup removes every fixture namespace and namespace Secret"
],
"completed_at": "2026-10-08T08:34:52.363483+00:00",
"instance_ids": [
"9977f047-d3f1-488c-b903-57178ffa8076",
"4ff337fc-feec-40f2-a1a2-a6c48cf5cae2",
"2695ee7a-afe7-4412-97c1-3d1f32dcf4c7"
],
"release_ids": [
"93255370-0b49-490e-8fd7-42bce01821ae",
"c4cff16d-88f6-4706-a6eb-ce1d05305054"
],
"result": "PASS",
"secret_storage_checks": {
"execution_backend.challenge_runtime_secrets": {
"row_count": 6,
"contains_plaintext_secret": false
},
"execution_backend.challenge_release_containers": {
"row_count": 4,
"contains_plaintext_secret": false
},
"execution_scheduler.challenge_instance": {
"row_count": 3,
"contains_plaintext_secret": false
},
"execution_runtime.runtime_operations": {
"row_count": 6,
"contains_plaintext_secret": false
},
"execution_runtime.runtime_bindings": {
"row_count": 3,
"contains_plaintext_secret": false
}
}
}
85 changes: 85 additions & 0 deletions docs/testing/2026-10-08-execution-settings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# 실행 설정 연동 검수

검수일: 2026년 10월 8일

백엔드가 비밀값 버전을 선택하고 런타임이 조회·주입하는 경로를 확인했습니다
환경변수와 참조는 CI 발행 파일부터 생성·reset까지 보존됩니다
네트워크는 기존 격리 프로필과 포트 계약을 사용합니다

## 확인한 명세

| 문서 | 확인한 계약 |
| --- | --- |
| [Runtime API 10월 5일](https://app.notion.com/p/3f00f19c72be80e0a37bd22cb115749e) | 승인 이미지·비동기 실행·NetworkPolicy, 기존 FLAG 파일 모델 |
| [백엔드 릴리스 API](https://app.notion.com/p/3c80f19c72be811b9bc7fa7acaf9c753) | 릴리스 이력과 활성 포인터 |
| [Registry와 백엔드](https://app.notion.com/p/3bb0f19c72be8194817bd79af9ba1822) | CI 발행 파일을 백엔드가 수집, 스케줄러는 Registry를 읽지 않음 |
| [스케줄러 API](https://app.notion.com/p/3a50f19c72be804d81f7dba8d8876fa8) | 백엔드 생성 요청과 저장된 설정으로 reset |

FLAG 관리 주체는 이번 요청에서 백엔드로 이전하도록 정했습니다
10월 5일의 VM 파일 방식은 구현과 문서에서 제거했습니다
공유 노션 페이지는 수정하지 않았습니다

## 코드 기준

| 저장소 | 검수 시작 commit |
| --- | --- |
| [백엔드 #26](https://github.com/MSG-CTF/msg-backend/pull/26) | 8642e68f05670b81b6aa36bb1180d685d5a9bf8d |
| [스케줄러 #59](https://github.com/MSG-CTF/instance-scheduler/pull/59) | c66b18e0bedf7ea027ec048fcd68606d4912196a |
| [런타임 #45](https://github.com/MSG-CTF/secure-provisioner/pull/45) | 701567f410a68518bb628463c8d5480559f31efc |
| DevSecOps main | 40513968fa9e4a8a624dc7c11a6e0a399aada323 |
| [문제 caller #79](https://github.com/MSG-CTF/2026_MSG_CTF/pull/79) | 9e53cf53abffe3f38214804192df578e8e6325e9 |
| [Broker #4](https://github.com/MSG-CTF/resource-broker/pull/4) | 99ff5b884e4bf2198dabca84a179c11f5a516785 |
| 프론트 main | c1aea65015fd89d4c0b7f09f27a34f70d2ca9f14 |

프론트의 생성 요청은 이미 challenge_id만 보내고 있어 수정하지 않았습니다
Broker는 현재 구현이 있는 #4로 실행했으며 코드 변경은 없습니다
조직의 전체 PR과 모든 문제의 풀이를 검수했다는 뜻은 아닙니다

## 자동 검사

| 대상 | 결과 | 실행 범위 |
| --- | --- | --- |
| 백엔드 | 99개 통과 | apps.instances 전체, PostgreSQL 17, 새 마이그레이션 확인 |
| 스케줄러 | 382개 통과, 100개 skip | Gradle 전체, Docker가 필요한 자동 통합 검사는 skip |
| 런타임 | 793개 통과, 4개 skip | Go 전체와 PostgreSQL 저장·재시작·worker 검사, 하위 사례 포함 |
| DevSecOps | 194개 통과 | Linux 전체, 발행 계약·입력 검증·workflow 의존 파일 검사 |

Runtime의 기존 K3s 환경 전용 4개 검사는 필요한 환경변수를 지정하지 않아 skip됐습니다
아래 실제 연동은 별도로 구성한 로컬 K3s에서 실행했습니다
Windows DevSecOps 전체 검사는 symlink·Git·bash 환경 차이로 실패해 Linux에서 다시 실행했습니다

## 실제 연동 결과

CI generator → 백엔드 → 스케줄러 → 실제 Broker → 런타임 → K3s를 연결했습니다
세 서비스의 저장소는 PostgreSQL을 사용했습니다
K3s는 v1.34.1+k3s1이며 일반 WEB 프로필의 시험용 이미지로 검사했습니다
이미지는 로컬 containerd에 미리 넣었고 scan·SBOM 자료는 검사 fixture를 사용했습니다

| 검수 | 결과 |
| --- | --- |
| 일반 env와 FLAG·INTERNAL_TOKEN 주입 | 앱의 일반 값과 비밀값 hash 일치 |
| Kubernetes 변수 보간 | $(APP_MODE)를 입력 문자열 그대로 전달 |
| 컨테이너별 Secret | 변경 불가 Secret, app 키만 연결, helper에는 연결 없음 |
| 같은 인스턴스의 비공개 helper | 접속 성공, helper는 ClusterIP |
| 다른 인스턴스의 비공개 helper | 접속 실패 |
| 새 릴리스·비밀값 버전으로 새 팀 생성 | revision 2와 새 값 선택 |
| 기존 팀 reset | revision 1과 기존 env·비밀값 버전 유지 |
| 참가자의 실행 설정·비밀값 등록 | 400·403, 관리자 JWT로 내부 조회도 401 |
| 스케줄러 v2 무인증 요청 | 401 |
| 저장소·메타데이터·로그 | 비밀값 원문 없음, 백엔드 DB는 암호문으로 저장 |
| reset·삭제 정리 | 세 namespace와 Secret 제거 |

원문 비밀값 대신 hash와 성공 여부만 기록했습니다
상세 결과: [로컬 연동 기록](2026-10-08-execution-settings.json)

## 반영할 때 남는 일

운영자는 암호화 키·worker 토큰과 문제별 비밀값을 등록해야 합니다
새 FLAG 릴리스를 승인하기 전에는 생성·reset을 잠시 중단하고 구형 대기 요청을 정리해야 합니다
인스턴스별 비밀값 생성과 FLAG 채점 hash의 릴리스별 관리, 외부 통신 예외는 별도 작업입니다
AFTERIMAGE와 Notebook의 기존 차단은 유지합니다
운영 GCP·PWN/gVisor·실제 문제 풀이·GHCR cold pull·새 공급망 scan은 이번 시험에 포함되지 않습니다

명세 이름 검사는 새 필드에서 위반이 없었습니다
기존 runtime-status 경로 한 건은 시작 commit과 현재 명세에 동일하게 남아 있습니다
호출 경로를 바꾸는 작업은 이 변경에 포함하지 않았습니다
52 changes: 52 additions & 0 deletions scripts/execution_settings_contract.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import re

ENV_NAME = re.compile(r"^[A-Z_][A-Z0-9_]{0,63}$")
SECRET_NAME = re.compile(r"^[a-z][a-z0-9_]{0,63}$")
SENSITIVE_NAME = re.compile(r"(?:SECRET|TOKEN|PASSWORD|PASSWD|PRIVATE_KEY|API_KEY|CREDENTIAL)")
MAX_ENV_COUNT = 32
MAX_ENV_BYTES = 16384
MAX_VALUE_BYTES = 4096


def validate_env(raw):
if not isinstance(raw, dict) or len(raw) > MAX_ENV_COUNT:
raise ValueError("env must be an object with at most 32 entries")
total = 0
result = {}
for name, value in raw.items():
if not isinstance(name, str) or not ENV_NAME.fullmatch(name):
raise ValueError("env names must be uppercase identifiers of at most 64 characters")
if name == "FLAG" or SENSITIVE_NAME.search(name):
raise ValueError("secret values must use secret_env instead of env")
if not isinstance(value, str) or "\x00" in value:
raise ValueError("env values must be strings without NUL")
try:
size = len(value.encode("utf-8"))
except UnicodeEncodeError:
raise ValueError("env values must be valid UTF-8") from None
if size > MAX_VALUE_BYTES:
raise ValueError("env values must be at most 4096 bytes")
total += len(name) + size
result[name] = value
if total > MAX_ENV_BYTES:
raise ValueError("env exceeds 16384 bytes")
return result


def validate_secret_env(raw, env):
if not isinstance(raw, dict) or len(raw) > MAX_ENV_COUNT:
raise ValueError("secret_env must be an object with at most 32 entries")
result = {}
for name, alias in raw.items():
if not isinstance(name, str) or not ENV_NAME.fullmatch(name):
raise ValueError("secret_env names must be uppercase identifiers")
if not isinstance(alias, str) or not SECRET_NAME.fullmatch(alias):
raise ValueError("secret_env values must be backend secret names")
if name in env:
raise ValueError("env and secret_env must not share names")
if name == "FLAG" and alias != "flag":
raise ValueError("FLAG must reference the backend secret named flag")
result[name] = alias
if len(env) + len(result) > MAX_ENV_COUNT:
raise ValueError("env and secret_env must contain at most 32 entries in total")
return result
13 changes: 12 additions & 1 deletion scripts/generate_publish_bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
import re
from pathlib import Path

if __package__:
from .execution_settings_contract import validate_env, validate_secret_env
else:
from execution_settings_contract import validate_env, validate_secret_env


DIGEST = re.compile(r"^sha256:[0-9a-f]{64}$")
COMMIT_SHA = re.compile(r"^[0-9a-f]{40}$")
Expand Down Expand Up @@ -155,6 +160,8 @@ def generate_bundle(
evidence_containers = []
for container in metadata["containers"]:
result = validated_results[container["name"]]
env = validate_env(container.get("env", {}))
aliases = validate_secret_env(container.get("secret_env", {}), env)
workload_containers.append(
{
"name": container["name"],
Expand All @@ -163,6 +170,8 @@ def generate_bundle(
{"port": port, "public": container["expose"]}
for port in container["ports"]
],
**({"env": env} if env else {}),
**({"secret_env": aliases} if aliases else {}),
}
)
evidence_containers.append(
Expand All @@ -182,7 +191,9 @@ def generate_bundle(
workload["healthcheck"] = metadata["healthcheck"]

artifact = {
"schema_version": "2.0",
"schema_version": "2.1" if any(
container.get("env") or container.get("secret_env") for container in workload_containers
) else "2.0",
"challenge_slug": metadata["challenge_slug"],
"revision": revision,
"registry_revision": revision,
Expand Down
7 changes: 7 additions & 0 deletions scripts/runtime_api_smoke_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@

if __package__:
from .healthcheck_contract import validate_healthcheck
from .execution_settings_contract import validate_env, validate_secret_env
else:
from healthcheck_contract import validate_healthcheck
from execution_settings_contract import validate_env, validate_secret_env


DIGEST_IMAGE = re.compile(r"^.+@sha256:[0-9a-f]{64}$")
Expand Down Expand Up @@ -140,6 +142,10 @@ def build_create_request(
for container in artifact_containers:
if not isinstance(container, dict):
raise ValueError("artifact container must be an object")
env = validate_env(container.get("env", {}))
aliases = validate_secret_env(container.get("secret_env", {}), env)
if aliases or "secret_ref" in container:
raise ValueError("secret_env requires a Backend release; direct CI smoke cannot resolve secrets")
name = container.get("name")
image = container.get("image")
if not isinstance(name, str) or not name:
Expand Down Expand Up @@ -177,6 +183,7 @@ def build_create_request(
"ports": ports,
"exposed_ports": exposed_ports,
"run_as_user": _positive_int(container.get("run_as_user", 10001), "run_as_user"),
**({"env": env} if env else {}),
}
)

Expand Down
37 changes: 35 additions & 2 deletions scripts/validate_info_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@

if __package__:
from .healthcheck_contract import validate_healthcheck
from .execution_settings_contract import validate_env, validate_secret_env
else:
from healthcheck_contract import validate_healthcheck
from execution_settings_contract import validate_env, validate_secret_env


SAFE_NAME = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$")
Expand Down Expand Up @@ -77,7 +79,7 @@ def _validate_ports(raw_ports, container_name):
def _validate_container(challenge_path, raw):
if not isinstance(raw, dict):
raise ValueError("each deployment container must be an object")
_reject_unknown_fields(raw, {"name", "build", "image", "ports", "expose"}, "container")
_reject_unknown_fields(raw, {"name", "build", "image", "ports", "expose", "env", "secret_env"}, "container")
name = _required_string(raw.get("name"), "container.name")
if not SAFE_NAME.fullmatch(name):
raise ValueError("container name must be a safe lowercase identifier")
Expand All @@ -95,6 +97,12 @@ def _validate_container(challenge_path, raw):
if not isinstance(expose, bool):
raise ValueError(f"{name}.expose must be a boolean")
container["expose"] = expose
env = validate_env(raw.get("env", {}))
aliases = validate_secret_env(raw.get("secret_env", {}), env)
if env:
container["env"] = env
if aliases:
container["secret_env"] = aliases

if has_build:
container["build"] = _resolve_build_path(challenge_path, raw["build"])
Expand All @@ -115,6 +123,30 @@ def _validate_container(challenge_path, raw):
return container


def _check_flag_not_in_build(challenge_path, containers, flag):
marker = flag.encode("utf-8")
for container in containers:
if container.get("secret_env", {}).get("FLAG") != "flag" or "build" not in container:
continue
build_dir = challenge_path / container["build"]
for path in build_dir.rglob("*"):
if path.is_symlink() or not path.is_file():
continue
try:
with path.open("rb") as source:
tail = b""
while chunk := source.read(65536):
if marker in tail + chunk:
relative = path.relative_to(challenge_path)
raise ValueError(
f"{container['name']} build context contains the challenge flag: {relative}; "
"remove it before using secret_env.FLAG"
)
tail = chunk[-(len(marker) - 1):] if len(marker) > 1 else b""
except OSError:
raise ValueError("cannot inspect build context for an embedded flag") from None


def validate_spec(challenge_path):
challenge_path = Path(challenge_path).resolve()
if not challenge_path.is_dir():
Expand All @@ -137,7 +169,7 @@ def validate_spec(challenge_path):
if not CATEGORY.fullmatch(category):
raise ValueError("category must be a lowercase identifier")
_required_string(raw.get("description"), "description")
_required_string(raw.get("flag"), "flag")
flag = _required_string(raw.get("flag"), "flag")

deployment = raw.get("deployment")
metadata = {
Expand Down Expand Up @@ -205,6 +237,7 @@ def validate_spec(challenge_path):
_validate_container(challenge_path, raw_container)
for raw_container in raw_containers
]
_check_flag_not_in_build(challenge_path, containers, flag)
names = [container["name"] for container in containers]
if len(names) != len(set(names)):
raise ValueError("container name values must be unique")
Expand Down
Loading
Loading