Policy tests
Ability::permitted_fields and condition_for are policy code — a regression is a silent data leak. Assert against them directly.
Ability::permitted_fields and
Ability::condition_for
are the policy code of a nestrs app — they decide which fields a caller
sees and which rows the data layer accepts (through
Repo). A regression there is a silent
data leak; a happy-path e2e does not catch it.
These are ideal unit-test targets: pure functions on policy types, no DI, no DB, microsecond runs. The demo tests its ability directly — quote them as the model.
Build an ability from claims
Section titled “Build an ability from claims”The tests reconstruct an Ability the way the guard does: an
AbilityBuilder carrying the scopes the token grants, the app policy’s
define, then build — which returns a Result, refusing a malformed rule
rather than building it. Small role-shaped helpers keep each assertion to one
line.
use nest_rs::authz::{Ability, AbilityBuilder, FieldSet};use sea_orm::{DatabaseBackend, EntityTrait, IdenStatic, QueryFilter, QueryTrait};// …
fn ability_for(roles: Vec<Role>, org_id: Uuid) -> Ability { ability_scoped(roles, org_id, constants::all())}
fn ability_scoped(roles: Vec<Role>, org_id: Uuid, scopes: Vec<String>) -> Ability { ability_of(roles, org_id, scopes, Subject::User(Uuid::nil()))}
fn ability_of(roles: Vec<Role>, org_id: Uuid, scopes: Vec<String>, sub: Subject) -> Ability { let claims = Claims { sub, client_id: "publish-web".into(), org_id, roles, scopes: scopes.clone(), }; let mut b = AbilityBuilder::new().with_granted_scopes(Some(scopes.into())); AuthzAbility.define(&claims, &mut b); b.build().expect("valid test ability")}
fn admin(org_id: Uuid) -> Ability { ability_for(vec![Role::Admin], org_id)}
fn member(org_id: Uuid) -> Ability { ability_for(vec![Role::User], org_id)}Field grants — every grant scenario
Section titled “Field grants — every grant scenario”permitted_fields::<E>(action, &model) answers the columns a grant leaves a
row, the same set a wire row built under that ability holds. Assert the columns
that must survive and the ones that must not; building the ability at all is a
test too, since a grant on Read withholding a column no null answers fails
build().
#[test]fn member_read_users_scopes_to_own_org_and_strips_email() { let org = Uuid::now_v7(); // … let fields = member(org) .permitted_fields::<user::Entity>(Action::Read, &user_model(Uuid::now_v7(), org)); match fields { FieldSet::Only(cols) => { assert!(cols.contains("id")); assert!(cols.contains("name")); assert!(!cols.contains("email"), "email is admin-only"); } _ => panic!("members must have a restricted field set"), }}What a row then holds on the wire — email: null for that member — is the
framework’s, judged where User::from(&row) builds it; an app’s suite asserts it
through an edge (Response masking).
Ability conditions — fail-closed by default
Section titled “Ability conditions — fail-closed by default”condition_for::<E>(action) returns the SQL filter Repo applies to
every read and by-id write. Render it with SeaORM’s query builder and
assert on the SQL. A granted action scopes by tenant; an ungranted
action pre-filters to nothing — the fail-closed 1 = 0, not TRUE.
#[test]fn member_read_users_scopes_to_own_org_and_strips_email() { let org = Uuid::now_v7(); let sql = user::Entity::find() .filter(member(org).condition_for::<user::Entity>(Action::Read)) .build(DatabaseBackend::Postgres) .to_string(); assert!(sql.contains("org_id"), "member must scope by org_id: {sql}"); // …}
#[test]fn member_cannot_delete_users() { let org = Uuid::now_v7(); assert!(!member(org).can::<user::Entity>(Action::Delete, &user_model(Uuid::now_v7(), org))); let sql = user::Entity::find() .filter(member(org).condition_for::<user::Entity>(Action::Delete)) .build(DatabaseBackend::Postgres) .to_string(); assert!( sql.contains("1 = 0"), "no Delete grant for members ⇒ pre-filter matches nothing: {sql}", );}The second test pins the invariant that makes the layer safe: no grant
means zero rows, never every row. A refactor that flipped the default
to TRUE would turn a missing grant into a full-table leak; this test
catches it the same day. Pair it with can::<E>(action, &model) /
can_class(action, TypeId) for the per-row and per-class decisions. A
relational rule is pinned through condition_for: can sees the model
alone and grants nothing on a relation.
What still belongs in e2e
Section titled “What still belongs in e2e”Policy unit tests prove the code is correct in isolation. The
e2e negative path proves it is wired in — that
Repo reads through the ambient ability, each wire row is judged for its
caller, and forgetting to import AuthzModule fails the boot
rather than silently allowing unscoped reads.
- Unit — every branch of
permitted_fields,condition_for,can. Fast, exhaustive. - E2E negative path — the wrong caller gets
403, the reply readsnullwhere a grant withholds a column and never holds an unexposed one, a missing authz module fails the boot loudly.