Compiling Authorization Policies to SQL for Secure SaaS Lists

Authentication & Security

Compile authorization policies into SQLAlchemy predicates so lists filter before pagination. Learn tenant scope, null rules, typed trees, and safe write checks.

TL;DR

  • For a list endpoint, apply authorization in the database query so unauthorized rows never cross the database boundary into application memory.
  • Represent policies as a typed, constrained abstract syntax tree, then compile supported nodes into SQLAlchemy expressions with bound values.
  • Keep tenant scope and other mandatory predicates outside user-editable policy logic. Combine rules with an explicit, documented deny and null policy.
  • Use the same authorization model for reads and writes. Re-evaluate permissions at mutation time and enforce critical invariants with database constraints or row-level security where appropriate.
  • Measure query plans, count behavior, pagination, and cross-tenant cases. A correct result set can still be operationally expensive.

Why filtering after loading records does not scale

A permission check on one object can happen after the application loads that object, provided the object is not exposed or acted on before the check. A list is different. If an endpoint selects 50,000 projects and filters them in Python down to the 30 visible to a caller, the application has already asked the database to read, transfer, decode, and allocate thousands of rows that the caller cannot see.

This “fetch all, then filter” pattern makes authorization proportional to the full dataset instead of the caller's visible slice. It can inflate database I/O, query latency, application memory, and garbage collection. It also tempts engineers to paginate before filtering, which can produce short pages, skipped results, and incorrect total counts. Filtering must participate in the query before ordering and pagination.

Compiling a policy to SQL means translating a declarative authorization rule into predicates the database can evaluate. A condition such as “the project belongs to this tenant and the caller owns it or has an editor grant” becomes a parameterized WHERE clause. SQLAlchemy's expression system builds these predicates as composable objects and binds values instead of concatenating caller data into SQL. SQLAlchemy SQL expression operators

Compilation is not a shortcut around policy design. It forces the team to define supported operators, null behavior, relationships, deny precedence, and the difference between row visibility and permission to change a row. The safest compiler has a small language and rejects anything it cannot translate with known semantics.

Separate mandatory scope from policy expressions

Start with the security boundary that every query must honor. For a tenant-owned resource, tenant_id == authenticated_tenant_id is mandatory. Add it as a structural constraint around the policy expression, not as one optional policy leaf that could be omitted by a malformed or overly broad rule.

A simple declarative policy might say a project is visible when the caller is an organization administrator, the caller owns the project, or the caller has an active read grant. The query shape is conceptually:

SELECT p.*
FROM project AS p
WHERE p.tenant_id = :authenticated_tenant_id
  AND (
      :is_tenant_admin
      OR p.owner_user_id = :authenticated_user_id
      OR EXISTS (
          SELECT 1
          FROM project_grant AS g
          WHERE g.tenant_id = p.tenant_id
            AND g.project_id = p.id
            AND g.subject_user_id = :authenticated_user_id
            AND g.permission IN ('read', 'write')
            AND g.revoked_at IS NULL
      )
  );

The tenant ID and user ID must come from verified server-side identity context. The caller may choose a search term or requested page size, but cannot set the tenant scope by passing a query parameter or policy field. The grant lookup correlates both tenant and project so a row in another organization cannot satisfy the subquery.

Separate the four inputs to authorization in code: subject (authenticated principal and trusted attributes), action (read, update, delete), resource (the row and its relevant attributes), and environment (request context, time, or network zone if the product uses them). Build a query predicate only from the subset of those inputs that can be represented safely at the database boundary. Complex decisions such as recent MFA or a live external risk score may need a distinct gate before the query runs.

Compile a typed policy tree, not arbitrary expressions

Do not accept Python snippets, SQL strings, ORM attribute names, or generic JSONPath expressions as policies. Parse stored policy documents into a versioned schema with a finite set of allowed fields and operators. Resolve field names through a server-owned registry of SQLAlchemy columns or relationship predicates. Reject unknown fields, wrong operand types, unsupported joins, and overly deep trees.

For example, an internal policy representation could be a discriminated union:

from dataclasses import dataclass
from typing import Literal

@dataclass(frozen=True)
class Eq:
    field: Literal["owner_user_id", "status"]
    value: str

@dataclass(frozen=True)
class HasGrant:
    permission: Literal["read", "write"]

@dataclass(frozen=True)
class AllOf:
    terms: tuple[object, ...]

@dataclass(frozen=True)
class AnyOf:
    terms: tuple[object, ...]

PolicyNode = Eq | HasGrant | AllOf | AnyOf

In production, use a validated model with recursive depth and collection-size limits. Keep the request's user ID and tenant ID separate from the policy AST so a policy author cannot replace authenticated identity with arbitrary input. A compiler can then map only registered fields to SQLAlchemy expressions:

from sqlalchemy import and_, or_, select

def compile_node(node, *, actor_id, tenant_id):
    if isinstance(node, Eq) and node.field == "owner_user_id":
        return Project.owner_user_id == actor_id
    if isinstance(node, Eq) and node.field == "status":
        return Project.status == node.value
    if isinstance(node, HasGrant):
        return select(ProjectGrant.id).where(
            ProjectGrant.tenant_id == tenant_id,
            ProjectGrant.project_id == Project.id,
            ProjectGrant.subject_user_id == actor_id,
            ProjectGrant.permission == node.permission,
            ProjectGrant.revoked_at.is_(None),
        ).exists()
    if isinstance(node, AllOf):
        return and_(*(compile_node(x, actor_id=actor_id, tenant_id=tenant_id)
                      for x in node.terms))
    if isinstance(node, AnyOf):
        return or_(*(compile_node(x, actor_id=actor_id, tenant_id=tenant_id)
                     for x in node.terms))
    raise ValueError("Unsupported policy node")

policy_predicate = compile_node(policy, actor_id=actor.id,
                                tenant_id=actor.tenant_id)
stmt = select(Project).where(
    Project.tenant_id == actor.tenant_id,
    policy_predicate,
)

This is a teaching example, not a drop-in authorization library. It shows the key boundary: values become parameters and fields resolve to reviewed code-owned expressions. A production compiler should produce a typed result or a controlled authorization error, not fall back to an unrestricted query when compilation fails.

Define policy semantics before adding operators

Make AND, OR, and deny precedence explicit

Boolean composition is straightforward only when the policy model says what it means. If a policy language supports deny rules, define whether an explicit deny overrides every allow, whether the absence of an allow is a denial, and how scopes combine. Write truth tables for representative cases and test them independently of SQL generation. Do not assume that a JSON policy document's visual order implies evaluation order.

Fail closed when a policy is missing, malformed, has an unknown version, or includes an unsupported node. Record the compilation error with the policy ID and version, but do not include sensitive attributes in an externally visible response. A deployment that cannot compile a security rule should deny the affected operation and alert operators.

Choose null and missing-attribute behavior

SQL uses three-valued logic. A comparison involving NULL is generally unknown, not true or false. Python's None checks and a policy language's “attribute missing” semantics may differ. Decide whether a missing resource attribute denies, is treated as an explicit null, or activates a separate condition. Compile null tests deliberately with IS NULL and IS NOT NULL, not equality to a bound null.

Beware negation. If status != 'archived' is intended to include rows whose status is null, SQL's status != 'archived' does not do that by itself. Use a tested expression that spells out whether null is included. Apply the same semantics when evaluating a policy for a single object in application code so list and detail endpoints do not disagree.

Use EXISTS for many-to-many grants where possible

A join to grants can duplicate project rows when several grants or group memberships match. Duplicate rows can corrupt pagination and make counts disagree with visible results. An EXISTS subquery can express “at least one matching grant” without multiplying the parent row. Another option is to select distinct resource IDs in a subquery, but inspect the plan and ordering implications.

Group-derived permissions add joins through group membership and group grants. Scope every edge by tenant, include revocation and soft-delete predicates, and index the columns used to correlate a resource and subject. If authorization depends on nested organization hierarchies, put a limit on depth or maintain an explicit closure/projection table rather than generating an unbounded recursive expression from a request.

Apply authorization before search, ordering, and pagination

Build the query in an order that preserves the visible result set: mandatory tenant scope, action-specific policy predicate, user search filters, stable ordering, then limit and offset or cursor. The total count must use the same authorization predicate as the row query. Otherwise, the count can disclose the number of hidden records even if no row body is returned.

For cursor pagination, include a deterministic unique tie-breaker and apply the access predicate on each page request. A signed cursor should bind the relevant filter and sort state, but it is not a grant of access. A caller can replay an old cursor after permission revocation, so the current authorization query must run again. See the PostgreSQL cursor pagination guide

Search indexes and full-text queries should operate only over authorized rows. It is not enough to retrieve global search hits and then redact fields if counts, timing, snippets, or highlights reveal a protected record. When users can search across large datasets, measure the actual plan with representative policy selectivity and include policy columns in the index design only when query plans demonstrate a benefit.

For expensive predicates, precompute a carefully maintained authorization projection or use database row-level security as another enforcement layer. A cache of policy results requires invalidation on role changes, grant revocation, tenant membership changes, and relevant resource updates. A stale cache can turn an optimization into an access-control bypass. PostgreSQL RLS patterns for tenant isolation

Use a second authorization check at mutation time

Query compilation is most valuable for collection reads, exports, and bulk operations. It does not remove the need to check write permissions. A client can submit a resource ID from an earlier page after its access has been revoked. An update should include the action-specific predicate in the database statement or re-check the current row within the transaction before changing it.

stmt = (
    update(Project)
    .where(
        Project.id == project_id,
        Project.tenant_id == actor.tenant_id,
        compile_node(update_policy, actor_id=actor.id,
                     tenant_id=actor.tenant_id),
    )
    .values(name=new_name)
    .returning(Project.id)
)
updated_id = session.execute(stmt).scalar_one_or_none()
if updated_id is None:
    raise ResourceNotFoundOrForbidden()

Use one transaction for the permission predicate and mutation so the decision is made against the state that is being changed. Whether the API returns 403 or a concealed 404 depends on the resource disclosure policy. The important invariant is that no mutation occurs when the predicate is false. For critical state transitions, add a database constraint or row-level policy that protects the invariant even if an application route forgets to compile a rule.

Measure correctness and query cost together

Compile the same policy fixtures through a reference evaluator and the SQL compiler, then compare the resulting resource IDs over generated rows. Include missing attributes, nulls, duplicate grants, revoked grants, group memberships, and explicit denies. This differential check catches semantic drift between single-object checks and list predicates.

Inspect generated SQL in tests and assert that untrusted values are bound parameters. Fuzz unknown field names, deeply nested conjunctions, unsupported functions, and very large IN lists. A compiler should reject them predictably without issuing a broad query. Log policy version, compilation outcome, and query timing, while keeping resource attributes and principal identifiers within appropriate access controls.

Use PostgreSQL EXPLAIN (ANALYZE, BUFFERS) on realistic cardinalities. Compare the authorized query with an unrestricted baseline, but do not treat the baseline as a production alternative. Check rows scanned versus rows returned, index use, join duplication, count query cost, and response latency at the expected tenant sizes. Test both users who can see a small fraction of the tenant and administrators who can see most of it; their best plans may differ.

Authorization correctness is not a throughput metric. A lower-latency query that accidentally omits a grant revocation predicate is a security defect. Keep the policy AST versioned, review changes as security-sensitive code, and include list, detail, export, and write endpoints in the same authorization coverage plan.

Frequently asked questions

Should I filter unauthorized rows in Python or in SQL?

For a collection endpoint, put the authorization predicate in SQL before ordering and pagination so unauthorized rows are not loaded into application memory. A single-record read may load a scoped candidate and then perform an object-level decision before exposing it. Use the same policy semantics across both paths.

Can JSON policies be translated directly into SQL text?

No. Parse a constrained policy schema into a typed tree and map approved fields and operators to SQLAlchemy expression objects. Bind values as parameters and reject unknown fields, unsupported operators, and excessive tree complexity. Never interpolate caller-controlled policy strings into SQL.

Why can SQL authorization return different results for null values than Python?

SQL comparisons use three-valued logic, where a comparison with NULL is unknown. Python equality and policy-language rules may treat missing values differently. Define null semantics explicitly and test both the in-memory evaluator and compiled SQL with null and absent attributes.

Does query-level authorization replace PostgreSQL row-level security?

No. Query-level predicates provide application-specific visibility and action rules. Row-level security can provide a database enforcement boundary for tenant isolation or other invariants. They can complement each other, but session context, roles, connection pooling, and policies must be configured and tested correctly.

Compile policies only when their semantics are testable

SQL compilation is a useful way to make collection authorization efficient and explicit. The key is a small policy language, a trusted mapping from policy nodes to database expressions, and a mandatory scope that no policy can remove. Pair it with write-time checks, database invariants, and query-plan measurement. If the policy cannot be represented safely in SQL, deny or use a different reviewed execution path rather than silently broadening the result.

If large lists or exports are straining your database, talk with our engineering team about query-level authorization, PostgreSQL policy enforcement, and a representative benchmark plan.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with application security

Discuss your project