Skip to content

feat(auth): accept Keycloak access tokens next to API-issued ones - #728

Draft
ThbltLmr wants to merge 1 commit into
mainfrom
feat/keycloak
Draft

ThbltLmr wants to merge 1 commit into
mainfrom
feat/keycloak

Conversation

@ThbltLmr

@ThbltLmr ThbltLmr commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator
  • Accept Keycloak access tokens alongside API-issued tokens so platform login can migrate without changing cameras, the engine, the annotator or scripts.
  • Verify Keycloak signatures and claims locally, then introspect each authenticated request so logout or revocation takes effect on the next request. Map admin / operator / viewer to API scopes admin / agent / user, using the organization_id claim for organization access.
  • Camera tokens are unchanged. Legacy user tokens remain enabled by default; LEGACY_USER_TOKENS_ENABLED=false rejects them and disables /login/creds with a 410.
  • Invalid tokens return 401; Keycloak outages return 503 with a 10-second backoff. /login/validate now returns a string sub and auth_source. Swagger authorization takes a pasted bearer token.

Set KEYCLOAK_ISSUER and KEYCLOAK_CLIENT_SECRET to enable Keycloak. KEYCLOAK_BACKCHANNEL_URL can point to its internal Docker address.

Tests cover token validation, role mapping, legacy compatibility, revocation and outage handling with mocked Keycloak responses. Local suite: 803 passed, 1 skipped. Logout was also checked against the envdev Keycloak.

Related: pyronear/new-pyro-platform#295, pyronear/pyro-envdev#68.

Demo

Keycloak token accepted by /login/validate, then rejected after an admin logs the user out.

keycloak-api-demo.mp4

Platform login through Keycloak and authenticated API calls. The initial 401 is a platform request sent without an Authorization header, tracked in pyronear/new-pyro-platform#295.

keycloak-platform-demo.mp4

@codecov

codecov Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.29630% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.77%. Comparing base (eaa40e8) to head (de86cc4).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
src/app/core/keycloak.py 90.78% 7 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #728      +/-   ##
==========================================
+ Coverage   95.68%   95.77%   +0.08%     
==========================================
  Files          65       66       +1     
  Lines        3685     3831     +146     
==========================================
+ Hits         3526     3669     +143     
- Misses        159      162       +3     
Flag Coverage Δ
backend 95.92% <96.29%> (+0.08%) ⬆️
client 91.83% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@MateoLostanlen

MateoLostanlen commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

@ThbltLmr is this still in draft ? no rush just to organiez reviews :)

@ThbltLmr

ThbltLmr commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

@ThbltLmr is this still in draft ? no rush just to organiez reviews :)

It's ready for review! but the matching PRs on the dev env and the platform are still in draft, so I matched their status (the API PR should not be merged before the dev env side I assume)

@fe51 fe51 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @ThbltLmr, thanks a lot for thoses exciting changes

The approach is nice. I tested it locally with the envdev stack and the platform branch: Keycloak login, organization isolation and role restrictions all behave as expected.

What is blocking (and related to a branch recentrly merged after your last commit)

  • The branch conflicts with main. The textual conflicts are trivial (main.py, imports and decode_token in dependencies.py).
  • After the rebase, POST /shares/ (pyronear/pyro-api#731) will break for Keycloak users: it stores created_by=token_payload.sub in an integer column with a foreign key to users.id, but a Keycloak sub is a UUID and the user has no row in users. Suggestion: make created_by a string holding the token subject, without the foreign key, and add a test creating a share with a Keycloak token.

Non-blocking

A single introspection or JWKS failure triggers a 10 s 503 for every Keycloak user of the process. Fine as a first version; we could later trip only after several consecutive failures.

To keep in mind for follow-ups

  • Set LEGACY_USER_TOKENS_ENABLED=false in production once the remaining clients (envdev init script and ETL, notebooks, pyro-annotator) are migrated.
  • Then rename agent / user to operator / viewer, and remove the users table and the /users and /login/creds endpoints.
    -Move cameras to Keycloak.
  • organization_id comes from Keycloak and is not checked against the database; a realm admin is an API super-admin. Acceptable for now.

Reconstruct PR #728 on current main while retaining newer camera image cleanup, share functionality, and service shutdown handling.

Store share creators as token subjects without a users foreign key. Add a data-preserving Alembic migration and regression coverage for Keycloak shares, legacy tokens, authorization, organization isolation, and migration round trips.
import sqlalchemy as sa
from alembic import op

revision: str = "a9c6d1e5f7b4"
from alembic import op

revision: str = "a9c6d1e5f7b4"
down_revision: Union[str, None] = "f8b5c0d4e6a3"

revision: str = "a9c6d1e5f7b4"
down_revision: Union[str, None] = "f8b5c0d4e6a3"
branch_labels: Union[str, Sequence[str], None] = None
revision: str = "a9c6d1e5f7b4"
down_revision: Union[str, None] = "f8b5c0d4e6a3"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
@fe51

fe51 commented Nov 18, 2026

Copy link
Copy Markdown
Member

Thanks for the rework, 2 previous blocking points are addressed (rebuilt on main, created_by stored as the token subject with migration and tests).

One new blocker, caused by pyronear/pyro-api#741 merged on main this morning: its migration a9c2e5f7b1d3 and the one in this PR (a9c6d1e5f7b4) both revise f8b5c0d4e6a3. Git sees no conflict, but Alembic ends up with two heads and alembic upgrade head fails at startup.

Suggested fix:

  • rebase on main;
  • set down_revision = "a9c2e5f7b1d3" in the share creator migration (the two touch different tables, so the order does not matter);
  • update the parent assertion in src/tests/test_share_migration.py (line 23), keeping f8b5c0d4e6a3 as the revision the test upgrades from.

I will be happy to approve once this is done :)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants