Repository navigation
Gatehouse is an in-process authorization library for Rust. You write policies as Rust code, register them on a PermissionChecker, and ask whether a subject may perform an action on a resource. There is no policy language, server or sidecar, and Gatehouse does not store your users, roles or relationships: it asks for them per request, through code you provide.
0.6.0 changes what an answer can be. Grants and vetoes are separate types, a failure to load the data a decision needs is reported as Indeterminate instead of as a denial, and audit output names the policy that decided without exposing backend error text. It is a breaking release: follow MIGRATION.md to upgrade from 0.5.1, and read Upgrading from 0.5.1 below before deploying. Rust 1.82 remains the minimum supported version. If you are on a 0.6.0 prerelease, 0.6.0 has the same API as 0.6.0-alpha.3.
At a glance
- Deny overrides, default deny. Vetoes (
VetoPolicy, registered withadd_veto) run before grants (Policy, registered withadd_policy). A definite veto denies; otherwise any grant allows; no grant means deny. The types stop a grant policy from vetoing and a veto policy from granting. - Three outcomes.
AccessEvaluationisGranted,DeniedorIndeterminate.Indeterminatemeans a policy that mattered could not be evaluated, usually because a fact backend failed, and it never grants.BoundEvaluator::authorizeandinto_result()keep the distinction inAccessError, so a handler can return 403 for a denial and 503 for an outage. - Request-scoped facts. Policies read backend data with
ctx.fact(...). AnEvaluationSessionbatches loads through yourFactSource, deduplicates and caches them for the request, and records each fact a decision consulted. - Strict list endpoints.
try_filter,try_filter_byandtry_lookup_pagereturn only authorized items and fail, with every original item and decision attached, if any item is indeterminate. - Audit trail. Every decision carries a trace naming the policy that decided and the facts it consulted. The
serdefeature serializes it, and the defaulttracingfeature emits spans and security events.
let mut checker = PermissionChecker::<Documents>::new();
checker.add_policy(
PolicyBuilder::<Documents>::new("Owner")
.when(|user, _action, document, _context| user.id == document.owner_id)
.build(),
);
checker.add_veto(
PolicyBuilder::<Documents>::new("Suspended")
.subjects(|user| user.suspended)
.build_veto(),
);
let session = EvaluationSession::empty();
let bound = checker.bind(&session, &user, &Read, &());
match bound.authorize(&document).await {
Ok(()) => { /* allowed */ }
Err(AccessError::Denied { .. }) => { /* 403 */ }
Err(_) => { /* 503: authorization could not be decided */ }
}
let visible = bound.try_filter(documents).await?;Start with the README quick start, then the examples. API documentation is on docs.rs.
Upgrading from 0.5.1
Fix the compile errors first, then review the behaviour changes below: they compile unchanged and alter authorization results, audit output or telemetry. Two of them close paths that granted access during a backend outage, so expect 5xx responses where an outage used to produce a 200.
Behaviour changes the compiler will not report
- Outages are
Indeterminate, notDenied. A failed fact load, or a customevaluate_batchthat returns the wrong number of results, now producesAccessEvaluation::Indeterminate.AccessEvaluationwas already#[non_exhaustive], so an existingmatchhas a wildcard arm and still compiles; that arm now receives outages. Add anIndeterminatearm, or useauthorizeorinto_result()and mapAccessError::Indeterminateto a 5xx.to_resultstill sends both outcomes to one error,assert_denied()now panics on an indeterminate evaluation (useassert_indeterminate()), and serialized output gains an indeterminate variant. A definite veto still wins over an outage, an unresolved veto blocks every grant, and an independent grant still succeeds when another grant policy failed.RebacPolicystill abstains onFound(false)andMissing. - Two outage paths now fail closed. In 0.5.1 a failed load inside a policy looked like an abstention, so
member.and(blocked.not())granted access when theblockedlookup failed, and a forbid policy whose data source failed let the grant through. Both are nowIndeterminate. This applies to facts loaded throughctx.fact,ctx.facts,ctx.facts_byandRebacPolicy. A policy that reads the raw session keeps the 0.5.1 behaviour: the mechanical rename fromctx.sessiontoctx.session()preserves both paths, so load withctx.fact(...)instead, or returnctx.indeterminate(...)(grants) orctx.veto_indeterminate(...)(vetoes) onFactLoadResult::Error. - Builder predicates combine with AND. Repeated
subjects,actions,resources,contextandwhencalls used to keep only the last predicate; now all must match. A grant can only get narrower, but a veto fires less often, so a veto built with a repeated setter can permit requests it used to block. Keep only the final call to preserve the old behaviour, and express alternatives withPolicyExt::or(grants) orVetoPolicyExt::any_of(vetoes). Scalar evaluation also runs context predicates before resource predicates, and an empty batch runs no predicates. - Decisions name the deciding policy.
OrPolicy,AnyOfVetoand delegates credit their first deciding child;AndPolicy,NotPolicyandAllOfVetocredit themselves. A grant througha.or(b)used to reportOrPolicyand now reportsaorb, with that policy's reason. This changesgranted_policy_type,assert_granted_by, theGranteddisplay, the serializedpolicy_typeand the evaluation span'spolicy.type. Per-policygatehouse::securityevents still name the registered policy. Give a combinator a stable name with.named(...), and usegrant_path()andforbidden_path()for the full route. - Backend error text stays out of audit output. An error built with
FactLoadError::backendrecords the placeholderbackend error (message withheld from audit output)in provenance, traces and serialized output, andRebacPolicyreasons name the failure class instead of quoting the error. Usebackend_messageorbackend_with_message(message, source)to record text you wrote; the source error stays available throughError::source. - Outage telemetry differs. An outage sets the evaluation span's
outcometoindeterminate(it wasdenied) and a security event'sevent.outcometounknown(it wasfailure). Batch spans gainindeterminate_count, anddenied_countno longer includes outages.policy.effectisallowordeny. Alerts that count denials or failures will stop seeing outages. default-features = falsenow removestracing. In 0.5.1tracingwas always compiled in. It is now a default feature, so a dependency declared withdefault-features = falseloses spans, security events and contract warnings unless it also enablestracing. Decisions, traces and provenance are unaffected.- Oversized lookup pages are rejected. A
LookupSourcethat returns more IDs than the requested limit now fails withLookupPageTooLargebefore hydration or authorization, instead of authorizing the whole page. - The old list names still drop outages silently.
filter,filter_byandlookup_pagebehave as before, omitting indeterminate items along with denials, but are deprecated. Move to thetry_methods, or tofilter_lossy,filter_by_lossyandlookup_page_lossywhere dropping them is intended.
Changes that fail to compile
- Grants and vetoes are separate types.
Policy::evaluateandevaluate_batchreturnGrantResultandVec<GrantResult>.Effect,Policy::effect,add_forbid_policyandPolicyBuilder::forbidare removed: replace.forbid().build()with.build_veto()and register it withadd_veto. Hand-written vetoes implementVetoPolicyand returnVetoResult, and a custom policy that both granted and vetoed must be split in two. - Combinators and delegation.
AndPolicy,OrPolicyandNotPolicyaccept grant policies only; compose vetoes withAllOfVeto,AnyOfVetoandVetoPolicyExt.DelegatingPolicyno longer implementsPolicy; register it withadd_delegate, which installs its grants and vetoes together. - Builder.
buildandbuild_vetoneed at least one predicate; writeallow_all()orforbid_all()for a policy that applies to every request. A helper that returns a builder after adding a predicate returnsPolicyBuilder<D, Conditional>. - Audit types.
PolicyEvalResultcan no longer be returned from a policy or converted into a policy result.Combinedhasdecisioninstead ofoutcome, plusprovenance, and there is a newDecisionenum with an indeterminate value.FactProvenancegainserror_kind; preferFactProvenance::from_load_resultto struct literals. - Contexts.
EvalCtxandBatchEvalCtxare built withEvalCtx::newandBatchEvalCtx::new, and the raw session is read withsession(). When you call a policy directly, pass its result throughctx.finish(...). - Decisions are sealed. The variants of
AccessEvaluationandAccessError, and theFilterErrorandLookupAuthorizedPagestructs, can be read and matched but not constructed outside the crate. Struct patterns on the variants need..; tests should get a decision from aPermissionChecker. - Bounds.
FactKeyrequiresDebugand providesrender().RelationshipQueryrequiresDebugon IDs and relations andDisplayon relations. - Lookup errors.
LookupAuthorizedErrorhas a third type parameter,Resource, defaulting to(), and newEvaluationandLookupPageTooLargevariants. - New warnings.
AccessEvaluation,GrantResult,VetoResultand awaited evaluations are#[must_use], and the old list names are deprecated, so builds that deny warnings need these addressed.
Added
BoundEvaluator::authorizeandAccessEvaluation::into_result, which returnResult<(), AccessError>and keep a denial and an indeterminate outcome apart, each with its reason, trace and fact errors.try_filter,try_filter_byandtry_lookup_page, andfilter_lossy,filter_by_lossyandlookup_page_lossy.- Recording contexts (
EvalCtx::factandfacts,BatchEvalCtx::facts_byandfact,record,finish) that attach consulted facts to the audit trail, andFactLoadErrorKindwithFactLoadError::kind. PolicyBuilder::allow_allandforbid_all, andAccessEvaluation::grant_path,forbidden_pathandis_indeterminate..named(...)onAndPolicy,OrPolicy,NotPolicy,AllOfVetoandAnyOfVeto.FactLoadError::backend_with_messageandaudit_detail, andError::sourceonFactLoadError.- A runnable quick start in the README, checked in CI against the packaged crate.
Changed
- Loading facts in chunks is linear in the number of keys; it was quadratic.
Deprecated
AccessEvaluation::denied_due_to_fact_load_error, planned for removal in 0.7. Useis_indeterminate()orinto_result(), andfact_load_errors()for diagnostics.filter,filter_byandlookup_page, which remain aliases of their_lossycounterparts.
Fixed
EvaluationSession::shared_empty()no longer retains fact state or cache entries when facts are read from it by mistake.
Security
- A
NotPolicyover a failed lookup, and a veto whose data source failed, granted access during an outage in 0.5.1. Both now fail closed when facts are loaded through the recording contexts. - Backend error messages, which can quote row values, no longer reach traces, logs or serialized audit output.
Verification
- The library is
#![forbid(unsafe_code)]. Its runtime dependencies areasync-traitandfutures-channel, plustracing(default) andserde(optional). - Decision semantics are covered by property tests, compile-fail tests for the grant and veto boundary, and loom tests for concurrent fact loading. Pull requests run mutation testing over the evaluator, combinators, decision attribution and audit redaction.
- CI checks Rust 1.82, runs the examples and the README quick start, and runs the PostgreSQL example against a live database. Releases publish from CI through crates.io Trusted Publishing after
cargo auditpasses.
Design background: #58, #61, #62, #63, #67. Full diff: v0.5.1...v0.6.0.