rls-multi-tenant
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTenant isolation that holds, and the test that proves it
真正成立的租户隔离,以及证明它有效的测试
The deliverable is the test, not the policy. The value is an assertion that goes red when
isolation breaks, because every way it breaks here is silent: no error, no warning, no log line,
and a catalog view that still reports the policy enabled.
The behavior below is the Azure SQL Database engine's; section 6 notes where it depends on the
build. Open the runnable checks when you need
the statement behind a message number below, or before changing one.
交付物是测试,而不是策略。 其价值在于提供一条断言:当隔离失效时,该断言会变红,因为这里每一种失效方式都是静默的:没有错误、没有警告、没有日志行,而且目录视图仍会报告策略已启用。
下面描述的是 Azure SQL Database engine 的行为;第 6 节说明了其中哪些部分取决于构建版本。需要查看下文某个消息编号对应的语句,或在修改前进行核对时,请打开可运行的检查。
1. A filter predicate is not the boundary
1. filter predicate
不是隔离边界
filter predicateMicrosoft Learn states it plainly: the application can rows, even if they will be filtered
during any other operation. For a low-privilege user holding tenant id 1, under a filter predicate
only:
INSERT| Statement | Result | What it costs |
|---|---|---|
| succeeds | the row exists, invisible to its author, visible to tenant 2 |
| succeeds | the row moves into another tenant, silently |
| 0 rows affected | the filter protects the read behind a write |
| 0 rows affected | same |
| | the key space of another tenant is probeable |
The first two rows are the leak. The application that wrote them can never read them back and never
delete them, because the filter now hides them from their own author. Recovering them means
disabling the policy.
The last row is separate and smaller. A filter predicate hides rows, not their existence:
on a duplicate key and success on a free one let a caller enumerate another tenant's keys one
attempt at a time. Use identifiers with no guessable ordering.
Msg 2627Microsoft Learn 明确指出:应用程序可以 行,即使这些行在任何其他操作中都会被过滤。对于仅持有 tenant id 1 的低权限用户,在只有 的情况下:
INSERTfilter predicate| 语句 | 结果 | 代价 |
|---|---|---|
| 成功 | 该行存在,但对其作者不可见,而 tenant 2 可以看到 |
| 成功 | 该行会静默移入另一个 tenant |
| 影响 0 行 | filter 会在写入操作背后保护读取 |
| 影响 0 行 | 同上 |
| | 可以探测另一个 tenant 的 key space |
前两行就是泄漏点。写入这些行的 application 永远无法再次读取或删除它们,因为 filter 现在会对其作者隐藏这些行。要恢复这些行,只能禁用 policy。
最后一行是另一个独立且影响较小的问题。 隐藏的是行,而不是行是否存在:key 重复时会出现 ,key 未被占用时则会写入成功,这使调用者能够逐次枚举另一个 tenant 的 key。使用不存在可推测顺序的 identifiers。
filter predicateMsg 26272. The block predicate, and why it is two predicates
2. block predicate
,以及为什么需要两个 predicate
block predicateLearn defines four block operations: , , and
. Adding the first two turns both cross-tenant writes into:
AFTER INSERTAFTER UPDATEBEFORE UPDATEBEFORE DELETEtext
Msg 33504: The attempted operation failed because the target object '<db>.<schema>.<table>'
has a block predicate that conflicts with this operation.The legitimate write into the caller's own tenant still succeeds.
AFTER UPDATEAFTER INSERTAFTER UPDATEsql
CREATE FUNCTION sec.fn_tenant(@tenant_id int)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN SELECT 1 AS ok
WHERE @tenant_id = CAST(SESSION_CONTEXT(N'tenant_id') AS int);
GO
CREATE SECURITY POLICY sec.p_orders
ADD FILTER PREDICATE sec.fn_tenant(tenant_id) ON dbo.orders,
ADD BLOCK PREDICATE sec.fn_tenant(tenant_id) ON dbo.orders AFTER INSERT,
ADD BLOCK PREDICATE sec.fn_tenant(tenant_id) ON dbo.orders AFTER UPDATE
WITH (STATE = ON);
GO
-- the other half of the guarantee: the application never rewrites a tenant id
DENY UPDATE ON dbo.orders(tenant_id) TO app_user;If the policy already exists with only a filter predicate, add the block predicates to it in one
statement. Do not drop and recreate the policy on a live database: between the and the
, every session reads and writes the table unfiltered.
DROPCREATEsql
ALTER SECURITY POLICY sec.p_orders
ADD BLOCK PREDICATE sec.fn_tenant(tenant_id) ON dbo.orders AFTER INSERT,
ADD BLOCK PREDICATE sec.fn_tenant(tenant_id) ON dbo.orders AFTER UPDATE;Learn adds two things. The optimizer skips an block predicate when the update changed
no column the predicate reads, so ordinary updates pay nothing for it. And Learn's middle-tier
example omits only because it denies on the tenant column instead. Take
both. and are redundant while a filter predicate is present, since
the filter has already removed the other tenant's rows from the statement.
AFTER UPDATEAFTER UPDATEUPDATEBEFORE UPDATEBEFORE DELETEMicrosoft Learn 定义了四种 block operation:、、 和 。添加前两个后,两种跨租户写入都会变成:
AFTER INSERTAFTER UPDATEBEFORE UPDATEBEFORE DELETEtext
Msg 33504: The attempted operation failed because the target object '<db>.<schema>.<table>'
has a block predicate that conflicts with this operation.对调用者自己 tenant 的合法写入仍然会成功。
人们经常漏掉 。 在已经配置 和 、但没有 的情况下,跨租户 insert 会被拒绝,而移动 tenant 的 update 仍会成功。该行会无错误地离开原 tenant。
AFTER UPDATEfilter predicateAFTER INSERTAFTER UPDATEsql
CREATE FUNCTION sec.fn_tenant(@tenant_id int)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN SELECT 1 AS ok
WHERE @tenant_id = CAST(SESSION_CONTEXT(N'tenant_id') AS int);
GO
CREATE SECURITY POLICY sec.p_orders
ADD FILTER PREDICATE sec.fn_tenant(tenant_id) ON dbo.orders,
ADD BLOCK PREDICATE sec.fn_tenant(tenant_id) ON dbo.orders AFTER INSERT,
ADD BLOCK PREDICATE sec.fn_tenant(tenant_id) ON dbo.orders AFTER UPDATE
WITH (STATE = ON);
GO
-- the other half of the guarantee: the application never rewrites a tenant id
DENY UPDATE ON dbo.orders(tenant_id) TO app_user;如果 policy 已经存在且只有 filter predicate,请用一条 statement 将 block predicate 加进去。不要在生产 database 上 drop 后再 recreate policy:在 与 之间,每个 session 都会在无过滤的情况下读取和写入 table。
DROPCREATEsql
ALTER SECURITY POLICY sec.p_orders
ADD BLOCK PREDICATE sec.fn_tenant(tenant_id) ON dbo.orders AFTER INSERT,
ADD BLOCK PREDICATE sec.fn_tenant(tenant_id) ON dbo.orders AFTER UPDATE;Microsoft Learn 还补充了两点。优化器会在 update 未改变 predicate 读取的任何列时跳过 block predicate,因此普通 update 不会为此付出成本。Microsoft Learn 的中间层示例之所以省略 ,只是因为它改为 tenant column 上的 。两者都要采用。只要存在 filter predicate, 和 就是冗余的,因为 filter 已经从 statement 中移除了其他 tenant 的行。
AFTER UPDATEAFTER UPDATEDENYUPDATEBEFORE UPDATEBEFORE DELETEMoving rows that already left their tenant
移动已经离开所属 tenant 的行
Rows written before the block predicates existed stay invisible to the tenant that owns them, and
the policy now refuses to move them back. With the session set to the row's current , an
to the right tenant fails with . Do not switch the policy off on a live database
to fix this, and do not add an exemption to the predicate. Run the repair as one transaction, as a
principal no application connects as, holding the two permissions in section 4:
tenant_idUPDATEMsg 33504sql
SET XACT_ABORT ON;
BEGIN TRANSACTION;
ALTER SECURITY POLICY sec.p_orders WITH (STATE = OFF);
UPDATE dbo.orders SET tenant_id = 42 WHERE id IN (1001, 1002); -- the reviewed list
ALTER SECURITY POLICY sec.p_orders WITH (STATE = ON);
COMMIT;While the transaction is open the engine holds a schema-modification lock on the policy. Every other
statement against the protected tables waits, including readers and cached plans, and none of
them sees unfiltered rows. Any error rolls the batch back and leaves the policy on. The cost is that
application traffic on those tables stalls for as long as the transaction runs. So decide each
row's owner from the audit trail beforehand, update an explicit list of keys rather than a broad
predicate, and keep the transaction short. Afterwards is 1 and
the catalog sweep in section 5 comes back empty.
NOLOCKsys.security_policies.is_enabled在 block predicate 存在之前写入的行,对其所属 tenant 依然不可见,而 policy 现在又拒绝将它们移回。将 session 设置为该行当前的 后,把行更新到正确 tenant 也会因 失败。不要为了修复而在生产 database 上关闭 policy,也不要给 predicate 添加 exemption。以 application 不会连接的主体执行修复,在一个 transaction 中完成,并持有第 4 节所述的两项权限:
tenant_idMsg 33504sql
SET XACT_ABORT ON;
BEGIN TRANSACTION;
ALTER SECURITY POLICY sec.p_orders WITH (STATE = OFF);
UPDATE dbo.orders SET tenant_id = 42 WHERE id IN (1001, 1002); -- the reviewed list
ALTER SECURITY POLICY sec.p_orders WITH (STATE = ON);
COMMIT;transaction 打开期间,engine 会持有 policy 上的 schema-modification lock。针对受保护 table 的其他所有 statement 都会等待,包括 reader 和 cached plan,而且它们都不会看到未经过滤的行。任何错误都会回滚整个 batch,并让 policy 保持启用。代价是这些 table 上的 application traffic 会在 transaction 持续期间全部停滞。因此,应事先根据 audit trail 确定每一行的 owner,更新明确的 key 列表,而不是使用宽泛的 predicate,并让 transaction 尽可能短。完成后, 为 1,第 5 节中的目录扫描结果也为空。
NOLOCKsys.security_policies.is_enabled3. How the tenant reaches the predicate, and what pooling does to it
3. tenant 如何到达 predicate,以及 pooling 会造成什么影响
Two designs, and the difference is in behavior, not style.
这里有两种设计,差异体现在行为上,而不只是风格。
SESSION_CONTEXT
is a variable, not an identity
SESSION_CONTEXTSESSION_CONTEXT
是变量,不是身份
SESSION_CONTEXTLearn is explicit that any user can set a session context for their session: a user granted only
plus , , and on one table can set its own tenant id to 2
and read tenant 2's rows. No grant is needed, and none can be revoked to stop it.
CONNECTSELECTINSERTUPDATEDELETESo a design is exactly as strong as the guarantee that nothing
attacker-influenced ever reaches that connection as SQL. owns that:
open it whenever any part of a statement here is assembled from input instead of passed as a
parameter, because under this design a successful injection rewrites the tenant boundary itself.
SESSION_CONTEXTprevent-sql-injectionMicrosoft Learn 明确指出,任何用户都可以为自己的 session 设置 session context:一个仅在某张 table 上拥有 、、、 和 权限的用户,可以把自己的 tenant id 设置为 2,并读取 tenant 2 的行。不需要任何额外 grant,而且也没有 grant 可以撤销这一能力。
CONNECTSELECTINSERTUPDATEDELETE因此, 方案的安全强度,恰好取决于以下保证:任何受攻击者影响的内容都不会以 SQL 形式到达该连接。 负责这一点:只要这里的任何 statement 是由输入拼接而成,而不是作为 parameter 传入,就应打开它,因为在此设计下,一次成功注入就会改写 tenant 边界本身。
SESSION_CONTEXTprevent-sql-injectionThe failure that reaches production
真正进入生产环境的失效方式
The tenant id outlives the request, because the connection does. With a small pool serving
concurrent requests that alternate between two tenants:
| Application shape | Cross-tenant reads |
|---|---|
| Set the context in one pooled request, run the query in another | a large share of requests |
| Set the context and run the query on one acquired connection | none |
| A database user per tenant, one pool per tenant, no session context | none |
No caller sees an error. The rate in a real application depends on its pool and its load; the
point is that the failure is silent. An application can set the tenant on every request and still
leak, when it hands the set and the query to the pool separately and the pool gives them different
connections. Two rules follow:
- Set the tenant and read on the same acquired connection, in one batch, one transaction, or one explicitly held connection. Not two calls to a pool.
- Never leave the tenant set when a connection returns to the pool. That failure is open, not closed: the next caller that forgets reads the previous tenant's rows.
@read_only = 1Msg 15664tenant id 的存活时间会超过 request,因为 connection 的存活时间更长。当一个小 pool 同时处理在两个 tenant 之间交替的并发 request 时:
| Application 形态 | 跨租户读取 |
|---|---|
| 在一次 pooled request 中设置 context,在另一次 request 中运行 query | 很大一部分 request |
| 在同一个 acquired connection 上设置 context 并运行 query | 无 |
| 每个 tenant 一个 database user,每个 tenant 一个 pool,不使用 session context | 无 |
没有任何调用方会看到错误。 真实 application 中的发生率取决于 pool 和 load;重点在于,这种失效是静默的。Application 可以每个 request 都设置 tenant,仍然发生泄漏:它把 set 与 query 分别交给 pool,而 pool 给二者分配了不同 connection。由此得出两条规则:
- 在同一个 acquired connection 上设置 tenant 并读取,可以在一个 batch、一个 transaction 或一个显式持有的 connection 中完成。不要对 pool 调用两次。
- 绝不要在 connection 返回 pool 时留下已设置的 tenant。 这种失效是 fail open,而不是 fail closed:下一个忘记设置 tenant 的调用方会读取上一个 tenant 的行。
@read_only = 1Msg 15664A database user per tenant
每个 tenant 使用一个 database user
The predicate reads or instead of session state, resolved
through a mapping table:
USER_NAME()DATABASE_PRINCIPAL_ID()sql
CREATE FUNCTION sec.fn_tenant_by_user(@tenant_id int)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN SELECT 1 AS ok FROM sec.tenant_map m
WHERE m.db_user = USER_NAME() AND m.tenant_id = @tenant_id;Setting under this predicate changes nothing, and borrowing another tenant's
identity with is refused with , since impersonation is a permission the
tenant does not hold. Connection pools are keyed by connection string, so each
tenant gets its own pool and there is no shared connection to leak through.
SESSION_CONTEXTEXECUTE AS USERMsg 15517The cost is one login, one database user, one connection string and one pool per tenant, which fits
hundreds of tenants and not tens of thousands. Choose it when isolation has to survive an
application bug rather than depend on its absence.
predicate 不再读取 session state,而是读取 或 ,并通过 mapping table 进行解析:
USER_NAME()DATABASE_PRINCIPAL_ID()sql
CREATE FUNCTION sec.fn_tenant_by_user(@tenant_id int)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN SELECT 1 AS ok FROM sec.tenant_map m
WHERE m.db_user = USER_NAME() AND m.tenant_id = @tenant_id;在此 predicate 下设置 不会产生任何作用;使用 借用另一个 tenant 的 identity 会被 拒绝,因为 impersonation 是 tenant 不持有的权限。Connection pool 以 connection string 为 key,因此每个 tenant 都会获得自己的 pool,也不存在可泄漏的共享 connection。
SESSION_CONTEXTEXECUTE AS USERMsg 15517代价是每个 tenant 都需要一个 login、一个 database user、一个 connection string 和一个 pool。它适合数百个 tenant,而不适合数万个 tenant。当隔离必须承受 application bug,而不是依赖 application 没有 bug 时,应选择这种方案。
4. Who bypasses the policy
4. 谁可以绕过 policy
| Principal | Reads through the policy | Can turn it off |
|---|---|---|
| A plain application user | no, 0 rows with no tenant set | no, |
| The table owner, which is also the database owner | no, 0 rows with no tenant set | yes |
A member of | no, 0 rows with no tenant set | yes, in one statement, then reads every row |
| no | no, |
| no | no, |
| Both of the above together | no | yes, in one statement, then reads every row |
Ownership is not a read-through. Learn says a user, a member and the table
owner are all filtered or blocked as the policy defines, and all three get zero rows with no tenant
set. What they hold is the ability to disable, a separate and auditable statement.
dbodb_ownerALTER ANY SECURITY POLICYALTERMsg 33268| 主体 | 经由 policy 读取 | 能否将其关闭 |
|---|---|---|
| 普通 application user | 否,未设置 tenant 时返回 0 行 | 否, |
| table owner,同时也是 database owner | 否,未设置 tenant 时返回 0 行 | 是 |
| 否,未设置 tenant 时返回 0 行 | 是,通过一条 statement 关闭后即可读取所有行 |
仅有 | 否 | 否, |
仅有 policy 所在 schema 上的 | 否 | 否, |
| 同时拥有上述两项权限 | 否 | 是,通过一条 statement 关闭后即可读取所有行 |
所有权不代表可以穿透 policy 读取。 Microsoft Learn 说明,dbo user、 成员和 table owner 都会按 policy 定义被过滤或阻止,并且三者在未设置 tenant 时都会得到 0 行。他们持有的是禁用 policy 的能力,这是一项独立且可审计的操作。
db_owner仅有 并不足够。 Microsoft Learn 将权限要求拆分为:修改 policy 需要 ,创建或删除 policy 需要 policy 所在 schema 上的 。禁用 policy 需要两者同时具备:单独拥有任意一项都会因 失败,而且该错误会被报告为缺少对象,而不是 permission failure。应将这两项权限配对授予 application 不会连接的主体。
ALTER ANY SECURITY POLICYALTER ANY SECURITY POLICYALTERMsg 332685. A policy can be present and not enforcing, in three ways
5. Policy 可以存在却没有生效,原因有三种
All three look healthy from the application: rows come back, nothing errors.
| Shape | What the application sees | What gives it away |
|---|---|---|
| every tenant's rows | |
| A predicate that returns a row when the tenant is unset | every tenant's rows, to a session that set nothing | nothing in any catalog view; |
| A second tenant-scoped table nobody added to the policy | that table unfiltered, while the covered table is correct | no predicate rows for that object |
A predicate of the form returns every row to a
session with no tenant set, while every catalog view reports a healthy enabled policy. Predicates
fail closed or they are not predicates. Never add an escape clause for administrative sessions.
WHERE @tenant_id = <context> OR <context> IS NULLThe third is a sweep, not a review. Run it after every migration that adds a table:
sql
SELECT QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' + QUOTENAME(t.name) AS table_name,
SUM(CASE WHEN sp.predicate_type = 0 THEN 1 ELSE 0 END) AS filter_predicates,
SUM(CASE WHEN sp.predicate_type = 1 THEN 1 ELSE 0 END) AS block_predicates,
MIN(CAST(pol.is_enabled AS int)) AS policy_enabled
FROM sys.tables t
JOIN sys.columns c
ON c.object_id = t.object_id AND c.name = N'tenant_id'
LEFT JOIN sys.security_predicates sp ON sp.target_object_id = t.object_id
LEFT JOIN sys.security_policies pol ON pol.object_id = sp.object_id
GROUP BY t.schema_id, t.name
HAVING SUM(CASE WHEN sp.predicate_type = 1 THEN 1 ELSE 0 END) < 2
OR MIN(CAST(pol.is_enabled AS int)) IS NULL
OR MIN(CAST(pol.is_enabled AS int)) = 0;predicate_type01sys.security_predicatestenant_idOne shape the sweep misses, per Learn: predicates are not replicated to a system-versioned table's
history table, which needs its own predicate by name.
从 application 的角度看,三者都很健康:能够返回行,也没有错误。
| 形态 | Application 看到什么 | 暴露方式 |
|---|---|---|
| 每个 tenant 的所有行 | |
| tenant 未设置时仍返回一行的 predicate | 未设置 tenant 的 session 可以看到每个 tenant 的所有行 | 任何 catalog view 中都看不出来; |
| 某张 tenant-scoped table 未被加入 policy | 该 table 未经过滤,而受覆盖的 table 仍然正确 | 该对象没有 predicate row |
形如 的 predicate 会向未设置 tenant 的 session 返回所有行,同时每个 catalog view 都会报告 policy 健康且已启用。Predicate 必须 fail closed,否则就不算真正的 predicate。 永远不要为 administrative session 添加 escape clause。
WHERE @tenant_id = <context> OR <context> IS NULL第三种情况需要做 sweep,而不是 review。每次添加 table 的 migration 后都应运行:
sql
SELECT QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' + QUOTENAME(t.name) AS table_name,
SUM(CASE WHEN sp.predicate_type = 0 THEN 1 ELSE 0 END) AS filter_predicates,
SUM(CASE WHEN sp.predicate_type = 1 THEN 1 ELSE 0 END) AS block_predicates,
MIN(CAST(pol.is_enabled AS int)) AS policy_enabled
FROM sys.tables t
JOIN sys.columns c
ON c.object_id = t.object_id AND c.name = N'tenant_id'
LEFT JOIN sys.security_predicates sp ON sp.target_object_id = t.object_id
LEFT JOIN sys.security_policies pol ON pol.object_id = sp.object_id
GROUP BY t.schema_id, t.name
HAVING SUM(CASE WHEN sp.predicate_type = 1 THEN 1 ELSE 0 END) < 2
OR MIN(CAST(pol.is_enabled AS int)) IS NULL
OR MIN(CAST(pol.is_enabled AS int)) = 0;predicate_type01sys.security_predicatestenant_id根据 Microsoft Learn,sweep 会漏掉一种情况:predicate 不会复制到 system-versioned table 的 history table,后者需要按名称配置自己的 predicate。
6. A security policy beside a vector index depends on the build
6. security policy
与 vector index
并存时是否可用取决于 build
security policyvector indexA tenant predicate on a chunk table looks like the cheapest defence against a retrieval answering
one tenant with another tenant's text, but whether a security policy and a vector index can share
a table is not documented (Microsoft Learn's CREATE VECTOR INDEX, VECTOR_SEARCH and row-level
security pages are silent on it) and differs between engine builds:
| Engine | Policy after the index | Index after the policy | Approximate search under the policy |
|---|---|---|---|
| Earlier builds of the Azure SQL Database container image | | | not reachable |
SQL Server 2025 (with | | | not reachable |
| Azure SQL Database, Fabric SQL database, and container image build 18.0.310.0_253 | created | created | the filter holds (no cross-tenant rows) and a block predicate refuses a cross-tenant insert ( |
So a policy on the chunk table protects it where the engine accepts the pair, but it turns every
approximate search into an exact scan, and on SQL Server 2025 it cannot be created at all. Make the
retrieval query's own tenant filter the boundary, keep the index, and keep a test that fails when
that filter is removed. If you also put a policy on the chunk table, check on the target database
that it is created, that a cross-tenant approximate query returns none of the other tenant's rows,
and whether the plan still shows a ; expect the fall back to an exact scan.
Vector Index SeekWhat does work: the filter predicate applies correctly to exact search over with
no vector index, and each tenant gets back only its own rows.
VECTOR_DISTANCE在 chunk table 上配置 tenant predicate,看起来是防止 retrieval 用一个 tenant 的文本回答另一个 tenant 时最廉价的防线;但 与 是否能共用一张 table 并无文档说明(Microsoft Learn 的 、 和 row-level security 页面对此均未提及),而且不同 engine build 的行为也不同:
security policyvector indexCREATE VECTOR INDEXVECTOR_SEARCH| Engine | 创建 index 后的 policy | 创建 policy 后的 index | policy 下的 approximate search |
|---|---|---|---|
| Azure SQL Database container image 的早期 build | | | 无法执行 |
SQL Server 2025(启用 | | | 无法执行 |
| Azure SQL Database、Fabric SQL database,以及 container image build 18.0.310.0_253 | 创建成功 | 创建成功 | filter 保持有效(没有跨 tenant 行),block predicate 会拒绝跨 tenant insert( |
因此,在 engine 接受这种组合时,chunk table 上的 policy 能够保护它,但会把每次 approximate search 变成 exact scan;在 SQL Server 2025 上则根本无法创建。应让 retrieval query 自身的 tenant filter 成为边界,保留 index,并保留一个在 filter 被移除时就会失败的 test。如果还在 chunk table 上配置 policy,应在目标 database 上检查:policy 是否创建成功、跨 tenant 的 approximate query 是否不返回其他 tenant 的行,以及执行计划中是否仍显示 ;应预期它会 fallback 到 exact scan。
Vector Index Seek可行的做法是:filter predicate 可以在没有 vector index 的情况下正确应用于基于 的 exact search,并且每个 tenant 只会获得自己的行。
VECTOR_DISTANCECheck it worked
检查是否生效
Three checks, cheapest first, against the reference file's setup script: holding four
rows, two each for tenants 1 and 2, and granted only and the four table
permissions.
dbo.ordersapp_userCONNECTOne: the filtered count is smaller than the table, and the administrator is not exempt. Run it
on an administrative connection, which is the only one that can impersonate:
sql
EXEC sys.sp_set_session_context @key = N'tenant_id', @value = 1;
SELECT COUNT(*) AS admin_tenant_1 FROM dbo.orders;
EXECUTE AS USER = 'app_user';
SELECT COUNT(*) AS app_tenant_1 FROM dbo.orders;
EXEC sys.sp_set_session_context @key = N'tenant_id', @value = 2;
SELECT COUNT(*) AS app_tenant_2 FROM dbo.orders;
EXEC sys.sp_set_session_context @key = N'tenant_id', @value = NULL;
SELECT COUNT(*) AS app_no_tenant FROM dbo.orders;
REVERT;Expected against four seeded rows: , , , , and the two twos are different rows. A
anywhere means the policy is not enforcing, which is section 5; zero everywhere means the predicate
is not reading the key you set.
22204Two: a cross-tenant write raises rather than vanishing.
sql
EXECUTE AS USER = 'app_user';
EXEC sys.sp_set_session_context @key = N'tenant_id', @value = 1;
INSERT INTO dbo.orders (order_id, tenant_id, customer, amount) VALUES (901, 2, N'probe', 1.00);
REVERT;Expect . If it succeeds you have the leak in section 1, and the row is already invisible
to the connection that wrote it.
Msg 33504Three: the isolation test, as the application's own user, on every deployment, saved as
:
tenant-isolation.sqlsql
SET NOCOUNT ON;
DECLARE @mine int = 1, @theirs int = 2, @fail int = 0, @n int;
-- unique per run: a failing run strands a probe row it can no longer see or delete
DECLARE @probe int = 900000 + ABS(CHECKSUM(NEWID())) % 90000;
EXEC sp_set_session_context @key = N'tenant_id', @value = 1;
-- 1. every visible row is mine
SELECT @n = COUNT(*) FROM dbo.orders WHERE tenant_id <> @mine;
IF @n <> 0 BEGIN PRINT 'FAIL 1: the filter predicate leaks another tenant''s rows'; SET @fail = 1; END
-- 2. an unfiltered aggregate cannot see more than the filtered set
SELECT @n = COUNT(*) FROM dbo.orders;
IF @n <> (SELECT COUNT(*) FROM dbo.orders WHERE tenant_id = @mine)
BEGIN PRINT 'FAIL 2: aggregate disagrees with the filtered set'; SET @fail = 1; END
-- 3. a write addressed to another tenant is REFUSED, not silently accepted
BEGIN TRY
INSERT INTO dbo.orders (order_id, tenant_id, customer, amount)
VALUES (@probe, @theirs, N'probe', 1.00);
PRINT 'FAIL 3: cross-tenant INSERT accepted, no BLOCK PREDICATE AFTER INSERT';
SET @fail = 1;
END TRY
BEGIN CATCH
IF ERROR_NUMBER() <> 33504 BEGIN PRINT CONCAT('FAIL 3: unexpected error ', ERROR_NUMBER()); SET @fail = 1; END
END CATCH
-- 4. moving one of my own rows into another tenant is REFUSED
INSERT INTO dbo.orders (order_id, tenant_id, customer, amount) VALUES (@probe + 1, @mine, N'probe', 1.00);
BEGIN TRY
UPDATE dbo.orders SET tenant_id = @theirs WHERE order_id = @probe + 1;
PRINT 'FAIL 4: tenant-move UPDATE accepted, no BLOCK PREDICATE AFTER UPDATE';
SET @fail = 1;
END TRY
BEGIN CATCH
IF ERROR_NUMBER() <> 33504 BEGIN PRINT CONCAT('FAIL 4: unexpected error ', ERROR_NUMBER()); SET @fail = 1; END
END CATCH
DELETE FROM dbo.orders WHERE order_id = @probe + 1;
-- 5. no tenant set means no rows: the predicate fails closed
EXEC sp_set_session_context @key = N'tenant_id', @value = NULL;
SELECT @n = COUNT(*) FROM dbo.orders;
IF @n <> 0 BEGIN PRINT 'FAIL 5: the predicate fails OPEN when no tenant is set'; SET @fail = 1; END
IF @fail = 1 THROW 50001, 'tenant isolation test FAILED', 1;
PRINT 'tenant isolation: ALL PASS';bash
export SQLCMDPASSWORD='<app-user-password>'
sqlcmd -S <server-name>.database.windows.net,1433 -d <database> -U app_user -C \
-b -m-1 -V 16 -i tenant-isolation.sql -o tenant-isolation.out
echo "exit $?"
grep -nE '^FAIL |^Msg ' tenant-isolation.outExpect exit , in the file, and no output from . sets
severity 16, above the severity 10 ignores, so a failed assertion does set a non-zero exit;
puts every message in the file, including the naming which assertion went red.
0tenant isolation: ALL PASSgrepTHROW-b-m-1PRINT-m-1sqlcmdmssql-tools18Msg-mPRINTPlant each failure and watch the test go red, which is the only evidence an assertion asserts
anything:
| Plant | Assertions that fail |
|---|---|
Drop the | 3 |
Drop the | 4 |
| 1, 2, 4, 5 |
| Swap in the predicate that returns rows when the tenant is unset | 5 |
Assertions 1 and 2 are the same claim from two angles: 2 catches a predicate that filters a direct
scan and not an aggregate. Add the pooling case in application test code, because no single
connection reproduces it: issue concurrent requests for two tenants against one pool and assert
every response carries only its own tenant, the shape that in section 3 returns another tenant's
rows for a large share of requests.
按成本从低到高,共有三项检查,可针对参考文件的 setup script 执行: 中有四行,tenant 1 和 tenant 2 各两行; 仅被授予 以及四项 table permission。
dbo.ordersapp_userCONNECT第一项:过滤后的 count 小于 table 的 count,并且 administrator 不会被豁免。 在 administrative connection 上运行它,因为只有该 connection 可以执行 impersonate:
sql
EXEC sys.sp_set_session_context @key = N'tenant_id', @value = 1;
SELECT COUNT(*) AS admin_tenant_1 FROM dbo.orders;
EXECUTE AS USER = 'app_user';
SELECT COUNT(*) AS app_tenant_1 FROM dbo.orders;
EXEC sys.sp_set_session_context @key = N'tenant_id', @value = 2;
SELECT COUNT(*) AS app_tenant_2 FROM dbo.orders;
EXEC sys.sp_set_session_context @key = N'tenant_id', @value = NULL;
SELECT COUNT(*) AS app_no_tenant FROM dbo.orders;
REVERT;对于预先植入的四行,预期结果为 、、、,并且两个 2 对应不同的行。任何地方出现 都表示 policy 没有生效,对应第 5 节;所有地方都是 则表示 predicate 没有读取所设置的 key。
222040第二项:跨租户写入应抛出错误,而不是悄然消失。
sql
EXECUTE AS USER = 'app_user';
EXEC sys.sp_set_session_context @key = N'tenant_id', @value = 1;
INSERT INTO dbo.orders (order_id, tenant_id, customer, amount) VALUES (901, 2, N'probe', 1.00);
REVERT;预期出现 。如果写入成功,就出现了第 1 节中的泄漏,而且该行已经对写入它的 connection 不可见。
Msg 33504第三项:隔离测试。以 application 自己的 user 在每次 deployment 上运行,并保存为 :
tenant-isolation.sqlsql
SET NOCOUNT ON;
DECLARE @mine int = 1, @theirs int = 2, @fail int = 0, @n int;
-- unique per run: a failing run strands a probe row it can no longer see or delete
DECLARE @probe int = 900000 + ABS(CHECKSUM(NEWID())) % 90000;
EXEC sp_set_session_context @key = N'tenant_id', @value = 1;
-- 1. every visible row is mine
SELECT @n = COUNT(*) FROM dbo.orders WHERE tenant_id <> @mine;
IF @n <> 0 BEGIN PRINT 'FAIL 1: the filter predicate leaks another tenant''s rows'; SET @fail = 1; END
-- 2. an unfiltered aggregate cannot see more than the filtered set
SELECT @n = COUNT(*) FROM dbo.orders;
IF @n <> (SELECT COUNT(*) FROM dbo.orders WHERE tenant_id = @mine)
BEGIN PRINT 'FAIL 2: aggregate disagrees with the filtered set'; SET @fail = 1; END
-- 3. a write addressed to another tenant is REFUSED, not silently accepted
BEGIN TRY
INSERT INTO dbo.orders (order_id, tenant_id, customer, amount)
VALUES (@probe, @theirs, N'probe', 1.00);
PRINT 'FAIL 3: cross-tenant INSERT accepted, no BLOCK PREDICATE AFTER INSERT';
SET @fail = 1;
END TRY
BEGIN CATCH
IF ERROR_NUMBER() <> 33504 BEGIN PRINT CONCAT('FAIL 3: unexpected error ', ERROR_NUMBER()); SET @fail = 1; END
END CATCH
-- 4. moving one of my own rows into another tenant is REFUSED
INSERT INTO dbo.orders (order_id, tenant_id, customer, amount) VALUES (@probe + 1, @mine, N'probe', 1.00);
BEGIN TRY
UPDATE dbo.orders SET tenant_id = @theirs WHERE order_id = @probe + 1;
PRINT 'FAIL 4: tenant-move UPDATE accepted, no BLOCK PREDICATE AFTER UPDATE';
SET @fail = 1;
END TRY
BEGIN CATCH
IF ERROR_NUMBER() <> 33504 BEGIN PRINT CONCAT('FAIL 4: unexpected error ', ERROR_NUMBER()); SET @fail = 1; END
END CATCH
DELETE FROM dbo.orders WHERE order_id = @probe + 1;
-- 5. no tenant set means no rows: the predicate fails closed
EXEC sp_set_session_context @key = N'tenant_id', @value = NULL;
SELECT @n = COUNT(*) FROM dbo.orders;
IF @n <> 0 BEGIN PRINT 'FAIL 5: the predicate fails OPEN when no tenant is set'; SET @fail = 1; END
IF @fail = 1 THROW 50001, 'tenant isolation test FAILED', 1;
PRINT 'tenant isolation: ALL PASS';bash
export SQLCMDPASSWORD='<app-user-password>'
sqlcmd -S <server-name>.database.windows.net,1433 -d <database> -U app_user -C \
-b -m-1 -V 16 -i tenant-isolation.sql -o tenant-isolation.out
echo "exit $?"
grep -nE '^FAIL |^Msg ' tenant-isolation.out预期退出码为 ,文件中包含 ,并且 没有任何输出。 将严重级别设为 16,高于 会忽略的严重级别 10,因此断言失败确实会设置非零退出码; 会把每条消息都写入文件,包括指出哪个断言变红的 。
0tenant isolation: ALL PASSgrepTHROW-b-m-1PRINT-m-1sqlcmdmssql-tools18-mMsgPRINT植入每种失败并观察 test 变红,这才是断言确实在断言的唯一证据:
| 植入项 | 失败的断言 |
|---|---|
Drop | 3 |
Drop | 4 |
| 1、2、4、5 |
| 换成 tenant 未设置时仍返回行的 predicate | 5 |
断言 1 和 2 从两个角度表达同一个主张:断言 2 可以捕获过滤 direct scan、却没有过滤 aggregate 的 predicate。还要在 application test code 中加入 pooling case,因为单一 connection 无法复现它:针对一个 pool 同时发出两个 tenant 的并发 request,并断言每个 response 只携带自己的 tenant;在第 3 节描述的形态中,这会为很大一部分 request 返回另一个 tenant 的行。
Do not
禁止事项
- Do not ship a filter predicate on its own. A cross-tenant insert succeeds under it and the row is then unreadable and undeletable by the application that wrote it.
- Do not add and stop. The tenant-move update still succeeds with only that block predicate in place.
AFTER INSERT - Do not set the tenant in one pooled call and query in another, and do not reach for
to make that safe. It refuses the correct caller and leaves the forgetful one leaking.
@read_only = 1 - Do not treat as an identity. Any caller on the connection rewrites it with no permission, so one concatenated statement defeats the whole policy.
SESSION_CONTEXT - Do not assume the table owner or reads through the policy. They do not. They disable it, which is a different and visible act.
db_owner - Do not grant believing it is inert alone. Paired with
ALTER ANY SECURITY POLICYon the policy's schema it is a full read of every protected table, in one statement.ALTER - Do not read as proof of isolation. A fail-open predicate and an uncovered table both leave it at 1.
is_enabled = 1 - Do not conclude row level security is unavailable because an engine build refuses it beside a vector index. The refusal is about the index, not about the policy.
- Do not leave the tenant column nullable. A row that arrives with no tenant is invisible to every tenant and belongs to none.
- Do not repair misplaced rows by turning the policy off outside a transaction. Until it is back on, every connection reads every tenant's rows.
- 不要只上线 filter predicate。跨租户 insert 会在其下成功,随后该行对写入它的 application 既不可读也不可删除。
- 不要添加 后就停手。只配置该 block predicate 时,移动 tenant 的 update 仍会成功。
AFTER INSERT - 不要在一次 pooled call 中设置 tenant、在另一次 call 中 query,也不要依赖 来保证安全。它会拒绝正确的 caller,却让忘记设置的 caller 继续泄漏。
@read_only = 1 - 不要把 当成 identity。连接上的任何 caller 都可以在没有 permission 的情况下重写它,因此一条拼接后的 statement 就能击穿整个 policy。
SESSION_CONTEXT - 不要假定 table owner 或 可以经由 policy 读取。他们不能;他们可以禁用 policy,这是另一项行为且可见。
db_owner - 不要在以为 单独无害的情况下授予它。它与 policy 所在 schema 上的
ALTER ANY SECURITY POLICY结合后,就能用一条 statement 读取每张受保护 table 的全部内容。ALTER - 不要把 当成隔离证明。Fail-open predicate 和未覆盖的 table 都会让它保持为 1。
is_enabled = 1 - 不要因为某个 engine build 拒绝在 vector index 旁使用 row-level security,就断定 row-level security 不可用。该拒绝针对的是 index,而不是 policy。
- 不要让 tenant column 可空。携带空 tenant 到达的 row 对所有 tenant 都不可见,也不属于任何 tenant。
- 不要在 transaction 外通过关闭 policy 来修复放错位置的 row。在它重新启用前,每个 connection 都会读取所有 tenant 的 row。
References
参考资料
- Open the runnable checks when a message number above is disputed, before changing one, or to rerun the pooling check and the four planted failures.
- Read Row-level security before designing a predicate more complex than one column, for the block operations, the permission split, and the cross-feature list that names indexed views and temporal tables.
- Read sp_set_session_context
before choosing session context over a user per tenant: the 8,000 byte value limit, the 1 MB
session total, and the argument.
@read_only - Read sqlcmd utility when wiring
the isolation test into a pipeline, for what ,
-band-mdo.-V - when any statement here is assembled rather than parameterised, which is what a session context design depends on.
prevent-sql-injectionfor getting an identity onto a working connection; use a custom least-privilege role for the permissions that identity receives.entra-id-auth - for the tenant column and its place in the key,
design-azure-sql-schemafor the predicate function as T-SQL, andt-sql-correctnesswithrag-on-azure-sqlfor the retrieval this policy sits under.vector-search-azure-sql
- 当上文某个消息编号存在争议、在修改前需要核对,或需要重新运行 pooling check 与四种植入失败时,请打开可运行的检查。
- 在设计比单列更复杂的 predicate、配置 block operation、拆分 permission,以及查看会点名 indexed view 和 temporal table 的跨 feature 列表之前,请阅读 Row-level security。
- 在选择 session context 而不是每个 tenant 使用一个 user 之前,请阅读 sp_set_session_context,了解 8,000 byte 的 value limit、1 MB 的 session total,以及 参数。
@read_only - 在将隔离 test 接入 pipeline 时,请阅读 sqlcmd utility,了解 、
-b和-m的作用。-V - 如果这里的任何 statement 是拼接而成而不是通过 parameter 传入,请使用 ,因为 session context 设计依赖于此。使用
prevent-sql-injection将 identity 配置到可工作的 connection 上;应使用自定义 least-privilege role 控制该 identity 获得的 permission。entra-id-auth - 使用 设计 tenant column 及其在 key 中的位置,使用
design-azure-sql-schema检查作为 T-SQL 的 predicate function,并使用t-sql-correctness与rag-on-azure-sql处理该 policy 所处的 retrieval 场景。vector-search-azure-sql