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 @@ -684,6 +684,7 @@ jobs:
aws s3 cp dist/artifact-v2.json "s3://${BUCKET}/${prefix}/artifact-v2.json"
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"

- name: SSM으로 Secure Provisioner smoke test 실행
env:
Expand All @@ -696,7 +697,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\",\"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\",\"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
53 changes: 50 additions & 3 deletions docs/challenge-execution-settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Scheduler는 생성·reset 전달, Runtime은 설정 적용·격리·준비 상
| build / image | workload.containers[].image | GHCR digest 고정 이미지로 발행 |
| ports / expose | workload.containers[].ports[].port/public | Runtime smoke에서는 ports/exposed_ports로 변환, expose 미전송 |
| deployment.resource_profile | resource_profile | CPU·메모리·임시 저장 용량 합산 지원 |
| deployment.healthcheck.container/port/path | workload.healthcheck | CI가 이미 보존함. Backend 릴리스 PR은 저장함. Scheduler 생성 요청과 Runtime 적용은 추가 연결 필요 |
| deployment.healthcheck.container/port/path | workload.healthcheck | CI 검증·보존 및 직접 Runtime smoke 전달 지원. Backend #26·Scheduler #59·Runtime 연결의 실제 생성 검증은 별도 필요 |
| flag | 없음 | CI output·bundle에 값 미포함. 런타임 FLAG 주입으로 자동 변환하지 않음 |
| registry_revision | registry_revision | workflow 입력으로 지정, release 식별 및 이력 관리 |

Expand Down Expand Up @@ -93,7 +93,7 @@ checker 등 운영 보조 서비스이거나 이름 차이일 수 있으므로
2. FLAG·DB 비밀번호·인증키는 원문 대신 승인된 비밀 참조를 bundle에 기록하는
방향으로 협의합니다. 참조 발급·접근 범위·동적 값 생성·reset 처리 소유자는
Backend/Runtime/보안팀이 정합니다. CI가 info.yaml.flag를 그대로 복사하지 않습니다.
3. healthcheck의 기존 HTTP 구조는 끝까지 보존합니다. TCP/exec, 시간 제한,
3. healthcheck의 기존 HTTP 구조는 아래 계약대로 끝까지 보존합니다. TCP/exec, 시간 제한,
startup/readiness 판정이 필요하면 공통 계약을 추가합니다. Runtime에 없는 키를 먼저 보내지 않습니다.
4. 쓰기 경로·용량은 제한된 storage 계약으로 정의합니다. hostPath나 임의 호스트
마운트는 입력받지 않습니다. Compose volume을 그대로 복사하지 않습니다.
Expand Down Expand Up @@ -128,6 +128,53 @@ Runtime 담당과 확인해야 합니다.
[Kubernetes Pod 네트워크](https://kubernetes.io/docs/concepts/workloads/pods/),
[NetworkPolicy](https://kubernetes.io/docs/concepts/services-networking/network-policies/).

## HTTP healthcheck 계약과 연결 현황

2026-10-07 확인 기준으로 기존 HTTP 검사 구조는 다음과 같습니다. 새 info.yaml
옵션을 추가한 것이 아니라 이미 있는 값을 검증하고 직접 smoke 요청에 보존합니다.

```yaml
deployment:
healthcheck:
container: web
port: 9090
path: /healthz
```

- container는 선언된 컨테이너 이름과 정확히 일치해야 합니다.
- port는 해당 컨테이너가 선언한 1..65535 정수 포트이며 비공개 포트도 가능합니다.
healthcheck를 지정했다고 공개 포트로 바꾸지 않습니다.
- path는 `/`로 시작하고 공백·제어 문자를 포함하지 않아야 합니다.
Scheduler·Runtime과 동일하게 UTF-16 코드 단위 1024개 이하로 제한합니다.
앞뒤 공백을 자동 삭제하지 않고 잘못된 입력으로 거절합니다.
- 생략 또는 null이면 bundle과 smoke 요청에 별도 healthcheck를 넣지 않습니다.
빈 객체나 일부 필드 누락, 미지원 필드는 거절합니다.
- TCP/exec 검사와 출제자 지정 timeout은 지원 계약에 포함하지 않습니다.
특히 PWN 준비 상태 기준은 별도 합의 없이 추가하지 않습니다.

| 단계 | 확인된 코드 | 아직 확인할 내용 |
|---|---|---|
| DevSecOps | info.yaml 검증 → bundle 보존 → 직접 smoke의 workload.healthcheck 전달 | 병합 후 caller SHA 갱신 및 실제 발행 bundle 시험 |
| Backend #26 | 릴리스 저장, 생성 요청의 healthcheck 전달 | 병합·배포, 실제 DB 왕복 및 연동 |
| Scheduler #59 | 저장·reset 보존, Runtime 요청 전달 코드 | 병합·배포와 SCHEDULER_INSTANCE_POLICY_HEALTHCHECK_ENABLED 설정 |
| Runtime | 컨테이너 HTTP readiness 적용, 준비 실패 시 WORKLOAD_NOT_READY와 정리 코드 | 승인된 실제 이미지로 정상·실패 생성 시험 |

Runtime의 HTTP 검사 구현은 배포 기준 커밋
[`701567f4`](https://github.com/MSG-CTF/secure-provisioner/blob/701567f410a68518bb628463c8d5480559f31efc/internal/provisioner/readiness.go),
요청 적용은 [create 처리](https://github.com/MSG-CTF/secure-provisioner/blob/701567f410a68518bb628463c8d5480559f31efc/internal/httpapi/create.go)에서 확인했습니다.
Backend는 [PR #26](https://github.com/MSG-CTF/msg-backend/pull/26),
Scheduler는 [PR #59](https://github.com/MSG-CTF/instance-scheduler/pull/59) 기준입니다.
코드가 있다는 사실과 전체 경로의 실제 성공은 구분합니다.

직접 Runtime smoke는 Backend·Scheduler를 거치지 않습니다. 모의 서버 테스트는
요청에 값이 전달되는지와 기존 삭제 처리를 확인하며, 실제 K3s probe 성공의 증거가 아닙니다.
healthcheck를 생략해도 Runtime 이미지 정책에 기본 검사가 있을 수 있으므로,
생략을 검사 완전 비활성이나 애플리케이션 정상 보장으로 해석하지 않습니다.

실제 연동에서는 정상 HTTP 검사 성공과 실패 경로를 각각 확인합니다.
실패한 컨테이너를 RUNNING으로 기록하지 않는지, 실패 정리가 완료되는지,
reset 뒤 동일한 healthcheck가 유지되는지도 각 담당과 확인해야 합니다.

## 담당별 요청

| 담당 | 요청 | 완료 조건 |
Expand Down Expand Up @@ -180,7 +227,7 @@ Actions에도 반영됩니다. 이번 PR에서 문제 저장소는 변경하지
- GCP Runtime의 무인증 HTTPS 연결 점검은 실제 생성·접속·reset·삭제 검증과 다릅니다.
실제 문제 배포 성공이나 전체 Linux/Docker 실행 검증으로 기록하지 않습니다.

확인 기준:
2026-10-05 당시 확인 기준 (최신 HTTP 계약은 위 2026-10-07 항목 참조):
- DevSecOps main: b39f232fc4759b70928c4960e7a17bb33264bcec
- Backend 릴리스 PR #26: fb9d0df3fac0ec0bb424eabdbc1e9ff75d48b883
(apps/instances/releases.py의 healthcheck 보존 확인, PR은 확인 시 Open)
Expand Down
14 changes: 12 additions & 2 deletions docs/gcp-runtime-https-smoke.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,20 @@

발행 bundle의 `artifact-v2.json`을 기존 `runtime_api_smoke_runner.py`에 입력한다. runner는 기본 인증서 검증을 켠 HTTPS로 create → Operation 조회 → delete → Operation 조회를 수행한다. 토큰은 runner 임시 파일에만 쓰고 작업 종료 시 지운다. 결과에는 토큰이나 FLAG 원문을 넣지 않는다. 발행된 digest가 아직 Provisioner 정책에 없으면 생성이 실패하며, 이미지 정책 검토·배포 후 재실행한다. 자동 승인이나 임의 digest 허용은 하지 않는다.

bundle에 `workload.healthcheck`가 있으면 `container`, `port`, `path`를 검증한 뒤
같은 위치의 Runtime 요청 필드로 전달한다. 생략/null이면 요청에서 생략한다.
컨테이너·포트 일치, 공백·제어 문자 금지, UTF-16 길이 1024 제한은 CI와 같은
검증 함수를 사용한다. 비공개 검사 포트를 exposed_ports에 추가하지 않는다.
기존 expose와 internal_connections 미전송 원칙도 유지한다.

## 단계적 적용과 복구

기존 AWS SSM smoke job 및 `enable_k3s_smoke_deploy` 입력은 그대로 둔다. 새 HTTPS job은 별도 플래그로만 실행한다. 먼저 승인된 Grade digest를 이용한 수동 GitHub runner 시험으로 공개 TLS·토큰·생성·삭제 Operation을 검증한다. 그다음 호출 저장소가 새 재사용 workflow 커밋을 고정하고, 발행할 digest의 정책 승인을 확인한 뒤 `ENABLE_RUNTIME_HTTPS_SMOKE=true`를 설정한다. 오류가 발생하면 이 변수만 `false`로 바꿔 자동 실행을 중단한다.

기존 검사·발행·AWS job의 실행 코드는 변경하지 않는다. 다만 HTTPS smoke가 실패하면 전체 workflow도 실패하므로, 성공한 workflow만 수집하는 Backend Poller는 해당 실행의 bundle을 등록할 수 없다. 정책 미승인 digest로 자동 job을 먼저 활성화하지 않는다.
기존 검사·발행과 AWS job의 활성화 조건을 유지한다. 공유 healthcheck 검증 모듈은
AWS staging에서도 runner와 함께 전달한다. HTTPS smoke가 실패하면 전체 workflow도
실패하므로, 성공한 workflow만 수집하는 Backend Poller는 해당 실행의 bundle을
등록할 수 없다. 정책 미승인 digest로 자동 job을 먼저 활성화하지 않는다.

## 검증 범위

Expand All @@ -23,11 +32,12 @@
현재 runner와 자동 job이 확인하는 항목은 다음과 같다.

- Runtime API의 HTTPS 인증서 검증과 인증된 요청.
- bundle의 HTTP healthcheck 검증·전달. 실제 probe 수행과 준비 상태 판정은 Runtime 소유다.
- 생성 Operation의 `SUCCEEDED`와 결과의 workload 식별자 확인.
- 반환된 endpoint의 형식과 공개 포트 계약 확인. endpoint 주소로 실제 접속하는 검사는 아니다.
- 삭제 Operation의 `SUCCEEDED` 확인. K3s 리소스를 직접 조회한 삭제 확인은 아니다.

공개 문제 URL의 HTTP 응답·healthcheck, 실행 이미지 digest 대조, K3s Namespace·Pod·Service 잔존 여부, 팀·인스턴스 격리는 별도 검증이 필요하다. 새 digest 자동 승인, Scheduler reset, PWN/gVisor, 팀 인증 게이트웨이도 이 변경에 포함하지 않는다.
공개 문제 URL의 실제 HTTP 응답, 전달된 healthcheck의 정상·실패 동작, 실행 이미지 digest 대조, K3s Namespace·Pod·Service 잔존 여부, 팀·인스턴스 격리는 별도 검증이 필요하다. 새 digest 자동 승인, Scheduler reset, PWN/gVisor, 팀 인증 게이트웨이도 이 변경에 포함하지 않는다. 이번 보완은 실제 서버를 호출하거나 HTTPS smoke를 활성화하지 않는다.

## 확인된 실행 기록

Expand Down
8 changes: 8 additions & 0 deletions scripts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,14 @@ Backend poller는 성공한 `-publish-bundle` artifact에서 이 파일을 수
public/private port는 publish bundle에 포트별로 보존하고 Runtime smoke 요청에서는
전체 `ports`와 공개할 `exposed_ports`로 변환합니다.

### `healthcheck_contract.py`

info.yaml 검증과 Runtime smoke에서 같은 HTTP healthcheck 검증을 사용합니다.
컨테이너·선언 포트 일치, 공백·제어 문자 금지, UTF-16 길이 1024 제한을 확인합니다.
별도 외부 의존성이 없으며 AWS staging에서도 runner와 함께 전달합니다.
smoke는 bundle의 healthcheck를 Runtime 요청에 보존하되 공개 포트 목록을 바꾸지 않습니다.
실제 HTTP probe 실행과 준비 상태 판정은 Runtime 담당입니다.

### `pipeline_timing.py`

GitHub Actions의 컨테이너별 `Build/Pull`, `Scan`, `GHCR Push` 구간을 측정하고
Expand Down
40 changes: 40 additions & 0 deletions scripts/healthcheck_contract.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""Validate the shared HTTP readiness contract without optional dependencies."""

import unicodedata


MAX_PATH_UTF16_UNITS = 1024


def validate_healthcheck(raw, containers):
if raw is None:
return None
if not isinstance(raw, dict):
raise ValueError("deployment.healthcheck must be an object")
if any(key not in {"container", "port", "path"} for key in raw):
raise ValueError("healthcheck contains unsupported fields")

name = raw.get("container")
if not isinstance(name, str) or not name:
raise ValueError("healthcheck.container must be a non-empty string")
by_name = {container["name"]: container for container in containers}
if name not in by_name:
raise ValueError("healthcheck.container must reference a declared container")
port = raw.get("port")
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
raise ValueError("healthcheck.port must be an integer in 1..65535")
if port not in by_name[name]["ports"]:
raise ValueError("healthcheck.port must reference a declared container port")

path = raw.get("path")
if not isinstance(path, str) or not path.startswith("/"):
raise ValueError("healthcheck.path must be an absolute HTTP path")
if any(
character.isspace() or unicodedata.category(character) in {"Cc", "Cs"}
for character in path
):
raise ValueError("healthcheck.path must not contain whitespace or control characters")
# Scheduler counts UTF-16 units; Runtime uses the same length convention.
if sum(2 if ord(character) > 0xFFFF else 1 for character in path) > MAX_PATH_UTF16_UNITS:
raise ValueError("healthcheck.path must not exceed 1024 UTF-16 units")
return {"container": name, "port": port, "path": path}
8 changes: 8 additions & 0 deletions scripts/runtime_api_smoke_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@
from urllib.parse import urlsplit, urlunsplit
from urllib.request import HTTPRedirectHandler, HTTPSHandler, Request, build_opener

if __package__:
from .healthcheck_contract import validate_healthcheck
else:
from healthcheck_contract import validate_healthcheck


DIGEST_IMAGE = re.compile(r"^.+@sha256:[0-9a-f]{64}$")
SERVICE_TOKEN = re.compile(r"^[A-Za-z0-9_-]{43,128}$")
Expand Down Expand Up @@ -179,6 +184,9 @@ def build_create_request(
raise ValueError("PWN workload must declare exactly one exposed container")

runtime_workload = {"containers": runtime_containers}
healthcheck = validate_healthcheck(workload.get("healthcheck"), runtime_containers)
if healthcheck is not None:
runtime_workload["healthcheck"] = healthcheck

resource_profile = artifact.get("resource_profile")
if not isinstance(resource_profile, dict):
Expand Down
29 changes: 6 additions & 23 deletions scripts/validate_info_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@

import yaml

if __package__:
from .healthcheck_contract import validate_healthcheck
else:
from healthcheck_contract import validate_healthcheck


SAFE_NAME = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$")
CATEGORY = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
Expand Down Expand Up @@ -110,28 +115,6 @@ def _validate_container(challenge_path, raw):
return container


def _validate_healthcheck(raw, containers):
if raw is None:
return None
if not isinstance(raw, dict):
raise ValueError("deployment.healthcheck must be an object")
_reject_unknown_fields(raw, {"container", "port", "path"}, "healthcheck")
container_name = _required_string(
raw.get("container"),
"healthcheck.container",
)
by_name = {container["name"]: container for container in containers}
if container_name not in by_name:
raise ValueError("healthcheck.container must reference a declared container")
port = _positive_int(raw.get("port"), "healthcheck.port")
if port > 65535 or port not in by_name[container_name]["ports"]:
raise ValueError("healthcheck.port must reference a declared container port")
path = _required_string(raw.get("path"), "healthcheck.path")
if not path.startswith("/") or any(ord(character) < 32 for character in path):
raise ValueError("healthcheck.path must be an absolute HTTP path")
return {"container": container_name, "port": port, "path": path}


def validate_spec(challenge_path):
challenge_path = Path(challenge_path).resolve()
if not challenge_path.is_dir():
Expand Down Expand Up @@ -240,7 +223,7 @@ def validate_spec(challenge_path):
"containers": containers,
"resource_profile": resource_profile,
})
healthcheck = _validate_healthcheck(deployment.get("healthcheck"), containers)
healthcheck = validate_healthcheck(deployment.get("healthcheck"), containers)
if healthcheck:
metadata["healthcheck"] = healthcheck
return metadata
Expand Down
17 changes: 17 additions & 0 deletions tests/test_generate_publish_bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from pathlib import Path

from scripts.generate_publish_bundle import generate_bundle
from scripts.runtime_api_smoke_runner import build_create_request


DIGEST_A = "sha256:" + "a" * 64
Expand Down Expand Up @@ -70,6 +71,22 @@


class GeneratePublishBundleTests(unittest.TestCase):
def test_generated_bundle_preserves_healthcheck_in_runtime_request(self):
bundle = generate_bundle(METADATA, RESULTS, SOURCE_REF, SOURCE_SHA, 3, EVIDENCE_ROOT)
artifact = json.loads(json.dumps(bundle["artifact"]))
request = build_create_request(
artifact,
target_id="broker-test2",
instance_id="00000000-0000-4000-8000-000000000001",
team_id="00000000-0000-4000-8000-000000000002",
)
self.assertEqual(request["workload"]["healthcheck"], METADATA["healthcheck"])
self.assertEqual(
[container["image"] for container in request["workload"]["containers"]],
[result["image"] for result in RESULTS],
)
self.assertNotIn("internal_connections", request["workload"])

def test_generates_runtime_artifact_and_registry_publish_document(self):
bundle = generate_bundle(
METADATA, RESULTS, SOURCE_REF, SOURCE_SHA, 3, EVIDENCE_ROOT
Expand Down
Loading
Loading