rls-multi-tenant

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Tenant 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
不是隔离边界

Microsoft Learn states it plainly: the application can
INSERT
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:
StatementResultWhat it costs
INSERT
a row stamped
tenant_id = 2
succeedsthe row exists, invisible to its author, visible to tenant 2
UPDATE
one of its own rows to
tenant_id = 2
succeedsthe row moves into another tenant, silently
UPDATE
a row of tenant 2
0 rows affectedthe filter protects the read behind a write
DELETE
a row of tenant 2
0 rows affectedsame
INSERT
a key that already exists in tenant 2
Msg 2627
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:
Msg 2627
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.
Microsoft Learn 明确指出:应用程序可以
INSERT
行,即使这些行在任何其他操作中都会被过滤。对于仅持有 tenant id 1 的低权限用户,在只有
filter predicate
的情况下:
语句结果代价
INSERT
一行并标记为
tenant_id = 2
成功该行存在,但对其作者不可见,而 tenant 2 可以看到
UPDATE
自己拥有的一行,将其改为
tenant_id = 2
成功该行会静默移入另一个 tenant
UPDATE
tenant 2 的一行
影响 0 行filter 会在写入操作背后保护读取
DELETE
tenant 2 的一行
影响 0 行同上
INSERT
tenant 2 中已经存在的 key
Msg 2627
可以探测另一个 tenant 的 key space
前两行就是泄漏点。写入这些行的 application 永远无法再次读取或删除它们,因为 filter 现在会对其作者隐藏这些行。要恢复这些行,只能禁用 policy。
最后一行是另一个独立且影响较小的问题。
filter predicate
隐藏的是行,而不是行是否存在:key 重复时会出现
Msg 2627
,key 未被占用时则会写入成功,这使调用者能够逐次枚举另一个 tenant 的 key。使用不存在可推测顺序的 identifiers。

2. The block predicate, and why it is two predicates

2.
block predicate
,以及为什么需要两个 predicate

Learn defines four block operations:
AFTER INSERT
,
AFTER UPDATE
,
BEFORE UPDATE
and
BEFORE DELETE
. Adding the first two turns both cross-tenant writes into:
text
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 UPDATE
is the one people leave out.
With the filter predicate and
AFTER INSERT
in place but no
AFTER UPDATE
, the cross-tenant insert is refused and the tenant-move update still succeeds. The row leaves the tenant with no error.
sql
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
DROP
and the
CREATE
, every session reads and writes the table unfiltered.
sql
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
AFTER UPDATE
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
AFTER UPDATE
only because it denies
UPDATE
on the tenant column instead. Take both.
BEFORE UPDATE
and
BEFORE DELETE
are redundant while a filter predicate is present, since the filter has already removed the other tenant's rows from the statement.
Microsoft Learn 定义了四种 block operation:
AFTER INSERT
、
AFTER UPDATE
、
BEFORE UPDATE
和
BEFORE DELETE
。添加前两个后,两种跨租户写入都会变成:
text
Msg 33504: The attempted operation failed because the target object '<db>.<schema>.<table>'
has a block predicate that conflicts with this operation.
对调用者自己 tenant 的合法写入仍然会成功。
人们经常漏掉
AFTER UPDATE
。
在已经配置
filter predicate
和
AFTER INSERT
、但没有
AFTER UPDATE
的情况下,跨租户 insert 会被拒绝,而移动 tenant 的 update 仍会成功。该行会无错误地离开原 tenant。
sql
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:在
DROP
与
CREATE
之间,每个 session 都会在无过滤的情况下读取和写入 table。
sql
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 读取的任何列时跳过
AFTER UPDATE
block predicate,因此普通 update 不会为此付出成本。Microsoft Learn 的中间层示例之所以省略
AFTER UPDATE
,只是因为它改为
DENY
tenant column 上的
UPDATE
。两者都要采用。只要存在 filter predicate,
BEFORE UPDATE
和
BEFORE DELETE
就是冗余的,因为 filter 已经从 statement 中移除了其他 tenant 的行。

Moving 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
tenant_id
, an
UPDATE
to the right tenant fails with
Msg 33504
. 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:
sql
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
NOLOCK
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
sys.security_policies.is_enabled
is 1 and the catalog sweep in section 5 comes back empty.
在 block predicate 存在之前写入的行,对其所属 tenant 依然不可见,而 policy 现在又拒绝将它们移回。将 session 设置为该行当前的
tenant_id
后,把行更新到正确 tenant 也会因
Msg 33504
失败。不要为了修复而在生产 database 上关闭 policy,也不要给 predicate 添加 exemption。以 application 不会连接的主体执行修复,在一个 transaction 中完成,并持有第 4 节所述的两项权限:
sql
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 都会等待,包括
NOLOCK
reader 和 cached plan,而且它们都不会看到未经过滤的行。任何错误都会回滚整个 batch,并让 policy 保持启用。代价是这些 table 上的 application traffic 会在 transaction 持续期间全部停滞。因此,应事先根据 audit trail 确定每一行的 owner,更新明确的 key 列表,而不是使用宽泛的 predicate,并让 transaction 尽可能短。完成后,
sys.security_policies.is_enabled
为 1,第 5 节中的目录扫描结果也为空。

3. 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_CONTEXT
是变量,不是身份

Learn is explicit that any user can set a session context for their session: a user granted only
CONNECT
plus
SELECT
,
INSERT
,
UPDATE
and
DELETE
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.
So a
SESSION_CONTEXT
design is exactly as strong as the guarantee that nothing attacker-influenced ever reaches that connection as SQL.
prevent-sql-injection
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.
Microsoft Learn 明确指出,任何用户都可以为自己的 session 设置 session context:一个仅在某张 table 上拥有
CONNECT
、
SELECT
、
INSERT
、
UPDATE
和
DELETE
权限的用户,可以把自己的 tenant id 设置为 2,并读取 tenant 2 的行。不需要任何额外 grant,而且也没有 grant 可以撤销这一能力。
因此,
SESSION_CONTEXT
方案的安全强度,恰好取决于以下保证:任何受攻击者影响的内容都不会以 SQL 形式到达该连接。
prevent-sql-injection
负责这一点:只要这里的任何 statement 是由输入拼接而成,而不是作为 parameter 传入,就应打开它,因为在此设计下,一次成功注入就会改写 tenant 边界本身。

The 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 shapeCross-tenant reads
Set the context in one pooled request, run the query in anothera large share of requests
Set the context and run the query on one acquired connectionnone
A database user per tenant, one pool per tenant, no session contextnone
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:
  1. 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.
  2. 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 = 1
looks like the fix, and the documentation reads as if it were. Learn presents it as preventing the value changing again until the connection returns to the pool, which is exactly what it does. On a reused pooled connection, though, the next tenant's correct attempt to claim its own id is refused with
Msg 15664
, while a request that forgets to set anything still reads the previous rows. It is safe only where the connection ends with the request.
tenant 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。由此得出两条规则:
  1. 在同一个 acquired connection 上设置 tenant 并读取,可以在一个 batch、一个 transaction 或一个显式持有的 connection 中完成。不要对 pool 调用两次。
  2. 绝不要在 connection 返回 pool 时留下已设置的 tenant。 这种失效是 fail open,而不是 fail closed:下一个忘记设置 tenant 的调用方会读取上一个 tenant 的行。
@read_only = 1
看起来像修复,文档读起来也像。Microsoft Learn 将它描述为:在 connection 返回 pool 之前阻止该值再次改变,而这正是它的实际作用。但在一个被复用的 pooled connection 上,下一个 tenant 正确尝试认领自己的 id 时会因
Msg 15664
被拒绝,而忘记设置任何值的 request 仍会读取上一个 tenant 的行。只有当 connection 会随 request 结束时,它才安全。

A database user per tenant

每个 tenant 使用一个 database user

The predicate reads
USER_NAME()
or
DATABASE_PRINCIPAL_ID()
instead of session state, resolved through a mapping table:
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
SESSION_CONTEXT
under this predicate changes nothing, and borrowing another tenant's identity with
EXECUTE AS USER
is refused with
Msg 15517
, 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.
The 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,而是读取
USER_NAME()
或
DATABASE_PRINCIPAL_ID()
,并通过 mapping table 进行解析:
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 下设置
SESSION_CONTEXT
不会产生任何作用;使用
EXECUTE AS USER
借用另一个 tenant 的 identity 会被
Msg 15517
拒绝,因为 impersonation 是 tenant 不持有的权限。Connection pool 以 connection string 为 key,因此每个 tenant 都会获得自己的 pool,也不存在可泄漏的共享 connection。
代价是每个 tenant 都需要一个 login、一个 database user、一个 connection string 和一个 pool。它适合数百个 tenant,而不适合数万个 tenant。当隔离必须承受 application bug,而不是依赖 application 没有 bug 时,应选择这种方案。

4. Who bypasses the policy

4. 谁可以绕过 policy

PrincipalReads through the policyCan turn it off
A plain application userno, 0 rows with no tenant setno,
Msg 33268
The table owner, which is also the database ownerno, 0 rows with no tenant setyes
A member of
db_owner
no, 0 rows with no tenant setyes, in one statement, then reads every row
ALTER ANY SECURITY POLICY
alone
nono,
Msg 33268
ALTER
on the schema holding the policy alone
nono,
Msg 33268
Both of the above togethernoyes, in one statement, then reads every row
Ownership is not a read-through. Learn says a
dbo
user, a
db_owner
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.
ALTER ANY SECURITY POLICY
alone is not enough.
Learn splits the requirement, altering a policy against that permission and creating or dropping one against
ALTER
on the schema. Disabling one needs both: either alone fails with
Msg 33268
, reported as a missing object rather than a permission failure. Grant them as a pair, to a principal no application connects as.
主体经由 policy 读取能否将其关闭
普通 application user否,未设置 tenant 时返回 0 行否,
Msg 33268
table owner,同时也是 database owner否,未设置 tenant 时返回 0 行是
db_owner
成员
否,未设置 tenant 时返回 0 行是,通过一条 statement 关闭后即可读取所有行
仅有
ALTER ANY SECURITY POLICY
否否,
Msg 33268
仅有 policy 所在 schema 上的
ALTER
否否,
Msg 33268
同时拥有上述两项权限否是,通过一条 statement 关闭后即可读取所有行
所有权不代表可以穿透 policy 读取。 Microsoft Learn 说明,dbo user、
db_owner
成员和 table owner 都会按 policy 定义被过滤或阻止,并且三者在未设置 tenant 时都会得到 0 行。他们持有的是禁用 policy 的能力,这是一项独立且可审计的操作。
仅有
ALTER ANY SECURITY POLICY
并不足够。
Microsoft Learn 将权限要求拆分为:修改 policy 需要
ALTER ANY SECURITY POLICY
,创建或删除 policy 需要 policy 所在 schema 上的
ALTER
。禁用 policy 需要两者同时具备:单独拥有任意一项都会因
Msg 33268
失败,而且该错误会被报告为缺少对象,而不是 permission failure。应将这两项权限配对授予 application 不会连接的主体。

5. 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.
ShapeWhat the application seesWhat gives it away
WITH (STATE = OFF)
every tenant's rows
sys.security_policies.is_enabled = 0
A predicate that returns a row when the tenant is unsetevery tenant's rows, to a session that set nothingnothing in any catalog view;
is_enabled
is still 1
A second tenant-scoped table nobody added to the policythat table unfiltered, while the covered table is correctno predicate rows for that object
A predicate of the form
WHERE @tenant_id = <context> OR <context> IS NULL
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.
The 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_type
is
0
for filter and
1
for block, read back from
sys.security_predicates
rather than recalled. Read the list rather than count it: a tenant mapping table carries a
tenant_id
column, legitimately has no predicate, and is dismissed once. Anything else in it is a tenant table that is not isolated. To see the sweep work, plant a failure: drop one block predicate from a correct table and that table appears.
One 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 看到什么暴露方式
WITH (STATE = OFF)
每个 tenant 的所有行
sys.security_policies.is_enabled = 0
tenant 未设置时仍返回一行的 predicate未设置 tenant 的 session 可以看到每个 tenant 的所有行任何 catalog view 中都看不出来;
is_enabled
仍为 1
某张 tenant-scoped table 未被加入 policy该 table 未经过滤,而受覆盖的 table 仍然正确该对象没有 predicate row
形如
WHERE @tenant_id = <context> OR <context> IS NULL
的 predicate 会向未设置 tenant 的 session 返回所有行,同时每个 catalog view 都会报告 policy 健康且已启用。Predicate 必须 fail closed,否则就不算真正的 predicate。 永远不要为 administrative session 添加 escape clause。
第三种情况需要做 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_type
的值
0
表示 filter,
1
表示 block;应从
sys.security_predicates
读回,而不能凭记忆判断。要读取列表,而不是只统计数量:tenant mapping table 也有
tenant_id
column,合理地没有 predicate,因此只会作为一条结果出现并应将其排除。除此之外,列表中的任何对象都是未隔离的 tenant table。要验证 sweep 确实有效,可以主动植入失败:从一张正确的 table 上 drop 一个 block predicate,该 table 就会出现在结果中。
根据 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

A 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:
EnginePolicy after the indexIndex after the policyApproximate search under the policy
Earlier builds of the Azure SQL Database container image
Msg 37579
Msg 42244
not reachable
SQL Server 2025 (with
PREVIEW_FEATURES = ON
, which
CREATE VECTOR INDEX
needs there)
Msg 37579
Msg 42244
not reachable
Azure SQL Database, Fabric SQL database, and container image build 18.0.310.0_253createdcreatedthe filter holds (no cross-tenant rows) and a block predicate refuses a cross-tenant insert (
Msg 33504
), but the vector index is not used:
WITH (FORCE_ANN_ONLY)
fails with
Msg 8622
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
Vector Index Seek
; expect the fall back to an exact scan.
What does work: the filter predicate applies correctly to exact search over
VECTOR_DISTANCE
with no vector index, and each tenant gets back only its own rows.
在 chunk table 上配置 tenant predicate,看起来是防止 retrieval 用一个 tenant 的文本回答另一个 tenant 时最廉价的防线;但
security policy
与
vector index
是否能共用一张 table 并无文档说明(Microsoft Learn 的
CREATE VECTOR INDEX
、
VECTOR_SEARCH
和 row-level security 页面对此均未提及),而且不同 engine build 的行为也不同:
Engine创建 index 后的 policy创建 policy 后的 indexpolicy 下的 approximate search
Azure SQL Database container image 的早期 build
Msg 37579
Msg 42244
无法执行
SQL Server 2025(启用
PREVIEW_FEATURES = ON
,
CREATE VECTOR INDEX
在该版本中需要此选项)
Msg 37579
Msg 42244
无法执行
Azure SQL Database、Fabric SQL database,以及 container image build 18.0.310.0_253创建成功创建成功filter 保持有效(没有跨 tenant 行),block predicate 会拒绝跨 tenant insert(
Msg 33504
),但 vector index 不会被使用:
WITH (FORCE_ANN_ONLY)
会因
Msg 8622
失败
因此,在 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 的行,以及执行计划中是否仍显示
Vector Index Seek
;应预期它会 fallback 到 exact scan。
可行的做法是:filter predicate 可以在没有 vector index 的情况下正确应用于基于
VECTOR_DISTANCE
的 exact search,并且每个 tenant 只会获得自己的行。

Check it worked

检查是否生效

Three checks, cheapest first, against the reference file's setup script:
dbo.orders
holding four rows, two each for tenants 1 and 2, and
app_user
granted only
CONNECT
and the four table permissions.
One: 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:
2
,
2
,
2
,
0
, and the two twos are different rows. A
4
anywhere means the policy is not enforcing, which is section 5; zero everywhere means the predicate is not reading the key you set.
Two: 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
Msg 33504
. If it succeeds you have the leak in section 1, and the row is already invisible to the connection that wrote it.
Three: the isolation test, as the application's own user, on every deployment, saved as
tenant-isolation.sql
:
sql
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
Expect exit
0
,
tenant isolation: ALL PASS
in the file, and no output from
grep
.
THROW
sets severity 16, above the severity 10
-b
ignores, so a failed assertion does set a non-zero exit;
-m-1
puts every message in the file, including the
PRINT
naming which assertion went red.
-m-1
is an ODBC
sqlcmd
instruction
, the 18.x build from
mssql-tools18
. With go-sqlcmd 1.10.0, no
Msg
header is printed on a severity 10 message at any
-m
value, so there the
PRINT
lines arrive with no number.
Plant each failure and watch the test go red, which is the only evidence an assertion asserts anything:
PlantAssertions that fail
Drop the
AFTER INSERT
block predicate
3
Drop the
AFTER UPDATE
block predicate
4
WITH (STATE = OFF)
1, 2, 4, 5
Swap in the predicate that returns rows when the tenant is unset5
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 执行:
dbo.orders
中有四行,tenant 1 和 tenant 2 各两行;
app_user
仅被授予
CONNECT
以及四项 table permission。
第一项:过滤后的 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
、
2
、
2
、
0
,并且两个 2 对应不同的行。任何地方出现
4
都表示 policy 没有生效,对应第 5 节;所有地方都是
0
则表示 predicate 没有读取所设置的 key。
第二项:跨租户写入应抛出错误,而不是悄然消失。
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;
预期出现
Msg 33504
。如果写入成功,就出现了第 1 节中的泄漏,而且该行已经对写入它的 connection 不可见。
第三项:隔离测试。以 application 自己的 user 在每次 deployment 上运行,并保存为
tenant-isolation.sql
:
sql
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
预期退出码为
0
,文件中包含
tenant isolation: ALL PASS
,并且
grep
没有任何输出。
THROW
将严重级别设为 16,高于
-b
会忽略的严重级别 10,因此断言失败确实会设置非零退出码;
-m-1
会把每条消息都写入文件,包括指出哪个断言变红的
PRINT
。
-m-1
是 ODBC
sqlcmd
指令
,对应
mssql-tools18
的 18.x build。使用 go-sqlcmd 1.10.0 时,无论
-m
取何值,严重级别 10 的消息都不会打印
Msg
header,因此其中的
PRINT
行不带编号。
植入每种失败并观察 test 变红,这才是断言确实在断言的唯一证据:
植入项失败的断言
Drop
AFTER INSERT
block predicate
3
Drop
AFTER UPDATE
block predicate
4
WITH (STATE = OFF)
1、2、4、5
换成 tenant 未设置时仍返回行的 predicate5
断言 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
    AFTER INSERT
    and stop. The tenant-move update still succeeds with only that block predicate in place.
  • Do not set the tenant in one pooled call and query in another, and do not reach for
    @read_only = 1
    to make that safe. It refuses the correct caller and leaves the forgetful one leaking.
  • Do not treat
    SESSION_CONTEXT
    as an identity. Any caller on the connection rewrites it with no permission, so one concatenated statement defeats the whole policy.
  • Do not assume the table owner or
    db_owner
    reads through the policy. They do not. They disable it, which is a different and visible act.
  • Do not grant
    ALTER ANY SECURITY POLICY
    believing it is inert alone. Paired with
    ALTER
    on the policy's schema it is a full read of every protected table, in one statement.
  • Do not read
    is_enabled = 1
    as proof of isolation. A fail-open predicate and an uncovered table both leave it at 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 既不可读也不可删除。
  • 不要添加
    AFTER INSERT
    后就停手。只配置该 block predicate 时,移动 tenant 的 update 仍会成功。
  • 不要在一次 pooled call 中设置 tenant、在另一次 call 中 query,也不要依赖
    @read_only = 1
    来保证安全。它会拒绝正确的 caller,却让忘记设置的 caller 继续泄漏。
  • 不要把
    SESSION_CONTEXT
    当成 identity。连接上的任何 caller 都可以在没有 permission 的情况下重写它,因此一条拼接后的 statement 就能击穿整个 policy。
  • 不要假定 table owner 或
    db_owner
    可以经由 policy 读取。他们不能;他们可以禁用 policy,这是另一项行为且可见。
  • 不要在以为
    ALTER ANY SECURITY POLICY
    单独无害的情况下授予它。它与 policy 所在 schema 上的
    ALTER
    结合后,就能用一条 statement 读取每张受保护 table 的全部内容。
  • 不要把
    is_enabled = 1
    当成隔离证明。Fail-open predicate 和未覆盖的 table 都会让它保持为 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
    @read_only
    argument.
  • Read sqlcmd utility when wiring the isolation test into a pipeline, for what
    -b
    ,
    -m
    and
    -V
    do.
  • prevent-sql-injection
    when any statement here is assembled rather than parameterised, which is what a session context design depends on.
    entra-id-auth
    for getting an identity onto a working connection; use a custom least-privilege role for the permissions that identity receives.
  • design-azure-sql-schema
    for the tenant column and its place in the key,
    t-sql-correctness
    for the predicate function as T-SQL, and
    rag-on-azure-sql
    with
    vector-search-azure-sql
    for the retrieval this policy sits under.
  • 当上文某个消息编号存在争议、在修改前需要核对,或需要重新运行 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 传入,请使用
    prevent-sql-injection
    ,因为 session context 设计依赖于此。使用
    entra-id-auth
    将 identity 配置到可工作的 connection 上;应使用自定义 least-privilege role 控制该 identity 获得的 permission。
  • 使用
    design-azure-sql-schema
    设计 tenant column 及其在 key 中的位置,使用
    t-sql-correctness
    检查作为 T-SQL 的 predicate function,并使用
    rag-on-azure-sql
    与
    vector-search-azure-sql
    处理该 policy 所处的 retrieval 场景。