Repository navigation
fix(tenancy): isole réellement la base par search_path PostgreSQL - #299
Conversation
TenantAwareDB envoyait le SET search_path en chaîne brute : SQLAlchemy 2.x lève ArgumentError, l'exception était avalée en debug et isolate_db n'isolait rien, sans alerte. Désormais : - search_path posé via set_config(..., true) avec paramètre lié sur un identifiant validé (fullmatch, 1 à 63 car.) puis cité : portée transaction, donc aucune fuite vers la requête suivante du pool, ré-appliqué après un commit intermédiaire (after_begin) ; - une erreur sur PostgreSQL est propagée ; SQLite, MySQL et MongoDB sont ignorés explicitement (détection du dialecte) ; - execute/fetch_* acceptent une chaîne (convertie en text()) ; - le tenant est validé aussi pour le cache et le scheduler : un tenant "*" (en-tête X-Tenant-ID) permettait cache.clear()/keys() sur tous les tenants ; - scheduler : un job sans job_id est préfixé par le tenant (sinon deux tenants se remplaçaient) et s'exécute avec le ContextVar du tenant d'enregistrement. Risque connu, inchangé : le tenant provient d'un en-tête HTTP non authentifié (TenantMiddleware) ; tout client peut choisir son tenant. Aucune injection SQL possible via tenant_id (regex stricte + paramètre lié). Le schéma du tenant doit exister, sinon PostgreSQL retombe sur public.
La chaîne affectée directement à pool._reset_on_return n'était égale à aucune valeur ResetStyle : le pool n'effectuait plus aucun reset au retour de connexion (ni rollback, ni commit). L'option native est maintenant transmise au moteur, qui la convertit et rejette les valeurs invalides au démarrage.
…ntrée - AUTOCOMMIT (isolation_level ou execution_options) : set_config local était perdu sans erreur et les requêtes lisaient public. Le search_path est maintenant relu dans la même transaction ; s'il n'a pas persisté, une RuntimeError explicite est levée (fail-closed, valable aussi derrière un pooler en mode statement). Choix assumé : pas de set_config de session, qui fuirait entre requêtes du pool. - tenants réservés refusés pour DB, cache et scheduler : public, information_schema, pg_* (insensible à la casse). - TenantMiddleware renvoie 400 JSON (invalid_tenant) dès l'entrée quand l'en-tête ou le sous-domaine est invalide ; l'absence d'en-tête garde le tenant par défaut, et rien ne change si la tenancy est désactivée. - pool_reset_on_return normalisé (casse, none/null/false, true) et validé au démarrage pour les adaptateurs sync et async. - scheduler : un callable objet à __call__ async conserve le tenant d'enregistrement.
Reviewer's GuideCette PR rend l’isolation multi-tenant PostgreSQL effective en configurant et vérifiant Sequence diagram for PostgreSQL tenant-isolated database accesssequenceDiagram
participant Caller
participant TenantAwareDB
participant AsyncSession
participant PostgreSQL
Caller->>TenantAwareDB: execute(query)
TenantAwareDB->>AsyncSession: _set_tenant_schema(sess)
TenantAwareDB->>PostgreSQL: set_config('search_path', :sp, true)
PostgreSQL-->>TenantAwareDB: transaction-scoped search_path
TenantAwareDB->>PostgreSQL: current_setting('search_path')
PostgreSQL-->>TenantAwareDB: tenant_schema, public
TenantAwareDB->>PostgreSQL: execute(query)
PostgreSQL-->>Caller: tenant-scoped result
AsyncSession-->>PostgreSQL: commit or rollback
PostgreSQL-->>AsyncSession: transaction ends, search_path discarded
Sequence diagram for tenant validation and request rejectionsequenceDiagram
actor Client
participant Middleware
participant TenantValidation
participant Handler
Client->>Middleware: HTTP request with X-Tenant-ID
Middleware->>TenantValidation: _validate_tenant(tenant_id)
alt invalid or reserved tenant
TenantValidation-->>Middleware: ValueError
Middleware-->>Client: 400 {error: invalid_tenant}
else valid tenant
TenantValidation-->>Middleware: validated tenant
Middleware->>Handler: call_next(request)
Handler-->>Client: response
end
Sequence diagram for tenant-aware scheduled job executionsequenceDiagram
participant Application
participant TenantAwareScheduler
participant Scheduler
participant Job
participant ContextVar
Application->>TenantAwareScheduler: add_job(func)
TenantAwareScheduler->>TenantAwareScheduler: _validate_tenant(tenant_id)
TenantAwareScheduler->>Scheduler: add_job(_bind_tenant(func, tenant), job_id)
Scheduler-->>Application: registered tenant-prefixed job
Scheduler->>Job: invoke wrapped callable
Job->>ContextVar: set tenant
Job-->>Job: access tenant-aware DB or cache
Job->>ContextVar: reset tenant
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
️✅ There are no secrets present in this pull request anymore.If these secrets were true positive and are still valid, we highly recommend you to revoke them. 🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request. |
There was a problem hiding this comment.
Hey - I've found 8 issues
Fixed security issues:
- SQL injection from untrusted request data interpolated into raw SQL strings (link)
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="xcore/kernel/tenancy/middleware.py" line_range="63" />
<code_context>
+ "detail": "Identifiant de tenant invalide ou réservé.",
+ },
+ )
+ tenant_id = requested or self._cfg.default_tenant
request.state.tenant_id = tenant_id
return await call_next(request)
</code_context>
<issue_to_address>
**Clients can select another tenant**
When a caller with a valid API key sends another tenant’s valid ID in `X-Tenant-ID`, `TenantMiddleware` checks only the syntax of `X-Tenant-ID`, then the router passes it to `PluginSupervisor`, which sets the tenant `ContextVar` used by `TenantAwareDB`; a caller with a valid API key can therefore choose another tenant and read its data.
Authorize the requested tenant against the authenticated principal before passing it to the supervisor.
</issue_to_address>
### Comment 2
<location path="xcore/kernel/tenancy/services.py" line_range="211" />
<code_context>
+
+ from sqlalchemy import event, text
+
+ params = {"sp": f'"{tenant}", public'}
+ await _maybe_await(sess.execute(text(_SET_SEARCH_PATH_SQL), params))
+ # Preuve que la valeur tient : en AUTOCOMMIT (ou derrière un pooler
</code_context>
<issue_to_address>
**Tenant queries reach shared tables**
When the tenant schema or a queried table is absent, `_set_tenant_schema` puts `public` in `search_path`, and PostgreSQL skips missing schemas and resolves absent tenant tables there. Tenant-aware queries therefore read or modify shared rows instead of failing closed.
Remove `public` from the tenant search path and ensure missing tenant schemas or tables fail closed.
Also at `xcore/kernel/tenancy/services.py:173`, `xcore/kernel/tenancy/services.py:212`.
</issue_to_address>
### Comment 3
<location path="xcore/kernel/tenancy/services.py" line_range="211" />
<code_context>
+
+ from sqlalchemy import event, text
+
+ params = {"sp": f'"{tenant}", public'}
+ await _maybe_await(sess.execute(text(_SET_SEARCH_PATH_SQL), params))
+ # Preuve que la valeur tient : en AUTOCOMMIT (ou derrière un pooler
</code_context>
<issue_to_address>
**Temporary tables shadow tenant tables**
When a tenant creates a temporary table and another tenant reuses that pooled connection, postgreSQL searches the connection's temporary schema ahead of `search_path` when `pg_temp` is omitted. An unqualified query therefore resolves to the earlier tenant's temporary table, exposing or corrupting tenant data.
Set the search path so the connection's temporary schema cannot shadow tenant relations.
</issue_to_address>
### Comment 4
<location path="xcore/kernel/tenancy/middleware.py" line_range="63" />
<code_context>
+ "detail": "Identifiant de tenant invalide ou réservé.",
+ },
+ )
+ tenant_id = requested or self._cfg.default_tenant
request.state.tenant_id = tenant_id
return await call_next(request)
</code_context>
<issue_to_address>
**Invalid defaults turn requests into errors**
When a request omits the tenant header and subdomain and `default_tenant` is malformed or reserved, `TenantMiddleware` assigns `default_tenant` without validating it, so tenant-aware services raise `ValueError` and otherwise ordinary requests become server errors.
Validate the configured default tenant before assigning it to the request.
</issue_to_address>
### Comment 5
<location path="xcore/kernel/tenancy/services.py" line_range="292-293" />
<code_context>
+ getattr(func, "__call__", None)
+ ):
+
+ @functools.wraps(func)
+ async def _async_wrapper(*a: Any, **k: Any) -> Any:
+ token = _current_tenant_id.set(tenant)
+ try:
</code_context>
<issue_to_address>
**Async callable objects cannot be wrapped**
When `TenantAwareScheduler.add_job` receives an async callable object without `__name__`, `_bind_tenant` applies `functools.wraps(func)` to the callable instance, which has no `__name__`; it raises `AttributeError` before the scheduler receives the job.
Wrap callable instances without requiring function-only attributes such as `__name__`.
</issue_to_address>
### Comment 6
<location path="xcore/services/database/adapters/async_sql.py" line_range="80-84" />
<code_context>
engine_kwargs.pop("pool_timeout", None)
engine_kwargs.pop("pool_recycle", None)
engine_kwargs.pop("pool_pre_ping", None)
+ else:
+ # Option native du pool : SQLAlchemy convertit "rollback"/"commit"/
+ # "none" en ResetStyle. Affecter la chaîne à pool._reset_on_return
+ # n'est comparé à aucune des valeurs attendues => plus aucun reset.
+ engine_kwargs["pool_reset_on_return"] = normalize_pool_reset(
+ self._pool_reset_on_return
+ )
</code_context>
<issue_to_address>
**SQLite reset settings are ignored**
When an async SQLite adapter uses a non-default or invalid `pool_reset_on_return` value, the SQLite branch skips `normalize_pool_reset` and does not pass the setting to the engine. Invalid values are accepted and configured reset behavior is ignored.
Normalize and pass `pool_reset_on_return` in the async SQLite branch.
</issue_to_address>
### Comment 7
<location path="xcore/kernel/tenancy/middleware.py" line_range="50" />
<code_context>
+ requested = request.headers.get(self._cfg.header) or (
+ self._from_subdomain(request) if self._cfg.subdomain else None
)
+ if requested:
+ # Valeur fournie par le client (non authentifiée) : rejet immédiat
+ # plutôt qu'une ValueError tardive dans DB/cache/scheduler.
</code_context>
<issue_to_address>
**Empty tenant headers select the default**
When the client sends an empty tenant header and no usable subdomain tenant is selected, `requested` is falsey, so `TenantMiddleware` skips `_validate_tenant` and selects the configured default instead of returning the promised 400 response.
Treat an explicitly supplied empty tenant header as invalid and return the 400 response.
Also at `xcore/kernel/tenancy/middleware.py:47-49`.
</issue_to_address>
### Comment 8
<location path="xcore/kernel/tenancy/services.py" line_range="237-240" />
<code_context>
yield sess
- async def execute(self, query: str, *args, **kwargs) -> Any:
+ async def execute(self, query: Any, *args, **kwargs) -> Any:
async with self._db.session() as sess:
await self._set_tenant_schema(sess)
- return await sess.execute(query, *args, **kwargs)
+ return await sess.execute(_as_statement(query), *args, **kwargs)
- async def fetch_one(self, query: str, *args, **kwargs) -> Any:
</code_context>
<issue_to_address>
**Legacy tenancy tests fail**
When the integration test suite runs the unchanged tenancy tests, `TenantAwareDB.execute` now turns SQL strings into `TextClause` objects, but the existing integration tests still search their recorded `execute` arguments for string fragments from the removed `SET search_path` SQL. The fake sessions also lack `get_bind()`, so schema setup is skipped and the tests fail instead of validating the new behavior.
Rewrite the integration tests to provide a PostgreSQL-like session and assert the new `set_config` behavior, or otherwise update their fakes and assertions for `TextClause` arguments.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 8 findings to address first, and the middleware accepts the client-supplied tenant header as the tenant identity, and the new database routing makes that value select a PostgreSQL schema; a caller could request another tenant’s schema and read its rows. Reverting stops future routing but cannot retract data already exposed, and the tenant-selection policy itself is the trust boundary.
Blocking findings: xcore/kernel/tenancy/middleware.py:63, xcore/kernel/tenancy/services.py:211, xcore/kernel/tenancy/services.py:211, xcore/kernel/tenancy/middleware.py:63, xcore/kernel/tenancy/services.py:293, and 3 more
| "detail": "Identifiant de tenant invalide ou réservé.", | ||
| }, | ||
| ) | ||
| tenant_id = requested or self._cfg.default_tenant |
There was a problem hiding this comment.
🟠 High · Clients can select another tenant
When a caller with a valid API key sends another tenant’s valid ID in X-Tenant-ID, TenantMiddleware checks only the syntax of X-Tenant-ID, then the router passes it to PluginSupervisor, which sets the tenant ContextVar used by TenantAwareDB; a caller with a valid API key can therefore choose another tenant and read its data.
Authorize the requested tenant against the authenticated principal before passing it to the supervisor.
Prompt for AI agents
In `xcore/kernel/tenancy/middleware.py` at line 63:
**Clients can select another tenant**
When a caller with a valid API key sends another tenant’s valid ID in `X-Tenant-ID`, `TenantMiddleware` checks only the syntax of `X-Tenant-ID`, then the router passes it to `PluginSupervisor`, which sets the tenant `ContextVar` used by `TenantAwareDB`; a caller with a valid API key can therefore choose another tenant and read its data.
Authorize the requested tenant against the authenticated principal before passing it to the supervisor.|
|
||
| from sqlalchemy import event, text | ||
|
|
||
| params = {"sp": f'"{tenant}", public'} |
There was a problem hiding this comment.
🔴 Critical · Tenant queries reach shared tables
When the tenant schema or a queried table is absent, _set_tenant_schema puts public in search_path, and PostgreSQL skips missing schemas and resolves absent tenant tables there. Tenant-aware queries therefore read or modify shared rows instead of failing closed.
Remove public from the tenant search path and ensure missing tenant schemas or tables fail closed.
Also at xcore/kernel/tenancy/services.py:173, xcore/kernel/tenancy/services.py:212.
Prompt for AI agents
In `xcore/kernel/tenancy/services.py` at line 211:
**Tenant queries reach shared tables**
When the tenant schema or a queried table is absent, `_set_tenant_schema` puts `public` in `search_path`, and PostgreSQL skips missing schemas and resolves absent tenant tables there. Tenant-aware queries therefore read or modify shared rows instead of failing closed.
Remove `public` from the tenant search path and ensure missing tenant schemas or tables fail closed.
Also at `xcore/kernel/tenancy/services.py:173`, `xcore/kernel/tenancy/services.py:212`.|
|
||
| from sqlalchemy import event, text | ||
|
|
||
| params = {"sp": f'"{tenant}", public'} |
There was a problem hiding this comment.
🟠 High · Temporary tables shadow tenant tables
When a tenant creates a temporary table and another tenant reuses that pooled connection, postgreSQL searches the connection's temporary schema ahead of search_path when pg_temp is omitted. An unqualified query therefore resolves to the earlier tenant's temporary table, exposing or corrupting tenant data.
Set the search path so the connection's temporary schema cannot shadow tenant relations.
Prompt for AI agents
In `xcore/kernel/tenancy/services.py` at line 211:
**Temporary tables shadow tenant tables**
When a tenant creates a temporary table and another tenant reuses that pooled connection, postgreSQL searches the connection's temporary schema ahead of `search_path` when `pg_temp` is omitted. An unqualified query therefore resolves to the earlier tenant's temporary table, exposing or corrupting tenant data.
Set the search path so the connection's temporary schema cannot shadow tenant relations.| "detail": "Identifiant de tenant invalide ou réservé.", | ||
| }, | ||
| ) | ||
| tenant_id = requested or self._cfg.default_tenant |
There was a problem hiding this comment.
🟡 Medium · Invalid defaults turn requests into errors
When a request omits the tenant header and subdomain and default_tenant is malformed or reserved, TenantMiddleware assigns default_tenant without validating it, so tenant-aware services raise ValueError and otherwise ordinary requests become server errors.
Validate the configured default tenant before assigning it to the request.
Prompt for AI agents
In `xcore/kernel/tenancy/middleware.py` at line 63:
**Invalid defaults turn requests into errors**
When a request omits the tenant header and subdomain and `default_tenant` is malformed or reserved, `TenantMiddleware` assigns `default_tenant` without validating it, so tenant-aware services raise `ValueError` and otherwise ordinary requests become server errors.
Validate the configured default tenant before assigning it to the request.| @functools.wraps(func) | ||
| async def _async_wrapper(*a: Any, **k: Any) -> Any: |
There was a problem hiding this comment.
🟡 Medium · Async callable objects cannot be wrapped
When TenantAwareScheduler.add_job receives an async callable object without __name__, _bind_tenant applies functools.wraps(func) to the callable instance, which has no __name__; it raises AttributeError before the scheduler receives the job.
Wrap callable instances without requiring function-only attributes such as __name__.
Prompt for AI agents
In `xcore/kernel/tenancy/services.py` at lines 292-293:
**Async callable objects cannot be wrapped**
When `TenantAwareScheduler.add_job` receives an async callable object without `__name__`, `_bind_tenant` applies `functools.wraps(func)` to the callable instance, which has no `__name__`; it raises `AttributeError` before the scheduler receives the job.
Wrap callable instances without requiring function-only attributes such as `__name__`.| else: | ||
| # Option native du pool : SQLAlchemy convertit "rollback"/"commit"/ | ||
| # "none" en ResetStyle. Affecter la chaîne à pool._reset_on_return | ||
| # n'est comparé à aucune des valeurs attendues => plus aucun reset. | ||
| engine_kwargs["pool_reset_on_return"] = normalize_pool_reset( |
There was a problem hiding this comment.
🟡 Medium · SQLite reset settings are ignored
When an async SQLite adapter uses a non-default or invalid pool_reset_on_return value, the SQLite branch skips normalize_pool_reset and does not pass the setting to the engine. Invalid values are accepted and configured reset behavior is ignored.
Normalize and pass pool_reset_on_return in the async SQLite branch.
Prompt for AI agents
In `xcore/services/database/adapters/async_sql.py` at lines 80-84:
**SQLite reset settings are ignored**
When an async SQLite adapter uses a non-default or invalid `pool_reset_on_return` value, the SQLite branch skips `normalize_pool_reset` and does not pass the setting to the engine. Invalid values are accepted and configured reset behavior is ignored.
Normalize and pass `pool_reset_on_return` in the async SQLite branch.| requested = request.headers.get(self._cfg.header) or ( | ||
| self._from_subdomain(request) if self._cfg.subdomain else None | ||
| ) | ||
| if requested: |
There was a problem hiding this comment.
🟡 Medium · Empty tenant headers select the default
When the client sends an empty tenant header and no usable subdomain tenant is selected, requested is falsey, so TenantMiddleware skips _validate_tenant and selects the configured default instead of returning the promised 400 response.
Treat an explicitly supplied empty tenant header as invalid and return the 400 response.
Also at xcore/kernel/tenancy/middleware.py:47-49.
Prompt for AI agents
In `xcore/kernel/tenancy/middleware.py` at line 50:
**Empty tenant headers select the default**
When the client sends an empty tenant header and no usable subdomain tenant is selected, `requested` is falsey, so `TenantMiddleware` skips `_validate_tenant` and selects the configured default instead of returning the promised 400 response.
Treat an explicitly supplied empty tenant header as invalid and return the 400 response.
Also at `xcore/kernel/tenancy/middleware.py:47-49`.Service postgres:16 et XCORE_TEST_PG_URL sur le job de tests ; asyncpg est installé à la demande (absent des dépendances du projet).
Deux tests de TestDBTenantIsolation vérifiaient l'ancienne chaîne SQL brute `SET search_path TO "acme"` envoyée sur n'importe quel backend. Le search_path n'est plus posé que sur PostgreSQL, via set_config(..., true) et un paramètre lié. Le faux backend se déclare PostgreSQL et les assertions portent sur l'appel set_config et sa valeur liée. Ces tests n'avaient pas été relancés (seul tests/unit l'avait été) et faisaient échouer « Quick Test » et la porte de PR. Ils échouent sur l'ancien code.
8a8dfaf to
ebbf4e8
Compare
…entrée de session (#301) ## Ce que ça remédie **Régression introduite par #299** : sur PostgreSQL avec `isolate_db: true`, tout plugin qui fait `async with session.begin():` échouait (`InvalidRequestError: A transaction is already begun`, HTTP 500). `TenantAwareDB._set_tenant_schema` exécutait `set_config` puis `current_setting` **à l'entrée de `session()`**, ce qui déclenchait l'autobegin de SQLAlchemy avant que le plugin n'ouvre sa propre transaction. Avec `isolate_db: false` tout passait. Idiome courant dans les plugins ERP (xstock, xsales, xpurchase…). Mes tests de #299 ne couvraient pas ce cas. ## Correctif `_set_tenant_schema` n'exécute plus aucun SQL à l'entrée de la session : il attache un écouteur `after_begin` qui pose `set_config('search_path', :sp, true)` et relit `current_setting` **au début de chaque transaction** (autobegin, `begin()` du plugin, après commit ou rollback). Toutes les garanties de #299 sont conservées : isolation dans la même transaction que les requêtes du plugin, **échec fermé** (`RuntimeError`) si le `search_path` n'a pas tenu (AUTOCOMMIT, pooler en mode statement), aucune fuite entre requêtes du pool. Si l'adaptateur a déjà ouvert la transaction (option `execution_options`), le `search_path` est posé immédiatement via `run_sync`. ## Tests - Sur PostgreSQL réel, rouges avant correctif : `session.begin()` du plugin, 50 sessions concurrentes de tenants différents sur un pool de 5 (mêlant `begin()`, commit/rollback et requête simple : 0 fuite), AUTOCOMMIT toujours refusé avec `begin()`. - Suite unitaire + intégration : 1469 passés / 15 ignorés (tests PostgreSQL sans `XCORE_TEST_PG_URL`, exécutés par le job CI qui a un service `postgres`), 2 échecs `test_xworker::test_build_app_*` (module `dateutil` absent de l'environnement de test), identiques sans ce changement. `isort` / `black` OK. - 3 tests de #299 supposaient du SQL exécuté à l'entrée de la session : adaptés pour passer par l'écouteur ; un test vérifie qu'aucun `execute` n'a lieu à l'entrée. ## À savoir - Le `search_path` est posé à la première requête de la transaction, plus à l'entrée de session : plus de SQL implicite avant le premier `execute` du plugin. - Non couvert : un plugin qui appelle `begin()` sur une session que l'adaptateur a déjà fait autobégin (cas `execution_options`) échoue toujours ; comportement de l'adaptateur déjà présent avec `isolate_db: false`. ## Summary by Sourcery Defer tenant search-path setup to transaction start so explicit plugin transactions work without compromising database isolation. Bug Fixes: - Prevent tenant session initialization from implicitly opening a transaction, allowing plugins to start explicit transactions with `session.begin()` without errors. - Reapply and validate the tenant-specific PostgreSQL `search_path` at the start of every transaction while preserving fail-closed isolation behavior. Enhancements: - Handle sessions whose transaction was already opened by the adapter while retaining tenant schema isolation. Tests: - Update tenancy unit and integration tests for deferred `after_begin` schema setup, explicit plugin transactions, transaction boundaries, concurrent pooled sessions, and AUTOCOMMIT rejection.
Ce que ça remédie
isolate_db: truen'isolait rien.TenantAwareDBenvoyaitSET search_pathen chaîne brute à SQLAlchemy 2.x :ArgumentError, avalée en debug. Sur un vrai PostgreSQL avecpublic,acmeetbetacontenant la même table, une session du tenantacmelisait la ligne depublic.set_config('search_path', :sp, true)(portée = transaction, valeur liée en paramètre, jamais d'interpolation), sur un tenant validé ([A-Za-z0-9_-]{1,63},fullmatch) et cité :"tenant", public. Aucune fuite vers la requête suivante du pool ; un écouteurafter_beginle ré-applique après uncommit()intermédiaire.execute,fetch_*etsession()sont couverts. Injection testée (a"; DROP SCHEMA public CASCADE; --).search_pathn'a pas tenu (isolation_level: AUTOCOMMIT, pooler en mode statement),RuntimeErrorexplicite au lieu d'une lecture silencieuse depublic.public,information_schema,pg_*(insensible à la casse),*, plus de 63 caractères, saut de ligne — pour la DB, le cache et le scheduler.X-Tenant-IDinvalide → 400{"error":"invalid_tenant"}(sans en-tête : tenant par défaut inchangé).*permettaitkeys()/clear()sur toutes les clés ; refusé.job_idn'était pas préfixé (deux tenants se remplaçaient) et s'exécutait avec le tenantdefault; préfixé et tenant d'enregistrement repris (y compris callable objet à__call__async).pool_reset_on_returnn'était jamais appliqué (la chaîne n'est pas unResetStyle). Passé àcreate_async_engine, valeurs normalisées (ROLLBACK,"None",None), valeur invalide → erreur claire au démarrage.Changements de comportement à connaître
isolate_db: true, la base bascule depublicvers le schéma du tenant. Le schéma doit exister ; sinon PostgreSQL retombe surpublic. Si des tables homonymes sont créées plus tard dans un schéma de tenant, elles masqueront celles depublic.ValueError(et 400 côté HTTP) ; lesjob_idimplicites changent de forme (acme:fn).X-Tenant-ID.Tests
tests/unit/kernel/test_tenancy_isolation_real.py). 50 sessions concurrentes sur 52 schémas, pool de 5 : 0 fuite.XCORE_TEST_PG_URL), 1 échec préexistant surmain(test_extensions.py::test_init_loads_extension). Avec un PostgreSQL réel : 1439 passés.isort/blackOK.TestTenantAwareDBréécrit (les mocks vérifiaient la chaîne SQL brute) sur SQLite réel.testdeci.ymlgagne un servicepostgres:16+XCORE_TEST_PG_URL+pip install asyncpgpour exécuter ces tests ; modification non exécutée avant cette PR (siasyncpgn'a pas de wheel pour une version de Python de la matrice, ce job le dira).Summary by Sourcery
Garantir l’isolation effective des tenants PostgreSQL et renforcer la validation ainsi que la propagation du contexte tenant dans les composants associés.
New Features:
search_path.Bug Fixes:
publiclorsque l’isolation PostgreSQL échoue ou que le mode de connexion ne la garantit pas.*.pool_reset_on_returnet rejeter les valeurs de configuration invalides.Enhancements:
CI:
Tests: