fix(tenant): guard against sanitization collisions with production tenant

The request-level tenant guard compared the raw user string exactly
(user == PRODUCTION_TENANT), but all local namespaces (Qdrant
collections, Redis keys) are derived through sanitize_user_id(), which
lowercases and strips/maps punctuation. Case or punctuation variants
("JPMSchweitzer", "jpmschweitzer.", " jpmschweitzer") therefore passed
the guard yet resolved to the production namespaces, letting a dev
instance on the shared services read/write production tenant data.

- context.py: compare sanitize_user_id(user) against the sanitized
  production tenant; expose the guard as public apply_tenant_guard()
- config.py: startup refusal validator uses the same sanitized
  comparison, so a colliding DEFAULT_USER refuses startup loudly
  instead of relying on the allowlist fallback
- tests: variant matrix at both config and request-context level,
  plus a non-colliding passthrough case

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-14 11:23:36 +02:00
co-authored by Claude Fable 5
parent b47c5b9281
commit e8e5d367b6
3 changed files with 83 additions and 4 deletions
+10 -1
View File
@@ -224,10 +224,19 @@ class Config(BaseSettings):
This is the hard stop of the tenant isolation guard: a dev/test
instance must never be able to read or write the production
tenant's data in the shared services.
The comparison is on the sanitized form: namespaces are derived
through sanitize_user_id(), so variants like "JPMSchweitzer" or
"jpmschweitzer." collide with the production namespaces and are
refused just as loudly.
"""
from src.core.multi_tenancy import sanitize_user_id
if (
self.ENVIRONMENT != Environment.PRODUCTION
and self.DEFAULT_USER == PRODUCTION_TENANT
and self.DEFAULT_USER is not None
and sanitize_user_id(self.DEFAULT_USER)
== sanitize_user_id(PRODUCTION_TENANT)
):
raise ValueError(
f"Refusing to start: ENVIRONMENT={self.ENVIRONMENT.value} is "