System runs

This page covers batch jobs and other code that runs without a signed-in user. It shows how to register a system principal with its purpose and the fields it may read, how the job opens a run before it queries anything, what the job is refused, how a run stays inside one tenant, and how a run is audited. The code is the Shop sample, whose nightly job prints shipping labels.

Register the principal

A job has no user and no role. You register it by name instead, and you declare up front why it processes personal data and exactly what it reads.

o.SystemPrincipals.Register(ShippingLabelBatch.Principal, p => p
    .AuthenticatedBy(WorkloadIdentity.ManagedIdentity("mi-shipping-labels"))
    .DbRole(DbRole.Batch)
    .Purpose(Purposes.Fulfilment, LawfulBasis.Contract)
    .Reads<Shipment>(s => s.RecipientName, s => s.DeliveryAddress)
    .PerTenant());

The registration is part of your access policy, next to the role mappings. A DPO can review it there. The command-line tool lists every registered principal in the Art. 30 record.

Open a run before any query

The job opens a run with its principal name, its purpose and the tenant. Everything it does with personal data happens inside that run.

using Custodian;
using Custodian.Dapper;

namespace Shop;

/// <summary>A label for one parcel.</summary>
public sealed record ShippingLabel(int ShipmentId, string RecipientName, string DeliveryAddress);

/// <summary>What one nightly label run printed, and the run id its audit entry carries.</summary>
public sealed record LabelRun(RunId Run, IReadOnlyList<ShippingLabel> Labels);

/// <summary>
/// The nightly job that prints shipping labels for one shop. It is a registered system principal: it opens a run with
/// its declared purpose before touching anything, reads only the two fields it declared, and is audited once per run.
/// It uses Dapper, so row-level security in the database is what keeps it inside its shop.
/// </summary>
public sealed class ShippingLabelBatch(IProcessingContext processing, ICustodian custodian)
{
    public const string Principal = "shipping-labels";

    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))]);
    }
}

BeginSystemRunAsync refuses a principal that is not registered, a purpose other than the registered one, and a per-tenant principal that names no tenant. Disposing the run closes it and writes its audit entry.

There is no default purpose for a job. Without an open run there is no processing context, and Custodian fails closed. The job does not even get a database connection. See A_job_that_has_not_opened_a_run_cannot_get_a_database_connection.

The label job uses Dapper. QueryPersonalAsync decrypts the delivery address for the label, as A_shipping_label_carries_the_decrypted_delivery_address shows. A run works the same way with EF Core.

Reads outside the declared fields are denied

The label job declared the recipient name and the delivery address of a shipment. It may read nothing else.

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

    var reading = () => shops.Nordic.DuringRun(ShippingLabelBatch.Principal, Purposes.Fulfilment).Query(db => db.Orders);

    await Assert.ThrowsAsync<PurposeViolationException>(reading);
}

Customer accounts are refused the same way. See The_label_run_cannot_read_customer_accounts_it_did_not_declare.

For a person, what happens outside the purpose is configuration. It can be a refusal, a masked value or break-glass access. For a system principal it is always a refusal. A job is never given masked values, and there is no break-glass for machines. If a job needs another field, declare it and let the change be reviewed.

One tenant per run

A per-tenant run carries its tenant into the database session. Row-level security then keeps every statement inside that tenant, including SQL the job wrote by hand.

The Nordic run prints labels for Nordic parcels only, although both shops share the table. See The_label_batch_prints_labels_only_for_parcels_of_its_own_shop.

To process every tenant with a per-tenant principal, open one run per tenant. Tenants and row-level security describes the session context and what Dapper needs at startup.

Audited once per run

A person's access is audited as it happens. A run is audited once, when it closes. The entry carries the principal as the actor, the purpose, the run id and the number of rows the run touched. It never carries a value.

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

    var printed = await shops.Nordic.PrintShippingLabels();

    var trail = await shops.Nordic.PrivacyOffice.AuditTrail();
    var entry = Assert.Single(trail.ForRun(printed.Run));
    Assert.Equal(AuditOperation.SystemRunCompleted, entry.Event.Operation);
    Assert.Equal(2, entry.Event.Count);
}

Keep the run id with whatever the job produced. The sample returns it next to the labels, so a label can be traced to the run that printed it. Audit trail describes how to read the entries back.

Next