Skip to main content

SQL Server Row-Level Security for Multi-Tenant Apps: Predicates, SESSION_CONTEXT and What Still Leaks

Choosing between shared tables, a schema per tenant and a database per tenant is covered in Designing Tenant Isolation Before the Data Model Becomes Expensive to Change. This guide picks up after that decision, for the case where tenants share tables on SQL Server or Azure SQL and row-level security (RLS) is the second layer behind the application's own filtering. The main question is what RLS actually guarantees: it removes the forgotten WHERE TenantId = @id, but it does not remove noisy neighbors, per-tenant restore problems or every kind of leak.

Two predicate types, four write operations

RLS uses an inline table-valued function as a predicate, enforced by a security policy. The two predicate types behave differently:

Predicate Applies to Behavior
FilterSELECT, UPDATE, DELETESilently removes rows. The application never learns they exist
BlockAFTER INSERT, AFTER UPDATE, BEFORE UPDATE, BEFORE DELETEFails the operation with an error

You need both kinds for tenancy. A filter predicate alone does not stop a write: the application can still insert a row that will be filtered on every later read, and a user can update a row so that it is filtered afterward. Block predicates close those gaps. Bulk operations such as BULK INSERT are subject to AFTER INSERT block predicates as well.

A tenant policy, following the documented middle-tier pattern

Microsoft's documentation shows the pattern for applications where all tenants share one database user: the app sets the tenant identifier in SESSION_CONTEXT after connecting, and the policy filters rows and blocks inserts for the wrong tenant. Adapted for a TenantId column (names are hypothetical):

CREATE SCHEMA Security;
GO

CREATE FUNCTION Security.fn_TenantPredicate(@TenantId int)
    RETURNS TABLE
    WITH SCHEMABINDING
AS
    RETURN SELECT 1 AS allowed
    WHERE DATABASE_PRINCIPAL_ID() = DATABASE_PRINCIPAL_ID('AppUser')
      AND CAST(SESSION_CONTEXT(N'TenantId') AS int) = @TenantId;
GO

CREATE SECURITY POLICY Security.TenantPolicy
    ADD FILTER PREDICATE Security.fn_TenantPredicate(TenantId) ON dbo.Orders,
    ADD BLOCK  PREDICATE Security.fn_TenantPredicate(TenantId) ON dbo.Orders AFTER INSERT
    WITH (STATE = ON);

-- The tenant column must never change after insert
DENY UPDATE ON dbo.Orders(TenantId) TO AppUser;
  • The filter predicate covers reads, and also updates and deletes of other tenants' rows, which are filtered out before they can be touched.
  • AFTER INSERT blocks inserting a row for another tenant.
  • The column DENY is how Microsoft's example prevents moving a row to another tenant. The alternative is an AFTER UPDATE block predicate, which the optimizer evaluates only when the columns used by the predicate actually change.
  • DATABASE_PRINCIPAL_ID ties the predicate to the application's database user, so other principals do not accidentally match.
  • SCHEMABINDING (the default) prevents altering the predicate function or the bound columns while the policy exists. Keep the predicate function and policy in a separate schema, as the documentation recommends, so their permissions can be managed apart from the tables.

A missing tenant value compares as NULL, so no rows match. That is the failure direction you want, but verify it in a test instead of assuming it.

Setting the tenant value: read-only, on every connection

The weak point is rarely the SQL. It is how the tenant value arrives. sp_set_session_context has a @read_only option: when it is 1, the value cannot be changed again until the connection is closed, which for pooled connections means returned to the pool. Using it prevents later code on the same connection, including injected SQL, from switching tenants. In EF Core, a connection interceptor can set the value whenever a connection is opened. This is a sketch, not production code:

public sealed class TenantSessionContextInterceptor : DbConnectionInterceptor
{
    private readonly ITenantAccessor _tenant;
    public TenantSessionContextInterceptor(ITenantAccessor tenant) => _tenant = tenant;

    public override async Task ConnectionOpenedAsync(
        DbConnection connection, ConnectionEndEventData eventData,
        CancellationToken cancellationToken = default)
    {
        await using var cmd = connection.CreateCommand();
        cmd.CommandText =
            "EXEC sp_set_session_context @key = N'TenantId', @value = @tenantId, @read_only = 1;";
        var p = cmd.CreateParameter();
        p.ParameterName = "@tenantId";
        p.Value = _tenant.TenantId
            ?? throw new InvalidOperationException("No tenant resolved for this request.");
        cmd.Parameters.Add(p);
        await cmd.ExecuteNonQueryAsync(cancellationToken);
    }
}

Two rules matter more than the code: set the value every time a connection is taken from the pool, and refuse to run a query when no tenant is resolved. Then test the pooled path explicitly by using one pooled connection for tenant A and then for tenant B, and asserting that no stale value survives.

Privileged users are subject to the policy too

Per the documentation, security policies apply to all users, including dbo, members of db_owner and the table owner. If sysadmin or db_owner users need to see all rows to troubleshoot, the policy itself must be written to allow that. Some third-party guides say the opposite, so settle it for your version by testing: impersonate each role with EXECUTE AS USER, count rows, then REVERT. The same technique is the standard way to test RLS in general.

Creating, altering or dropping a security policy requires ALTER ANY SECURITY POLICY, intended for highly privileged users. Dbo users can alter or drop policies, although those changes can be audited, so restrict the permission to very few accounts and alert on changes to policies and predicate functions.

What RLS does not stop

The documentation is explicit about limits that matter for a multi-tenant design:

Area Caveat
Crafted queriesErrors can leak values, for example a divide-by-zero revealing that a hidden value equals a specific number
Policy managerA malicious manager colluding with a user could infer data with side channels through crafted functions
StatisticsDBCC SHOW_STATISTICS reports unfiltered data, so access is restricted to owners and high-privilege roles
Change Data CaptureCan expose full rows to db_owner and the CDC gating role
Change TrackingCan reveal the primary keys of filtered rows to users with the right permissions
Indexed viewsCannot be created on tables with a security policy
Temporal tablesThe policy on the current table is not copied to the history table; add one to each
Partitioned viewsBlock predicates are not supported

RLS also does nothing for shared compute. One tenant's heavy query still slows the others, and restoring or exporting one tenant is still data surgery. RLS is a strong second layer against leaks, and the isolation model decides everything else.

Predicate design and performance

The documentation advises keeping predicate functions simple: avoid type conversions, avoid recursion (including indirect recursion), avoid excessive joins, and avoid logic that depends on session SET options such as date format, which can leak information if users can run arbitrary queries. Predicates are evaluated as part of every query on the table, so measure their cost on your own schema and indexes instead of assuming it is free.

A checklist before relying on RLS

  1. Put TenantId on every table, with filter and block predicates, and deny updates to the tenant column.
  2. Set the tenant with @read_only = 1 every time a connection is opened, and make the data layer refuse to run without one.
  3. Test pooled reuse across two tenants, and test that a missing value returns no rows.
  4. Impersonate the application login, an admin role and a reporting login, and compare row counts.
  5. Restrict ALTER ANY SECURITY POLICY and alert on changes to policies and predicate functions.
  6. Review features in use (CDC, change tracking, temporal tables, indexed views) against the caveats above.
  7. Measure query cost with the policy enabled, on production-like data.

Where to stay cautious

Behavior is documented for specific SQL Server and Azure SQL versions, so recheck the current row-level security documentation for yours. If uniform, modest tenants share a small team's database, shared tables with RLS as a backstop are a reasonable start, as long as RLS is treated as defense in depth and not the only control. If one customer's contract or one noisy workload can end the business, a stronger boundary is worth paying for early.

Comments