From 8c1f5a997f7ec528d92c4bf534f096ec37aca68e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=84=B8=EB=B9=88=20=EA=B6=8C?= Date: Tue, 23 Jun 2026 16:22:39 +0900 Subject: [PATCH] Prevent unsafe injection release paths from shipping PR #1005 could not ship while legacy live fault injection, fail-open internal ops auth, and prefix-based safe-inject workspaces remained reachable. This removes the destructive live eval execution surface, makes internal ops token checks fail closed unless an explicit local/test disable flag is set, and narrows safe-inject workspace selection to exact configured values. Constraint: #1005 must not be merged to main or deployed; branch targets develop only. Constraint: No production kubectl/deploy commands executed; verification is local tests and static checks. Rejected: Keep legacy --live behind --confirm | confirm still leaves a destructive release path reachable. Rejected: Preserve prefix workspace defaults | prefix matching expands safe-inject beyond configured test workspaces. Confidence: high Scope-risk: moderate Directive: Do not reintroduce destructive live fault helpers or blank-token fail-open behavior without a new reviewed release gate. Tested: AI_LLM_API_KEY= OPENAI_API_KEY= uv run --extra dev pytest -q Tested: AI_LLM_API_KEY= OPENAI_API_KEY= uv run --extra dev python -m eval.online.live_eval --dry-run --no-write Tested: AI_LLM_API_KEY= OPENAI_API_KEY= uv run --extra dev python -m eval.online.live_eval --live --confirm --no-write exits with disabled message Tested: ./gradlew :services:operations-backend:test --tests com.bifrost.ops.auth.security.SecurityConfigTest --tests com.bifrost.ops.internalops.safeinject.SafeInjectionServiceTest Tested: rg static checks for removed destructive live helpers, kubectl scale/exec commands, fail-open token logic, and safeinject/e2e prefix matching Not-tested: Real --safe-live against deployed operations-backend; no real deploy/cluster mutation allowed. --- docs/api/springboot.md | 8 +- docs/design/backend-fastapi/server-design.md | 2 +- docs/design/backend-springboot/auth.md | 2 +- docs/design/backend-springboot/governance.md | 2 +- docs/design/backend-springboot/server.md | 4 +- ...70\353\262\244\355\206\240\353\246\254.md" | 2 +- services/ai-service/eval/online/live_eval.py | 353 +----------------- .../eval/online/live_fault_specs.py | 75 +--- .../ai-service/eval/online/test_live_eval.py | 130 ++----- .../ops/auth/security/SecurityConfig.java | 25 +- .../safeinject/SafeInjectionService.java | 4 +- .../src/main/resources/application.yml | 7 +- .../ops/auth/security/SecurityConfigTest.java | 14 +- .../safeinject/SafeInjectionServiceTest.java | 26 ++ 14 files changed, 119 insertions(+), 535 deletions(-) diff --git a/docs/api/springboot.md b/docs/api/springboot.md index 4b8e1c76..6ec4e58b 100644 --- a/docs/api/springboot.md +++ b/docs/api/springboot.md @@ -254,7 +254,7 @@ Family catalog 요약: | Monitoring | overview/resource-events/incidents list/detail/detail facade/report list/report body 200 | `WorkspaceAccessGuard.requireAccess` | | Cluster | Kafka/connect/throughput 조회 200 | 인증 사용자, workspace scope 없음 | | Internal `/internal` | tenant provision 200, tenant delete 202, pipeline provision 202 또는 422, status 200, delete 202 | internal control-plane surface | -| Internal `/internal/ops` read | health/version/tool-catalog 200, ready 200 또는 503, connector status/list, datasource list, SQL read, Kafka cluster info, topology/lag/log search/metrics/alerts/traces/task trace/incident summary 200 | agent-facing 내부 API. `internal.ops.token` 설정 시 `X-Internal-Token` service identity header가 필요하며, public frontend ingress는 이 경로를 프록시하지 않는다 | +| Internal `/internal/ops` read | health/version/tool-catalog 200, ready 200 또는 503, connector status/list, datasource list, SQL read, Kafka cluster info, topology/lag/log search/metrics/alerts/traces/task trace/incident summary 200 | agent-facing 내부 API. `internal.ops.token`과 일치하는 `X-Internal-Token` service identity header가 필요하며, public frontend ingress는 이 경로를 프록시하지 않는다 | | Internal `/internal/ops` safe injection | connector fault injection create 200, cleanup 200, residuals 200 | 테스트/장애 주입용 내부 표면이며 runtime tool catalog에는 포함되지 않는다 | | Internal `/internal/ops` mutation | connector restart/pause/resume, Kafka Connect consumer group restart: 성공 200, gate 실패 400/403/409, Connect 실패 502/504 | service identity gate 통과 후 controller가 `X-Agent-Run-Id`·`X-Agent-Step-Id`·`X-Idempotency-Key`를 필수 검증하고, `PolicyGuard` 결정에 따라 `X-Approval-Id` 또는 `X-Change-Ticket-Id`를 `MutationGate`에서 검증한다 | | Internal governance | approvals create/preapproved 201, list/get/decision/validate 200, change-ticket create 201/approve 200/get/validate 200 | service identity gate 대상이다. approval decision과 change-ticket create/approve는 추가로 Spring Security principal이 필요하다 | @@ -275,7 +275,7 @@ Family catalog 요약: | `/api/v1/workspaces/{wsId}/kafka/principals` list | authenticated | workspace access | | `/api/v1/workspaces/{wsId}/kafka/principals` create/deactivate/revoke/rotate/secret | authenticated | OWNER/ADMIN 또는 workspace owner. Secret 조회는 principal `ACTIVE`와 Secret 네이밍/키 무결성까지 확인 | | `/api/v1/clusters/**` | authenticated | workspace scope 없음 | -| `/internal/ops/**` | optional service identity gate | `internal.ops.token` 설정 시 `X-Internal-Token`과 정확히 일치해야 한다. 토큰이 비어 있으면 로컬/기존 배포 호환을 위해 게이트가 비활성화된다. mutation은 추가로 agent headers/idempotency/policy approval 또는 change ticket/ownership을 코드에서 검증 | +| `/internal/ops/**` | service identity gate | `internal.ops.token`은 `X-Internal-Token`과 정확히 일치해야 한다. 토큰이 비어 있으면 fail-closed로 거부하며, 로컬/테스트 우회는 `internal.ops.auth-disabled=true`일 때만 명시적으로 허용된다. mutation은 추가로 agent headers/idempotency/policy approval 또는 change ticket/ownership을 코드에서 검증 | | `/internal/ops/approvals/{id}/decision` | service identity gate + method-level principal check | `SecurityContext`의 `AuthenticatedUser`가 `tenantId`/`decidedBy`와 일치하고 approval actor와 같아야 함 | ## Alias 제거 @@ -284,9 +284,9 @@ Family catalog 요약: ## 3. Common Headers -내부 운영 API(`/internal/ops/**`)는 public frontend ingress에 노출하지 않는 agent-facing API다. FastAPI가 내부 서비스 경로로 호출하며, `internal.ops.token`이 설정된 환경에서는 모든 `/internal/ops/**` 요청에 `X-Internal-Token` service identity header가 필요하다. agent 호출 추적에는 다음 헤더를 사용한다. `AgentHeaders`가 request id로 인정하는 이름은 `X-Agent-Request-Id`와 `X-Request-Id`이고, 둘 다 없거나 unsafe하면 서버가 UUID를 생성한다. +내부 운영 API(`/internal/ops/**`)는 public frontend ingress에 노출하지 않는 agent-facing API다. FastAPI가 내부 서비스 경로로 호출하며, 모든 `/internal/ops/**` 요청에는 `internal.ops.token`과 일치하는 `X-Internal-Token` service identity header가 필요하다. agent 호출 추적에는 다음 헤더를 사용한다. `AgentHeaders`가 request id로 인정하는 이름은 `X-Agent-Request-Id`와 `X-Request-Id`이고, 둘 다 없거나 unsafe하면 서버가 UUID를 생성한다. -- service identity: `X-Internal-Token` (설정된 경우 필수) +- service identity: `X-Internal-Token` - request id: `X-Agent-Request-Id` 또는 `X-Request-Id` - `X-Agent-Run-Id` - `X-Agent-Step-Id` diff --git a/docs/design/backend-fastapi/server-design.md b/docs/design/backend-fastapi/server-design.md index c57e0412..0ff92622 100644 --- a/docs/design/backend-fastapi/server-design.md +++ b/docs/design/backend-fastapi/server-design.md @@ -387,7 +387,7 @@ Retrieval 에이전트의 **문서 RAG**([§1 Agent Principles](agent-principles ### 10. 보안 1. 현재 FastAPI route에는 frontend 사용자 JWT 검증 dependency가 연결되어 있지 않다. -2. Spring `/internal/ops/**`는 service-to-service identity gate로 보호한다(#646). FastAPI(spring_client)가 `X-Internal-Token`(설정 `AI_INTERNAL_OPS_TOKEN`)을 동봉하고, ops-backend는 `internal.ops.token`과 일치할 때만 허용한다. 토큰 미설정 시 게이트 비활성(로컬/기존 환경 호환) — gitops가 양쪽에 동일 시크릿을 주입해 활성화한다. 추가로 공개 진입점인 frontend는 `/internal/ops`를 프록시하지 않는다(에이전트 전용). +2. Spring `/internal/ops/**`는 service-to-service identity gate로 보호한다(#646). FastAPI(spring_client)가 `X-Internal-Token`(설정 `AI_INTERNAL_OPS_TOKEN`)을 동봉하고, ops-backend는 `internal.ops.token`과 일치할 때만 허용한다. 토큰 미설정은 fail-closed이며, 로컬/테스트 우회는 `internal.ops.auth-disabled=true`일 때만 허용된다. 추가로 공개 진입점인 frontend는 `/internal/ops`를 프록시하지 않는다(에이전트 전용). 3. LLM output으로 API path를 직접 만들지 않는다. 4. tool allowlist 밖 요청은 거부한다. 5. Secret, token, connection string은 prompt와 report에 넣지 않는다. diff --git a/docs/design/backend-springboot/auth.md b/docs/design/backend-springboot/auth.md index de4dbfb9..ddbe3f55 100644 --- a/docs/design/backend-springboot/auth.md +++ b/docs/design/backend-springboot/auth.md @@ -35,7 +35,7 @@ ``` - `project_member.role`은 `OWNER`/`ADMIN`/`MEMBER`다. 멤버 목록 조회는 세 역할 모두 가능하고, workspace 수정·멤버 추가/수정/삭제·settings 수정은 `OWNER`/`ADMIN`만 가능하다. -- 내부 운영 API(`/internal/ops`)는 agent-facing 내부 API다. public frontend ingress는 이 경로를 프록시하지 않고, FastAPI가 내부 서비스 경로로 호출한다. `SecurityConfig`는 `internal.ops.token`이 설정된 경우 `X-Internal-Token` service identity header 일치를 요구하며, 토큰이 비어 있으면 로컬/기존 배포 호환을 위해 게이트를 비활성화한다. mutation controller는 여기에 더해 agent headers, approval, idempotency, project/resource ownership을 자체 검증한다([governance](./governance.md)). +- 내부 운영 API(`/internal/ops`)는 agent-facing 내부 API다. public frontend ingress는 이 경로를 프록시하지 않고, FastAPI가 내부 서비스 경로로 호출한다. `SecurityConfig`는 `internal.ops.token`과 `X-Internal-Token` service identity header 일치를 요구하며, 토큰이 비어 있으면 fail-closed로 거부한다. 로컬/테스트 우회는 `internal.ops.auth-disabled=true`일 때만 허용된다. mutation controller는 여기에 더해 agent headers, approval, idempotency, project/resource ownership을 자체 검증한다([governance](./governance.md)). ### 5. 시드·보안 diff --git a/docs/design/backend-springboot/governance.md b/docs/design/backend-springboot/governance.md index 31900825..9ce28b29 100644 --- a/docs/design/backend-springboot/governance.md +++ b/docs/design/backend-springboot/governance.md @@ -14,7 +14,7 @@ | governance facade | `/internal/ops/approvals/**`, `/internal/ops/change-tickets/**` | | mutation subset | connector restart/pause/resume, Kafka Connect-managed consumer group restart | -`/internal/ops/**`는 agent-facing 내부 API이며 public frontend ingress에 노출하지 않는다. `SecurityConfig`는 `internal.ops.token`이 설정된 경우 `X-Internal-Token` service identity header 일치를 요구한다. 토큰이 비어 있으면 로컬/기존 배포 호환을 위해 게이트를 비활성화한다. Mutation controller가 추가로 적용하는 gate는 agent header, workspace/resource ownership, idempotency, `PolicyGuard` 기반 approval 또는 change-ticket, Kafka Connect REST 결과 mapping이다. +`/internal/ops/**`는 agent-facing 내부 API이며 public frontend ingress에 노출하지 않는다. `SecurityConfig`는 `internal.ops.token`과 `X-Internal-Token` service identity header 일치를 요구하며, 토큰이 비어 있으면 fail-closed로 거부한다. 로컬/테스트 우회는 `internal.ops.auth-disabled=true`일 때만 명시적으로 허용된다. Mutation controller가 추가로 적용하는 gate는 agent header, workspace/resource ownership, idempotency, `PolicyGuard` 기반 approval 또는 change-ticket, Kafka Connect REST 결과 mapping이다. ### 2. Mutation 처리 순서 diff --git a/docs/design/backend-springboot/server.md b/docs/design/backend-springboot/server.md index 431396de..ede3a31e 100644 --- a/docs/design/backend-springboot/server.md +++ b/docs/design/backend-springboot/server.md @@ -56,7 +56,7 @@ Spring Boot는 FastAPI Agent의 판단을 신뢰하지 않는다. FastAPI가 이 | 항목 | 설명 | | --- | --- | -| service identity | `internal.ops.token` 설정 시 `X-Internal-Token` 일치를 요구한다. 토큰이 비어 있으면 로컬/기존 배포 호환을 위해 게이트가 비활성화된다 | +| service identity | `internal.ops.token`과 `X-Internal-Token` 일치를 요구한다. 토큰이 비어 있으면 fail-closed로 거부하며, 로컬/테스트 우회는 `internal.ops.auth-disabled=true`일 때만 허용된다 | | user/project scope | 요청 사용자가 project 권한을 갖는가 | | resource ownership | resource가 해당 project 소유 또는 허용 범위인가 | | operation allowlist | 현재는 controller endpoint와 `/internal/ops/admin/tool-catalog` 22개 항목이 agent-callable boundary | @@ -328,7 +328,7 @@ Mutation timeout이 발생해도 Spring은 자동 재시도하지 않는다. Kaf - idempotency replay가 중복 실행을 만들지 않아야 한다. - before/after evidence row 생성은 `MutationGate` regression으로 확인하고, 현재 API regression 기준에서는 envelope field가 비어 있음을 확인한다. - forbidden operation은 endpoint가 없거나 policy deny되어야 한다. -- `internal.ops.token`이 설정된 환경에서는 FastAPI service identity header가 없거나 다르면 실패해야 한다. 토큰 미설정 로컬/기존 환경은 호환을 위해 허용된다. +- FastAPI service identity header가 없거나 `internal.ops.token`과 다르면 실패해야 한다. 토큰 미설정은 fail-closed이며, 로컬/테스트 우회는 `internal.ops.auth-disabled=true`일 때만 허용된다. ### 14. 결론 diff --git "a/docs/test/agent-\354\232\264\354\230\201\355\205\214\354\212\244\355\212\270-\354\235\270\353\262\244\355\206\240\353\246\254.md" "b/docs/test/agent-\354\232\264\354\230\201\355\205\214\354\212\244\355\212\270-\354\235\270\353\262\244\355\206\240\353\246\254.md" index e2a11f1c..f9c8f7fa 100644 --- "a/docs/test/agent-\354\232\264\354\230\201\355\205\214\354\212\244\355\212\270-\354\235\270\353\262\244\355\206\240\353\246\254.md" +++ "b/docs/test/agent-\354\232\264\354\230\201\355\205\214\354\212\244\355\212\270-\354\235\270\353\262\244\355\206\240\353\246\254.md" @@ -96,7 +96,7 @@ RCA 파이프라인: Classifier → (incident→rootcause map) → RCA evaluator ### B-4. 내부 토큰 우회 차단 (Spring 합동) - agent는 Spring 호출에 `X-Internal-Token` 동봉([spring_client.py](services/ai-service/app/tools/spring_client.py)76-89), 승인 시 `X-Approval-Id` 동봉. **집행은 Spring SecurityConfig/MutationGate**. -- 측정: 무토큰으로 `/internal/ops/**` 직접 호출 시 401/403 차단율(=공개 API 우회 차단). 단 운영 토큰 설정 여부(`INTERNAL_OPS_TOKEN`) 먼저 확인 — 비면 게이트 비활성. +- 측정: 무토큰으로 `/internal/ops/**` 직접 호출 시 401/403 차단율(=공개 API 우회 차단). `INTERNAL_OPS_TOKEN` 미설정은 fail-closed이며, 로컬/테스트 우회는 `INTERNAL_OPS_AUTH_DISABLED=true`일 때만 허용된다. --- diff --git a/services/ai-service/eval/online/live_eval.py b/services/ai-service/eval/online/live_eval.py index 240694d2..bac86113 100644 --- a/services/ai-service/eval/online/live_eval.py +++ b/services/ai-service/eval/online/live_eval.py @@ -5,10 +5,11 @@ 한 뒤 기존 메트릭 모듈(app.evaluation)로 AC@1/AC@3/AC@5/Avg@5/ECE 를 산출하고 JSON+markdown 리포트를 eval/reports/ 에 남긴다. -두 모드: +모드: --dry-run (기본): 클러스터를 절대 건드리지 않는다. spec 검증 + 채점 파이프라인을 작은 fixture (expected, predicted_ranking, confidence)로 돌려 AC@k/ECE 가 정상 계산됨을 증명. - --live : 실제 주입/폴링/복구를 수행(가드). kubectl/DB 접근은 이 플래그 뒤에서만 호출. + --live : legacy destructive fault injection is hard-disabled. + --safe-live : operations-backend safe-injection API로 신규 라벨 테스트 리소스만 생성/정리. 채점은 acceptable set 을 지원한다: RCA top-k 안에 spec.expected_root_cause_ids 중 *하나라도* 들어오면 hit. 메트릭 모듈(EvalCase)은 단일 accepted_root_cause_id 만 받으므로, 예측 랭킹을 @@ -16,17 +17,16 @@ 실행: cd services/ai-service && .venv/bin/python -m eval.online.live_eval # dry-run - cd services/ai-service && .venv/bin/python -m eval.online.live_eval --live ... # 실주입(가드) + cd services/ai-service && .venv/bin/python -m eval.online.live_eval --safe-live --confirm ... """ from __future__ import annotations import argparse import json import os -import subprocess import sys import time -from dataclasses import dataclass, field +from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path from typing import Sequence @@ -35,11 +35,7 @@ from app.evaluation.metrics import EvalCase, build_eval_report from eval.online.live_fault_specs import ( - CDC_PRODUCTS_SINK, - CDC_PRODUCTS_SOURCE, - EDA_CUSTOMERS_SOURCE, FAULT_SPECS, - FaultSpec, get_root_cause, list_fault_specs, ) @@ -49,6 +45,10 @@ ) REPORTS_DIR = Path(__file__).resolve().parents[2] / "eval" / "reports" +DESTRUCTIVE_LIVE_DISABLED_MESSAGE = ( + "legacy --live destructive fault injection is disabled in release artifacts; " + "use --safe-live for non-destructive safe injection." +) # ───────────────────────────────────────────────────────────────────────────── @@ -279,11 +279,7 @@ def build_dry_run_observations() -> list[FaultObservation]: def run_dry_run(*, write: bool = True) -> dict: """spec 검증 + 채점 파이프라인 증명. 클러스터 무접촉.""" - # spec import 시점에 이미 _validate() 통과. 여기서 auto fault 가 inject/recover 를 갖는지 재확인. - auto = list_fault_specs("auto") - for spec in auto: - assert spec.inject_steps and spec.recover_steps, spec.fault_id - + # spec import 시점에 이미 _validate() 통과. destructive auto fault 는 release artifact 에 없다. observations = build_dry_run_observations() report = score_observations(observations) report["mode"] = "dry-run" @@ -299,289 +295,6 @@ def run_dry_run(*, write: bool = True) -> dict: return report -# ───────────────────────────────────────────────────────────────────────────── -# LIVE — 실제 주입/폴링/복구. 모든 클러스터 접근은 --live 뒤에서만. -# -# 설계: 이 하니스는 *운영자 머신*에서 돈다. 클러스터 접근은 직접 DB 자격증명이 아니라 -# `kubectl exec` subprocess(psql/curl)로만 한다. DB 자격증명은 각 deployment 의 env -# ($POSTGRES_USER/$POSTGRES_DB)에 이미 있으므로 컨테이너 안에서 그대로 참조한다. -# -# clean-state 는 incident resolve(게이트된 prod write)에 의존하지 않는다. 대신 주입 직전 -# UTC baseline timestamp 를 찍고, baseline 이후 *새로* 생성된 incident/RCA 만 본다. 같은 -# grouping 의 OPEN incident 가 이미 있으면 dedup 으로 새 incident 가 안 뜰 수 있어 WARNING -# 을 남기고 timestamp 기준으로 진행한다. -# ───────────────────────────────────────────────────────────────────────────── -TENANT_ID = "8898903c-d5db-4a8c-9ff3-104632f4f70f" - -# 트래픽 유발 — sink 가 죽은 동안 source 에 row 를 넣어 CDC 가 sink 로 흘려보내다 실패하게 한다. -# tenant-postgres deployment 안에서 컨테이너 env($POSTGRES_USER/$POSTGRES_DB)로 psql 실행. -TRAFFIC_SQL = ( - "insert into public.products (name,category,price,stock,created_at) " - "select 'live-eval-'||g,'rca-test',(random()*100)::numeric(10,2)," - "(random()*1000)::int,now() from generate_series(1,300) g;" -) -# Connect REST 재시작 — connect pod 이름을 grep 으로 동적 해석(deploy 이름이 환경마다 다름). -_CONNECT_POD = ( - "CPOD=$(kubectl -n platform-kafka get pods -o name | grep -i connect | head -1 " - "| sed 's|pod/||')" -) - - -def _connect_restart_cmd(connector: str) -> str: - return ( - f"{_CONNECT_POD}; " - f'kubectl -n platform-kafka exec "$CPOD" -- ' - f'curl -s -X POST "http://localhost:8083/connectors/{connector}/restart?includeTasks=true"' - ) - - -def _run_cmd(cmd: str, *, timeout: int = 180, check: bool = False) -> tuple[int, str]: - """주입/복구/폴링 스텝을 subprocess 로 실행(live 전용). - - spec 에 선언됐거나 이 모듈 상수로 만든 신뢰 입력만 shell 로 넘긴다(사용자 자유 입력 아님). - check=True 면 비0 종료에서 RuntimeError 를 던진다(주입 실패를 조용히 넘기지 않기 위함). - """ - proc = subprocess.run( # noqa: S602 - 신뢰된 spec/상수 커맨드만 실행 - cmd, - shell=True, - capture_output=True, - text=True, - timeout=timeout, - ) - out = (proc.stdout + proc.stderr).strip() - if check and proc.returncode != 0: - raise RuntimeError(f"command failed (rc={proc.returncode}): {cmd}\n{out}") - return proc.returncode, out - - -def _kubectl_psql(namespace: str, deploy: str, sql: str, *, timeout: int = 60) -> str: - """`kubectl exec` 로 psql 을 돌려 결과(stdout)를 돌려준다(live 전용). - - -tA -F'|' 로 헤더/정렬 없는 pipe 구분 결과를 받는다. 자격증명은 컨테이너 env 참조. - sh -c 로 감싸 컨테이너 *내부*에서 $POSTGRES_USER/$POSTGRES_DB 를 확장하고(로컬 셸이 - 빈 값으로 확장하던 버그 방지), SQL 은 stdin(psql -f -)으로 넘겨 따옴표 충돌을 없앤다. - """ - cmd = ( - f"kubectl -n {namespace} exec -i deploy/{deploy} -- " - "sh -c 'psql -U \"$POSTGRES_USER\" -d \"$POSTGRES_DB\" -tA -F\"|\" -f -'" - ) - proc = subprocess.run( # noqa: S602 - 신뢰된 spec/상수 커맨드만 실행 - cmd, shell=True, capture_output=True, text=True, timeout=timeout, input=sql, - ) - if proc.returncode != 0: - out = (proc.stdout + proc.stderr).strip() - raise RuntimeError(f"psql failed on {namespace}/{deploy}: {out}") - return proc.stdout.strip() - - -def _capture_baseline(spec: FaultSpec) -> str: - """주입 직전 UTC baseline timestamp 를 metadb 시계로 찍고, dedup 위험을 경고(live 전용). - - DB 시계(now())를 기준으로 잡아 운영자 머신과의 시계 오차를 없앤다. 같은 grouping 의 OPEN - incident 가 이미 있으면 새 incident 가 dedup 될 수 있어 WARNING 후 timestamp 로 진행한다. - 반환: 이후 'created_at > ' 필터에 쓸 ISO-ish UTC 문자열. - """ - baseline = _kubectl_psql( - "metadb", "metadb", "select now() at time zone 'utc';" - ).strip() - if not baseline: - # DB 시계를 못 읽으면 운영자 머신 UTC 로 폴백(시계 오차 위험은 로그로 남긴다). - baseline = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") - print(f" [WARN] metadb 시계 조회 실패 → 로컬 UTC baseline 사용: {baseline}") - - # dedup 위험 점검: 같은 grouping_key 의 OPEN incident 가 이미 있는가. - if spec.grouping_key_pattern: - gk = spec.grouping_key_pattern.replace("'", "''") - existing = _kubectl_psql( - "metadb", - "metadb", - f"select count(*) from incidents where tenant_id='{TENANT_ID}' " - f"and grouping_key='{gk}' and status='OPEN';", - ).strip() - if existing and existing.isdigit() and int(existing) > 0: - print( - f" [WARN] grouping_key={spec.grouping_key_pattern!r} 의 OPEN incident 가 " - f"{existing}건 존재 → dedup 으로 새 incident 가 안 뜰 수 있음. " - f"baseline({baseline}) 이후 신규만 timestamp 로 잡아 진행한다." - ) - print(f" baseline(UTC) = {baseline}") - return baseline - - -def _poll_incident(baseline: str, *, timeout: int = 30) -> tuple[str | None, str]: - """baseline 이후 생성된 신규 incident 1건을 metadb 에서 조회(live 전용). - - 반환: (incident_id|None, raw_line). 없으면 (None, ""). - """ - bl = baseline.replace("'", "''") - out = _kubectl_psql( - "metadb", - "metadb", - f"select id,severity,status,title from incidents " - f"where tenant_id='{TENANT_ID}' and created_at > '{bl}' " - f"order by created_at desc limit 1;", - timeout=timeout, - ).strip() - if not out: - return None, "" - first = out.splitlines()[0] - incident_id = first.split("|", 1)[0].strip() if first else None - return (incident_id or None), first - - -def _poll_rca_ranking(baseline: str, *, timeout: int = 30) -> tuple[list[str], list[float]]: - """baseline 이후 생성된 최신 RCA report_snapshot 1건의 top-k 랭킹을 agentdb 에서 조회. - - report_snapshot 은 *run 당 1행*이고, 전체 랭킹은 body->'root_cause_candidates'(rank 순 - 배열)에 들어있다. 그래서 최신 1행을 잡아 body 의 후보 배열을 (root_cause_id, confidence) - 로 풀어 ranking 을 만든다. body 가 비어있으면 top-1(root_cause_id,confidence) 컬럼으로 폴백. - - 반환: (ranking[str], confidences[float]) — 비어있으면 ([], []). - """ - bl = baseline.replace("'", "''") - # body 의 후보 배열을 행으로 펼쳐 rank 순서대로 (id|conf) 를 받는다. - sql = ( - "with latest as (" - " select id, root_cause_id, confidence, body, created_at " - " from report_snapshot " - f" where created_at > '{bl}' " - " order by created_at desc limit 1" - ") " - "select c->>'root_cause_id', c->>'confidence' " - "from latest, " - " lateral jsonb_array_elements(coalesce(body->'root_cause_candidates','[]'::jsonb)) " - " with ordinality as t(c, ord) " - "order by ord;" - ) - out = _kubectl_psql("agentdb", "agentdb", sql, timeout=timeout).strip() - ranking: list[str] = [] - confidences: list[float] = [] - if out: - for line in out.splitlines(): - parts = line.split("|") - rc = (parts[0] if parts else "").strip() - if not rc: - continue - ranking.append(rc) - conf_str = parts[1].strip() if len(parts) > 1 else "" - try: - confidences.append(float(conf_str) if conf_str else 0.0) - except ValueError: - confidences.append(0.0) - return ranking, confidences - - # 폴백: body 에 후보 배열이 없으면 top-1 컬럼만이라도 잡는다. - top = _kubectl_psql( - "agentdb", - "agentdb", - f"select root_cause_id,confidence from report_snapshot " - f"where created_at > '{bl}' order by created_at desc limit 1;", - timeout=timeout, - ).strip() - if top: - parts = top.splitlines()[0].split("|") - rc = (parts[0] if parts else "").strip() - if rc: - ranking = [rc] - conf_str = parts[1].strip() if len(parts) > 1 else "" - try: - confidences = [float(conf_str) if conf_str else 0.0] - except ValueError: - confidences = [0.0] - return ranking, confidences - - -def _poll_rca_result( - spec: FaultSpec, baseline: str, *, timeout_s: int, interval_s: int = 15 -) -> FaultObservation: - """주입 후 metadb(incident)+agentdb(RCA) 를 폴링해 top-k 를 포착(live 전용). - - timeout_s 까지 interval_s 간격으로: 신규 incident 가 뜨고 그 뒤 RCA 랭킹이 채워지면 포착. - timeout 이면 captured=False 로 빈 랭킹 관측을 돌려준다(채점은 miss 로 잡힌다). - """ - deadline = time.monotonic() + timeout_s - incident_id: str | None = None - incident_line = "" - while time.monotonic() < deadline: - if incident_id is None: - incident_id, incident_line = _poll_incident(baseline) - if incident_id: - print(f" incident 포착: {incident_line}") - if incident_id is not None: - ranking, confs = _poll_rca_ranking(baseline) - if ranking: - print(f" RCA top-k 포착: {ranking[:5]}") - return FaultObservation( - fault_id=spec.fault_id, - expected_root_cause_ids=spec.expected_root_cause_ids, - predicted_ranking=ranking, - predicted_confidences=confs, - incident_id=incident_id, - grouping_key=spec.grouping_key_pattern, - captured=True, - note=f"live: incident={incident_id}", - ) - time.sleep(interval_s) - - print(f" [WARN] {spec.fault_id}: timeout({timeout_s}s) — incident/RCA 미포착.") - return FaultObservation( - fault_id=spec.fault_id, - expected_root_cause_ids=spec.expected_root_cause_ids, - predicted_ranking=[], - predicted_confidences=[], - incident_id=incident_id, - grouping_key=spec.grouping_key_pattern, - captured=False, - note=f"live: timeout {timeout_s}s", - ) - - -def _run_inject_steps(spec: FaultSpec) -> None: - """spec inject 스텝 실행 + sink_db_down 은 추가로 트래픽 유발(live 전용).""" - for step in spec.inject_steps: - if step.lstrip().startswith("#"): - continue - _run_cmd(step, check=True) - # sink 가 죽은 동안 source 에 row 를 넣어 CDC 가 sink write 를 시도하다 실패하게 한다. - if spec.fault_id == "sink_db_down": - time.sleep(3) # mariadb pod 가 내려갈 시간을 잠깐 준다. - # _kubectl_psql(sh -c + stdin)로 실행 — 컨테이너 내부 env 확장 + 따옴표 충돌 회피. - try: - _kubectl_psql("tenantdb", "tenant-postgres", TRAFFIC_SQL) - except Exception as exc: # 트래픽 유발 실패는 무시하고 진행. - print(f" [WARN] 트래픽 유발 실패(무시하고 진행): {exc}") - - -def _run_recover_steps(spec: FaultSpec) -> None: - """spec recover 스텝 실행 + Connect REST 로 관련 connector 재시작(live 전용). - - *항상* 호출돼야 한다(run_live 의 finally). 한 스텝이 실패해도 나머지는 계속 시도한다. - """ - errors: list[str] = [] - for step in spec.recover_steps: - if step.lstrip().startswith("#"): - continue - try: - _run_cmd(step) - except Exception as exc: # 복구는 best-effort — 한 스텝 실패가 나머지를 막지 않게. - errors.append(f"{step!r}: {exc}") - - # Connect REST 재시작(동적 pod 해석). spec.recover_steps 의 deploy/kafka-connect exec - # 가 환경에 따라 실패할 수 있어, 검증된 pod-grep 방식으로 한 번 더 확실히 재시작한다. - restart_targets = { - "sink_db_down": [CDC_PRODUCTS_SINK], - "source_db_down": [CDC_PRODUCTS_SOURCE, EDA_CUSTOMERS_SOURCE], - } - for connector in restart_targets.get(spec.fault_id, []): - try: - _run_cmd(_connect_restart_cmd(connector)) - except Exception as exc: - errors.append(f"connect-restart {connector}: {exc}") - - if errors: - print(f" [WARN] recover 중 일부 스텝 실패(best-effort): {'; '.join(errors)}") - - def run_live( fault_ids: Sequence[str] | None, *, @@ -589,47 +302,9 @@ def run_live( poll_interval_s: int = 15, confirm: bool = False, ) -> dict: - """auto fault 만 실제 주입/폴링/복구. 반드시 --confirm 동반(이중 가드). - - 한 fault 사이클: baseline 캡처 → 주입 → 폴링(timeout) → **항상 복구(finally)** → 다음. - 복구는 try/finally 로 보장돼 폴링 중 예외/크래시가 나도 클러스터가 깨진 채 남지 않는다. - """ - if not confirm: - raise SystemExit( - "live 주입은 --confirm 가 함께 있어야 한다(이중 가드). " - "이 작업 범위에서는 live 주입을 실행하지 말 것." - ) - auto = {s.fault_id: s for s in list_fault_specs("auto")} - selected = ( - [auto[f] for f in fault_ids if f in auto] if fault_ids else list(auto.values()) - ) - if not selected: - raise SystemExit("선택된 auto fault 가 없다.") - - observations: list[FaultObservation] = [] - for spec in selected: - print(f"\n=== live fault: {spec.fault_id} ({spec.layer}) ===") - baseline = _capture_baseline(spec) - obs: FaultObservation - try: - print(" inject...") - _run_inject_steps(spec) - time.sleep(2) - print(f" poll(timeout={poll_timeout_s}s, interval={poll_interval_s}s)...") - obs = _poll_rca_result( - spec, baseline, timeout_s=poll_timeout_s, interval_s=poll_interval_s - ) - finally: - # 복구는 무조건 — 예외가 나도 클러스터를 원복한다(replicas/selfHeal/connector). - print(" recover...") - _run_recover_steps(spec) - observations.append(obs) - - report = score_observations(observations) - report["mode"] = "live" - json_path, md_path = write_reports(report, mode="live") - report["_report_paths"] = {"json": str(json_path), "md": str(md_path)} - return report + """Legacy destructive live fault injection is intentionally unavailable.""" + _ = (fault_ids, poll_timeout_s, poll_interval_s, confirm) + raise SystemExit(DESTRUCTIVE_LIVE_DISABLED_MESSAGE) # ───────────────────────────────────────────────────────────────────────────── @@ -929,7 +604,7 @@ def main(argv: Sequence[str] | None = None) -> int: mode.add_argument( "--live", action="store_true", - help="가드. auto fault 실제 주입/폴링/복구(--confirm 필수).", + help="legacy destructive live fault injection is disabled; use --safe-live.", ) mode.add_argument( "--safe-live", diff --git a/services/ai-service/eval/online/live_fault_specs.py b/services/ai-service/eval/online/live_fault_specs.py index 42e7caf6..39770eee 100644 --- a/services/ai-service/eval/online/live_fault_specs.py +++ b/services/ai-service/eval/online/live_fault_specs.py @@ -5,7 +5,7 @@ dedup용 grouping_key 패턴, (5) 안전 등급을 선언한다. 안전 등급: - - 'auto' : 가역적이고 운영 영향이 격리되어 --live 실행 시 자동 주입/복구 가능. + - 'auto' : release artifact 에서는 현재 사용하지 않는다. 자동 주입은 safe_live_fault_specs.py 로만 둔다. - 'manual' : 의도된 주입 방법은 명확하나 운영자 승인/수동 단계가 필요(자동 주입 금지). - 'unsafe' : prod에서 주입이 위험하거나 사실상 재현 불가(문서화만, 절대 자동 주입 금지). @@ -14,8 +14,8 @@ - confusion_root_cause_ids 는 RCA가 헷갈릴 법한 후보로, 리포트에서 오답 분석에 사용. 모든 root_cause_id 는 app.catalogs.root_causes 카탈로그에 대해 검증된다(import 시 assert). -스텝(inject/recover)은 *데이터/선언*일 뿐 여기서 실행되지 않는다 — 실행은 live_eval.py 가 ---live 가드 뒤에서 subprocess 로만 수행한다. +스텝(inject/recover)은 문서화 전용 데이터다. legacy --live 실행기는 release artifact 에서 +hard-disabled 되어 있으며, 비파괴 자동 주입은 safe_live_fault_specs.py 경로만 사용한다. """ from __future__ import annotations @@ -33,28 +33,6 @@ CDC_PRODUCTS_SINK = "5d4b0826-ba4b-4e3a-9f21-0d2cca4efc84-sink" EDA_CUSTOMERS_SOURCE = "d9d9497b-4d8e-4baa-937b-6007aaa6b6dd-source" -# tenantdb 스케일 in/out 은 ArgoCD selfHeal(app 3-data-tenantdb)이 ~40s 내 되돌린다. -# 주입 전 selfHeal 을 끄고, 복구 후 다시 켜야 한다. -ARGOCD_APP = "3-data-tenantdb" -DISABLE_SELFHEAL = ( - "kubectl -n argocd patch application 3-data-tenantdb --type merge " - '-p \'{"spec":{"syncPolicy":{"automated":{"selfHeal":false,"prune":false}}}}\'' -) -ENABLE_SELFHEAL = ( - "kubectl -n argocd patch application 3-data-tenantdb --type merge " - '-p \'{"spec":{"syncPolicy":{"automated":{"selfHeal":true,"prune":true}}}}\'' -) -# Connect REST 재시작 (task 강제 재기동, 복구 가속). -RESTART_SINK_CONNECTOR = ( - "kubectl -n platform-kafka exec deploy/kafka-connect -- " - f"curl -s -X POST localhost:8083/connectors/{CDC_PRODUCTS_SINK}/restart?includeTasks=true" -) -RESTART_SOURCE_CONNECTOR = ( - "kubectl -n platform-kafka exec deploy/kafka-connect -- " - f"curl -s -X POST localhost:8083/connectors/{CDC_PRODUCTS_SOURCE}/restart?includeTasks=true" -) - - @dataclass(frozen=True) class FaultSpec: """단일 장애 시나리오의 주입/복구/채점 선언.""" @@ -69,7 +47,7 @@ class FaultSpec: confusion_root_cause_ids: tuple[str, ...] = () # 인시던트 dedup 용 grouping_key 패턴(주입 전 같은 key 의 OPEN 인시던트를 resolve). grouping_key_pattern: str = "" - # 주입/복구 스텝 — *선언만*. 실행은 live_eval 이 --live 에서만 subprocess 로 수행. + # 주입/복구 스텝 — release artifact 에서는 자동 실행되지 않는다. inject_steps: tuple[str, ...] = () recover_steps: tuple[str, ...] = () # injection 이 selfHeal 영향을 받는가(끄고/켜야 하는가). @@ -82,38 +60,27 @@ def primary_root_cause_id(self) -> str: # ───────────────────────────────────────────────────────────────────────────── -# Fault catalog — 8 layers. auto = 실제 --live 자동 주입 가능. manual/unsafe = 문서화만. +# Fault catalog — 8 layers. legacy destructive auto injection has been removed. # ───────────────────────────────────────────────────────────────────────────── FAULT_SPECS: tuple[FaultSpec, ...] = ( # ── sink layer ──────────────────────────────────────────────────────────── FaultSpec( fault_id="sink_db_down", layer="sink", - description="sink mariadb deployment 를 replicas=0 으로 내려 write 연결 timeout 유발.", - safety="auto", + description="sink DB down 시나리오. legacy destructive live injection path is removed.", + safety="unsafe", expected_root_cause_ids=("SINK_DB_CONNECTION_TIMEOUT",), confusion_root_cause_ids=("SINK_WRITE_LATENCY", "CONNECTOR_TASK_FAILED"), grouping_key_pattern=f"{CDC_PRODUCTS_SINK}:SINK_CONNECTION_TIMEOUT", - requires_selfheal_disable=True, - inject_steps=( - DISABLE_SELFHEAL, - "kubectl -n tenantdb scale deploy tenant-mariadb --replicas=0", - ), - recover_steps=( - "kubectl -n tenantdb scale deploy tenant-mariadb --replicas=1", - "kubectl -n tenantdb rollout status deploy/tenant-mariadb --timeout=120s", - RESTART_SINK_CONNECTOR, - ENABLE_SELFHEAL, - ), - notes="pod-down → connection refused/timeout. sink connector task FAILED 로 표출되므로 " - "CONNECTOR_TASK_FAILED 와 혼동 가능(confusion).", + notes="기존 deployment scale 기반 자동 주입은 release artifact 에서 제거됐다. " + "비파괴 검증은 safe_live_fault_specs.py 를 사용한다.", ), # ── source layer ────────────────────────────────────────────────────────── FaultSpec( fault_id="source_db_down", layer="source", - description="source postgres deployment 를 replicas=0 으로 내려 extract 연결 실패 유발.", - safety="auto", + description="source DB down 시나리오. legacy destructive live injection path is removed.", + safety="unsafe", # pod-down 은 host unreachable 로도 보이므로 둘 다 정답으로 인정. expected_root_cause_ids=( "SOURCE_DB_CONNECTION_TIMEOUT", @@ -121,18 +88,8 @@ def primary_root_cause_id(self) -> str: ), confusion_root_cause_ids=("SOURCE_READ_LATENCY", "CONNECTOR_TASK_FAILED"), grouping_key_pattern=f"{CDC_PRODUCTS_SOURCE}:SOURCE_CONNECTION_TIMEOUT", - requires_selfheal_disable=True, - inject_steps=( - DISABLE_SELFHEAL, - "kubectl -n tenantdb scale deploy tenant-postgres --replicas=0", - ), - recover_steps=( - "kubectl -n tenantdb scale deploy tenant-postgres --replicas=1", - "kubectl -n tenantdb rollout status deploy/tenant-postgres --timeout=120s", - RESTART_SOURCE_CONNECTOR, - ENABLE_SELFHEAL, - ), - notes="pod-down = host unreachable. timeout 과 reachability 가 acceptable set 으로 함께 인정.", + notes="기존 deployment scale 기반 자동 주입은 release artifact 에서 제거됐다. " + "timeout 과 reachability 가 acceptable set 으로 함께 인정.", ), # ── pipeline/connector layer ────────────────────────────────────────────── FaultSpec( @@ -146,10 +103,8 @@ def primary_root_cause_id(self) -> str: "PIPELINE_TASK_RETRY_EXHAUSTED", ), grouping_key_pattern=f"{CDC_PRODUCTS_SINK}:CONNECTOR_TASK_FAILED", - inject_steps=( - f"# 반복 restart 로 task 안정성 저하: {RESTART_SINK_CONNECTOR} (loop)", - ), - recover_steps=(RESTART_SINK_CONNECTOR,), + inject_steps=("# 반복 restart 로 task 안정성 저하(수동 절차만 문서화)",), + recover_steps=("# connector 상태 확인 후 필요 시 수동 복구",), notes="restart 자체는 가역적이나 반복 restart 가 sink 쓰기 일관성을 흔들 수 있어 manual. " "실제 FAILED 를 보장하려면 sink_db_down 과 결합하는 편이 결정적.", ), diff --git a/services/ai-service/eval/online/test_live_eval.py b/services/ai-service/eval/online/test_live_eval.py index 37979db1..52ba58b0 100644 --- a/services/ai-service/eval/online/test_live_eval.py +++ b/services/ai-service/eval/online/test_live_eval.py @@ -1,9 +1,8 @@ """#981 dry-run unit tests for the live RCA eval harness. 클러스터 무접촉. spec 카탈로그 무결성 + 채점 파이프라인(AC@k/Avg@5/ECE)이 fixture 에 대해 -정확히 계산되는지 검증한다. live 주입 경로는 (1) --confirm 가드, (2) subprocess 를 전부 -가짜로 바꿔 baseline→inject→poll→recover 배선과 *복구 항상 실행(finally)* 만 검증한다. -실제 kubectl/cluster 는 절대 건드리지 않는다. +정확히 계산되는지 검증한다. legacy live 주입 경로는 release artifact 에서 hard-disabled 이며, +safe-live 는 HTTP 테스트 더블만 사용한다. 실제 cluster 는 절대 건드리지 않는다. """ from __future__ import annotations @@ -49,9 +48,16 @@ def test_safety_levels_are_valid_and_auto_have_steps() -> None: assert spec.inject_steps and spec.recover_steps, spec.fault_id -def test_auto_faults_present() -> None: - auto = list_fault_specs("auto") - assert {s.fault_id for s in auto} == {"sink_db_down", "source_db_down"} +def test_no_legacy_auto_faults_present() -> None: + assert list_fault_specs("auto") == () + + +def test_legacy_fault_catalog_has_no_executable_destructive_steps() -> None: + forbidden = ("kubectl", "--replicas", "scale deploy", " exec ") + for spec in FAULT_SPECS: + for step in (*spec.inject_steps, *spec.recover_steps): + lowered = step.lower() + assert not any(token in lowered for token in forbidden), spec.fault_id def test_safe_faults_present_and_catalog_backed() -> None: @@ -115,108 +121,22 @@ def test_dry_run_writes_reports(tmp_path, monkeypatch) -> None: assert "AC@1" in md_p.read_text(encoding="utf-8") -# ── live 가드(클러스터 무접촉 보장) ────────────────────────────────────────── +# ── live hard-disable / safe-live guard(클러스터 무접촉 보장) ───────────────── def test_live_requires_confirm() -> None: - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as exc: run_live(None, confirm=False) + assert "disabled" in str(exc.value) -def test_safe_live_requires_confirm() -> None: - with pytest.raises(SystemExit): - run_safe_live(["auth"], confirm=False, safe_project_id="e2e-rca-test") +def test_live_is_disabled_even_with_confirm() -> None: + with pytest.raises(SystemExit) as exc: + run_live(["sink_db_down"], confirm=True) + assert "safe-live" in str(exc.value) -def test_live_never_touches_subprocess_without_confirm(monkeypatch) -> None: - # confirm 없이는 어떤 subprocess(_run_cmd)도 호출되면 안 된다(SystemExit 가 먼저). - def _boom(*a, **k): # pragma: no cover - 호출되면 실패 - raise AssertionError("confirm 없이 subprocess 가 호출됨") - - monkeypatch.setattr(le, "_run_cmd", _boom) +def test_safe_live_requires_confirm() -> None: with pytest.raises(SystemExit): - run_live(["sink_db_down"], confirm=False) - - -def _install_fake_cluster(monkeypatch, *, calls: list[str], baseline: str, - ranking_after: int = 0, raise_on_poll: bool = False): - """kubectl 접근(_run_cmd/_kubectl_psql)을 전부 가짜로 갈아끼워 클러스터 무접촉으로 만든다. - - - _run_cmd: 실행된 모든 inject/recover 커맨드를 calls 에 기록(실제 실행 X). - - _kubectl_psql: baseline/incident/RCA 쿼리를 SQL 키워드로 분기해 합성 결과를 돌려준다. - """ - state = {"poll": 0} - - def fake_run_cmd(cmd, *, timeout=180, check=False): - calls.append(cmd) - return 0, "" - - def fake_psql(namespace, deploy, sql, *, timeout=60): - if "now()" in sql: - return baseline - if "count(*)" in sql: - return "0" # 기존 OPEN incident 없음 - if "from incidents" in sql: - return f"inc-1|CRITICAL|OPEN|sink down" - if "report_snapshot" in sql: - if raise_on_poll: - raise RuntimeError("poll boom") - state["poll"] += 1 - if state["poll"] < ranking_after: - return "" # 아직 RCA 미생성 - return "SINK_DB_CONNECTION_TIMEOUT|0.88\nSINK_WRITE_LATENCY|0.40" - return "" - - monkeypatch.setattr(le, "_run_cmd", fake_run_cmd) - monkeypatch.setattr(le, "_kubectl_psql", fake_psql) - monkeypatch.setattr(le.time, "sleep", lambda *_a, **_k: None) - return state - - -def test_live_cycle_inject_poll_recover_wiring(monkeypatch, tmp_path) -> None: - # baseline→inject→poll(포착)→recover 가 한 사이클로 배선됐는지, 채점까지 도는지. - monkeypatch.setattr(le, "REPORTS_DIR", tmp_path) - calls: list[str] = [] - _install_fake_cluster(monkeypatch, calls=calls, baseline="2026-06-22 00:00:00") - - report = run_live(["sink_db_down"], confirm=True, poll_timeout_s=60, poll_interval_s=0) - - assert report["mode"] == "live" - assert report["total_cases"] == 1 - assert report["AC@1"] == 1.0 # 포착된 top-1 이 expected 와 일치. - # inject(scale 0) 와 recover(scale 1) 가 모두 실행됐다. - assert any("scale deploy tenant-mariadb --replicas=0" in c for c in calls) - assert any("scale deploy tenant-mariadb --replicas=1" in c for c in calls) - - -def test_live_recovery_runs_even_on_poll_exception(monkeypatch, tmp_path) -> None: - # 폴링 중 예외가 나도 finally 로 복구(scale 1 + selfHeal on)가 *반드시* 실행돼야 한다. - monkeypatch.setattr(le, "REPORTS_DIR", tmp_path) - calls: list[str] = [] - _install_fake_cluster( - monkeypatch, calls=calls, baseline="2026-06-22 00:00:00", raise_on_poll=True - ) - - with pytest.raises(RuntimeError): - run_live(["sink_db_down"], confirm=True, poll_timeout_s=60, poll_interval_s=0) - - # 예외가 났어도 복구 스텝이 실행됐다(클러스터가 깨진 채 남지 않음). - assert any("scale deploy tenant-mariadb --replicas=1" in c for c in calls) - assert any('"selfHeal":true' in c for c in calls) - - -def test_live_timeout_yields_uncaptured_miss(monkeypatch, tmp_path) -> None: - # RCA 가 끝까지 안 뜨면 captured=False miss 로 잡히고 복구는 그대로 실행된다. - monkeypatch.setattr(le, "REPORTS_DIR", tmp_path) - calls: list[str] = [] - # ranking_after 를 매우 크게 줘 timeout 내 RCA 가 절대 안 채워지게. - _install_fake_cluster( - monkeypatch, calls=calls, baseline="2026-06-22 00:00:00", ranking_after=10_000 - ) - - report = run_live(["sink_db_down"], confirm=True, poll_timeout_s=0, poll_interval_s=0) - assert report["total_cases"] == 1 - assert report["rows"][0]["captured"] is False - assert report["AC@1"] == 0.0 - assert any("scale deploy tenant-mariadb --replicas=1" in c for c in calls) + run_safe_live(["auth"], confirm=False, safe_project_id="e2e-rca-test") class _FakeResponse: @@ -305,14 +225,6 @@ def test_safe_live_injects_scores_and_cleans_without_destructive_helpers(monkeyp _FakeSafeClient.calls = [] monkeypatch.setattr(httpx, "Client", _FakeSafeClient) monkeypatch.setattr(le, "REPORTS_DIR", tmp_path) - monkeypatch.setattr( - le, "_run_cmd", - lambda *a, **k: (_ for _ in ()).throw(AssertionError("destructive command")), - ) - monkeypatch.setattr( - le, "_kubectl_psql", - lambda *a, **k: (_ for _ in ()).throw(AssertionError("db exec")), - ) report = run_safe_live( ["auth"], diff --git a/services/operations-backend/src/main/java/com/bifrost/ops/auth/security/SecurityConfig.java b/services/operations-backend/src/main/java/com/bifrost/ops/auth/security/SecurityConfig.java index 0b64910e..29cc0875 100644 --- a/services/operations-backend/src/main/java/com/bifrost/ops/auth/security/SecurityConfig.java +++ b/services/operations-backend/src/main/java/com/bifrost/ops/auth/security/SecurityConfig.java @@ -35,7 +35,9 @@ public PasswordEncoder passwordEncoder() { @Bean public SecurityFilterChain filterChain(HttpSecurity http, - @Value("${internal.ops.token:}") String internalOpsToken) throws Exception { + @Value("${internal.ops.token:}") String internalOpsToken, + @Value("${internal.ops.auth-disabled:false}") + boolean internalOpsAuthDisabled) throws Exception { http .csrf(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) @@ -47,10 +49,13 @@ public SecurityFilterChain filterChain(HttpSecurity http, .requestMatchers(HttpMethod.GET, SecurityPaths.PROTECTED_AUTH_GET_PATHS).authenticated() .requestMatchers(SecurityPaths.ACTUATOR_PATHS).permitAll() .requestMatchers(SecurityPaths.OPEN_API_PATHS).permitAll() - // (#646) 내부 전용 API는 service-to-service 토큰으로 게이트. 토큰 미설정 시 비활성(기존 호환). + // (#646) 내부 전용 API는 service-to-service 토큰으로 게이트. 기본은 fail-closed. .requestMatchers(SecurityPaths.INTERNAL_OPS_PATHS).access((authentication, context) -> new AuthorizationDecision( - internalOpsAllowed(internalOpsToken, context.getRequest().getHeader(INTERNAL_OPS_TOKEN_HEADER)))) + internalOpsAllowed( + internalOpsToken, + context.getRequest().getHeader(INTERNAL_OPS_TOKEN_HEADER), + internalOpsAuthDisabled))) .anyRequest().authenticated() ) .exceptionHandling(eh -> eh.authenticationEntryPoint(entryPoint)) @@ -59,11 +64,17 @@ public SecurityFilterChain filterChain(HttpSecurity http, } /** - * /internal/ops 게이트 판정(#646): 토큰이 설정되지 않은 환경(빈 값)에서는 허용해 기존 배포 호환을 - * 유지하고, 설정된 경우에만 요청 헤더와 정확히 일치할 때 허용한다. gitops가 ai-service·ops-backend에 - * 동일 시크릿을 주입하면 외부 무인증 접근이 차단된다. + * /internal/ops 게이트 판정(#646): 기본은 fail-closed다. expected token 이 비어 있으면 거부하고, + * 명시적인 local/test 우회 플래그가 켜진 경우에만 토큰 검사를 건너뛴다. */ static boolean internalOpsAllowed(String expectedToken, String providedHeader) { - return expectedToken == null || expectedToken.isBlank() || expectedToken.equals(providedHeader); + return internalOpsAllowed(expectedToken, providedHeader, false); + } + + static boolean internalOpsAllowed(String expectedToken, String providedHeader, boolean authDisabled) { + if (authDisabled) { + return true; + } + return expectedToken != null && !expectedToken.isBlank() && expectedToken.equals(providedHeader); } } diff --git a/services/operations-backend/src/main/java/com/bifrost/ops/internalops/safeinject/SafeInjectionService.java b/services/operations-backend/src/main/java/com/bifrost/ops/internalops/safeinject/SafeInjectionService.java index ff5d6fd8..db7ded87 100644 --- a/services/operations-backend/src/main/java/com/bifrost/ops/internalops/safeinject/SafeInjectionService.java +++ b/services/operations-backend/src/main/java/com/bifrost/ops/internalops/safeinject/SafeInjectionService.java @@ -263,9 +263,7 @@ private void requireTestWorkspace(String projectId, WorkspaceEntity workspace) { candidates.add(nullToEmpty(workspace.getName())); boolean allowed = candidates.stream() .map(v -> v.toLowerCase(Locale.ROOT)) - .anyMatch(v -> allowedProjects.contains(v) - || v.startsWith("safeinject") - || v.startsWith("e2e-rca-test")); + .anyMatch(allowedProjects::contains); if (!allowed) { throw new ApiException(ErrorCode.WORKSPACE_FORBIDDEN, "safe injection is allowed only for configured test workspaces"); diff --git a/services/operations-backend/src/main/resources/application.yml b/services/operations-backend/src/main/resources/application.yml index 93357155..354f7a78 100644 --- a/services/operations-backend/src/main/resources/application.yml +++ b/services/operations-backend/src/main/resources/application.yml @@ -51,12 +51,13 @@ tempo: enabled: ${TEMPO_ENABLED:false} url: ${TEMPO_URL:http://tempo.monitoring:3200} -# /internal/ops service-to-service 인증(#646). 값이 있으면 ai-service가 동봉하는 X-Internal-Token과 -# 일치할 때만 /internal/ops/**를 허용한다. 비면 게이트 비활성 → 로컬/기존 환경 호환. gitops가 ai-service -# (AI_INTERNAL_OPS_TOKEN)와 동일 시크릿을 주입한다. +# /internal/ops service-to-service 인증(#646). 기본은 fail-closed: INTERNAL_OPS_TOKEN이 비면 +# /internal/ops/**를 거부한다. 로컬/테스트 우회는 INTERNAL_OPS_AUTH_DISABLED=true로만 명시한다. +# gitops가 ai-service(AI_INTERNAL_OPS_TOKEN)와 동일 시크릿을 주입한다. internal: ops: token: ${INTERNAL_OPS_TOKEN:} + auth-disabled: ${INTERNAL_OPS_AUTH_DISABLED:false} # safe live fault injection 전용 내부 경로. 기본값은 테스트 workspace slug만 허용한다. safe-inject: diff --git a/services/operations-backend/src/test/java/com/bifrost/ops/auth/security/SecurityConfigTest.java b/services/operations-backend/src/test/java/com/bifrost/ops/auth/security/SecurityConfigTest.java index c9ba892e..ea1d51c7 100644 --- a/services/operations-backend/src/test/java/com/bifrost/ops/auth/security/SecurityConfigTest.java +++ b/services/operations-backend/src/test/java/com/bifrost/ops/auth/security/SecurityConfigTest.java @@ -26,10 +26,10 @@ void rejectsLegacyApiAuthAlias() throws IOException { // (#646) /internal/ops service-identity 게이트 판정 @Test - void internalOpsGateDisabledWhenTokenUnset() { - assertThat(SecurityConfig.internalOpsAllowed("", "anything")).isTrue(); - assertThat(SecurityConfig.internalOpsAllowed("", null)).isTrue(); - assertThat(SecurityConfig.internalOpsAllowed(null, null)).isTrue(); + void internalOpsGateRejectsWhenTokenUnset() { + assertThat(SecurityConfig.internalOpsAllowed("", "anything")).isFalse(); + assertThat(SecurityConfig.internalOpsAllowed("", null)).isFalse(); + assertThat(SecurityConfig.internalOpsAllowed(null, null)).isFalse(); } @Test @@ -38,4 +38,10 @@ void internalOpsGateAllowsMatchingTokenOnly() { assertThat(SecurityConfig.internalOpsAllowed("s3cret", "wrong")).isFalse(); assertThat(SecurityConfig.internalOpsAllowed("s3cret", null)).isFalse(); } + + @Test + void internalOpsGateAllowsOnlyWithExplicitDisableFlag() { + assertThat(SecurityConfig.internalOpsAllowed("", null, true)).isTrue(); + assertThat(SecurityConfig.internalOpsAllowed(null, "anything", true)).isTrue(); + } } diff --git a/services/operations-backend/src/test/java/com/bifrost/ops/internalops/safeinject/SafeInjectionServiceTest.java b/services/operations-backend/src/test/java/com/bifrost/ops/internalops/safeinject/SafeInjectionServiceTest.java index 16a84d4c..0ed8dd02 100644 --- a/services/operations-backend/src/test/java/com/bifrost/ops/internalops/safeinject/SafeInjectionServiceTest.java +++ b/services/operations-backend/src/test/java/com/bifrost/ops/internalops/safeinject/SafeInjectionServiceTest.java @@ -77,6 +77,32 @@ void rejectsWorkspaceOutsideSafeAllowlist() { .hasMessageContaining("configured test workspaces"); } + @Test + void rejectsPrefixMatchWhenWorkspaceIsNotExactlyAllowed() { + workspace("e2e-rca-test-prod", UUID.randomUUID()); + + assertThatThrownBy(() -> service.create("e2e-rca-test-prod", + new SafeInjectionCreateRequest("run-prefix", "auth", null))) + .isInstanceOf(ApiException.class) + .hasMessageContaining("configured test workspaces"); + } + + @Test + void allowsWorkspaceOnlyWhenExactValueIsConfigured() { + workspace("safeinject-prod", UUID.randomUUID()); + SafeInjectionService exactService = new SafeInjectionService( + client, + workspaceRepository, + NS, + CLUSTER, + "safeinject-prod"); + + SafeInjectionCreateResult result = exactService.create("safeinject-prod", + new SafeInjectionCreateRequest("run-exact", "schema", null)); + + assertThat(result.connectorName()).startsWith("safeinject-"); + } + @Test void rejectsConnectorNameOverrideSoCleanupRemainsDeterministic() { assertThatThrownBy(() -> service.create("e2e-rca-test",