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/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..34a41d7 --- /dev/null +++ b/flow-agent/flow_agent/auth.py @@ -0,0 +1,287 @@ +"""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 + +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, Security, status +from fastapi.security import APIKeyHeader, HTTPAuthorizationCredentials, HTTPBearer + +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 + +# 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-style Bearer API key ('sk-flow-...')", +) +security_header = APIKeyHeader( + name="X-API-Key", + auto_error=False, + description="API key sent in the 'X-API-Key' header ('sk-flow-...')", +) + + +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. + """ + + +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 + 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: + """Return a prefixed key carrying 256 bits of URL-safe entropy.""" + return f"{prefix}{secrets.token_urlsafe(32)}" + + +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]]: + """Return the stored key entries, or ``[]`` when no store exists yet. + + 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: + 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" + ) + + return [entry for entry in entries if isinstance(entry, dict)] + + +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": KEY_STORE_VERSION, + "updated_at": datetime.now(timezone.utc).isoformat(), + "keys": keys, + } + + try: + 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]: + """Create and store a key, returning its metadata. + + 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`. + """ + 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.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]]: + """Return the metadata of every stored key.""" + return load_api_keys(key_file) + + +def _resolve_target(keys: List[Dict[str, Any]], target: str) -> Optional[int]: + """Return the index of the entry ``target`` names, or ``None`` if absent. + + 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. + """ + for index, entry in enumerate(keys): + if entry.get("key") == target: + return index + + 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] + + +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 + + 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: + """Remove 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 + + del keys[index] + save_api_keys(keys, key_file) + return True + + +def get_active_keys(key_file: Optional[Path] = None) -> List[str]: + """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] = [] + + env_master = os.environ.get("FLOW_API_KEY", "").strip() + if env_master: + active_keys.append(env_master) + + 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". + """ + 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. + + 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 secrets.compare_digest(candidate.encode("utf-8"), known.encode("utf-8")) + + +def verify_api_key( + bearer: Optional[HTTPAuthorizationCredentials] = Security(security_bearer), + x_api_key: Optional[str] = Security(security_header), +) -> Optional[str]: + """FastAPI dependency that authenticates an inbound request. + + 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. + """ + 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 # 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() + + if not client_token: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Missing API key: send 'Authorization: Bearer ' or 'X-API-Key'.", + headers={"WWW-Authenticate": "Bearer"}, + ) + + for valid_key in valid_keys: + if _constant_time_equals(client_token, valid_key): + return client_token + + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + 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 4f149d0..8198f3f 100644 --- a/flow-agent/main.py +++ b/flow-agent/main.py @@ -100,6 +100,68 @@ def cmd_projects(args) -> int: return 0 +def cmd_key(args) -> int: + """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 + + 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 + + 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 + + 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 + + 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 + + # --------------------------------------------------------------------------- # # parser # --------------------------------------------------------------------------- # @@ -196,9 +258,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/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 diff --git a/flow-agent/tests/test_api_auth.py b/flow-agent/tests/test_api_auth.py new file mode 100644 index 0000000..be6ba71 --- /dev/null +++ b/flow-agent/tests/test_api_auth.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +"""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 +import os +import shutil +import tempfile +import unittest +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 +from flow_agent.auth import ( + create_api_key, + 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: + """Stand-in for FlowEngine so no upstream account is touched.""" + + 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): + """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 + + 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"] + + 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): + """With no keys anywhere, requests pass for backwards compatibility.""" + self.assertFalse(is_auth_enforced(self.key_file)) + + 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): + """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)) + + res = self.client.post("/api/v1/image", json={"prompt": "p", "aspect": "1:1"}) + self.assertEqual(res.status_code, 401) + self.assertIn("Missing API key", res.json()["detail"]) + + def test_auth_blocks_invalid_key(self): + """An unrecognised credential is refused.""" + create_api_key(name="test-device", key_file=self.key_file) + + res = self.client.post( + "/api/v1/image", + json={"prompt": "p", "aspect": "1:1"}, + headers={"Authorization": "Bearer sk-flow-invalid-token-12345"}, + ) + self.assertEqual(res.status_code, 401) + self.assertIn("invalid or has been revoked", res.json()["detail"]) + + def test_auth_succeeds_with_valid_bearer_token(self): + """The OpenAI SDK's Authorization header authenticates.""" + entry = create_api_key(name="test-device", key_file=self.key_file) + + res = self.client.post( + "/api/v1/image", + 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): + """The X-API-Key header authenticates too.""" + entry = create_api_key(name="test-device", key_file=self.key_file) + + 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 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)) + + 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): + """A revoked key stops working once another active key exists.""" + entry = create_api_key(name="temp-key", key_file=self.key_file) + revoked = entry["key"] + revoke_api_key("temp-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, + ) + + 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 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()