Valtuutus.Data.Postgres.Weasel
2.4.0
See the version list below for details.
dotnet add package Valtuutus.Data.Postgres.Weasel --version 2.4.0
NuGet\Install-Package Valtuutus.Data.Postgres.Weasel -Version 2.4.0
<PackageReference Include="Valtuutus.Data.Postgres.Weasel" Version="2.4.0" />
<PackageVersion Include="Valtuutus.Data.Postgres.Weasel" Version="2.4.0" />
<PackageReference Include="Valtuutus.Data.Postgres.Weasel" />
paket add Valtuutus.Data.Postgres.Weasel --version 2.4.0
#r "nuget: Valtuutus.Data.Postgres.Weasel, 2.4.0"
#:package Valtuutus.Data.Postgres.Weasel@2.4.0
#addin nuget:?package=Valtuutus.Data.Postgres.Weasel&version=2.4.0
#tool nuget:?package=Valtuutus.Data.Postgres.Weasel&version=2.4.0
Valtuutus
Valtuutus is a high-performance Relationship-Based Access Control (ReBAC) authorization library for .NET, inspired by Google Zanzibar.
It enables fine-grained authorization for ASP.NET Core and .NET applications — modeling permissions and access control through relationships instead of relying only on roles.
Features:
- Google Zanzibar-inspired permission model
- High-performance authorization engine
- ASP.NET Core / .NET integration
- Strongly typed schema support (source generator)
- Multiple evaluation engines (Check, LookupEntity, LookupSubject, SubjectPermission, Explain)
- Low-allocation execution
- Native AOT compatible
The implementation is inspired on permify and other ReBAC open source projects.
<a href="https://bencher.dev/perf/valtuutus?clear=true&key=true&reports_per_page=4&branches_per_page=8&testbeds_per_page=8&benchmarks_per_page=8&plots_per_page=8&reports_page=1&branches_page=1&testbeds_page=1&benchmarks_page=1&plots_page=1&tab=branches&measures=b549a9dd-6ff0-4525-b90a-c9e3af815580&branches_search=main&branches=1bffa1be-8399-4560-814d-30231501957f%2C9e4cbdcf-9fee-4cd3-ada1-62aefe433145&heads=deb5918c-87b4-4bdb-9b46-25e563bdba14%2C5bdd1841-0a0f-4532-84b7-87ef3d065302&testbeds=072da3db-e609-4676-99a6-5b9262df6086&benchmarks_search=check_complex&benchmarks=86537617-e761-40b8-bd7a-8ad4b6559b47%2C177b6be7-d449-45cb-928a-04f792c80c43%2C8dc1fb40-6499-45e0-be05-23bbf539cd7e%2Cfa90791e-1700-480d-a973-a5df9b695431&start_time=1782864000000&utm_medium=share&utm_source=bencher&utm_content=img&utm_campaign=perf%2Bimg&utm_term=valtuutus"><img src="https://api.bencher.dev/v0/projects/valtuutus/perf/img?branches=1bffa1be-8399-4560-814d-30231501957f%2C9e4cbdcf-9fee-4cd3-ada1-62aefe433145&heads=deb5918c-87b4-4bdb-9b46-25e563bdba14%2C5bdd1841-0a0f-4532-84b7-87ef3d065302&testbeds=072da3db-e609-4676-99a6-5b9262df6086&specs=&benchmarks=86537617-e761-40b8-bd7a-8ad4b6559b47%2C177b6be7-d449-45cb-928a-04f792c80c43%2C8dc1fb40-6499-45e0-be05-23bbf539cd7e%2Cfa90791e-1700-480d-a973-a5df9b695431&measures=b549a9dd-6ff0-4525-b90a-c9e3af815580&start_time=1782864000000" title="valtuutus" alt="valtuutus - Bencher" /></a>
Functionality
The library is designed to be simple and easy to use. Each subset of functionality is divided in engines. The engines are:
- ICheckEngine: The engine that handles the answering of three questions:
Can entity U perform action Y in resource Z? For that, use theCheckfunction.What permissions entity U have in resource Z? For that, use theSubjectPermissionfunction.Why did that permission check succeed or fail?For that, use theExplainfunction — returns a full resolution tree showing every evaluated relation, attribute, and expression.
- ILookupSubjectEngine: The engine that can answer:
Which subjects of type T have permission Y on entity:X?For that, use theLookupfunction. - ILookupEntityEngine: The engine that can answer:
Which resources of type T can entity:X have permission Y?For that, use theLookupEntityfunction. Supports scoped queries and cursor pagination — see below. - IDataWriterProvider: This is the provider that can write your relational or attribute data.
- IDbDataWriterProvider: Works similarly to
IDataWriterProvider, with the addition of accepting a connection and transaction as parameters. - Read here about how the relational data is stored.
- Read here for engine usage examples (Check, Explain, SubjectPermission, LookupSubject, LookupEntity).
LookupEntity — scoped queries and pagination
LookupEntity returns a LookupEntityPage:
LookupEntityPage page = await lookupEntityEngine.LookupEntity(
new LookupEntityRequest("task", "view", "user", "alice"),
cancellationToken);
// page.EntityIds — IReadOnlyList<string>
// page.ContinuationToken — null if no more pages
// page.SnapToken — the snap token the page was read at
Scope — constrain results to a parent entity
Use EntityScope when you need to answer a scoped question like
"which tasks in project X can this user view?" — the same query you'd back a
GET /projects/{projectId}/tasks endpoint with.
Without scope, LookupEntity returns all tasks the user can view across the entire system.
With scope, results are limited to tasks that have the specified relation to the given parent entity —
so only tasks belonging to project-1 are considered.
var page = await lookupEntityEngine.LookupEntity(
new LookupEntityRequest("task", "view", "user", "alice")
{
Scope = new EntityScope(
Relation: "parent", // the relation on "task" that points to its parent
SubjectType: "project", // the parent entity type
SubjectId: "project-1" // the specific parent to scope to
)
},
cancellationToken);
Pagination
Leave SnapToken unset to read each page at the latest snapshot, or pass the previous page's SnapToken to read every page from the same one.
string? token = null;
do
{
var page = await lookupEntityEngine.LookupEntity(
new LookupEntityRequest("task", "view", "user", "alice")
{
Scope = new EntityScope("parent", "project", "project-1"),
PageSize = 50,
ContinuationToken = token
},
cancellationToken);
Process(page.EntityIds);
token = page.ContinuationToken;
} while (token is not null);
Documentation
| Guide | Description |
|---|---|
| Getting Started | End-to-end quickstart — install, configure, write data, check permissions |
| Modeling Authorization | Schema DSL walkthrough with the GitHub example |
| Schema Reference | Complete reference for every keyword, operator, and type in the DSL |
| Authorization Patterns | Ready-made patterns: RBAC, hierarchical RBAC, ABAC, multi-tenancy |
| Using the Engines | Code examples for Check, Explain, SubjectPermission, LookupSubject, LookupEntity, depth |
| Storing Data | Writing, deleting, snap tokens |
| Source Generator | Build-time schema constants and compiled fn functions |
| Testing | Unit-testing your authorization model with the InMemory provider |
| Caching | Reducing database load with FusionCache |
| Telemetry | OpenTelemetry activity sources, emitted spans, and what to monitor |
Usage
Install the package from NuGet:
If using Postgres:
dotnet add package Valtuutus.Data.Postgres
If using SqlServer:
dotnet add package Valtuutus.Data.SqlServer
Requires SQL Server 2016 or later (database compatibility level 130+), Azure SQL Database or Azure SQL Managed Instance.
If using MySQL or MariaDB:
dotnet add package Valtuutus.Data.MySql
Requires MySQL 8.4 or later, or MariaDB 10.11 or later.
If you prefer using an InMemory provider:
dotnet add package Valtuutus.Data.InMemory
Adding to DI:
builder.Services.AddValtuutusCore(c =>
...
See examples of how to define your schema here.
If using Postgres:
builder.Services
.AddPostgres(_ => () => new NpgsqlConnection(builder.Configuration.GetConnectionString("PostgresDb")!));
If using SqlServer:
builder.Services
.AddSqlServer(_ => () => new SqlConnection(builder.Configuration.GetConnectionString("SqlServerDb")!));
If using MySQL or MariaDB:
using MySqlConnector;
using Valtuutus.Data.MySql;
builder.Services
.AddMySql(
_ => () => new MySqlConnection(builder.Configuration.GetConnectionString("MySqlDb")!),
new ValtuutusMySqlOptions(MySqlServerType.MySql)); // MySqlServerType.MariaDb for MariaDB
If using InMemory:
builder.Services
.AddInMemory();
Database migrations
If you are using a DB provider to store your data, please look at the scripts that create the tables that Valtuutus require to function. Run each provider's scripts in order; the file names start with a timestamp, and an upgrade runs only the scripts newer than the ones already applied.
- Postgres: initial, lookup indexes
- SqlServer: initial, lookup indexes, drop TVP_ListIds
- MySQL and MariaDB: initial
Applying the schema with Weasel
Instead of running the scripts yourself, reference the Weasel package for your provider
(Valtuutus.Data.Postgres.Weasel, Valtuutus.Data.SqlServer.Weasel or
Valtuutus.Data.MySql.Weasel; .NET 9 or later) and opt in on the data builder. The tables are
created and migrated with the schema and table names from your provider options, when the host
starts, under a database lock so instances starting together take turns:
builder.Services.AddValtuutusCore(/* schema */)
.AddPostgres(_ => () => new NpgsqlConnection(connectionString))
.AddPostgresWeasel(); // AddSqlServerWeasel / AddMySqlWeasel for the other providers
To apply at a time you choose instead (a migration job, a deploy step), call
await app.Services.ApplyValtuutusSchemaAsync(); (the opt-in call is still required, and its
hosted service also runs if a host starts).
AutoCreate controls how far an apply may go: CreateOrUpdate (default) creates what is missing
and alters what drifted, CreateOnly never alters, None changes nothing. All is refused
because it recreates the tables and deletes their data. ConnectionFactory supplies a different
connection, for example a user allowed to run DDL, or one per tenant:
.AddPostgresWeasel(o =>
{
o.AutoCreate = AutoCreate.CreateOnly;
o.ConnectionFactory = _ => () => new NpgsqlConnection(migrationConnectionString);
});
Indexes and columns you add yourself are left in place. LockTimeout (default one minute) bounds
how long an apply waits for another instance holding the lock before it fails.
Weasel and the scripts produce the same schema. Weasel does not detect two kinds of later drift:
a changed column collation on SQL Server, and a dropped JSON_VALID check on MySQL.
Schema and table name customization
The relational providers accept an options object to customise the database schema and table names. Pass it as the second argument to AddPostgres, AddSqlServer or AddMySql. It is optional for Postgres and SQL Server; AddMySql requires it, because it declares the server type:
// Postgres — defaults: schema="public", tables="transactions", "relation_tuples", "attributes"
builder.Services.AddValtuutusCore(/* schema */)
.AddPostgres(
_ => () => new NpgsqlConnection(connectionString),
new ValtuutusPostgresOptions(
schema: "authz",
transactionsTableName: "transactions",
relationsTableName: "relation_tuples",
attributesTableName: "attributes"));
// SQL Server — defaults: schema="dbo", same table names
builder.Services.AddValtuutusCore(/* schema */)
.AddSqlServer(
_ => () => new SqlConnection(connectionString),
new ValtuutusSqlServerOptions(
schema: "authz",
transactionsTableName: "transactions",
relationsTableName: "relation_tuples",
attributesTableName: "attributes"));
// MySQL / MariaDB — defaults: schema="" (the connection's database), same table names
builder.Services.AddValtuutusCore(/* schema */)
.AddMySql(
_ => () => new MySqlConnection(connectionString),
new ValtuutusMySqlOptions(
serverType: MySqlServerType.MySql,
schema: "authz", // the MySQL database holding the tables
transactionsTableName: "transactions",
relationsTableName: "relation_tuples",
attributesTableName: "attributes"));
Make sure the migration script targets the same schema and table names you configure here.
ValtuutusPostgresOptions also exposes two Npgsql-specific properties for automatic prepared statements:
| Property | Default | Meaning |
|---|---|---|
MaxAutoPrepare |
64 |
Maximum number of statements Npgsql will auto-prepare |
AutoPrepareMinUsages |
2 |
Minimum executions before a statement is prepared |
These map directly to Npgsql's prepared statement feature and can improve performance for repeated queries under load.
ValtuutusPostgresOptions, ValtuutusSqlServerOptions and ValtuutusMySqlOptions also expose LookupHopsPerQuery (default 12 on Postgres and MySQL, 2 on SQL Server): how many levels of a recursive relation one lookup query reads. See How lookups run.
Using query concurrent limiting
It is expected that you don't want to allow Valtuutus to expand queries while it has resources. The default limit is 5 concurrent queries for the same request. To change that, you can use the AddConcurrentQueryLimit method, for example:
builder.Services
.AddPostgres(_ => () => new NpgsqlConnection(builder.Configuration.GetConnectionString("PostgresDb")!)) // Replace this with any provider you want
.AddConcurrentQueryLimit(10);
Change your data provider according to your database.
Caching
Valtuutus supports caching the calls to the engines through the Valtuutus.Data.Caching package. To use it, install like:
dotnet add package Valtuutus.Data.Caching
In your DI setup, add the caching component:
builder.Services
.AddPostgres(_ => () => new NpgsqlConnection(builder.Configuration.GetConnectionString("PostgresDb")!)) // Replace this with any provider you want
.AddCaching(); // <-- This line
This packages requires that you set up the amazing FusionCache library. Click here for more information.
Telemetry
The library uses OpenTelemetry to provide telemetry data. To enable it, just add a source with the name "Valtuutus":
builder.Services
.AddOpenTelemetry()
.WithTracing(telemetry =>
{
telemetry
.AddSource("Valtuutus")
...
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
-
net10.0
- Microsoft.Extensions.Hosting.Abstractions (>= 10.0.0)
- Valtuutus.Data.Postgres (>= 2.4.0)
- Weasel.Postgresql (>= 9.45.0)
-
net11.0
- Valtuutus.Data.Postgres (>= 2.4.0)
- Weasel.Postgresql (>= 9.45.0)
-
net9.0
- Microsoft.Extensions.Hosting.Abstractions (>= 10.0.0)
- Valtuutus.Data.Postgres (>= 2.4.0)
- Weasel.Postgresql (>= 9.45.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
## Summary
Valtuutus 2.4.0 drops .NET 8 and adds opt-in packages that create and migrate the Valtuutus tables with JasperFx Weasel, using the schema and table names from the provider options. It also orders transactions written in the same millisecond, makes relation deletes on Postgres and SQL Server use their indexes, and cuts allocations when reading rows.
## Changes that need attention
- **net8.0 dropped (#362):** every package now targets net9.0, net10.0 and net11.0. .NET 8 support ends 2026-11-10, and the Weasel packages are net9+ only. Projects still on net8.0 stay on 2.3.x.
- **Microsoft.Extensions floors raised to 9.0 (#365):** ObjectPool, DependencyInjection, DependencyInjection.Abstractions and Hosting.Abstractions now require . The Weasel packages require Hosting.Abstractions 10.0.0, because Weasel's JasperFx dependency does.
- **InMemory: an empty string in a delete filter is now a value (#369):** now deletes direct tuples only, as on the relational providers. Before, InMemory treated as any and also deleted userset tuples. A whitespace-only value is also matched literally now. Only a field matches anything.
- **SQL Server: unused type dropped (#364):** run the new migration . Installs that keep the tables in another schema should run under that schema. Skipping it is harmless; the type is just unused.
## Features
- **Weasel schema migrations (#362):** three new opt-in packages:
-
-
- (MySQL and MariaDB)
- Options: (default ; is refused because it drops data), (e.g. a DDL user or per-tenant connections), , (default 1 min).
- Nodes starting together take turns through a cross-node lock (Postgres advisory lock, , ), bounded by and the cancellation token.
- The lock covers one database on every provider. On MySQL, names are server-wide, so the lock name is plus a hash of the database (#371). Applies to different databases on one server don't wait for each other, and is limited to 31 characters there.
- Tables are add-only: indexes and columns you add survive an apply.
- A Weasel install is physically identical to a script install; contract tests check this for every provider. The scripts stay for teams that apply migrations themselves.
- Known blind spots (see README): Weasel doesn't detect a later changed column collation on SQL Server, or a dropped MySQL check.
- **Public default constructors for provider options (#366):** and give the default schema and table names, so you can change only what you need.
- **SQL Server registers its concrete options type (#363):** now also registers (same instance), like and .
## Fixes
- **Transactions written in the same millisecond keep their order (#368):** transaction ids were ULIDs whose 80 bits after the timestamp are random. Two writes in one millisecond could get ids in reverse order: reading at the second write's snap token missed the first, and a result cached at that token was wrong. Ids now come from , which keeps them strictly increasing per clock:
- a 16-bit counter per millisecond;
- no lock and no sleep;
- a clock going back keeps the last millisecond.
This holds within one process. Writes from different nodes still order by their clocks, and the settle window covers that. The InMemory writer no longer waits 10 ms between writes to avoid the collision.
## Performance
- **Relation deletes use the indexes on Postgres and SQL Server (#369):** each delete matched every filter with on all six fields. No index serves that predicate, so it scanned all of once per filter. Filters are now grouped by the fields they set, and each group runs one equality-only statement, the shape MySQL already used. On 1M tuples, revoking one exact tuple went from about 200 ms to 0.2 ms on Postgres, and from about 1 s to 0.15 ms on SQL Server. A delete by subject only (e.g. offboarding a user) still reads the table, because no index leads with the subject columns, but it now does so once per delete instead of once per filter.
- **Fewer allocations reading rows (#370):** the Postgres and SQL Server readers and the batched lookup and check runners now share MySQL's key decoder. Results:
- A key a row repeats from the previous row comes back as the same string.
- On Postgres, keys are read as UTF-8 bytes into a reused buffer.
- A repeated attribute value reuses one parsed element.
- On Postgres, allocates 44% less (108 → 60 KB per call) and SQL Server 9% less.
- No scenario got slower.
## Pull requests
- #362 feat(data): opt-in Weasel schema migrations; drop net8.0
- #363 refactor(sqlserver): register the concrete options type like the other providers
- #364 chore(sqlserver): drop the unused TVP_ListIds type
- #365 chore(deps): raise Microsoft.Extensions floors to 9.0
- #366 feat(data): public default constructors for the provider options
- #368 fix(data): stamp transactions with monotonic ULIDs
- #369 perf(data): delete relations with one equality-only statement per filter shape
- #370 perf(data): reuse repeated keys and attribute values while reading rows
- #371 fix(mysql-weasel): take the schema lock per database
- #372 test: share one database server per provider across the test run
- #361 Build(deps): Bump actions/setup-dotnet from 6.0.0 to 6.1.0