Skip to content

fix: reload approved OAuth API keys from DB on startup#104

Open
piyushdotcomm wants to merge 1 commit intosugarlabs:mainfrom
piyushdotcomm:fix/oauth-key-persistence
Open

fix: reload approved OAuth API keys from DB on startup#104
piyushdotcomm wants to merge 1 commit intosugarlabs:mainfrom
piyushdotcomm:fix/oauth-key-persistence

Conversation

@piyushdotcomm
Copy link
Copy Markdown

@piyushdotcomm piyushdotcomm commented Mar 25, 2026

Problem

After a server restart, settings.API_KEYS is only repopulated from the
API_KEYS environment variable via sync_env_keys_to_db(). OAuth-approved
keys stored in the database are never reloaded into memory.

Since verify_api_key() validates all requests against settings.API_KEYS
(in-memory only), every OAuth user receives a 401 Invalid API key error
after any server restart or redeployment — even if their key is valid in
the database.

Fix

In startup_event() in main.py, after calling sync_env_keys_to_db(db),
query all approved and active API keys from the database and load them into
settings.API_KEYS:

approved_keys = db.query(APIKey).filter(
    APIKey.approved == True,
    APIKey.is_active == True
).all()
for key_obj in approved_keys:
    if key_obj.key not in settings.API_KEYS:
        settings.API_KEYS[key_obj.key] = {
            "name": key_obj.name,
            "can_change_model": key_obj.can_change_model
        }

This ensures all OAuth-issued keys are always available in memory after
startup, regardless of whether the server was restarted.

Fixes #102

After a server restart, settings.API_KEYS was only populated from the
API_KEYS environment variable via sync_env_keys_to_db(). OAuth-approved
keys stored in the database were not reloaded, causing all OAuth users
to receive 401 Invalid API key on every restart.

This fix queries all approved and active API keys from the database at
startup and loads them into settings.API_KEYS, ensuring OAuth users
retain access across restarts and redeployments.

Fixes: sugarlabs#102
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.

bug: OAuth-authenticated users lose API access after every server restart

1 participant