Tenants and row-level security

This page covers what Custodian does in the database itself. Tenants share tables, and every personal row carries its tenant. The application connects as one of five database roles. Each connection carries the processing context in its session, and row-level security reads it. The page ends with the Dapper integration, which relies on all of this.

1. Tenants share tables

Custodian's multi-tenancy is shared tables. It adds a TenantId column to every personal table. You do not declare it on the entity, and you do not set it. Custodian stamps it on save from the signed-in user's tenant. The middleware supplies that tenant, as ASP.NET Core describes.

The Shop sample runs two shops, Nordic and Alpine, in one database.

[Theory, EachProvider]
public async Task A_sales_clerk_sees_only_the_customers_of_their_own_shop(DatabaseProvider provider)
{
    await using var shops = await servers.OpenShop(provider);
    var astrid = await shops.Nordic.SignUp(Customers.Astrid());
    await shops.Alpine.SignUp(Customers.Bruno());

    var names = await shops.Nordic.As(Staff.Sales).For(Purposes.CustomerAccount).Query(db => db.Customers.Select(c => c.Name));

    Assert.Equal([astrid.Name], names);
}

The query has no tenant condition. Custodian adds one to every EF Core query on a personal entity. That filter is the first of two enforcements. The second is row-level security in the database, which section 4 describes. A tenant is kept apart even when the query never passes through EF Core.

2. Five database roles

Custodian never connects as the end user. It connects with one credential per database role, and you give it a connection string for each. Getting started shows the registration. DbRole has five values, and each stands for a database role with a fixed name.

public static string RoleName(DbRole role) => role switch
{
    DbRole.Reader => "app_reader",
    DbRole.Writer => "app_writer",
    DbRole.Privacy => "app_privacy",
    DbRole.Retention => "app_retention",
    DbRole.Batch => "app_batch",
    _ => throw new ArgumentOutOfRangeException(nameof(role)),
};

When a user declares a purpose, Custodian opens the connection as the database role their application role maps to. If several of the user's roles allow the purpose, it picks the least privileged one. A read outside the purpose can only connect as Reader.

You create the five roles and grant them what they need on your tables. Give each the least it needs. No application role should own a table or be able to bypass row-level security. A separate owner role creates the schema and installs the policies, and the application never connects as that role. The samples' test harness sets the roles up this way in SqlServerServer.cs and PostgreSqlServer.cs. With those grants the reader role reads and cannot write or change the schema. See The_reader_role_cannot_write_to_a_table and The_reader_role_cannot_create_a_table.

3. Session context

A shared credential would hide who is acting. So Custodian writes the processing context into the database session of every connection it opens. The session carries the actor, the tenant, the purpose and the roles. An assisted session adds the customer it is on behalf of. A system run that spans tenants adds its run.

The two databases hold the values differently.

A connection opened without Custodian has no session context at all.

4. Row-level security

The schema installer puts a row-level-security policy on every personal table. Section 5 of Getting started shows the call. The policy compares each row's tenant with the tenant in the session. A row of another tenant is not visible and cannot be written. In an assisted session the policy also limits the rows to those of the one customer. The one exception to the tenant rule is a system run registered for all tenants, which System runs covers.

The policy fails closed. With no tenant in the session, no row matches.

[Theory, EachProvider]
public async Task Raw_sql_without_session_context_finds_no_customers(DatabaseProvider provider)
{
    await using var shops = await servers.OpenShop(provider);
    await shops.Nordic.SignUp(Customers.Astrid());

    var names = await shops.RawSqlWithoutSessionContext<string>("SELECT name FROM customers");

    Assert.Empty(names);
}

That query runs as app_reader on a plain connection, without Custodian. It may select from the table and it finds nothing.

With a session context, raw SQL sees one tenant. SELECT name FROM customers has no WHERE clause and still returns only the caller's shop. See Raw_sql_in_one_shop_finds_only_that_shops_customers and Raw_sql_in_one_shop_finds_only_that_shops_parcels.

Tables that hold no personal data get no policy. See Raw_sql_without_session_context_still_sees_the_product_catalogue.

5. A pooled connection leaks nothing

Connection pools hand the same physical connection to one request after another. The session context must not travel with it. The test below makes a Nordic clerk and an Alpine clerk use the same physical connection, one after the other.

[Theory, EachProvider]
public async Task A_pooled_connection_reused_by_another_shop_sees_only_that_shops_customers(DatabaseProvider provider)
{
    await using var shops = await servers.OpenShop(provider);
    await shops.Nordic.SignUp(Customers.Astrid());
    var bruno = await shops.Alpine.SignUp(Customers.Bruno());

    var names = await shops.Alpine.RawSqlOnAConnectionLastUsedBy<string>(shops.Nordic, "SELECT name FROM customers");

    Assert.Equal([bruno.Name], names);
}

The second user sees their own tenant and nothing of the first. On SQL Server the pool resets the session when it hands the connection out again, and Custodian sets the new context on open. On PostgreSQL the values were local to a transaction that has already ended.

If the next user of that connection is not Custodian at all, it finds no context left behind. See A_pooled_connection_reused_without_custodian_carries_no_session_context. The Clinic proves the same for health data in A_pooled_connection_reused_by_a_Riverside_clinician_shows_none_of_Northsides_patients.

6. Dapper

EF Core queries pass through Custodian's filters. SQL that you write yourself does not, so the database has to hold the line. That is why the Dapper integration requires row-level security. Turn the integration on with UseDapper. The Shop also names the table that Shipment is stored in.

o.UseDapper();
o.Model.Configure<Shipment>(m => m.Table("shipments"));

The Shop's nightly label job uses Dapper.

private const string ParcelsAwaitingDispatch =
    """
    SELECT id AS Id, order_id AS OrderId, recipient_subject_id AS RecipientSubjectId,
           recipient_name AS RecipientName, delivery_address AS DeliveryAddress
    FROM shipments
    WHERE delivered_at IS NULL
    """;

public async Task<LabelRun> PrintAsync(TenantId shop, CancellationToken cancellationToken)
{
    await using var run = await processing.BeginSystemRunAsync(Principal, Purposes.Fulfilment, shop, cancellationToken);
    await using var connection = await custodian.OpenAsync(DbRole.Batch, cancellationToken);

    var parcels = await connection.QueryPersonalAsync<Shipment>(ParcelsAwaitingDispatch, cancellationToken: cancellationToken);

    return new LabelRun(run.Id, [.. parcels.Select(p => new ShippingLabel(p.Id, p.RecipientName, p.DeliveryAddress))]);
}

custodian.OpenAsync opens a connection as the given database role, with the current processing context in its session. Declare the purpose first. Without a context it throws ProcessingContextMissingException, as A_job_that_has_not_opened_a_run_cannot_get_a_database_connection shows.

QueryPersonalAsync<T> runs your SQL and maps the rows to a classified entity. It checks the purpose, decrypts encrypted fields and audits the read. The query must select from the entity's table by name and return the subject column. Row-level security keeps the result inside the tenant. See The_label_batch_prints_labels_only_for_parcels_of_its_own_shop and A_shipping_label_carries_the_decrypted_delivery_address.

You can also run plain Dapper calls on the same connection. Then only row-level security applies. The tests in section 4 that run raw SQL in one shop work that way.

7. The startup check

UseDapper adds a check that runs before the application serves anything. It looks at every personal table and verifies that an enabled row-level-security policy is on it. Outside the Development environment a missing policy stops the application with RowLevelSecurityMissingException, which names the tables.

[Theory, EachProvider]
public async Task The_shop_refuses_to_start_in_production_when_parcels_have_no_row_level_security(DatabaseProvider provider)
{
    await using var shops = await servers.OpenShop(provider);
    await shops.RemoveRowLevelSecurityFrom("shipments");

    var starting = () => shops.StartApp(Environments.Production);

    await Assert.ThrowsAsync<RowLevelSecurityMissingException>(starting);
}

In Development the same finding is logged as a warning and the application starts. A fresh checkout can then run before its schema is installed. See The_shop_still_starts_in_development_when_parcels_have_no_row_level_security. When every table has its policy, production starts normally. See The_shop_starts_in_production_when_every_personal_table_has_row_level_security.

A migration that drops or disables a policy is therefore caught the next time the application starts.

Next