Skip to content

fix(environments): Reject inactive or expired server API keys - #9204

Open
Ishkirat-Singh wants to merge 1 commit into
Flagsmith:mainfrom
Ishkirat-Singh:fix/reject-invalid-environment-api-keys
Open

Ishkirat-Singh wants to merge 1 commit into
Flagsmith:mainfrom
Ishkirat-Singh:fix/reject-invalid-environment-api-keys

Conversation

@Ishkirat-Singh

Copy link
Copy Markdown

Root cause

EnvironmentKeyAuthentication.authenticate() resolves the X-Environment-Key header through Environment.get_from_cache(). That lookup matched server-side keys with api_keys__key=api_key only, so EnvironmentAPIKey.active and EnvironmentAPIKey.expires_at were never consulted. A deactivated or expired server key authenticated exactly like a valid one until its row was deleted, while the hosted Edge API already rejected such keys via is_valid.

Fixing only the initial lookup was not enough: the resolved environment is cached per API key for ENVIRONMENT_CACHE_SECONDS, so an environment cached while the key was valid would keep authenticating after the key was deactivated or deleted.

Changes

  • Environment.get_from_cache() now only matches server-side keys that are active and not expired (single filter, so the conditions apply to the same api_keys join rather than separate ones).
  • EnvironmentAPIKey now invalidates the cached environment (and the bad-key cache) when the key is updated or deleted, so deactivation and deletion take effect on the next request instead of after the cache TTL. This mirrors how Environment.clear_environment_cache already handles environment updates.
  • Added regression tests covering a deactivated key, an expired key, and deactivation/deletion of a key whose environment has already been cached.

Time-based expiry is enforced when the environment is loaded: an environment already in the cache can keep authenticating for at most ENVIRONMENT_CACHE_SECONDS (60s by default) past the key's expiry. Deactivation and deletion are immediate because the cache entry is invalidated.

How to test

Automated:

pytest tests/unit/features/test_unit_features_views.py -k server_api_key

All four tests fail on main with assert 200 == 403 and pass with this change. The surrounding suites (tests/unit/features/test_unit_features_views.py, tests/unit/environments/test_unit_environments_authentication.py, tests/unit/environments/test_unit_environments_views_sdk_environment.py, tests/unit/environments/test_unit_environments_models.py) pass, including the strict query-count tests for the environment document endpoint.

Manual:

  1. Create a server-side SDK key for an environment and confirm GET /api/v1/flags/ with X-Environment-Key: <key> returns 200.
  2. Deactivate the key (PATCH .../api-keys/<id>/ with {"active": false}, or via the dashboard) and repeat the request: it now returns 403 instead of 200.
  3. Repeat with a key whose expires_at is in the past: the request returns 403.

Fixes #8304

@Ishkirat-Singh
Ishkirat-Singh requested a review from a team as a code owner December 1, 2026 03:49
@Ishkirat-Singh
Ishkirat-Singh requested review from emyller and removed request for a team December 1, 2026 03:49
@vercel

vercel Bot commented Dec 1, 2026

Copy link
Copy Markdown

@Ishkirat-Singh is attempting to deploy a commit to the Flagsmith Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions github-actions Bot added the api Issue related to the REST API label Dec 1, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

2 issues found across 2 files

Confidence score: 3/5

  • api/environments/models.py invalidates only the updating worker’s LocMemCache, so other Gunicorn workers can keep authenticating with the old Environment for up to 60 seconds. Use a shared cache or cross-worker invalidation.
  • api/environments/models.py lacks an authentication test for an active key with a future expires_at, leaving this query branch vulnerable to regressions. Add coverage for that case.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="api/environments/models.py">

<violation number="1" location="api/environments/models.py:316">
P2: Add an authentication test for an active key with a future `expires_at`; current future-expiry coverage does not exercise this query branch, so a regression could reject valid keys unnoticed.

(Based on your team's feedback about backend diff coverage.)</violation>

<violation number="2" location="api/environments/models.py:733">
P1: With the default `LocMemCache`, this delete affects only the worker handling the key update; other Gunicorn workers keep authenticating from their cached `Environment` until the 60-second TTL. Use shared or cross-worker invalidation so revocation takes effect on every worker.</violation>
</file>

Tip: cubic used a learning from your PR history. Let your coding agent read cubic learnings directly with the cubic MCP.

Re-trigger cubic

self._clear_caches()

def _clear_caches(self) -> None:
environment_cache.delete(self.key)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: With the default LocMemCache, this delete affects only the worker handling the key update; other Gunicorn workers keep authenticating from their cached Environment until the 60-second TTL. Use shared or cross-worker invalidation so revocation takes effect on every worker.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At api/environments/models.py, line 733:

<comment>With the default `LocMemCache`, this delete affects only the worker handling the key update; other Gunicorn workers keep authenticating from their cached `Environment` until the 60-second TTL. Use shared or cross-worker invalidation so revocation takes effect on every worker.</comment>

<file context>
@@ -713,6 +721,18 @@ def natural_key(self):  # type: ignore[no-untyped-def]
+        self._clear_caches()
+
+    def _clear_caches(self) -> None:
+        environment_cache.delete(self.key)
+        bad_environments_cache.delete(self.key)
+
</file context>

& Q(api_keys__active=True)
& (
Q(api_keys__expires_at__isnull=True)
| Q(api_keys__expires_at__gt=timezone.now())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Add an authentication test for an active key with a future expires_at; current future-expiry coverage does not exercise this query branch, so a regression could reject valid keys unnoticed.

(Based on your team's feedback about backend diff coverage.)

View Feedback

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At api/environments/models.py, line 316:

<comment>Add an authentication test for an active key with a future `expires_at`; current future-expiry coverage does not exercise this query branch, so a regression could reject valid keys unnoticed.

(Based on your team's feedback about backend diff coverage.) </comment>

<file context>
@@ -307,7 +307,15 @@ def get_from_cache(cls, api_key: str | None) -> "Environment | None":
+                & Q(api_keys__active=True)
+                & (
+                    Q(api_keys__expires_at__isnull=True)
+                    | Q(api_keys__expires_at__gt=timezone.now())
+                )
+            )
</file context>

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

Labels

api Issue related to the REST API

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Deactivated or expired EnvironmentAPIKeys still authenticate against SDK endpoints

1 participant