Skip to content

feat: implement API key authentication, CLI management, and endpoint protection - #24

Draft
iceblue03 wants to merge 3 commits into
kodelyx:mainfrom
iceblue03:feat/api-key-authentication
Draft

iceblue03 wants to merge 3 commits into
kodelyx:mainfrom
iceblue03:feat/api-key-authentication

Conversation

@iceblue03

@iceblue03 iceblue03 commented Oct 18, 2026 •

Copy link
Copy Markdown

Summary

Adds optional API key authentication to the FastAPI surface, a key subcommand to
manage keys from the terminal, and a test suite covering both. Enforcement is
off until a key exists, so an existing single-user deployment keeps working
with no configuration and no flag.

Motivation

The server exposes image and video generation over HTTP, and its default bind is
127.0.0.1. The moment it is started with --host 0.0.0.0 — a container, a LAN
box, a NAS — every route that spends Veo/Imagen credits is reachable by anyone
who can reach the port, with no credential and no audit trail. This adds that
credential, without breaking the local single-user workflow the README documents.

Detailed changes

flow_agent/auth.py (new). Key generation (secrets.token_urlsafe(32)),
constant-time verification, an on-disk store written atomically via a temp file
and os.replace with a best-effort 0600, and FLOW_API_KEY as an optional
environment master key.

flow_agent/api.py. Every credit-spending and account-reading route takes
dependencies=[Depends(verify_api_key)] — 14 path operations. GET /, /health
and /openapi.json stay public, so probes and the docs page keep working.

main.py. A key subcommand group: create (name/alias, prints the key
once), list (state, alias, masked key, creation time), revoke (deactivate),
delete (remove permanently). Both matchers accept the key string or the alias,
and the output never echoes a key string back to the terminal — only its masked
form.

tests/test_api_auth.py. 17 cases: pass-through with no keys, 401 for a
missing/invalid credential, both accepted headers, the master key, revocation,
public routes, and the failure modes listed below.

Verification

$ python -m pytest tests/test_api_auth.py -q
17 passed
$ python -m pytest tests -q
2 failed, 92 passed

The two failures are in tests/test_engine.py
(test_command_drops_arguments_that_were_not_given,
test_command_keeps_falsy_values_that_are_not_absent) and are pre-existing:
a pristine worktree at the branch's parent commit fails the same two. They are
untouched by this change.

Behaviour matrix, verified end-to-end through TestClient against the fixed
revision:

Scenario Before After
No keys registered, no credential 200 200 (unchanged)
Key registered, no credential 401 401
Authorization: Bearer <key> 200 200
X-API-Key: <key> 200 200
?api_key=<key> 200 — key copied into logs 401
Non-ASCII credential 500 401
Non-ASCII FLOW_API_KEY, ASCII request 500 401
Key store corrupt / unreadable 200, enforcement silently off 503
key create --name <existing> duplicate created silently refused, exit 1
key delete <alias shared by two> deleted both refused, exit 1

Design decisions

  • No enforcement switch. is_auth_enforced() is len(get_active_keys()) > 0;
    enforcement follows from key presence. Turning it off means revoking or
    deleting every key (and unsetting FLOW_API_KEY), which is the state a fresh
    clone is already in.
  • Fail closed. A store that exists but cannot be read or parsed raises
    KeyStoreError; requests answer 503 rather than falling back to no
    enforcement. Availability loss here is visible and fixable; an unauthorised
    generation against someone's billing account is neither.
  • Headers only. A query-string credential is not a convenience worth the
    leak: it lands in access logs, shell history and Referer headers, and it is
    unnecessary here because media routes are not guarded.

Known gaps

  • No user-facing documentation yet. README.md, docs/API_REFERENCE.md and
    docs/CLI_REFERENCE.md do not mention the key group or the auth contract —
    in particular that zero registered keys means no authentication, which an
    operator binding 0.0.0.0 needs to know. Worth a follow-up before this is
    advertised as a security feature.

  • Media routes (GET /v1/media/{id}) remain public. If they are ever guarded,
    a header-only rule needs rethinking for plain browser downloads, which cannot
    set one.

  • --host 0.0.0.0 with no keys registered is still an unauthenticated public
    server; the code cannot refuse to start, because that is also the documented
    local default path.

  • Interacts with feat: add direct image stream preview and web dashboard for OpenAI image API #23 (feat/openai-image-stream-preview). The dashboard that
    PR adds generates through this same route: flow_agent/api.py:877 calls
    fetch('/v1/images/generations', ...) and that file carries no Authorization
    or X-API-Key header anywhere, so registering a key makes the dashboard answer
    401 while the page itself stays public. That is enforcement working as
    designed, but the dashboard then needs a way to authenticate, and a secret
    inside page script is not one. The two PRs also conflict: both sit on main at
    7d7abdd, and
    git merge-tree --write-tree origin/feat/openai-image-stream-preview origin/feat/api-key-authentication
    reports CONFLICT (content) in flow-agent/flow_agent/api.py, because feat: add direct image stream preview and web dashboard for OpenAI image API #23
    rewrites the same route decorators this PR adds
    dependencies=[Depends(verify_api_key)] to. Whichever of the two merges first,
    the other needs that file rebased by hand.

AI disclosure

The code, the English rewrite and the test suite were produced with AI
assistance; the author reviewed and owns the result.

…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
@iceblue03 iceblue03 changed the title feat: implement API key authentication, CLI management, and endpoint … feat: implement API key authentication, CLI management, and endpoint protection Oct 18, 2026
…redentials

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant