Valtuutus.Data.Postgres
3.0.0
See the version list below for details.
dotnet add package Valtuutus.Data.Postgres --version 3.0.0
NuGet\Install-Package Valtuutus.Data.Postgres -Version 3.0.0
<PackageReference Include="Valtuutus.Data.Postgres" Version="3.0.0" />
<PackageVersion Include="Valtuutus.Data.Postgres" Version="3.0.0" />
<PackageReference Include="Valtuutus.Data.Postgres" />
paket add Valtuutus.Data.Postgres --version 3.0.0
#r "nuget: Valtuutus.Data.Postgres, 3.0.0"
#:package Valtuutus.Data.Postgres@3.0.0
#addin nuget:?package=Valtuutus.Data.Postgres&version=3.0.0
#tool nuget:?package=Valtuutus.Data.Postgres&version=3.0.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, pending transactions
- SqlServer: initial, lookup indexes, drop TVP_ListIds, pending transactions
- MySQL and MariaDB: initial, pending transactions
On SQL Server, consider turning on READ_COMMITTED_SNAPSHOT for the Valtuutus database (Azure SQL Database has it on by default): without it, a read that touches rows an open write changed waits for that write to finish.
On MySQL and MariaDB, writes in your own transaction (an IDbDataWriterProvider overload that takes a transaction) are best made at READ COMMITTED. Under the server default, REPEATABLE READ, a delete keeps gap locks next to the tuples it tombstones, and concurrent deletes of neighbouring tuples can deadlock; retry the transaction when that happens. Writes Valtuutus commits itself already use READ COMMITTED.
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(); from the Valtuutus.Data namespace (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(MySqlServerType.MySql)
{
Schema = "authz", // the MySQL database holding the tables
TransactionsTableName = "transactions",
RelationsTableName = "relation_tuples",
AttributesTableName = "attributes",
});
Set only the names you change; the others keep their defaults. 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
- Npgsql (>= 9.0.3)
- Valtuutus.Data.Db (>= 3.0.0)
-
net11.0
- Npgsql (>= 9.0.3)
- Valtuutus.Data.Db (>= 3.0.0)
-
net9.0
- Npgsql (>= 9.0.3)
- Valtuutus.Data.Db (>= 3.0.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Valtuutus.Data.Postgres:
| Package | Downloads |
|---|---|
|
Valtuutus.Data.Postgres.Weasel
Valtuutus Postgres schema migrations with Weasel; Valtuutus is a high-performance Relationship-Based Access Control (ReBAC) authorization library for .NET inspired by Google Zanzibar, for fine-grained permissions in ASP.NET Core and .NET applications. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 3.0.2 | 162 | 11/10/2026 |
| 3.0.1 | 116 | 11/9/2026 |
| 3.0.0 | 104 | 11/9/2026 |
| 2.4.0 | 103 | 11/9/2026 |
| 2.3.2 | 110 | 11/3/2026 |
| 2.3.1 | 128 | 11/3/2026 |
| 2.3.0 | 127 | 10/29/2026 |
| 2.2.1 | 190 | 10/28/2026 |
| 2.2.0 | 123 | 10/25/2026 |
| 2.1.0 | 112 | 10/20/2026 |
| 2.0.0 | 109 | 10/16/2026 |
| 1.6.0 | 124 | 10/16/2026 |
| 1.5.0 | 98 | 10/14/2026 |
| 1.4.0 | 131 | 10/3/2026 |
| 1.3.0 | 369 | 7/30/2026 |
| 1.2.0 | 149 | 7/24/2026 |
| 1.1.0 | 133 | 7/17/2026 |
| 1.0.0 | 145 | 7/11/2026 |
| 0.11.1-beta | 146 | 7/4/2026 |
| 0.11.0-beta | 170 | 6/26/2026 |
## Summary
Valtuutus 3.0 makes snap tokens safe against out-of-order commits. A request without a snap token now reads at a **settled** token: one no write can still commit under. So an answer read at a token, cached or not, never changes afterwards. This needs a new table on Postgres, SQL Server and MySQL/MariaDB.
3.0 also lets relations point at entities of different types, aligns arrow validation with how arrows are evaluated, and simplifies the caching, Weasel and provider option APIs.
## Before you upgrade: apply the new migration
Postgres, SQL Server, MySQL and MariaDB need the table. Until it exists, writes and requests without a snap token fail.
- **Scripts:** run for your provider:
- [Postgres](src/Valtuutus.Data.Postgres/Database/migrations/20261109120000_transactions_pending.sql)
- [SQL Server](src/Valtuutus.Data.SqlServer/Database/migrations/20261109120000_transactions_pending.sql)
- [MySQL/MariaDB](src/Valtuutus.Data.MySql/Database/migrations/20261109120000_transactions_pending.sql)
- **Custom schema or table names:** the table is named after your transactions table (), in the same schema. Edit the script to match.
- **Weasel packages:** create it on the next apply; nothing to do.
- **InMemory:** needs nothing.
## Breaking changes
- **Arrows are validated on the entity each tuple points at (#384).**
- An arrow () evaluates its member on the entity a tuple names. For a userset target that is the group itself, not the group's members. Every engine already did this, as SpiceDB and Permify do.
- The schema check validated the member on the type the userset resolves to instead. A schema could pass while that arrow path never granted.
- Now the member must exist on every entity the relation names directly, and the error says how to fix it: define the member on that entity (e.g. ) or remove the userset target.
- Every known schema we checked parses unchanged.
- ** and are removed (#385).**
- With settled tokens an answer cached at a token can't go stale, so shortening how long recent answers are cached only cost hits.
- Results are now cached for . Delete lines that set either option.
- A custom used with caching must return settled tokens from (see ).
- ** moved to the namespace (#386).**
- One method now serves every Weasel package and runs every registered applier, so referencing two Weasel packages no longer makes the call ambiguous.
- Add where you call it. is now public there.
- **Provider schema and table names are properties (#387).**
- The four-name constructors of , and are gone.
- Set only the names you change: , or . Blank names are still refused.
## Features
- **Settled snap tokens (#376 Postgres, #377 MySQL/MariaDB, #378 SQL Server, #380 InMemory).**
- The problem: a write takes its id before it commits. When a write with an older id committed after a newer one, its rows landed inside a snapshot requests had already read. An answer cached at that token went stale, and a late revoke could keep answering allowed.
- How it's fixed:
- writes now register while in flight;
- a request without a token reads at the newest committed id below every open write;
- a write whose id isn't above the newest committed one (e.g. from a node whose clock is behind) takes a new id above it ().
- Stress run: 20 s, 16 writers in caller transactions toggling the same tuples, 8 readers rechecking every answer at its token afterwards.
| provider | answers that changed, 2.4 | 3.0 |
|---|---|---|
| Postgres | 62,102 of 378,627 | 0 of 181,561 |
| SQL Server (RCSI) | 235,437 of 522,894 | 0 of 412,104 |
| MySQL 8.4 | 117,352 of 366,589 | 0 of 317,551 |
| MariaDB 10.11 | 127,403 of 402,123 | 0 of 356,320 |
- Costs:
- **Write latency:** a single write takes about 0.15 ms longer on Postgres.
- **Check latency under heavy write load:** checks without a token are slower. p50 under 16 writers: Postgres 0.16 → 0.20 ms, MySQL 0.35 → 0.49 ms.
- **Check latency without writers:** within a few microseconds of 2.4.
- **Long transactions:** a long transaction you own holds settled tokens back until it commits. Requests carrying a token, such as the one returned, are unaffected.
- On SQL Server, a request without a token no longer waits for open writes, with or without . Data reads touching rows an open write changed still wait without RCSI; the README recommends turning it on.
- InMemory (#380): requests in another scope now see writes made elsewhere, and concurrent writes apply in id order.
- **The cache only stores final answers (#379).**
- After a write, the cache's latest token moves to the provider's latest settled token, not the written one.
- A request carrying a token newer than the latest token the cache knows is answered without the cache, until that token settles.
- **Relations whose targets are of different types (#382).**
- is now accepted.
- Each subject is evaluated as its own type.
- An arrow over such a relation needs the member on every target type. It compiles to one batched query per target type where possible.
- **Native AOT smoke test in CI (#383).** A Native AOT app is published with warnings as errors and run against InMemory, Postgres, MySQL and SQL Server on every build, so an AOT regression fails CI.
## Fixes
- **MySQL/MariaDB: resolving the latest token no longer takes row locks (#375).** It was a locking read, so it waited for every open write and deadlocked with writers under load. Stress run: 49,742 deadlocks on MySQL, 4,113 on MariaDB. It is now a consistent read.
- **MySQL: deletes no longer deadlock under concurrent writes (#381).**
- With mostly tombstoned tuples, MySQL planned the delete as a table scan that locked every row. An optimizer hint now makes it seek the index the filter leads with: 0 deadlocks in the same stress run, against 82–139.
- MariaDB can still deadlock on deletes in your own transaction under . Use there, or retry (README).
## Pull requests
- #375 fix(mysql): resolve the latest snap token with a consistent read
- #376 feat(postgres): resolve only settled snap tokens
- #377 feat(mysql): resolve only settled snap tokens
- #378 feat(sqlserver): resolve only settled snap tokens
- #379 feat(caching): cache only answers at settled tokens
- #380 fix(inmemory): share the latest token across scopes and write in id order
- #381 fix(mysql): delete relations through the index the filter leads with
- #382 feat(lang): relations whose targets are of different entity types
- #383 ci: publish and run a Native AOT smoke app
- #384 feat(lang)!: validate an arrow's member on each entity the relation names
- #385 feat(caching)!: retire the settle window
- #386 feat(weasel)!: one ApplyValtuutusSchemaAsync for every provider
- #387 feat(db)!: set provider schema and table names with init properties
- #388 test(inmemory): bound the executor drain waits by 30 s
- #374 Build(deps): Bump EnricoMi/publish-unit-test-result-action