What is a centralized policy module in a monolith authorization architecture?
Most monoliths don't start without authorization; they start with authorization everywhere. A controller checks user.role == "admin", a service method checks ownership, a template hides a button for viewers, and a query adds WHERE tenant_id = ?. Each check is reasonable on its own. Over time they drift apart. The button is hidden, but the endpoint still accepts the request. The export job skips the check entirely because it runs without a request. Changing "editors can delete drafts" means grepping for role names across the codebase and hoping you found every copy. Ask "who can refund an order?" and the honest answer is "let me read the code."
A centralized policy module replaces those scattered checks with one decision function: can(subject, action, resource, context), which returns allow or deny along with a reason. It is pure and has no side effects. It reads the inputs it is given and returns a decision. It does not write to the database, send notifications or throw redirects. Callers depend on that contract instead of on role names. A billing module asks whether this subject can perform invoice.refund on this invoice. It never learns that the answer comes from a "finance" role.
The pattern suits teams running a modular monolith with several modules, background jobs and more than a couple of roles. That is the point where scattered checks start contradicting each other. The payoff is that rules live in one place where they can be read, unit-tested and audited, without splitting the system into services to get that separation.
How does a single can() decision function work across modules?
The policy module answers one question: may this actor perform this action on this resource? It does not throw HTTP errors, load records or know about routes. Each module enforces the answer at its own boundary, which is the use-case entry point such as ArchiveProject or IssueRefund. Because enforcement lives there, a background job, a CLI task, an event handler or an internal call from another module passes through the same check as an HTTP request.
HTTP handler job worker CLI task
\ | /
v v v
[ use-case handler (owning module) ]
builds descriptor: type, id, owner, tenant, state
|
v
[ policy.can(actor, action, descriptor) ]
|
allow / deny + reason
The owning module loads its own record and passes a small descriptor containing type, id, owner, tenant and state. The policy module never reads another module's tables. That keeps module boundaries intact and makes can() a pure function that is easy to unit-test.
| Enforcement point | Strength | Weakness |
|---|---|---|
| HTTP middleware only | Simple and visible in one place | Jobs, CLI tasks and internal calls bypass it |
| Every service method | Thorough | Noisy, checks the same thing twice, and denials surface deep in call stacks where the cause is hard to trace |
| Use-case entry points | Covers every caller once, close to the domain | Requires discipline about what counts as an entry point |
Check at use-case entry points. Once a use case has authorized the action, the internal methods it calls can trust that decision instead of checking it again.
+--------------+ +------------+ +----------+ +---------------+
| HTTP handler | | job worker | | CLI task | | event handler |
+------+-------+ +-----+------+ +----+-----+ +-------+-------+
+-------+--------+--------------+---------+------+
v v
+------------------------------+ +------------------------------+
| Projects module | | Billing module |
| use case: ArchiveProject | | use case: IssueRefund |
| 1. load own project record | | 1. load own refund record |
| 2. build descriptor | | 2. build descriptor |
| 3. call policy.can() | | 3. call policy.can() |
| 4. allow: run, no re-checks | | 4. allow: run, no re-checks |
+--------------+---------------+ +--------------+---------------+
| descriptor: type, id, owner, |
| tenant, state |
+----------------+----------------+
v
+-----------------------------------+
| Policy module |
| can(actor, action, descriptor) |
| pure function: no DB reads, |
| no HTTP errors, no routes |
+-----------------+-----------------+
v
allow / deny + reason, enforced by the use case
Every entry point, including HTTP, jobs, CLI tasks and event handlers, calls a use-case handler in the owning module. That handler loads its own record, builds a small descriptor and asks the pure policy.can() function for a decision, which the use case then enforces.
How do you implement RBAC with permissions as data and add attribute conditions?
Start with permissions as named strings like invoice.approve, invoice.edit, and customer.export. Roles are a lookup table from role name to a set of those strings, stored as data in config or a database table rather than in code. Call sites ask can(user, "invoice.approve", invoice) and never ask user.role == "finance_manager". That indirection is the point. When finance decides that team leads may also approve invoices, someone adds invoice.approve to the team_lead row, and no code changes or deploys are needed.
Pure RBAC stops working as soon as the answer depends on the specific record. Three conditions come up early:
- Ownership: a user may edit only invoices they created.
- Tenant scoping: the invoice must belong to the caller's organization.
- Record state: only draft invoices can be edited.
Put these checks inside can(), after the role check passes. Return a decision object such as { allowed: false, reason: "invoice.edit: status is 'sent', not 'draft'" } instead of a bare boolean. The reason string feeds logs and error messages.
To keep the rules from collecting in one file, each module registers its own policies against the shared interface. The invoicing module registers handlers for invoice.*, and can() dispatches by prefix. The interface stays central while the rules live next to the code they protect.
These choices have costs:
- Pure RBAC leads to role explosion. Without conditions, teams end up encoding attributes into role names, such as
editor_own_drafts_eu. - Conditions make "who can do X?" harder to answer. Once rules depend on record attributes, you can no longer answer by reading the role table. You have to evaluate against real data.
type User = { id: string; orgId: string; roles: string[] };
type Decision = { allowed: boolean; reason: string };
type Policy = (user: User, action: string, resource: Record<string, any>) => Decision;
// Loaded from config or a DB table. Granting team leads approval is a data edit, not a deploy.
const rolePermissions: Record<string, string[]> = {
finance_manager: ["invoice.approve", "invoice.edit"],
team_lead: ["invoice.approve"],
clerk: ["invoice.edit"],
};
// Modules register record-level rules by prefix ("invoice" handles "invoice.*").
const policies = new Map<string, Policy>();
export function registerPolicy(prefix: string, policy: Policy) { policies.set(prefix, policy); }
export function can(user: User, action: string, resource: Record<string, any> = {}): Decision {
// RBAC first: does any of the user's roles carry this named permission?
const granted = user.roles.some((r) => rolePermissions[r]?.includes(action));
if (!granted) return { allowed: false, reason: `${action}: no role grants this permission` };
// Then attribute and relationship conditions owned by the module.
const policy = policies.get(action.split(".")[0]);
return policy ? policy(user, action, resource) : { allowed: true, reason: `${action}: granted by role` };
}
// invoicing/policy.ts: rules live next to the code they protect.
registerPolicy("invoice", (user, action, inv) => {
const deny = (why: string) => ({ allowed: false, reason: `${action}: ${why}` });
if (inv.orgId !== user.orgId) return deny("invoice belongs to another organization");
if (action === "invoice.edit") {
if (inv.createdBy !== user.id) return deny("only the creator may edit");
if (inv.status !== "draft") return deny(`status is '${inv.status}', not 'draft'`);
}
return { allowed: true, reason: `${action}: role and conditions passed` };
});
// Call site checks a permission, never a role name.
const d = can({ id: "u_42", orgId: "org_7", roles: ["clerk"] }, "invoice.edit",
{ orgId: "org_7", createdBy: "u_42", status: "sent" });
if (!d.allowed) console.warn(d.reason); // invoice.edit: status is 'sent', not 'draft'
A single can() function that checks a data-driven role-to-permission map, then dispatches to a module-registered invoice policy for tenant, ownership, and draft-state conditions, returning a decision with a reason string.
How should you authorize list endpoints and queries without N+1 checks?
A list endpoint that loads 500 rows and then calls can(user, "read", row) on each one does two kinds of damage. If a decision needs related data, such as the parent project's tenant or the document's owner team, every call can trigger its own query, and the endpoint becomes an N+1 problem. Pagination also breaks. If you fetch page 1 and then drop the rows the user can't see, the page comes back short, and the total count leaks how many hidden records exist.
The fix is for the policy module to answer a second question: "which records can this user read?" A scope helper such as readable_scope(user, "document") returns a set of query constraints instead of a boolean. For example, it might return tenant_id = user.tenant_id AND (owner_id = user.id OR state = 'published'). The returned structure is neutral, either a list of field/operator/value conditions or a predicate object, so the policy module never imports another module's ORM models. The documents repository translates those constraints into its own WHERE clause and then applies sorting, pagination and counts on the already-filtered set. The database does the filtering in one query.
This creates a second expression of the same rule, and the two can drift apart. Someone updates can() to allow archived documents for auditors and forgets the scope. To catch that, drive both from one shared table of test cases: each case is a user, a record and an expected read decision. For every case, assert that the record appears in the scoped list exactly when can() returns true.
# policy/documents.py: one module owns both expressions of the read rule
from dataclasses import dataclass
@dataclass(frozen=True)
class Cond: # neutral constraint, so the policy module never imports ORM models
field: str
value: object # equality only, to keep the example small
def can_read_document(user, doc) -> bool: # point check
return doc.tenant_id == user.tenant_id and (
doc.owner_id == user.id or doc.state == "published")
def readable_scope(user): # same rule as an AND of OR-groups
return [[Cond("tenant_id", user.tenant_id)],
[Cond("owner_id", user.id), Cond("state", "published")]]
# documents/repository.py: the owning module turns constraints into its own SQL
COLUMNS = {"tenant_id", "owner_id", "state"} # whitelist; never interpolate unknown names
def list_readable(conn, user, limit, offset):
clauses, params = [], []
for group in readable_scope(user):
parts = []
for c in group:
if c.field not in COLUMNS:
raise ValueError(f"unmapped policy field: {c.field}")
parts.append(f"{c.field} = ?")
params.append(c.value)
clauses.append("(" + " OR ".join(parts) + ")")
# Filter in the database first, then sort and paginate the filtered set
sql = ("SELECT id FROM documents WHERE " + " AND ".join(clauses)
+ " ORDER BY id LIMIT ? OFFSET ?")
return [row[0] for row in conn.execute(sql, params + [limit, offset])]
# tests: one shared case table drives both expressions
def test_scope_agrees_with_can(conn, cases): # cases: (user, doc), docs already inserted
for user, doc in cases:
visible = set(list_readable(conn, user, limit=10_000, offset=0))
assert (doc.id in visible) == can_read_document(user, doc), (user, doc)
A policy-owned scope helper returns neutral constraints, the documents repository turns them into one parameterized, paginated WHERE clause, and a shared test asserts that the scoped list and can() agree for every case.
How do you make missing permission checks detectable and decisions observable?
Start from default-deny: if no rule matches, can() returns false. Then make the omission visible. Each use-case handler declares its required permission at registration, and a test enumerates every registered handler and fails if any lacks a declaration. Add an architectural or lint test that forbids modules from importing role constants or calling repositories directly from handlers. These checks catch the common mistakes but not every bypass, such as raw SQL or a forgotten can() call inside a helper. Code review still matters.
Test the policy as a matrix of subject × action × resource state → expected decision. These tests call can() on in-memory objects, so they need no database and run in milliseconds:
| Subject | Action | Resource state | Expected |
|---|---|---|---|
| editor, same org | invoice.update | draft | allow |
| editor, same org | invoice.update | paid | deny |
| editor, other org | invoice.read | draft | deny |
| viewer | invoice.update | draft | deny |
A handful of integration tests per module then prove that the endpoint actually calls the policy, for example by checking that a viewer gets a 403.
For observability, log every denial with the subject, the permission name and the reason (for example, "invoice.update denied: status=paid"). You can also log a sample of allows. With these logs, a question like "why can't Dana edit this?" is answered from the log entry, not by tracing call paths.
The payoff is lower cost over time. A rule changes in one place, an audit reads one module, and access bugs are diagnosed from logs instead of code archaeology.
# test_invoice_policy.py: runs in milliseconds, no database or HTTP.
import pytest
from app.authz.policy import can, Subject, Invoice # the one policy module
from app.handlers import REGISTRY # name -> registered use-case handler
ACME, GLOBEX = "org-acme", "org-globex"
# subject x action x resource state -> expected decision
CASES = [
# (role, subject org, action, invoice org, status, expected)
("editor", ACME, "invoice.update", ACME, "draft", True),
("editor", ACME, "invoice.update", ACME, "paid", False),
("editor", ACME, "invoice.read", GLOBEX, "draft", False),
("viewer", ACME, "invoice.update", ACME, "draft", False),
# Default-deny: an action with no rule must be refused.
("editor", ACME, "invoice.purge", ACME, "draft", False),
]
@pytest.mark.parametrize("role,org,action,inv_org,status,expected", CASES)
def test_policy_matrix(role, org, action, inv_org, status, expected):
subject = Subject(user_id="u-123", role=role, org_id=org)
invoice = Invoice(id="inv-42", org_id=inv_org, status=status)
assert can(subject, action, invoice) is expected
def test_every_handler_declares_a_permission():
# Turns a forgotten declaration into a failing test.
missing = [
name for name, handler in REGISTRY.items()
if not getattr(handler, "required_permission", None)
]
assert not missing, f"Handlers without a declared permission: {missing}"
A pytest table-driven matrix calls can() on in-memory subjects and invoices, including a default-deny case. A second test walks the handler registry and fails if any handler has no declared permission.
When should you avoid centralizing authorization, and what does it cost?
That payoff has a price. The central module becomes a coupling hotspot: every team edits it, so merge conflicts pile up, reviews queue behind one set of owners, and the file drifts toward a god module that knows every domain. The mitigation is to keep the decision interface central but let each module register its own policies, with those files owned by that module's team. The core then only dispatches and logs.
Resource descriptors cost something too. The policy needs attributes such as owner, tenant and status, so callers either load the record before checking or thread that data through calls that didn't need it. Per-request caching avoids repeated loads, but caching roles across requests creates a staleness window: a revoked admin keeps access, or a newly granted user is refused, until the entry expires. Keep the cache request-scoped unless you can invalidate it on role changes.
Migration is the riskiest step. Moving scattered checks can silently drop one, and nothing fails loudly when it happens. Run the old and new checks side by side, log every disagreement, and switch over only after each mismatch is explained.
| Situation | Recommendation | Reason |
|---|---|---|
| Small app, one or two roles, few entry points | Defer | Inline checks are readable and the setup cost is not recovered |
| Growing monolith, many modules and roles | Centralize | Each rule change touches one place instead of many |
| Already split into services with their own authorization needs | Avoid a shared module | It re-couples services that were split to be independent |
The trade is upfront work against lower ongoing cost. You build the interface, descriptors, test harness and migration shadowing once, and in return every later rule change is smaller and easier to verify.
What are the alternatives, and how do you plan for extracting services later?
Each alternative solves a narrower problem than a central module, and each is cheaper in a different way.
| Approach | Where it fits | Overhead |
|---|---|---|
| Scattered inline checks | Small apps with two or three roles | Almost none at first. Later, rules drift between handlers, and an audit means reading every one. |
| Middleware-only route guards | Coarse gates such as "admins only" on whole endpoints | Cheap, but the guard runs before the resource is loaded, so it cannot express ownership, tenancy or state. |
| Framework per-model policy classes | Apps built tightly around one framework's models | Good locality, but rules spanning several models and query filtering for lists get duplicated or bolted on. |
| External policy engine or policy language | Many services sharing rules, or a separate team authoring policy | A new runtime to deploy and monitor, attribute data to sync into it, a language to learn, and a network hop on hot paths. |
An external engine can be the right answer once several deployables need identical decisions. In a single process, it mostly adds moving parts. Plain code behind a stable interface is the cheaper first step, and it does not rule out moving to an engine later.
Moving later depends on the shape of the contract. Call sites pass a subject, an action and an explicit resource descriptor (type, ID, owner, tenant), not an ORM object. They get back a decision and nothing more. Because the descriptor is plain data, it serializes. If a module becomes its own service, you can make two kinds of change without editing any caller:
- Replace the
can()implementation with a client that sends the same descriptor over the network. - Load the same policy package in both processes.
The changes you do need to make are latency budgets, caching and a failure mode. Denying by default when the policy service is unreachable is the usual choice.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to monolith authorization architecture, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.