How do you implement row-level security in SQL Server?

Instruction: Explain SQL Server row-level security using a trusted database-user-to-tenant mapping. Distinguish filtering from blocking unauthorized writes, and describe the limitations when application users share one database login.

Context: This question probes the candidate's understanding of database security practices, specifically focusing on their ability to implement row-level security to ensure data privacy and compliance.

Updated

Official answer

In SQL Server, use a schema-bound inline table-valued function as the policy predicate. This example assumes each caller authenticates as a distinct database user. Administrators maintain Security.TenantAccess(database_user sysname, tenant_id int) with a unique pair; callers cannot modify that mapping or impersonate another user. The protected table is dbo.Orders with a non-NULL integer tenant_id.

Run function creation as its own batch:

CREATE FUNCTION Security.CanAccessTenant(@tenant_id int)
RETURNS TABLE WITH SCHEMABINDING
AS RETURN
  SELECT 1 AS permitted
  WHERE EXISTS (
    SELECT 1 FROM Security.TenantAccess AS a
    WHERE a.database_user = USER_NAME()
      AND a.tenant_id = @tenant_id
  );

Then create the policy:

CREATE SECURITY POLICY Security.OrderTenantPolicy
ADD FILTER PREDICATE Security.CanAccessTenant(tenant_id) ON dbo.Orders,
ADD BLOCK PREDICATE Security.CanAccessTenant(tenant_id) ON dbo.Orders AFTER INSERT,
ADD BLOCK PREDICATE Security.CanAccessTenant(tenant_id) ON dbo.Orders AFTER UPDATE
WITH (STATE = ON, SCHEMABINDING = ON);

Filtering restricts visible rows; block predicates reject newly unauthorized tenant values. Restrict policy administration and grant only needed table operations. Test authorized/unauthorized reads, inserts, tenant changes and pooled connections as real application roles.

A shared database login needs a different, trusted application-context design: USER_NAME cannot distinguish its end users. RLS is one control, not proof of end-to-end isolation or compliance.

Sources: RLS semantics, policy syntax.

Related Questions