Security and multi-tenancy
Isolation and permissions are enforced by the engine on every read and write, not left to each page.
Permissions
With AddHttpApi(), permissions come from the signed-in user’s claims (type permission, configurable with
PermissionClaimType). Deny by default: anonymous callers get 401, callers without the claim 403.
| Claim | Grants |
|---|---|
crud:cities:view |
List, get, schema, lookups of cities |
crud:cities:create / update / delete |
That action |
crud:cities:restore |
See and restore soft-deleted rows |
crud:cities:purge |
Delete soft-deleted rows for good: only this exact claim, never a wildcard |
crud:cities:* |
Every action of cities except purge |
crud:* |
Every action of every page except purge |
crud:cities:{name}:view / :edit |
A [Restricted] field: only this exact claim (below) |
crud:cities:all |
Skip the page’s row rules: only this exact claim (below) |
CrudPages.City.Claims.View etc. hold these strings. The schema’s permissions tells UIs which buttons to show.
The host role (AddHttpApi(o => o.HostRole = "admin")) may do everything, including purge, across tenants.
Roles in the database (Attritect.Permissions)
Keep roles in your own database and manage them from screens instead of issuing claims:
// DbContext.OnModelCreating
modelBuilder.AddCrudPermissions(); // CrudRoles, CrudRolePermissions, CrudUserRoles (add a migration)
// Program.cs
builder.Services.AddCrudEngine(o => o.AddPagesFrom(...).AddPermissionPages()) // Roles, Role permissions, User roles
.UseEntityFrameworkCore<AppDbContext>()
.AddHttpApi(o => o.HostRole = "admin")
.UseDatabasePermissions<AppDbContext>(); // database roles + permission claims
- A role holds permission texts written exactly like the claims above (
crud:cities:*,crud:cities:population:view). A user role links a user id (ICrudUser.Id) to a role, in one tenant (Tenant, the id as text) or in every tenant (empty). - The check is the same as for claims: same wildcards, purge and named rights only by their exact text, the host
allowed everything. Permission claims still count (
o.IncludeClaims = falseto use the database only). - The caller’s permissions are loaded once per request, so a change applies to the next request.
- The three role pages share the permission
crud:permissions:*(CrudPermissions.Management). With multi-tenancy they are shared pages: tenants may read them, but only the host changes them, because roles apply across tenants. Whoever can change roles can grant anything, so give this permission to administrators only. GET {prefix}/pages/permissionslists everything there is to grant (actions per page, restore and purge on soft-delete pages,allon pages with row rules,{field}:view/:editfor restricted fields), for role editors such as the pro permission matrix.
Your own rules: implement ICrudPermissionProvider and register it; the
engine never replaces your registration. Implement its second IsAllowedAsync(permission, right) for restricted
fields and “all rows”: the default answer is no (fail closed). AllowAllPermissions = true switches checks off (development only).
Pages the API only reads
[CrudPage("audit-notes", Entity = typeof(AuditNote), ApiReadOnly = true)] // a page you own
o.MakeApiReadOnly("some-page"); // a page you don't
o.AddPermissionPages(apiReadOnly: true); // the three role pages
Create, update, delete, restore and purge over HTTP (and the Pro import) answer 403 for everyone, the host role included; the schema reports them as not allowed, so UIs hide the buttons. Your own code (services, seed data, jobs) still writes the page. Lock the role pages when the host must not reach tenant data: otherwise the host, who is allowed everything, could assign itself a role in any tenant through the API.
What the host role can do
The host is allowed every permission, across tenants: it reads every tenant’s rows, writes shared pages (the role pages too), sees restricted fields and, with Pro, every tenant’s audit history. If your platform admins must not see or change tenant data, don’t give them the host role for that work, lock the role pages, and narrow the rest by replacing the permission provider.
Code that calls the service
The HTTP API checks permissions before it calls ICrudService<T>; the service itself doesn’t, by default, so a
job or use case that calls it on behalf of a user must check first:
if (!await permissions.IsAllowedAsync("orders", CrudAction.Update, ct)) // ICrudPermissionProvider
throw new CrudForbiddenException("You may not change orders.");
await orders.UpdateAsync(id, model, ct);
Or turn on o.EnforcePermissionsInService = true in AddCrudEngine: the service then checks list, get, create,
update, delete, restore, purge and lookups itself. Code that runs without a user (seeding, background jobs) then needs a
permission provider that allows it. Your own EF queries are never checked or tenant-filtered by the engine: filter
and check them yourself.
Permissions stay current
The database permission provider keeps a caller’s grants until the role pages change (saves through them signal
it) or MaxCacheAge passes (default 1 minute), so a Blazor circuit open for hours sees new and removed roles. When
your own code writes the role tables, call CrudPermissionChanges.Notify().
Options belong to the classes that read them
AddHttpApi(o => ...) options are read by the default HTTP classes: HostRole and PermissionClaimType by
ClaimsPermissionProvider and HttpTenantContext, TenantClaimType and TenantHeader by HttpTenantContext.
Replace one of those classes and its options no longer apply: your replacement decides (the database permission
provider, for example, takes the host from the tenant context).
Restricted fields
[Grid, Field, Restricted("salary")]
public decimal? Salary { get; set; }
| Claim | Effect |
|---|---|
| none | The value is removed (null), the column and field leave the schema, filtering or sorting on it is a 400 |
crud:employees:salary:view |
Visible; in forms it’s read-only and saving keeps the stored value |
...:salary:view + ...:salary:edit |
Normal field |
Only the exact claims or the host role grant these; crud:* doesn’t. Use a nullable type so hidden values read as
null. Exports leave hidden columns out, imports can’t set read-only fields, and audit history hides their values.
The generator adds CrudPages.Employee.Claims.Salary.View / .Edit.
Row rules
Limit which rows a caller sees and changes, inside their tenant:
[CrudPage("work-items", Entity = typeof(WorkItem))]
[OwnRows] // only rows they created (the entity's CreatedBy)
public class WorkItemModel { ... }
[CrudPage("orders", Entity = typeof(Order))]
[ScopeBy(nameof(Order.BranchId), "branch_id")] // BranchId must be one of the user's branch_id claims
public class OrderModel { ... }
public class ConfidentialRule(ICrudUser user) : ICrudRowRule<Document> // anything else, as a filter
{
public ValueTask<Expression<Func<Document, bool>>?> GetFilterAsync(string page, CancellationToken ct) =>
ValueTask.FromResult<Expression<Func<Document, bool>>?>(user.Id == "boss" ? null : d => !d.Confidential);
}
- Rules apply together, to every read (list, get, lookups, history) and write (update, delete, restore, purge), in SQL. Rows outside them behave like another tenant’s: hidden, 404.
- A new or changed row must stay inside the rules (403): e.g. a user of branch 1 can’t create a branch-2 order.
crud:{page}:all(exact claim or the host role) skips the rules: managers, auditors.- Unique values stay unique across all rows, including ones the caller can’t see.
- On pages with row rules, audit history shows rows the caller can see, and deleted items only the caller’s own.
- Startup fails if
[OwnRows]has noCreatedByor[ScopeBy]names a missing property (no compile-time check yet).
Multi-tenancy
builder.Services.AddCrudEngine(o => o.AddPagesFrom(asm).UseMultiTenancy<int>()) // tenant key type
Who is the tenant: the user’s tenant_id claims (TenantClaimType) list their tenants; with several, the
X-Tenant header (TenantHeader) picks the active one. A tenant the user doesn’t belong to is a 403. Override
HttpTenantContext (or register your own ITenantContext) for other schemes.
Which pages are tenant data ([CrudPage(Tenancy = ...)]):
| Tenancy | Rows | Who writes |
|---|---|---|
Auto (default) |
Tenant-owned if the entity has TenantId, else global |
|
Tenant |
Each tenant sees only its rows | the tenant |
Shared |
Everyone reads the same rows | the host only |
SharedWithTenantRows |
Shared rows (TenantId = null) plus each tenant’s own |
host: shared rows; tenants: their own |
What the engine guarantees: lists, gets, lookups, unique checks and reference checks are filtered; new rows get the active tenant (never a value from the request); another tenant’s row is a 404 (its existence isn’t revealed); updates can’t move a row to another tenant.
Tenant databases
Any tenant can have its own database while the others share one; global pages use a host database:
engine.UseTenantDatabases<AppDbContext>((o, cs) => o.UseSqlServer(cs), t =>
{
t.Host = hostConnection;
t.Shared = sharedConnection;
t.Dedicated(42, tenant42Connection); // tenant 42 alone
});
Or t.UseResolver<MyResolver>() (an ITenantConnectionResolver) to read the mapping from anywhere. The tenant
filter stays on in every database.
Read replicas
engine.UseReadStore<ReplicaDbContext>(); // same model, another connection
Lists, gets and lookups read the replica; everything that must be current (reloading a row just saved, unique and foreign-key checks, loading rows to change) uses the write side.
Other protections
- Only
[Field]properties are written (no over-posting);[SafeText]blocks HTML in text. - All values are SQL parameters; nothing is evaluated in memory.
- Soft-deleted rows are hidden everywhere and can’t be linked to; see Delete and audit.