Repository navigation
fix(environments): Reject inactive or expired server API keys - #9204
Ishkirat-Singh wants to merge 1 commit into
Conversation
|
@Ishkirat-Singh is attempting to deploy a commit to the Flagsmith Team on Vercel. A member of the Team first needs to authorize it. |
There was a problem hiding this comment.
2 issues found across 2 files
Confidence score: 3/5
api/environments/models.pyinvalidates only the updating worker’sLocMemCache, so other Gunicorn workers can keep authenticating with the oldEnvironmentfor up to 60 seconds. Use a shared cache or cross-worker invalidation.api/environments/models.pylacks an authentication test for an active key with a futureexpires_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) |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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.)
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>
Root cause
EnvironmentKeyAuthentication.authenticate()resolves theX-Environment-Keyheader throughEnvironment.get_from_cache(). That lookup matched server-side keys withapi_keys__key=api_keyonly, soEnvironmentAPIKey.activeandEnvironmentAPIKey.expires_atwere 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 viais_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 sameapi_keysjoin rather than separate ones).EnvironmentAPIKeynow 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 howEnvironment.clear_environment_cachealready handles environment updates.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:
All four tests fail on
mainwithassert 200 == 403and 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:
GET /api/v1/flags/withX-Environment-Key: <key>returns 200.PATCH .../api-keys/<id>/with{"active": false}, or via the dashboard) and repeat the request: it now returns 403 instead of 200.expires_atis in the past: the request returns 403.Fixes #8304