From cb119207bf7cdb43e4184ede1a1bb027da09f4bd Mon Sep 17 00:00:00 2001 From: Hyeonwoo Jo Date: Sun, 18 Oct 2026 02:02:58 +0900 Subject: [PATCH 1/3] feat: implement API key authentication, CLI management, and endpoint protection - Add flow_agent/auth.py supporting Bearer and X-API-Key token authentication - Protect image/video generation and balance endpoints with constant-time verification - Maintain backward-compatible development mode when no keys are configured - Add 'key {create,list,revoke,delete}' CLI subcommand in main.py - Support FLOW_API_KEY environment variable as master key - Add unit tests in tests/test_api_auth.py (100% pass) - Update roadmap in engine-architecture-plan.md --- .../plans/engine-architecture-plan.md | 2 +- flow-agent/flow_agent/__init__.py | 16 + flow-agent/flow_agent/api.py | 31 +- flow-agent/flow_agent/auth.py | 285 ++++++++++++++++++ flow-agent/main.py | 75 +++++ flow-agent/tests/test_api_auth.py | 203 +++++++++++++ 6 files changed, 596 insertions(+), 16 deletions(-) create mode 100644 flow-agent/flow_agent/auth.py create mode 100644 flow-agent/tests/test_api_auth.py diff --git a/docs/superpowers/plans/engine-architecture-plan.md b/docs/superpowers/plans/engine-architecture-plan.md index 5371426..b5750be 100644 --- a/docs/superpowers/plans/engine-architecture-plan.md +++ b/docs/superpowers/plans/engine-architecture-plan.md @@ -54,5 +54,5 @@ Transform Google Flow image and video generation into a high-throughput, program ## 3. Future Roadmap - [ ] **Docker Containerization**: Multi-stage `Dockerfile` and `docker-compose.yml` for cloud deployments. -- [ ] **Optional API Key Authentication**: Bearer token middleware for public-facing deployments. +- [x] **Optional API Key Authentication**: Bearer token middleware, CLI key management, and constant-time verification for public-facing deployments. - [ ] **Web UI Dashboard**: Built-in visual prompt testing playground served on `/`. diff --git a/flow-agent/flow_agent/__init__.py b/flow-agent/flow_agent/__init__.py index c063445..3773fb3 100644 --- a/flow-agent/flow_agent/__init__.py +++ b/flow-agent/flow_agent/__init__.py @@ -3,6 +3,15 @@ from .engine import EngineError, FlowEngine, extract_json from .api import app from .mcp_server import create_sse_app, run_stdio +from .auth import ( + create_api_key, + delete_api_key, + is_auth_enforced, + list_api_keys, + mask_key, + revoke_api_key, + verify_api_key, +) __version__ = "1.0.0" @@ -13,5 +22,12 @@ "app", "create_sse_app", "run_stdio", + "create_api_key", + "delete_api_key", + "is_auth_enforced", + "list_api_keys", + "mask_key", + "revoke_api_key", + "verify_api_key", "__version__", ] diff --git a/flow-agent/flow_agent/api.py b/flow-agent/flow_agent/api.py index cc5bad3..c3ebb2f 100644 --- a/flow-agent/flow_agent/api.py +++ b/flow-agent/flow_agent/api.py @@ -14,11 +14,12 @@ from pathlib import Path from typing import Any, Optional -from fastapi import FastAPI, HTTPException, Request +from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, StreamingResponse from pydantic import BaseModel, ConfigDict, Field +from .auth import verify_api_key from .engine import EngineError, FlowEngine app = FastAPI( @@ -260,7 +261,7 @@ async def frames(): # --------------------------------------------------------------------------- # -@app.post("/v1/images/generations") +@app.post("/v1/images/generations", dependencies=[Depends(verify_api_key)]) async def openai_images(payload: ImageGenerationRequest, request: Request): """Generate an image from an OpenAI images payload.""" aspect = SIZE_TO_ASPECT.get(payload.size.strip().lower()) @@ -295,7 +296,7 @@ async def openai_images(payload: ImageGenerationRequest, request: Request): return payload_out -@app.post("/v1/chat/completions") +@app.post("/v1/chat/completions", dependencies=[Depends(verify_api_key)]) async def openai_chat(payload: ChatCompletionRequest, request: Request): """Generate from the last user turn and answer with a Markdown link.""" prompt = _prompt_from_messages(payload.messages) @@ -332,9 +333,9 @@ async def openai_chat(payload: ChatCompletionRequest, request: Request): # --------------------------------------------------------------------------- # -@app.post("/v1/generate/image") -@app.post("/v1/image") -@app.post("/api/v1/image") +@app.post("/v1/generate/image", dependencies=[Depends(verify_api_key)]) +@app.post("/v1/image", dependencies=[Depends(verify_api_key)]) +@app.post("/api/v1/image", dependencies=[Depends(verify_api_key)]) async def flow_image(payload: FlowImageRequest): """Generate an image, speaking the engine's own vocabulary.""" try: @@ -350,9 +351,9 @@ async def flow_image(payload: FlowImageRequest): raise HTTPException(status_code=502, detail=str(exc)) from exc -@app.post("/v1/generate/video") -@app.post("/v1/video") -@app.post("/api/v1/video") +@app.post("/v1/generate/video", dependencies=[Depends(verify_api_key)]) +@app.post("/v1/video", dependencies=[Depends(verify_api_key)]) +@app.post("/api/v1/video", dependencies=[Depends(verify_api_key)]) async def flow_video(payload: FlowVideoRequest): """Generate a video, speaking the engine's own vocabulary.""" try: @@ -370,8 +371,8 @@ async def flow_video(payload: FlowVideoRequest): raise HTTPException(status_code=502, detail=str(exc)) from exc -@app.get("/v1/balance") -@app.get("/api/v1/balance") +@app.get("/v1/balance", dependencies=[Depends(verify_api_key)]) +@app.get("/api/v1/balance", dependencies=[Depends(verify_api_key)]) async def flow_balance(refresh: bool = False): """Credits per account, cached by default and probed with `?refresh=true`.""" try: @@ -380,8 +381,8 @@ async def flow_balance(refresh: bool = False): raise HTTPException(status_code=502, detail=str(exc)) from exc -@app.get("/v1/stats") -@app.get("/api/v1/stats") +@app.get("/v1/stats", dependencies=[Depends(verify_api_key)]) +@app.get("/api/v1/stats", dependencies=[Depends(verify_api_key)]) async def flow_stats(): """Generation history and engine totals, read from the database.""" try: @@ -390,8 +391,8 @@ async def flow_stats(): raise HTTPException(status_code=502, detail=str(exc)) from exc -@app.get("/v1/projects") -@app.get("/api/v1/projects") +@app.get("/v1/projects", dependencies=[Depends(verify_api_key)]) +@app.get("/api/v1/projects", dependencies=[Depends(verify_api_key)]) async def flow_projects(cookies: Optional[str] = None): try: return {"projects": await engine.get_projects(cookies=cookies)} diff --git a/flow-agent/flow_agent/auth.py b/flow-agent/flow_agent/auth.py new file mode 100644 index 0000000..0ad700e --- /dev/null +++ b/flow-agent/flow_agent/auth.py @@ -0,0 +1,285 @@ +# -*- coding: utf-8 -*- +""" +Google Flow Agent API Key 인증 및 접근 제어 모듈. + +이 모듈은 외부 네트워크 노출 시 무단 이미지 및 비디오 생성을 방지하기 위한 +API Key의 생성, 안전한 파일 저장, 조회, 비활성화(폐기), +그리고 FastAPI 요청 수신 시 암호학적 상시 시간(constant-time) 검증 기능을 제공합니다. + +OpenAI Python SDK 표준(Authorization: Bearer ) 및 범용 HTTP 클라이언트의 +X-API-Key 헤더를 모두 지원하며, 등록된 키가 없는 경우에는 기존 로컬 개발 환경과의 +하위 호환성을 위해 무인증(개발 모드)으로 투명하게 동작합니다. +""" + +from __future__ import annotations + +import json +import os +import secrets +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Dict, List, Optional + +from fastapi import HTTPException, Request, Security, status +from fastapi.security import APIKeyHeader, HTTPAuthorizationCredentials, HTTPBearer + +# API 키 접두사 및 기본 저장 경로 +KEY_PREFIX = "sk-flow-" +DEFAULT_DATA_DIR = Path(__file__).resolve().parent.parent / "data" +DEFAULT_KEY_FILE = DEFAULT_DATA_DIR / "api_keys.json" + +# OpenAPI(Swagger UI) 자물쇠 버튼 활성화를 위한 보안 스키마 정의 +# auto_error=False로 설정하여 미입력 시에도 내부 verify_api_key에서 하위 호환성(미설정 시 통과)을 제어합니다. +security_bearer = HTTPBearer( + auto_error=False, + description="OpenAI 표준 규격 Bearer API Key ('sk-flow-...' 형식)", +) +security_header = APIKeyHeader( + name="X-API-Key", + auto_error=False, + description="HTTP 헤더 기반 API Key ('sk-flow-...' 형식)", +) + + +def get_key_file_path(custom_path: Optional[Path] = None) -> Path: + """ + API 키 저장소 파일의 절대 경로를 반환하며 부모 디렉터리가 없으면 생성합니다. + + Args: + custom_path: 사용자 지정 파일 경로 (기본값: data/api_keys.json) + + Returns: + Path: 보장된 키 파일 경로 + """ + path = custom_path or DEFAULT_KEY_FILE + path.parent.mkdir(parents=True, exist_ok=True) + return path + + +def generate_secret_key(prefix: str = KEY_PREFIX) -> str: + """ + 암호학적으로 안전한 무작위 난수 기반의 API Key 문자열을 생성합니다. + + Python 표준 secrets 모듈을 사용하여 32바이트(256비트) 엔트로피의 + URL-safe Base64 문자열을 생성하고 접두사를 부여합니다. + """ + random_part = secrets.token_urlsafe(32) + return f"{prefix}{random_part}" + + +def load_api_keys(key_file: Optional[Path] = None) -> List[Dict[str, Any]]: + """ + 디스크에 저장된 API 키 목록을 불러옵니다. + + 파일이 존재하지 않거나 유효하지 않은 JSON 형식인 경우 빈 리스트를 반환합니다. + """ + path = get_key_file_path(key_file) + if not path.exists(): + return [] + + try: + data = json.loads(path.read_text(encoding="utf-8")) + if isinstance(data, dict) and "keys" in data and isinstance(data["keys"], list): + return data["keys"] + if isinstance(data, list): + return data + return [] + except Exception: + # 파일 손상 또는 읽기 실패 시 안전하게 빈 목록 반환 + return [] + + +def save_api_keys(keys: List[Dict[str, Any]], key_file: Optional[Path] = None) -> None: + """ + API 키 목록을 디스크에 원자적(atomic) 방식으로 안전하게 저장합니다. + + 임시 파일에 먼저 기록한 뒤 os.replace를 수행하여 쓰기 도중 프로세스가 + 중단되더라도 원본 파일이 깨지지 않도록 보호합니다. + """ + path = get_key_file_path(key_file) + tmp_path = path.with_suffix(".tmp") + + payload = { + "version": 1, + "updated_at": datetime.now(timezone.utc).isoformat(), + "keys": keys, + } + + tmp_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") + # 파일 권한을 소유자 읽기/쓰기로 제한 (보안 강화) + try: + os.chmod(tmp_path, 0o600) + except OSError: + pass + tmp_path.replace(path) + + +def create_api_key( + name: str = "default", + key_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + 새로운 API 키를 생성하고 저장소에 등록한 뒤 메타데이터를 반환합니다. + + Args: + name: 키 식별자 별칭 (예: 'my-laptop', 'production-bot') + key_file: 저장할 파일 경로 (기본값: data/api_keys.json) + + Returns: + Dict[str, Any]: 생성된 키 정보 (key, name, created_at, active) + """ + key_value = generate_secret_key() + new_entry = { + "key": key_value, + "name": name.strip() or "default", + "created_at": datetime.now(timezone.utc).isoformat(), + "active": True, + } + + keys = load_api_keys(key_file) + keys.append(new_entry) + save_api_keys(keys, key_file) + return new_entry + + +def list_api_keys(key_file: Optional[Path] = None) -> List[Dict[str, Any]]: + """등록된 모든 API 키 메타데이터 목록을 반환합니다.""" + return load_api_keys(key_file) + + +def mask_key(key: str) -> str: + """ + 화면 출력 또는 로깅 시 보안을 위해 API 키의 중간 부분을 마스킹합니다. + 예: 'sk-flow-abc123456789...wxyz' -> 'sk-flow-abc1...wxyz' + """ + if len(key) <= 16: + return "****" + return f"{key[:12]}...{key[-4:]}" + + +def revoke_api_key(target: str, key_file: Optional[Path] = None) -> bool: + """ + API Key 문자열 또는 키 이름(별칭)을 기준으로 키를 비활성화(revoked) 처리합니다. + + Args: + target: 비활성화할 API 키 전체 문자열 또는 이름(name) + key_file: 대상 파일 경로 + + Returns: + bool: 성공적으로 대상을 찾아 비활성화했으면 True, 미발견 시 False + """ + keys = load_api_keys(key_file) + found = False + + for item in keys: + if item.get("key") == target or item.get("name") == target: + item["active"] = False + item["revoked_at"] = datetime.now(timezone.utc).isoformat() + found = True + + if found: + save_api_keys(keys, key_file) + return found + + +def delete_api_key(target: str, key_file: Optional[Path] = None) -> bool: + """ + API Key를 저장소에서 영구 삭제합니다. + """ + keys = load_api_keys(key_file) + initial_len = len(keys) + keys = [item for item in keys if item.get("key") != target and item.get("name") != target] + + if len(keys) < initial_len: + save_api_keys(keys, key_file) + return True + return False + + +def get_active_keys(key_file: Optional[Path] = None) -> List[str]: + """ + 현재 인증에 유효한 모든 활성 API 키 문자열 집합을 반환합니다. + 환경 변수 'FLOW_API_KEY'가 설정되어 있는 경우 해당 마스터 키도 포함됩니다. + """ + active_keys: List[str] = [] + + # 1. 환경 변수 기반 마스터 키 확인 + env_master = os.environ.get("FLOW_API_KEY", "").strip() + if env_master: + active_keys.append(env_master) + + # 2. 파일 저장소 기반 등록 키 확인 + for item in load_api_keys(key_file): + if item.get("active", True) and "key" in item: + active_keys.append(item["key"]) + + return active_keys + + +def is_auth_enforced(key_file: Optional[Path] = None) -> bool: + """ + 현재 서버가 API Key 인증 필수 모드인지 확인합니다. + + 환경 변수 'FLOW_API_KEY'가 지정되어 있거나, 등록된 활성 키가 1개 이상 존재하면 + 인증 필수 모드(True)로 동작합니다. + 키가 전무한 초기 상태에서는 로컬 하위 호환성을 위해 무인증(False)으로 동작합니다. + """ + return len(get_active_keys(key_file)) > 0 + + +def verify_api_key( + request: Request, + bearer: Optional[HTTPAuthorizationCredentials] = Security(security_bearer), + x_api_key: Optional[str] = Security(security_header), +) -> Optional[str]: + """ + FastAPI 의존성(Depends) 함수로서 수신된 요청의 API Key 유효성을 검증합니다. + + 검사 우선순위: + 1. HTTP 'Authorization: Bearer ' 헤더 (OpenAI SDK 표준) + 2. HTTP 'X-API-Key: ' 헤더 (일반 HTTP 클라이언트/cURL) + 3. URL 쿼리 파라미터 '?api_key=' (브라우저 직접 다운로드 및 미디어 접근용) + + 보안 비교: + - 타이밍 공격(timing attack)을 방지하기 위해 secrets.compare_digest를 사용합니다. + + 오류 처리: + - 인증 필수 모드에서 유효한 키가 누락되었거나 일치하지 않을 경우 HTTP 401 오류를 발생시킵니다. + """ + valid_keys = get_active_keys() + + # 등록된 키가 없으면 로컬 개발 하위 호환성을 위해 통과 + if not valid_keys: + return None + + # 클라이언트가 전달한 토큰 추출 + client_token: Optional[str] = None + + if bearer and bearer.credentials: + client_token = bearer.credentials.strip() + elif x_api_key: + client_token = x_api_key.strip() + else: + # 쿼리 파라미터 대체 확인 + query_key = request.query_params.get("api_key") + if query_key: + client_token = query_key.strip() + + if not client_token: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="API Key가 누락되었습니다. 'Authorization: Bearer ' 또는 'X-API-Key' 헤더를 제공해야 합니다.", + headers={"WWW-Authenticate": "Bearer"}, + ) + + # 상시 시간(constant-time) 비교를 통한 토큰 유효성 검사 + for valid_key in valid_keys: + if secrets.compare_digest(client_token, valid_key): + return client_token + + # 일치하는 키가 없는 경우 접근 거부 + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="제공된 API Key가 유효하지 않거나 비활성화되었습니다.", + headers={"WWW-Authenticate": "Bearer"}, + ) diff --git a/flow-agent/main.py b/flow-agent/main.py index 4f149d0..ac433e6 100644 --- a/flow-agent/main.py +++ b/flow-agent/main.py @@ -100,6 +100,62 @@ def cmd_projects(args) -> int: return 0 +def cmd_key(args) -> int: + """API Key 생성, 목록 조회, 비활성화 및 삭제 서브커맨드 처리 핸들러.""" + from flow_agent import create_api_key, delete_api_key, list_api_keys, mask_key, revoke_api_key + + action = args.key_action + if action == "create": + entry = create_api_key(name=args.name) + print("=" * 68) + print(" 🔑 새로운 Google Flow API Key가 성공적으로 생성되었습니다.") + print("=" * 68) + print(f" - 별칭 (Name) : {entry['name']}") + print(f" - API Key : {entry['key']}") + print(f" - 생성 일시 : {entry['created_at']}") + print("=" * 68) + print(" [주의] 생성된 키는 안전한 장소에 보관하십시오.") + print(" OpenAI SDK 사용 예시:") + print(f' client = OpenAI(base_url="http://<호스트>:8001/v1", api_key="{entry["key"]}")') + print("=" * 68) + return 0 + + if action == "list": + keys = list_api_keys() + if not keys: + print("등록된 API Key가 없습니다. 'python main.py key create' 명령으로 새 키를 생성하세요.") + return 0 + print(f"{'상태':<6} | {'별칭 (Name)':<20} | {'API Key':<24} | {'생성 일시'}") + print("-" * 75) + for k in keys: + status_str = "활성" if k.get("active", True) else "비활성" + print( + f"{status_str:<6} | {k.get('name', 'default'):<20} | " + f"{mask_key(k.get('key', '')):<24} | {k.get('created_at', '')}" + ) + return 0 + + if action == "revoke": + target = args.target + success = revoke_api_key(target) + if success: + print(f"성공: API Key '{target}'가 비활성화되었습니다.") + return 0 + print(f"오류: 대상 API Key 또는 별칭 '{target}'을 찾을 수 없습니다.", file=sys.stderr) + return 1 + + if action == "delete": + target = args.target + success = delete_api_key(target) + if success: + print(f"성공: API Key '{target}'가 영구 삭제되었습니다.") + return 0 + print(f"오류: 대상 API Key 또는 별칭 '{target}'을 찾을 수 없습니다.", file=sys.stderr) + return 1 + + return 0 + + # --------------------------------------------------------------------------- # # parser # --------------------------------------------------------------------------- # @@ -196,9 +252,28 @@ def build_parser() -> argparse.ArgumentParser: projects.add_argument("--cookies", default=None) projects.set_defaults(func=cmd_projects) + key_parser = sub.add_parser("key", help="manage API keys for server authentication") + key_sub = key_parser.add_subparsers(dest="key_action", required=True) + + key_create = key_sub.add_parser("create", help="generate a new API key") + key_create.add_argument("--name", default="default", help="name or alias for this key") + key_create.set_defaults(func=cmd_key) + + key_list = key_sub.add_parser("list", help="list all registered API keys") + key_list.set_defaults(func=cmd_key) + + key_revoke = key_sub.add_parser("revoke", help="deactivate an API key") + key_revoke.add_argument("target", help="API key string or name to deactivate") + key_revoke.set_defaults(func=cmd_key) + + key_delete = key_sub.add_parser("delete", help="permanently delete an API key") + key_delete.add_argument("target", help="API key string or name to delete") + key_delete.set_defaults(func=cmd_key) + return parser + def main(argv=None) -> int: args = build_parser().parse_args(argv) try: diff --git a/flow-agent/tests/test_api_auth.py b/flow-agent/tests/test_api_auth.py new file mode 100644 index 0000000..d191a95 --- /dev/null +++ b/flow-agent/tests/test_api_auth.py @@ -0,0 +1,203 @@ +# -*- coding: utf-8 -*- +""" +Google Flow Agent API Key 인증 기능 단위 테스트 (Unit Tests). + +이 테스트 모듈은 FastAPI surface 상에서 다음 핵심 동작을 검증합니다: +1. API Key가 등록되지 않은 상태(개발 모드)에서 하위 호환성 유지 (무인증 요청 허용). +2. API Key가 등록되었거나 FLOW_API_KEY 환경 변수가 설정된 상태에서 비인가 요청 차단 (401 반환). +3. 유효하지 않은 API Key 전달 시 401 오류 반환. +4. 유효한 'Authorization: Bearer ' 헤더 전달 시 인가 성공. +5. 유효한 'X-API-Key: ' 헤더 전달 시 인가 성공. +6. 공개 엔드포인트(/health, /)는 API Key 없이 상시 접근 가능. +""" + +import json +import os +import shutil +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from fastapi.testclient import TestClient + +from flow_agent import api, auth +from flow_agent.auth import ( + create_api_key, + delete_api_key, + get_active_keys, + is_auth_enforced, + revoke_api_key, + verify_api_key, +) + + +class FakeEngine: + """테스트를 위한 가짜 FlowEngine 스텁 클래스.""" + + binary = Path("/tmp/fake/flow") + + def available(self) -> bool: + return True + + async def generate_image(self, **kwargs): + return { + "job_id": "test-job-1", + "account_id": "test-acct-1", + "status": "succeeded", + "files": [{"path": "/tmp/fake_output.jpg"}], + } + + async def generate_video(self, **kwargs): + return { + "job_id": "test-job-2", + "status": "submitted", + "files": [], + } + + async def get_balance(self, refresh=False): + return {"accounts": [], "total_credits": 100, "unread": 0} + + async def get_stats(self): + return {"total_generations": 1} + + async def get_projects(self, cookies=None): + return [] + + +class TestApiKeyAuthentication(unittest.TestCase): + """API Key 인증 및 엔드포인트 보안 검증 테스트 케이스.""" + + def setUp(self): + # 임시 디렉터리 생성하여 격리된 키 파일 환경 구축 + self.temp_dir = tempfile.mkdtemp() + self.key_file = Path(self.temp_dir) / "api_keys.json" + + # 테스트용 스텁 엔진 주입 + self.fake_engine = FakeEngine() + api.engine = self.fake_engine + + # DEFAULT_KEY_FILE을 임시 파일로 패치 + self.auth_file_patcher = patch.object(auth, "DEFAULT_KEY_FILE", self.key_file) + self.auth_file_patcher.start() + + # 환경 변수 백업 및 초기화 + self.orig_env_key = os.environ.get("FLOW_API_KEY") + if "FLOW_API_KEY" in os.environ: + del os.environ["FLOW_API_KEY"] + + # FastAPI TestClient 생성 + self.client = TestClient(api.app) + + def tearDown(self): + self.auth_file_patcher.stop() + if self.orig_env_key is not None: + os.environ["FLOW_API_KEY"] = self.orig_env_key + elif "FLOW_API_KEY" in os.environ: + del os.environ["FLOW_API_KEY"] + + shutil.rmtree(self.temp_dir, ignore_errors=True) + + def test_unauthenticated_mode_when_no_keys_configured(self): + """키가 전혀 등록되지 않은 경우 하위 호환성을 위해 요청이 통과하는지 검증합니다.""" + self.assertFalse(is_auth_enforced(self.key_file)) + + # 인증 헤더 없이 요청 + res = self.client.get("/health") + self.assertEqual(res.status_code, 200) + + # 이미지 생성 엔드포인트도 개발 모드에서는 통과 + res = self.client.post( + "/api/v1/image", + json={"prompt": "test prompt", "aspect": "1:1"}, + ) + self.assertEqual(res.status_code, 200) + + def test_auth_enforced_blocks_missing_key(self): + """키가 등록된 상태에서 인증 헤더가 누락되면 401 오류가 발생하는지 검증합니다.""" + # 키 생성 + entry = create_api_key(name="test-device", key_file=self.key_file) + self.assertTrue(is_auth_enforced(self.key_file)) + + # 보호 대상 엔드포인트에 인증 없이 요청 -> 401 반환해야 함 + res = self.client.post( + "/api/v1/image", + json={"prompt": "test prompt", "aspect": "1:1"}, + ) + self.assertEqual(res.status_code, 401) + self.assertIn("API Key가 누락되었습니다", res.json()["detail"]) + + def test_auth_blocks_invalid_key(self): + """유효하지 않은 API Key로 요청 시 401 오류가 발생하는지 검증합니다.""" + create_api_key(name="test-device", key_file=self.key_file) + + headers = {"Authorization": "Bearer sk-flow-invalid-token-12345"} + res = self.client.post( + "/api/v1/image", + json={"prompt": "test prompt", "aspect": "1:1"}, + headers=headers, + ) + self.assertEqual(res.status_code, 401) + self.assertIn("유효하지 않거나 비활성화되었습니다", res.json()["detail"]) + + def test_auth_succeeds_with_valid_bearer_token(self): + """OpenAI 표준 'Authorization: Bearer ' 전달 시 성공적으로 통과하는지 검증합니다.""" + entry = create_api_key(name="test-device", key_file=self.key_file) + valid_key = entry["key"] + + headers = {"Authorization": f"Bearer {valid_key}"} + res = self.client.post( + "/api/v1/image", + json={"prompt": "test prompt", "aspect": "1:1"}, + headers=headers, + ) + self.assertEqual(res.status_code, 200) + self.assertEqual(res.json()["job_id"], "test-job-1") + + def test_auth_succeeds_with_x_api_key_header(self): + """'X-API-Key: ' 헤더 전달 시 성공적으로 통과하는지 검증합니다.""" + entry = create_api_key(name="test-device", key_file=self.key_file) + valid_key = entry["key"] + + headers = {"X-API-Key": valid_key} + res = self.client.get("/v1/balance", headers=headers) + self.assertEqual(res.status_code, 200) + self.assertEqual(res.json()["total_credits"], 100) + + def test_env_var_flow_api_key_acts_as_master_key(self): + """환경 변수 FLOW_API_KEY가 마스터 키로 정상 작동하는지 검증합니다.""" + os.environ["FLOW_API_KEY"] = "sk-flow-master-secret-key" + self.assertTrue(is_auth_enforced(self.key_file)) + + headers = {"Authorization": "Bearer sk-flow-master-secret-key"} + res = self.client.get("/v1/balance", headers=headers) + self.assertEqual(res.status_code, 200) + + def test_revoked_key_is_rejected(self): + """비활성화(revoked)된 키는 거부되는지 검증합니다.""" + entry = create_api_key(name="temp-key", key_file=self.key_file) + valid_key = entry["key"] + + # 비활성화 실행 + revoke_api_key("temp-key", key_file=self.key_file) + + headers = {"Authorization": f"Bearer {valid_key}"} + res = self.client.get("/v1/balance", headers=headers) + # 키가 비활성화되어 유효 키가 0개가 되면 하위 호환 모드가 되거나 거부됨 + # 만약 다른 활성 키가 있다면 명확히 401 + create_api_key(name="another-active-key", key_file=self.key_file) + + res = self.client.get("/v1/balance", headers=headers) + self.assertEqual(res.status_code, 401) + + def test_public_endpoints_remain_accessible(self): + """키가 강제되는 상황에서도 /health 등 공개 엔드포인트는 인증 없이 접근 가능한지 검증합니다.""" + create_api_key(name="test-device", key_file=self.key_file) + + res = self.client.get("/health") + self.assertEqual(res.status_code, 200) + self.assertEqual(res.json()["status"], "ok") + + +if __name__ == "__main__": + unittest.main() From c83b33eb81c29216e24d9d9a44f55184c1c51cbe Mon Sep 17 00:00:00 2001 From: Hyeonwoo Jo Date: Sun, 18 Oct 2026 15:27:30 +0900 Subject: [PATCH 2/3] fix(auth): fail closed on an unreadable key store, accept non-ASCII credentials Behaviour fixes across the API key surface: - Credentials are read from headers only. The ?api_key= query-string fallback is removed: it copied keys into access logs, browser history and Referer headers, and bought nothing, because media routes are not guarded. - Credentials are compared as UTF-8 bytes. secrets.compare_digest refuses str outside ASCII, so a non-ASCII key raised TypeError and answered 500 -- for a wrong key and for the correct one alike. Both now answer 401. - load_api_keys() no longer swallows every exception. A store that exists but cannot be read or parsed raises KeyStoreError, is_auth_enforced() reports True for it, and verify_api_key() answers 503. Such a store previously returned [], which switched enforcement off and let unauthenticated requests through -- the opposite of what the module is for. - create_api_key() refuses a duplicate alias, and revoke/delete refuse an alias shared by several entries instead of silently acting on all of them. - The module, the `python main.py key` subcommand and the tests are English; every other .md and .py in this repository already is. Tests: tests/test_api_auth.py grows from 8 to 17 cases, 17 passed on Python 3.11.9. --- flow-agent/flow_agent/auth.py | 312 +++++++++++++++--------------- flow-agent/main.py | 92 +++++---- flow-agent/tests/test_api_auth.py | 204 ++++++++++++------- 3 files changed, 341 insertions(+), 267 deletions(-) diff --git a/flow-agent/flow_agent/auth.py b/flow-agent/flow_agent/auth.py index 0ad700e..34a41d7 100644 --- a/flow-agent/flow_agent/auth.py +++ b/flow-agent/flow_agent/auth.py @@ -1,14 +1,15 @@ -# -*- coding: utf-8 -*- -""" -Google Flow Agent API Key 인증 및 접근 제어 모듈. - -이 모듈은 외부 네트워크 노출 시 무단 이미지 및 비디오 생성을 방지하기 위한 -API Key의 생성, 안전한 파일 저장, 조회, 비활성화(폐기), -그리고 FastAPI 요청 수신 시 암호학적 상시 시간(constant-time) 검증 기능을 제공합니다. - -OpenAI Python SDK 표준(Authorization: Bearer ) 및 범용 HTTP 클라이언트의 -X-API-Key 헤더를 모두 지원하며, 등록된 키가 없는 경우에는 기존 로컬 개발 환경과의 -하위 호환성을 위해 무인증(개발 모드)으로 투명하게 동작합니다. +"""API key authentication and access control for the Flow Agent server. + +Keys are generated here, stored on disk, revoked here, and verified in constant +time on every inbound request. The OpenAI SDK's ``Authorization: Bearer `` +header and the generic ``X-API-Key`` header are both accepted. Credentials are +read from headers only: a query-string credential would be copied into access +logs, browser history and ``Referer`` headers. + +The feature is opt-in by construction -- it is a no-op until at least one key +exists, so a fresh clone works with no configuration -- and it fails closed: +a store that exists but cannot be read yields HTTP 503 rather than silently +disabling enforcement. """ from __future__ import annotations @@ -20,266 +21,267 @@ from pathlib import Path from typing import Any, Dict, List, Optional -from fastapi import HTTPException, Request, Security, status +from fastapi import HTTPException, Security, status from fastapi.security import APIKeyHeader, HTTPAuthorizationCredentials, HTTPBearer -# API 키 접두사 및 기본 저장 경로 KEY_PREFIX = "sk-flow-" DEFAULT_DATA_DIR = Path(__file__).resolve().parent.parent / "data" DEFAULT_KEY_FILE = DEFAULT_DATA_DIR / "api_keys.json" +KEY_STORE_VERSION = 1 -# OpenAPI(Swagger UI) 자물쇠 버튼 활성화를 위한 보안 스키마 정의 -# auto_error=False로 설정하여 미입력 시에도 내부 verify_api_key에서 하위 호환성(미설정 시 통과)을 제어합니다. +# auto_error=False keeps Swagger's padlock usable while leaving the meaning of a +# missing credential to verify_api_key (nothing registered => pass through). security_bearer = HTTPBearer( auto_error=False, - description="OpenAI 표준 규격 Bearer API Key ('sk-flow-...' 형식)", + description="OpenAI-style Bearer API key ('sk-flow-...')", ) security_header = APIKeyHeader( name="X-API-Key", auto_error=False, - description="HTTP 헤더 기반 API Key ('sk-flow-...' 형식)", + description="API key sent in the 'X-API-Key' header ('sk-flow-...')", ) -def get_key_file_path(custom_path: Optional[Path] = None) -> Path: +class KeyStoreError(RuntimeError): + """The key store exists but cannot be read, parsed or trusted. + + Telling this apart from "there is no store" is what makes the failure + closed: an unreadable store must never look like an empty one. """ - API 키 저장소 파일의 절대 경로를 반환하며 부모 디렉터리가 없으면 생성합니다. - Args: - custom_path: 사용자 지정 파일 경로 (기본값: data/api_keys.json) - Returns: - Path: 보장된 키 파일 경로 - """ +def get_key_file_path(custom_path: Optional[Path] = None) -> Path: + """Return the key store path, creating its parent directory if needed.""" path = custom_path or DEFAULT_KEY_FILE - path.parent.mkdir(parents=True, exist_ok=True) + try: + path.parent.mkdir(parents=True, exist_ok=True) + except OSError as exc: + raise KeyStoreError(f"cannot create key store directory {path.parent}: {exc}") from exc return path def generate_secret_key(prefix: str = KEY_PREFIX) -> str: - """ - 암호학적으로 안전한 무작위 난수 기반의 API Key 문자열을 생성합니다. + """Return a prefixed key carrying 256 bits of URL-safe entropy.""" + return f"{prefix}{secrets.token_urlsafe(32)}" - Python 표준 secrets 모듈을 사용하여 32바이트(256비트) 엔트로피의 - URL-safe Base64 문자열을 생성하고 접두사를 부여합니다. - """ - random_part = secrets.token_urlsafe(32) - return f"{prefix}{random_part}" + +def mask_key(key: str) -> str: + """Return a display-safe rendering of ``key`` ('sk-flow-abc1...wxyz').""" + if len(key) <= 16: + return "****" + return f"{key[:12]}...{key[-4:]}" def load_api_keys(key_file: Optional[Path] = None) -> List[Dict[str, Any]]: - """ - 디스크에 저장된 API 키 목록을 불러옵니다. + """Return the stored key entries, or ``[]`` when no store exists yet. - 파일이 존재하지 않거나 유효하지 않은 JSON 형식인 경우 빈 리스트를 반환합니다. + Accepts both the written envelope (``{"version": 1, "keys": [...]}``) and a + hand-written bare list. Raises :class:`KeyStoreError` when the file exists + but cannot be read or has no recognisable shape. """ path = get_key_file_path(key_file) if not path.exists(): return [] try: - data = json.loads(path.read_text(encoding="utf-8")) - if isinstance(data, dict) and "keys" in data and isinstance(data["keys"], list): - return data["keys"] - if isinstance(data, list): - return data - return [] - except Exception: - # 파일 손상 또는 읽기 실패 시 안전하게 빈 목록 반환 - return [] + raw = path.read_text(encoding="utf-8") + except OSError as exc: + raise KeyStoreError(f"cannot read key store {path}: {exc}") from exc + try: + data = json.loads(raw) + except ValueError as exc: + raise KeyStoreError(f"key store {path} is not valid JSON: {exc}") from exc + + if isinstance(data, dict) and isinstance(data.get("keys"), list): + entries = data["keys"] + elif isinstance(data, list): + entries = data + else: + raise KeyStoreError( + f"key store {path} must be a list of keys or an object holding a 'keys' list" + ) -def save_api_keys(keys: List[Dict[str, Any]], key_file: Optional[Path] = None) -> None: - """ - API 키 목록을 디스크에 원자적(atomic) 방식으로 안전하게 저장합니다. + return [entry for entry in entries if isinstance(entry, dict)] - 임시 파일에 먼저 기록한 뒤 os.replace를 수행하여 쓰기 도중 프로세스가 - 중단되더라도 원본 파일이 깨지지 않도록 보호합니다. - """ + +def save_api_keys(keys: List[Dict[str, Any]], key_file: Optional[Path] = None) -> None: + """Write ``keys`` atomically, owner-only readable where the OS allows it.""" path = get_key_file_path(key_file) tmp_path = path.with_suffix(".tmp") - payload = { - "version": 1, + "version": KEY_STORE_VERSION, "updated_at": datetime.now(timezone.utc).isoformat(), "keys": keys, } - tmp_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") - # 파일 권한을 소유자 읽기/쓰기로 제한 (보안 강화) try: - os.chmod(tmp_path, 0o600) - except OSError: - pass - tmp_path.replace(path) - + tmp_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") + try: + os.chmod(tmp_path, 0o600) + except OSError: + pass # Windows and some filesystems cannot express 0600: best effort + tmp_path.replace(path) + except OSError as exc: + raise KeyStoreError(f"cannot write key store {path}: {exc}") from exc -def create_api_key( - name: str = "default", - key_file: Optional[Path] = None, -) -> Dict[str, Any]: - """ - 새로운 API 키를 생성하고 저장소에 등록한 뒤 메타데이터를 반환합니다. - Args: - name: 키 식별자 별칭 (예: 'my-laptop', 'production-bot') - key_file: 저장할 파일 경로 (기본값: data/api_keys.json) +def create_api_key(name: str = "default", key_file: Optional[Path] = None) -> Dict[str, Any]: + """Create and store a key, returning its metadata. - Returns: - Dict[str, Any]: 생성된 키 정보 (key, name, created_at, active) + The alias is how a later ``revoke`` or ``delete`` names this key, so it has + to stay unique; a duplicate is refused with :class:`ValueError`. """ - key_value = generate_secret_key() - new_entry = { - "key": key_value, - "name": name.strip() or "default", + alias = name.strip() or "default" + keys = load_api_keys(key_file) + if any(entry.get("name") == alias for entry in keys): + raise ValueError(f"a key named {alias!r} already exists") + + new_entry: Dict[str, Any] = { + "key": generate_secret_key(), + "name": alias, "created_at": datetime.now(timezone.utc).isoformat(), "active": True, } - - keys = load_api_keys(key_file) keys.append(new_entry) save_api_keys(keys, key_file) return new_entry def list_api_keys(key_file: Optional[Path] = None) -> List[Dict[str, Any]]: - """등록된 모든 API 키 메타데이터 목록을 반환합니다.""" + """Return the metadata of every stored key.""" return load_api_keys(key_file) -def mask_key(key: str) -> str: - """ - 화면 출력 또는 로깅 시 보안을 위해 API 키의 중간 부분을 마스킹합니다. - 예: 'sk-flow-abc123456789...wxyz' -> 'sk-flow-abc1...wxyz' - """ - if len(key) <= 16: - return "****" - return f"{key[:12]}...{key[-4:]}" +def _resolve_target(keys: List[Dict[str, Any]], target: str) -> Optional[int]: + """Return the index of the entry ``target`` names, or ``None`` if absent. - -def revoke_api_key(target: str, key_file: Optional[Path] = None) -> bool: + The key string wins over the alias, and an alias shared by more than one + entry is refused rather than silently applied to all of them. """ - API Key 문자열 또는 키 이름(별칭)을 기준으로 키를 비활성화(revoked) 처리합니다. + for index, entry in enumerate(keys): + if entry.get("key") == target: + return index - Args: - target: 비활성화할 API 키 전체 문자열 또는 이름(name) - key_file: 대상 파일 경로 + matches = [index for index, entry in enumerate(keys) if entry.get("name") == target] + if not matches: + return None + if len(matches) > 1: + raise ValueError( + f"{len(matches)} keys share the alias {target!r}; pass the key string instead" + ) + return matches[0] - Returns: - bool: 성공적으로 대상을 찾아 비활성화했으면 True, 미발견 시 False - """ - keys = load_api_keys(key_file) - found = False - for item in keys: - if item.get("key") == target or item.get("name") == target: - item["active"] = False - item["revoked_at"] = datetime.now(timezone.utc).isoformat() - found = True +def revoke_api_key(target: str, key_file: Optional[Path] = None) -> bool: + """Deactivate the key ``target`` names; ``False`` when nothing matches.""" + keys = load_api_keys(key_file) + index = _resolve_target(keys, target) + if index is None: + return False - if found: - save_api_keys(keys, key_file) - return found + keys[index]["active"] = False + keys[index]["revoked_at"] = datetime.now(timezone.utc).isoformat() + save_api_keys(keys, key_file) + return True def delete_api_key(target: str, key_file: Optional[Path] = None) -> bool: - """ - API Key를 저장소에서 영구 삭제합니다. - """ + """Remove the key ``target`` names; ``False`` when nothing matches.""" keys = load_api_keys(key_file) - initial_len = len(keys) - keys = [item for item in keys if item.get("key") != target and item.get("name") != target] + index = _resolve_target(keys, target) + if index is None: + return False - if len(keys) < initial_len: - save_api_keys(keys, key_file) - return True - return False + del keys[index] + save_api_keys(keys, key_file) + return True def get_active_keys(key_file: Optional[Path] = None) -> List[str]: - """ - 현재 인증에 유효한 모든 활성 API 키 문자열 집합을 반환합니다. - 환경 변수 'FLOW_API_KEY'가 설정되어 있는 경우 해당 마스터 키도 포함됩니다. + """Return every credential that currently authenticates a request. + + That is the ``FLOW_API_KEY`` master key when set, plus every non-revoked + stored entry. Raises :class:`KeyStoreError` if the store is unreadable. """ active_keys: List[str] = [] - # 1. 환경 변수 기반 마스터 키 확인 env_master = os.environ.get("FLOW_API_KEY", "").strip() if env_master: active_keys.append(env_master) - # 2. 파일 저장소 기반 등록 키 확인 - for item in load_api_keys(key_file): - if item.get("active", True) and "key" in item: - active_keys.append(item["key"]) + for entry in load_api_keys(key_file): + if entry.get("active", True) and entry.get("key"): + active_keys.append(entry["key"]) return active_keys def is_auth_enforced(key_file: Optional[Path] = None) -> bool: + """Return whether the server requires a credential. + + Enforcement follows from key presence -- an environment master key or at + least one stored key -- so there is no separate switch. An unreadable store + reports ``True``: "cannot tell how many keys exist" must never read as + "no keys exist". """ - 현재 서버가 API Key 인증 필수 모드인지 확인합니다. + try: + return len(get_active_keys(key_file)) > 0 + except KeyStoreError: + return True + + +def _constant_time_equals(candidate: str, known: str) -> bool: + """Compare two credentials without leaking length or content via timing. - 환경 변수 'FLOW_API_KEY'가 지정되어 있거나, 등록된 활성 키가 1개 이상 존재하면 - 인증 필수 모드(True)로 동작합니다. - 키가 전무한 초기 상태에서는 로컬 하위 호환성을 위해 무인증(False)으로 동작합니다. + The comparison runs on UTF-8 bytes because ``secrets.compare_digest`` + refuses ``str`` outside ASCII, which would otherwise turn a non-ASCII + credential into an unhandled ``TypeError`` (HTTP 500). """ - return len(get_active_keys(key_file)) > 0 + return secrets.compare_digest(candidate.encode("utf-8"), known.encode("utf-8")) def verify_api_key( - request: Request, bearer: Optional[HTTPAuthorizationCredentials] = Security(security_bearer), x_api_key: Optional[str] = Security(security_header), ) -> Optional[str]: - """ - FastAPI 의존성(Depends) 함수로서 수신된 요청의 API Key 유효성을 검증합니다. - - 검사 우선순위: - 1. HTTP 'Authorization: Bearer ' 헤더 (OpenAI SDK 표준) - 2. HTTP 'X-API-Key: ' 헤더 (일반 HTTP 클라이언트/cURL) - 3. URL 쿼리 파라미터 '?api_key=' (브라우저 직접 다운로드 및 미디어 접근용) + """FastAPI dependency that authenticates an inbound request. - 보안 비교: - - 타이밍 공격(timing attack)을 방지하기 위해 secrets.compare_digest를 사용합니다. - - 오류 처리: - - 인증 필수 모드에서 유효한 키가 누락되었거나 일치하지 않을 경우 HTTP 401 오류를 발생시킵니다. + Reads ``Authorization: Bearer `` first, then ``X-API-Key``. Returns the + presented credential, or ``None`` when nothing is enforced. Raises 401 for a + missing or unrecognised credential, and 503 when the key store cannot be read. """ - valid_keys = get_active_keys() + try: + valid_keys = get_active_keys() + except KeyStoreError as exc: + # Fail closed: an unreadable store must not degrade into no enforcement. + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail=f"API key store is unavailable: {exc}", + ) from exc - # 등록된 키가 없으면 로컬 개발 하위 호환성을 위해 통과 if not valid_keys: - return None - - # 클라이언트가 전달한 토큰 추출 - client_token: Optional[str] = None + return None # nothing registered: local development stays unauthenticated + client_token = "" if bearer and bearer.credentials: client_token = bearer.credentials.strip() elif x_api_key: client_token = x_api_key.strip() - else: - # 쿼리 파라미터 대체 확인 - query_key = request.query_params.get("api_key") - if query_key: - client_token = query_key.strip() if not client_token: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="API Key가 누락되었습니다. 'Authorization: Bearer ' 또는 'X-API-Key' 헤더를 제공해야 합니다.", + detail="Missing API key: send 'Authorization: Bearer ' or 'X-API-Key'.", headers={"WWW-Authenticate": "Bearer"}, ) - # 상시 시간(constant-time) 비교를 통한 토큰 유효성 검사 for valid_key in valid_keys: - if secrets.compare_digest(client_token, valid_key): + if _constant_time_equals(client_token, valid_key): return client_token - # 일치하는 키가 없는 경우 접근 거부 raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="제공된 API Key가 유효하지 않거나 비활성화되었습니다.", + detail="The supplied API key is invalid or has been revoked.", headers={"WWW-Authenticate": "Bearer"}, ) diff --git a/flow-agent/main.py b/flow-agent/main.py index ac433e6..8198f3f 100644 --- a/flow-agent/main.py +++ b/flow-agent/main.py @@ -101,56 +101,62 @@ def cmd_projects(args) -> int: def cmd_key(args) -> int: - """API Key 생성, 목록 조회, 비활성화 및 삭제 서브커맨드 처리 핸들러.""" + """Create, list, revoke or delete the API keys this server accepts.""" from flow_agent import create_api_key, delete_api_key, list_api_keys, mask_key, revoke_api_key + from flow_agent.auth import KEY_PREFIX, KeyStoreError - action = args.key_action - if action == "create": - entry = create_api_key(name=args.name) - print("=" * 68) - print(" 🔑 새로운 Google Flow API Key가 성공적으로 생성되었습니다.") - print("=" * 68) - print(f" - 별칭 (Name) : {entry['name']}") - print(f" - API Key : {entry['key']}") - print(f" - 생성 일시 : {entry['created_at']}") - print("=" * 68) - print(" [주의] 생성된 키는 안전한 장소에 보관하십시오.") - print(" OpenAI SDK 사용 예시:") - print(f' client = OpenAI(base_url="http://<호스트>:8001/v1", api_key="{entry["key"]}")') - print("=" * 68) - return 0 + def label(target: str) -> str: + # Echo a masked form of a key string; never print the secret itself. + return mask_key(target) if target.startswith(KEY_PREFIX) else target - if action == "list": - keys = list_api_keys() - if not keys: - print("등록된 API Key가 없습니다. 'python main.py key create' 명령으로 새 키를 생성하세요.") + action = args.key_action + try: + if action == "create": + entry = create_api_key(name=args.name) + key_value = entry["key"] + print("=" * 68) + print(" New Google Flow API key created.") + print("=" * 68) + print(f" - Name : {entry['name']}") + print(f" - API Key : {key_value}") + print(f" - Created : {entry['created_at']}") + print("=" * 68) + print(" [!] Store this key somewhere safe; it is not shown again.") + print(" OpenAI SDK example:") + print(f' client = OpenAI(base_url="http://:8001/v1", api_key="{key_value}")') + print("=" * 68) return 0 - print(f"{'상태':<6} | {'별칭 (Name)':<20} | {'API Key':<24} | {'생성 일시'}") - print("-" * 75) - for k in keys: - status_str = "활성" if k.get("active", True) else "비활성" - print( - f"{status_str:<6} | {k.get('name', 'default'):<20} | " - f"{mask_key(k.get('key', '')):<24} | {k.get('created_at', '')}" - ) - return 0 - if action == "revoke": - target = args.target - success = revoke_api_key(target) - if success: - print(f"성공: API Key '{target}'가 비활성화되었습니다.") + if action == "list": + keys = list_api_keys() + if not keys: + print("No API keys registered. Create one with 'python main.py key create'.") + return 0 + print(f"{'State':<8} | {'Name':<20} | {'API Key':<24} | Created") + print("-" * 75) + for k in keys: + state = "active" if k.get("active", True) else "revoked" + print( + f"{state:<8} | {k.get('name', 'default'):<20} | " + f"{mask_key(k.get('key', '')):<24} | {k.get('created_at', '')}" + ) return 0 - print(f"오류: 대상 API Key 또는 별칭 '{target}'을 찾을 수 없습니다.", file=sys.stderr) - return 1 - if action == "delete": - target = args.target - success = delete_api_key(target) - if success: - print(f"성공: API Key '{target}'가 영구 삭제되었습니다.") - return 0 - print(f"오류: 대상 API Key 또는 별칭 '{target}'을 찾을 수 없습니다.", file=sys.stderr) + if action == "revoke": + if revoke_api_key(args.target): + print(f"Revoked API key '{label(args.target)}'.") + return 0 + print(f"error: no API key or alias named '{label(args.target)}'", file=sys.stderr) + return 1 + + if action == "delete": + if delete_api_key(args.target): + print(f"Deleted API key '{label(args.target)}'.") + return 0 + print(f"error: no API key or alias named '{label(args.target)}'", file=sys.stderr) + return 1 + except (KeyStoreError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) return 1 return 0 diff --git a/flow-agent/tests/test_api_auth.py b/flow-agent/tests/test_api_auth.py index d191a95..be6ba71 100644 --- a/flow-agent/tests/test_api_auth.py +++ b/flow-agent/tests/test_api_auth.py @@ -1,14 +1,11 @@ # -*- coding: utf-8 -*- -""" -Google Flow Agent API Key 인증 기능 단위 테스트 (Unit Tests). - -이 테스트 모듈은 FastAPI surface 상에서 다음 핵심 동작을 검증합니다: -1. API Key가 등록되지 않은 상태(개발 모드)에서 하위 호환성 유지 (무인증 요청 허용). -2. API Key가 등록되었거나 FLOW_API_KEY 환경 변수가 설정된 상태에서 비인가 요청 차단 (401 반환). -3. 유효하지 않은 API Key 전달 시 401 오류 반환. -4. 유효한 'Authorization: Bearer ' 헤더 전달 시 인가 성공. -5. 유효한 'X-API-Key: ' 헤더 전달 시 인가 성공. -6. 공개 엔드포인트(/health, /)는 API Key 없이 상시 접근 가능. +"""Unit tests for API key authentication on the FastAPI surface. + +Covers the no-key pass-through (backwards compatibility), 401 for missing and +invalid credentials, both accepted headers, the ``FLOW_API_KEY`` master key, +revocation, the public endpoints, and the failure modes that must never +regress: a non-ASCII credential or stored key, an unreadable or malformed key +store, and credentials offered in the query string. """ import json @@ -19,6 +16,8 @@ from pathlib import Path from unittest.mock import patch +from fastapi import HTTPException +from fastapi.security import HTTPAuthorizationCredentials from fastapi.testclient import TestClient from flow_agent import api, auth @@ -27,13 +26,18 @@ delete_api_key, get_active_keys, is_auth_enforced, + list_api_keys, revoke_api_key, verify_api_key, ) +# A credential outside ASCII. ``secrets.compare_digest`` refuses such ``str`` +# arguments, so this has to be handled rather than crash the request. +NON_ASCII_KEY = "sk-flow-\uD55C\uAE00-\uD0A4" + class FakeEngine: - """테스트를 위한 가짜 FlowEngine 스텁 클래스.""" + """Stand-in for FlowEngine so no upstream account is touched.""" binary = Path("/tmp/fake/flow") @@ -49,11 +53,7 @@ async def generate_image(self, **kwargs): } async def generate_video(self, **kwargs): - return { - "job_id": "test-job-2", - "status": "submitted", - "files": [], - } + return {"job_id": "test-job-2", "status": "submitted", "files": []} async def get_balance(self, refresh=False): return {"accounts": [], "total_credits": 100, "unread": 0} @@ -66,27 +66,22 @@ async def get_projects(self, cookies=None): class TestApiKeyAuthentication(unittest.TestCase): - """API Key 인증 및 엔드포인트 보안 검증 테스트 케이스.""" + """Authentication behaviour of the protected and public routes.""" def setUp(self): - # 임시 디렉터리 생성하여 격리된 키 파일 환경 구축 self.temp_dir = tempfile.mkdtemp() self.key_file = Path(self.temp_dir) / "api_keys.json" - # 테스트용 스텁 엔진 주입 self.fake_engine = FakeEngine() api.engine = self.fake_engine - # DEFAULT_KEY_FILE을 임시 파일로 패치 self.auth_file_patcher = patch.object(auth, "DEFAULT_KEY_FILE", self.key_file) self.auth_file_patcher.start() - # 환경 변수 백업 및 초기화 self.orig_env_key = os.environ.get("FLOW_API_KEY") if "FLOW_API_KEY" in os.environ: del os.environ["FLOW_API_KEY"] - # FastAPI TestClient 생성 self.client = TestClient(api.app) def tearDown(self): @@ -99,105 +94,176 @@ def tearDown(self): shutil.rmtree(self.temp_dir, ignore_errors=True) def test_unauthenticated_mode_when_no_keys_configured(self): - """키가 전혀 등록되지 않은 경우 하위 호환성을 위해 요청이 통과하는지 검증합니다.""" + """With no keys anywhere, requests pass for backwards compatibility.""" self.assertFalse(is_auth_enforced(self.key_file)) - # 인증 헤더 없이 요청 - res = self.client.get("/health") - self.assertEqual(res.status_code, 200) - - # 이미지 생성 엔드포인트도 개발 모드에서는 통과 - res = self.client.post( - "/api/v1/image", - json={"prompt": "test prompt", "aspect": "1:1"}, - ) + self.assertEqual(self.client.get("/health").status_code, 200) + res = self.client.post("/api/v1/image", json={"prompt": "p", "aspect": "1:1"}) self.assertEqual(res.status_code, 200) def test_auth_enforced_blocks_missing_key(self): - """키가 등록된 상태에서 인증 헤더가 누락되면 401 오류가 발생하는지 검증합니다.""" - # 키 생성 - entry = create_api_key(name="test-device", key_file=self.key_file) + """A stored key turns enforcement on and a bare request gets 401.""" + create_api_key(name="test-device", key_file=self.key_file) self.assertTrue(is_auth_enforced(self.key_file)) - # 보호 대상 엔드포인트에 인증 없이 요청 -> 401 반환해야 함 - res = self.client.post( - "/api/v1/image", - json={"prompt": "test prompt", "aspect": "1:1"}, - ) + res = self.client.post("/api/v1/image", json={"prompt": "p", "aspect": "1:1"}) self.assertEqual(res.status_code, 401) - self.assertIn("API Key가 누락되었습니다", res.json()["detail"]) + self.assertIn("Missing API key", res.json()["detail"]) def test_auth_blocks_invalid_key(self): - """유효하지 않은 API Key로 요청 시 401 오류가 발생하는지 검증합니다.""" + """An unrecognised credential is refused.""" create_api_key(name="test-device", key_file=self.key_file) - headers = {"Authorization": "Bearer sk-flow-invalid-token-12345"} res = self.client.post( "/api/v1/image", - json={"prompt": "test prompt", "aspect": "1:1"}, - headers=headers, + json={"prompt": "p", "aspect": "1:1"}, + headers={"Authorization": "Bearer sk-flow-invalid-token-12345"}, ) self.assertEqual(res.status_code, 401) - self.assertIn("유효하지 않거나 비활성화되었습니다", res.json()["detail"]) + self.assertIn("invalid or has been revoked", res.json()["detail"]) def test_auth_succeeds_with_valid_bearer_token(self): - """OpenAI 표준 'Authorization: Bearer ' 전달 시 성공적으로 통과하는지 검증합니다.""" + """The OpenAI SDK's Authorization header authenticates.""" entry = create_api_key(name="test-device", key_file=self.key_file) - valid_key = entry["key"] - headers = {"Authorization": f"Bearer {valid_key}"} res = self.client.post( "/api/v1/image", - json={"prompt": "test prompt", "aspect": "1:1"}, - headers=headers, + json={"prompt": "p", "aspect": "1:1"}, + headers={"Authorization": f"Bearer {entry['key']}"}, ) self.assertEqual(res.status_code, 200) self.assertEqual(res.json()["job_id"], "test-job-1") def test_auth_succeeds_with_x_api_key_header(self): - """'X-API-Key: ' 헤더 전달 시 성공적으로 통과하는지 검증합니다.""" + """The X-API-Key header authenticates too.""" entry = create_api_key(name="test-device", key_file=self.key_file) - valid_key = entry["key"] - headers = {"X-API-Key": valid_key} - res = self.client.get("/v1/balance", headers=headers) + res = self.client.get("/v1/balance", headers={"X-API-Key": entry["key"]}) self.assertEqual(res.status_code, 200) self.assertEqual(res.json()["total_credits"], 100) def test_env_var_flow_api_key_acts_as_master_key(self): - """환경 변수 FLOW_API_KEY가 마스터 키로 정상 작동하는지 검증합니다.""" + """FLOW_API_KEY authenticates on its own, with no stored key.""" os.environ["FLOW_API_KEY"] = "sk-flow-master-secret-key" self.assertTrue(is_auth_enforced(self.key_file)) - headers = {"Authorization": "Bearer sk-flow-master-secret-key"} - res = self.client.get("/v1/balance", headers=headers) + res = self.client.get( + "/v1/balance", headers={"Authorization": "Bearer sk-flow-master-secret-key"} + ) self.assertEqual(res.status_code, 200) def test_revoked_key_is_rejected(self): - """비활성화(revoked)된 키는 거부되는지 검증합니다.""" + """A revoked key stops working once another active key exists.""" entry = create_api_key(name="temp-key", key_file=self.key_file) - valid_key = entry["key"] - - # 비활성화 실행 + revoked = entry["key"] revoke_api_key("temp-key", key_file=self.key_file) - headers = {"Authorization": f"Bearer {valid_key}"} - res = self.client.get("/v1/balance", headers=headers) - # 키가 비활성화되어 유효 키가 0개가 되면 하위 호환 모드가 되거나 거부됨 - # 만약 다른 활성 키가 있다면 명확히 401 - create_api_key(name="another-active-key", key_file=self.key_file) + # The only key is gone, so nothing is enforced and the request passes. + self.assertEqual( + self.client.get( + "/v1/balance", headers={"Authorization": f"Bearer {revoked}"} + ).status_code, + 200, + ) - res = self.client.get("/v1/balance", headers=headers) + create_api_key(name="another-active-key", key_file=self.key_file) + res = self.client.get("/v1/balance", headers={"Authorization": f"Bearer {revoked}"}) self.assertEqual(res.status_code, 401) def test_public_endpoints_remain_accessible(self): - """키가 강제되는 상황에서도 /health 등 공개 엔드포인트는 인증 없이 접근 가능한지 검증합니다.""" + """Health stays reachable while enforcement is on.""" create_api_key(name="test-device", key_file=self.key_file) res = self.client.get("/health") self.assertEqual(res.status_code, 200) self.assertEqual(res.json()["status"], "ok") + def test_non_ascii_credential_is_rejected_not_crashed(self): + """A credential outside ASCII yields 401, never an unhandled TypeError.""" + create_api_key(name="test-device", key_file=self.key_file) + bearer = HTTPAuthorizationCredentials(scheme="Bearer", credentials=NON_ASCII_KEY) + + with self.assertRaises(HTTPException) as caught: + verify_api_key(bearer=bearer, x_api_key=None) + + self.assertEqual(caught.exception.status_code, 401) + + def test_non_ascii_stored_key_does_not_break_verification(self): + """A stored non-ASCII master key still refuses a wrong key with 401.""" + os.environ["FLOW_API_KEY"] = NON_ASCII_KEY + + res = self.client.get( + "/v1/balance", headers={"Authorization": "Bearer sk-flow-plain-ascii-key"} + ) + self.assertEqual(res.status_code, 401) + + def test_corrupt_store_fails_closed(self): + """A store that is not JSON must never switch enforcement off.""" + create_api_key(name="test-device", key_file=self.key_file) + self.key_file.write_text("{ not json at all", encoding="utf-8") + + self.assertTrue(is_auth_enforced(self.key_file)) + res = self.client.post("/api/v1/image", json={"prompt": "p", "aspect": "1:1"}) + self.assertEqual(res.status_code, 503) + + def test_store_without_keys_list_fails_closed(self): + """A store whose shape is unrecognised fails closed as well.""" + self.key_file.write_text('{"version": 1}', encoding="utf-8") + + self.assertTrue(is_auth_enforced(self.key_file)) + self.assertEqual(self.client.get("/v1/balance").status_code, 503) + + def test_unreadable_store_fails_closed(self): + """A store path that cannot be read as a file fails closed.""" + self.key_file.mkdir() # the path exists, but read_text() cannot read it + + self.assertTrue(is_auth_enforced(self.key_file)) + self.assertEqual(self.client.get("/v1/balance").status_code, 503) + + def test_query_parameter_credential_is_rejected(self): + """Credentials are read from headers only, never the query string.""" + entry = create_api_key(name="test-device", key_file=self.key_file) + + res = self.client.get(f"/v1/balance?api_key={entry['key']}") + self.assertEqual(res.status_code, 401) + + def test_duplicate_alias_is_rejected(self): + """Aliases identify a key, so a duplicate is refused.""" + create_api_key(name="laptop", key_file=self.key_file) + + with self.assertRaises(ValueError): + create_api_key(name="laptop", key_file=self.key_file) + + def test_ambiguous_alias_target_is_rejected(self): + """An alias shared by two hand-written entries names no single key.""" + self.key_file.write_text( + json.dumps( + { + "keys": [ + {"key": "sk-flow-one", "name": "dup", "active": True}, + {"key": "sk-flow-two", "name": "dup", "active": True}, + ] + } + ), + encoding="utf-8", + ) + + with self.assertRaises(ValueError): + delete_api_key("dup", key_file=self.key_file) + + self.assertEqual(len(list_api_keys(self.key_file)), 2) + self.assertTrue(delete_api_key("sk-flow-one", key_file=self.key_file)) + self.assertEqual(len(list_api_keys(self.key_file)), 1) + + def test_active_keys_lists_env_and_stored_keys(self): + """Both credential sources are reported as active.""" + entry = create_api_key(name="test-device", key_file=self.key_file) + os.environ["FLOW_API_KEY"] = "sk-flow-master-secret-key" + + active = get_active_keys(self.key_file) + self.assertIn(entry["key"], active) + self.assertIn("sk-flow-master-secret-key", active) + if __name__ == "__main__": unittest.main() From d5bd8b2315a9e14099099fcad16712ecc68c033f Mon Sep 17 00:00:00 2001 From: Hyeonwoo Jo Date: Sun, 18 Oct 2026 15:39:43 +0900 Subject: [PATCH 3/3] docs: document API key authentication, CLI management, and add test isolation fixture --- README.md | 21 +++++++++++++-- docs/API_REFERENCE.md | 51 ++++++++++++++++++++++++++++++------ docs/CLI_REFERENCE.md | 37 ++++++++++++++++++++++++++ flow-agent/tests/conftest.py | 15 +++++++++++ 4 files changed, 114 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 32627e1..6c36486 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,7 @@ Interactive docs open at **`http://127.0.0.1:8001/docs`** ```bash curl -X POST http://127.0.0.1:8001/api/v1/image \ -H "Content-Type: application/json" \ + -H "Authorization: Bearer sk-flow-..." \ -d '{"prompt": "neon cyber dragon over misty mountains", "aspect": "16:9"}' ``` @@ -184,6 +185,22 @@ curl -X POST http://127.0.0.1:8001/api/v1/image \ } ``` +### 🔒 API Key Authentication + +Protect your server when exposing it publicly (e.g. via Cloudflare Tunnel or reverse proxy): + +```bash +# Generate a new API key +python main.py key create --name "my-laptop" +# → key: sk-flow-JNhS...Wxyz + +# List, revoke, or delete keys +python main.py key list +python main.py key revoke "my-laptop" +``` + +Once a key is created, all protected endpoints enforce authentication via `Authorization: Bearer ` or `X-API-Key: `. Setting the `FLOW_API_KEY` environment variable also acts as a master key. + --- ## OpenAI SDK — Drop-in Replacement @@ -193,8 +210,8 @@ Change **one line** in your existing OpenAI code: ```python from openai import OpenAI -# ← Change only this line -client = OpenAI(base_url="http://127.0.0.1:8001/v1", api_key="not-needed") +# ← Change only this line (use api_key="not-needed" if authentication is unconfigured) +client = OpenAI(base_url="http://127.0.0.1:8001/v1", api_key="your-sk-flow-key") # Everything else stays exactly the same ↓ response = client.images.generate( diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index f8c3fcf..39eaeb7 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -12,12 +12,13 @@ All endpoints assume the server is running at its default address. ## Table of Contents 1. [Endpoints Overview](#1-endpoints-overview) -2. [Native Flow Endpoints (`/api/v1/*`)](#2-native-flow-endpoints) -3. [OpenAI-Compatible Endpoints (`/v1/*`)](#3-openai-compatible-endpoints) -4. [System Endpoints](#4-system-endpoints) -5. [Route Aliases](#5-route-aliases) -6. [Error Responses](#6-error-responses) -7. [Client Examples](#7-client-examples) +2. [Authentication](#2-authentication) +3. [Native Flow Endpoints (`/api/v1/*`)](#3-native-flow-endpoints) +4. [OpenAI-Compatible Endpoints (`/v1/*`)](#4-openai-compatible-endpoints) +5. [System Endpoints](#5-system-endpoints) +6. [Route Aliases](#6-route-aliases) +7. [Error Responses](#7-error-responses) +8. [Client Examples](#8-client-examples) --- @@ -47,11 +48,43 @@ All endpoints assume the server is running at its default address. | :--- | :--- | :--- | | `GET` | `/health` | Engine liveness check | -> **Route Aliases**: Every `/api/v1/*` native endpoint is also reachable under `/v1/*` for convenience. See [Section 5](#5-route-aliases) for the full alias map. +> **Route Aliases**: Every `/api/v1/*` native endpoint is also reachable under `/v1/*` for convenience. See [Section 6](#6-route-aliases) for the full alias map. --- -## 2. Native Flow Endpoints +## 2. Authentication + +Flow Agent supports optional API key authentication for production and public deployments. + +### Operating Modes + +- **Unauthenticated (Local / Dev Mode)**: If no API keys are registered and `FLOW_API_KEY` is unset, authentication is disabled so existing local workflows work without credentials. +- **Enforced Mode**: Active when at least one API key is created via `python main.py key create` or the `FLOW_API_KEY` environment variable is set. Protected endpoints require a valid key. + +### Providing Credentials + +Credentials are accepted from headers only: +1. **Authorization Header (OpenAI SDK Standard)**: + ```http + Authorization: Bearer sk-flow-... + ``` +2. **X-API-Key Header (Standard HTTP Client)**: + ```http + X-API-Key: sk-flow-... + ``` + +*(Note: Credentials in query parameters like `?api_key=` are deliberately rejected to prevent key leakage in server access logs and `Referer` headers).* + +### Public Endpoints + +The following routes are always accessible without credentials: +- `GET /health` (Liveness probe) +- `GET /docs`, `GET /redoc`, `GET /openapi.json` (API documentation) +- `GET /v1/media/*`, `GET /api/v1/media/*` (Generated media downloads) + +--- + +## 3. Native Flow Endpoints ### 2.1 Generate Image @@ -485,9 +518,11 @@ All errors return a JSON body with a `detail` field: | HTTP Status | Meaning | | :--- | :--- | | `400 Bad Request` | Invalid parameter value (e.g. unsupported image size) | +| `401 Unauthorized` | API key missing, invalid, or revoked when authentication is enforced | | `404 Not Found` | Media file not found or path traversal blocked | | `422 Unprocessable Entity` | Request body validation failure (missing required field, out-of-range value) | | `502 Bad Gateway` | Google Flow upstream refused the generation request (anti-abuse / rate limit) — not a server error | +| `503 Service Unavailable` | API key store corrupted or unreadable (Fail-Closed protection enforces request refusal) | > **Note on 502:** A `502` means the code path executed correctly and Google declined the request. Retrying after a cooldown of 30–120 s usually succeeds. Attaching the Flow Chrome extension and using `--captcha broker` significantly reduces the chance of refusal. diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 0fcaa5b..b9129d3 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -17,6 +17,7 @@ Complete command-line documentation for **Flow Agent** and the underlying **Flow - [balance](#15-balance--account-credits) - [stats](#16-stats--generation-history) - [projects](#17-projects--list-flow-projects) + - [key](#18-key--manage-api-keys) 2. [Engine Binary (`./bin/flow`)](#2-engine-binary-binflow) 3. [Environment Variables](#3-environment-variables) 4. [Exit Codes](#4-exit-codes) @@ -237,6 +238,41 @@ python main.py projects --cookies cookies/account_abc.json --- +### 1.8 `key` — Manage API Keys + +Manages API keys used to secure the REST API endpoints when exposing the server externally. + +```bash +python main.py key {create,list,revoke,delete} [options] +``` + +#### Subcommands + +| Subcommand | Arguments | Description | +| :--- | :--- | :--- | +| `create` | `[--name NAME]` | Generate a new random secret API key (`sk-flow-...`) and register it. Refuses duplicate names. | +| `list` | None | List all registered API keys with their status and masked secrets | +| `revoke` | `TARGET` | Deactivate an API key by its secret value or unique alias name (soft delete) | +| `delete` | `TARGET` | Permanently remove an API key from the local store (hard delete) | + +**Examples:** + +```bash +# Generate a new API key with an alias +python main.py key create --name "my-laptop" + +# List all keys +python main.py key list + +# Revoke a key by alias or secret +python main.py key revoke "my-laptop" + +# Permanently delete a key +python main.py key delete "my-laptop" +``` + +--- + ## 2. Engine Binary (`./bin/flow`) The low-level Go binary (`flow-macos` on macOS, `flow-linux` on Linux, `flow-windows.exe` on Windows) is invoked automatically by the Python layer. It can also be used directly for advanced workflows. @@ -351,6 +387,7 @@ Starts the WebSocket bridge on `ws://127.0.0.1:9222` that the Chrome Flow extens | Variable | Default | Description | | :--- | :--- | :--- | | `IMAGE_MODEL` | `narwhal` | Default image model key. Overrides the `--model` default without passing the flag. | +| `FLOW_API_KEY` | *(empty)* | Optional master secret key. Enforces API authentication across all protected REST routes. | | `FLOW_COOKIES_DIR` | `cookies/` | Directory to scan for account JSON bundles. | | `FLOW_OUTPUT_DIR` | `output/` | Directory where generated images and videos are saved. | | `FLOW_DB_PATH` | `data/flow.db` | SQLite database path for generation history. | diff --git a/flow-agent/tests/conftest.py b/flow-agent/tests/conftest.py index 8bf5294..57ec7b1 100644 --- a/flow-agent/tests/conftest.py +++ b/flow-agent/tests/conftest.py @@ -9,3 +9,18 @@ ROOT = Path(__file__).resolve().parent.parent if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) + +import pytest + +@pytest.fixture(autouse=True) +def isolate_api_keys_for_tests(tmp_path, monkeypatch): + """ + 모든 테스트에 대해 API 키 저장소를 임시 경로로 격리합니다. + + 실제 운영 환경의 data/api_keys.json 파일이나 시스템 환경 변수(FLOW_API_KEY)가 + 테스트 스위트에 유입되어 인증 오류(401)를 발생시키는 것을 방지합니다. + """ + test_key_file = tmp_path / "isolated_api_keys.json" + monkeypatch.setattr("flow_agent.auth.DEFAULT_KEY_FILE", test_key_file) + monkeypatch.delenv("FLOW_API_KEY", raising=False) + yield test_key_file