permissify · authorization gem

StockLive · authorization architecture

Permission is a question you ask, not a role you are.

Permissify answers user.can?(:edit, article) by evaluating small, named checks that were captured at boot through a metaprogrammed DSL and stored in a central Registry. This page shows the two moments that make it work — register and evaluate — and why we chose them.

1domain rules, one home
2metaprogramming moments
∞checks composable
0role checks in views
01 — the problem

Roles scatter. Activities concentrate.

Today StockLive authorizes with Pundit (22 policy files) and role checks sprinkled through controllers, views, and services. The trouble isn't Pundit — it's that "who you are" (admin?, superadmin?, staff?) leaks into places that should only ask "what may happen here".

# The leak: identity mixed into a view
if current_user.admin? || current_user.superadmin?
  link_to "Approve", approve_path(@assessment)
end

# The rule: ask the activity, everywhere
if can?(:approve, @assessment)
  link_to "Approve", approve_path(@assessment)
end

Permissify gives every domain one file of named checks. A controller, a view, and a background job all ask the same question and get the same answer — because the answer is computed in one place from facts, not re-derived from roles at each call site.

Scope · ADR-0004

Permissify is built as a separate gem repo (StockLive-Group/permissify) and consumed by the single StockLive monolith via a Gemfile git source — the same shape as Predicate. A separate repo, not a separate product or deployment. It earns adoption through a gradual migration alongside Pundit (see the sequence), not framework design in isolation.

02 — choose it for the contract, not the syntax

Why Permissify instead of Pundit.

This is not an argument that Pundit is weak. Pundit deliberately uses plain Ruby policy classes, a user plus record, explicit authorize calls, and policy scopes. That is an excellent default for many Rails applications. Permissify is justified only if StockLive values a registered activity system more than Pundit's policy-class locality: one vocabulary across products, explicit tenant-aware context, boot-time contract validation, structured decisions, and explainable traces.

Keep Pundit when

The app is conventional, policies remain easy to find, user + record is sufficient, and plain Ruby locality matters more than a global registry.

Choose Permissify when

Many surfaces must share named activities, tenant and relationship facts, reason codes, validation, tracing, and migration evidence as one contract.

Add Predicate (optional)

Only if a reusable boolean fact already exists. Permissify decides fully without it — see the optional Predicate section.

Decision guide and dependency model

each tab is a separate architectural question

A different unit of organization—not merely a different spelling

QuestionPunditPermissify
Primary unitOne policy class per record type, with query methods such as update?.One registered entity with named activities, checks, references, and metadata.
Public questionauthorize post, policy(post).update?.decide(actor:, activity:, resource:, tenant:); can? is the boolean convenience.
ContextIntentionally user + record; wrap them when more context is truly required.A typed, immutable context makes actor, resource, tenant and resolved facts first-class.
DiscoveryRuby constant lookup maps a record to a policy and controller action to a query.An immutable registry maps entity + activity to a validated rule at boot.
ResultA boolean query; authorize raises on denial and retains policy/query details.A structured Decision: allowed, stable reason code, rule ID, trace ID and safe error class.
CollectionsMature Policy::Scope#resolve convention and policy_scope helpers.Must provide an explicit host-owned database scope contract; booleans never filter rows in memory.
Completenessverify_authorized and verify_policy_scoped catch forgotten calls during development; Pundit says these are not enforcement failsafes.Adapter verification plus boot validation catch missing enforcement, unknown activities, missing references and malformed declarations.
AuditabilityExcellent local readability because each policy is ordinary Ruby; richer reasons/traces are application conventions.Registry metadata and structured decisions make a cross-product permission inventory and safe explanation protocol part of the gem contract.
Risk and costEstablished ecosystem, familiar debugging, low conceptual overhead.A bespoke security kernel, metaprogramming, migration cost, independent releases and a larger proof burden.

Do not replace Pundit merely to remove policy files

  • Pundit policies are POROs, not an inherently opaque framework.
  • A small app gains little from a global registry and explanation protocol.
  • Permissify must prove scopes, enforcement verification and error behavior before parity.
  • If rules are still scattered role checks, moving them into a DSL does not fix the model.

The StockLive-specific case for Permissify

  • Activities become stable domain vocabulary across Manage and future product surfaces.
  • Tenant, relationship and grant inputs are explicit instead of hidden in controller state.
  • Every denial can carry a safe reason and trace identifier through HTML, Turbo, JSON and jobs.
  • The separate gem can validate declarations and compatibility independently, while StockLive owns business rules.

A real StockLive path · ContactPolicy

Today · Pundit — 14 methods, two repeated role checks
class ContactPolicy < ApplicationPolicy
  def index?   = user.assessor?
  def edit?    = user.assessor?
  # …9 more, all user.assessor?…
  def destroy? = user.assessor? && user.staff?
  def approve? = user.assessor? && user.staff?
  def push_to_nextlot? = user.assessor? && user.staff?

  class Scope < Scope
    def resolve = scope.where(user: user)
  end
end
Permissify — two facts, two permissions, explicit aliases + scope
Permissify.define(:contact) do
  fact(:assessor) { |ctx| ctx.actor.assessor? }
  fact(:staff)    { |ctx| ctx.actor.staff? }

  permission(:viewable)   { |ctx| ctx.all?(:assessor) }
  permission(:manageable) { |ctx| ctx.all?(:assessor, :staff) }

  action :index,   maps_to: :viewable
  action :edit,    maps_to: :viewable
  action :destroy, maps_to: :manageable
  action :approve, maps_to: :manageable
  action :push_to_nextlot, maps_to: :manageable

  scope(:viewable) { |actor, relation, _env| relation.where(user: actor) }
end

The 14 repeated user.assessor? collapse into one named fact; the four assessor? && staff? guards become one :manageable permission; the Pundit Scope becomes an explicit authorized_scope. Other real paths migrate the same way — BookingPolicy (user.staff?), ApplicationPolicy's leaky scope.all default, and more in the full gallery and phased plan: 02 — Pundit eradication.

Decision lock

Permissify remains a separate, standalone gem. Pundit is a temporary migration comparator, not a dependency. Predicate is an optional fact source behind a host-owned adapter, not the authorization authority.

03 — the pieces & the flow

Small objects, three layers, exactly two flows.

Permissify isn't a framework you configure — it's a thin stack of single-purpose objects. Read it bottom-up: a foundation that turns DSL blocks into data, a core that decides and (later) remembers, and an edge of mixins your models and controllers call. Everything the system does happens in one of two moments — register (once, at boot) or evaluate (once per can?).

Module map — lib/permissify/

calls flow downward; data flows up
Edge · what your app touches
Subject
User mixin. user.can? / cannot?. Entry point.
Resource
Model mixin. Auto-loads app/permissions/<entity>_permissions.rb; adds ?-checks.
Controller
authorize!, verify_authorized, can? view helper.
▲ data     ▼ calls
Core · decide
Authorization
Maps action→activity, builds a typed decision context, enforces default-deny.
Core
Evaluates the registered rule against the decision context. (Cache is deferred — see below.)
Configuration
Action map plus explicit actor, grant, scope, clock, and instrumentation ports.
DecisionContext
Explicit actor, resource, tenant, and evaluated facts. Immutable for one decision.
Decision
Allowed/denied, stable reason code, rule ID, trace ID, and error classification.
▲ data     ▼ calls
Foundation · DSL becomes data
DSL
Builder + SectionBuilder. method_missing captures each check.
Registry
The lookup table: entity → { facts, permissions, actions }. Plain data.
Combinators · Helpers
all_of/any_of, predicates. Added only when rules repeat.
Rails glue
Railtie
Zeitwerk-ignores app/permissions/, reloads the Registry on to_prepare, runs boot-time validation.

Who owns what

FileLayerSingle responsibility
subject.rbedgeUser mixin — can?, cannot?. The question people ask.
resource.rbedgeModel mixin — auto-load the entity's permission file; expose ?-checks.
controller.rbedgeauthorize! (raises NotAuthorized); verify_authorized catches actions that forgot.
authorization.rbcoreAction→activity map, build the typed decision context, deny by default on anything unknown.
core.rbcoreLook the permission up in the Registry and call its lambda. Evaluation only.
decision_context.rbcoreImmutable actor/resource/tenant/facts input. No generic host attribute dump.
decision.rbcoreStructured result: allowed, reason code, rule ID, trace ID, and safe error class.
configuration.rbcoreAction map and explicit ports. No implicit host constants or invisible bypass.
registry.rbbaseStore & fetch entity → { checks, sections }. No behaviour, just data.
dsl.rbbaseBuilder/SectionBuilder — method_missing turns each block into a Registry entry.
railtie.rbglueZeitwerk ignore, dev reload, boot-time validation of the whole Registry.

The two flows, as real call stacks

This is the whole system. Registration happens once per boot (and per code reload in dev); evaluation happens once per can?. The interactive pipeline further down is exactly the request stack, animated.

boot · once register → Registry

# config.to_prepare — every boot & code reload
Railtie loads app/permissions/*.rb
└─ Permissify.define(:article) do … end
   └─ Builder.new(:article).instance_eval(&block)
      ├─ method_missing(:draft)        ─▶ Registry.add_check
      ├─ method_missing(:owned) ─▶ Registry.add_check
      └─ section(:permissions) do … end
         └─ SectionBuilder.instance_eval
            └─ method_missing(:editable)
                ─▶ add_check(…, section: :permissions)
✦ boot validation: reject unknown / duplicate /
  missing refs before the first request
═▶ Registry[:article] = { checks:{…},
      sections:{ permissions:{ editable: λ, … } } }

request · per call evaluate → allow / deny

user.can?(:edit, article)          # Subject
└─ Authorization.can?(user, :edit, article)
   ├─ default deny # unknown entity/action/rule ⇒ false
   ├─ perm  = action_map[:edit]  # :editable (or deny)
   ├─ ctx = DecisionContext.new(actor: user, resource: article, tenant: org)
   │          # explicit actor/resource/tenant/facts; no attribute dump
   └─ Core.call_section(:article,
            :permissions, :editable, ctx)
      └─ λ.call(ctx)
          # draft(ctx) && (owned(ctx) || admin(ctx))
          ⇒ Decision(allowed, reason, rule, trace_id)
# enforcement at the boundary
authorize!(:edit, @article) ⇒ raise unless can?
after_action :verify_authorized
   ⇒ fail loud if an action never authorized

Two properties fall out of this shape and matter more than any convenience: default-deny (an unknown entity, action, missing rule, or a raised error resolves to false, never true) and mandatory enforcement (verify_authorized turns a forgotten authorize! into a loud failure, not a silent hole). A friendlier can? is the visible part; these two are the reason to build it.

04 — isolation as an executable contract

A separate repository earns its cost by proving the boundary.

Permissify is a library inside StockLive's runtime, not another product or service. Its repository boundary exists to make dependency direction, independent boot, security review, compatibility, and rollback executable facts. Moving files is not enough: the contract below is what prevents isolation from becoming opacity.

Dependency direction

The gem cannot casually reach into StockLive constants, models, helpers, or tables. Host knowledge enters only through public ports.

Independent proof

A pure-Ruby boot and isolated suite catch hidden coupling that namespace conventions and static checks miss.

Smaller security kernel

Authorization mechanics have a compact review surface, stricter ownership, threat modelling, and focused adversarial tests.

Stable public API

can?, authorize!, scopes, decisions, and registration are deliberate contracts rather than application reach-ins.

Pin and rollback

StockLive pins an immutable revision, tests it as a consumer, and can restore the previous known-good revision without reverting unrelated app work.

Compatibility matrix

The gem proves its supported Ruby and Rails combinations independently while StockLive proves the one combination it deploys.

Differential migration

Pundit and Permissify can evaluate the same requests in shadow mode, producing explicit mismatch evidence before authority changes.

Future reuse without extraction

A second trusted consumer can adopt the same mechanics without copying code or forcing StockLive business rules into the library.

05 — metaprogramming, moment one

Register: a block of Ruby becomes a data structure.

Inside Permissify.define, the block runs under instance_eval against a small DSL object. Each fact(:draft) { … }, permission(:editable) { … } and action :edit, maps_to: :editable call writes one immutable entry into the Registry under the entity. Duplicate names, missing blocks, and unknown aliases fail loudly at boot — there is no method_missing guesswork.

define(:article) → Registry

step through method_missing
The DSL you write
What the Registry holds
Permissify::Registry

The point: the DSL block has no runtime meaning of its own. It's a script whose only job is to populate a lookup table. After boot the Registry is just data — entity → { checks, sections } — and every later question is a fast dictionary read, not a re-parse.

# lib/permissify/dsl.rb — every call writes one Registry entry
class DSL
  def fact(name, &block)
    @definition.facts[name.to_sym] = block          # capture the fact
  end

  def permission(name, &block)
    @definition.permissions[name.to_sym] = block
  end

  def action(name, maps_to:)                       # explicit alias — no fallback
    @definition.actions[name.to_sym] = maps_to.to_sym
  end
end
06 — metaprogramming, moment two

Evaluate: one question, six deterministic stages.

user.can?(:edit, article) doesn't hunt for a policy class. It runs a fixed pipeline: reject unknown input, map the action to a registered permission, build an explicit decision context, look the rule up in the Registry, evaluate it, and return a structured decision. Cache and global superuser bypass are deliberately absent from the baseline path. Drive it below.

user.can?(action, article)

change any input — the pipeline recomputes live
STAGE 0
Registered?
—
STAGE 1
Action → Permission
—
STAGE 2
Build context
—
STAGE 3
Registry lookup
—
STAGE 4
Evaluate rule
—
STAGE 5
Decision result
—
verdict
—
choose inputs

Notice what the verdict never touches: the word role. An admin can't edit a published article here because editable is defined as draft && (owner || admin) — state is a first-class fact. Change the rule in one file and every call site moves with it.

07 — why this shape

What's foundational, and what's deferred.

Not every clever mechanism belongs in the first version. The left column is load-bearing — remove it and authorization is unsafe. The right column is a later, measured optimization; shipping it early trades real safety for speculative speed.

Foundational — build first
✓ Default deny

Unknown entity, unregistered action, missing rule, or a raised error all resolve to false. Access is never the fallback.

✓ Mandatory enforcement

verify_authorized turns a controller action that forgot to authorize! into a loud failure — the lesson from GitHub's CodeQL check. This, not a nicer can?, is the point.

✓ DB-level authorized scopes

Authorized collections return an ActiveRecord::Relation scoped by organisation + ownership — safe by construction, never post-filtering loaded Ruby objects.

✓ method_missing DSL → Registry

Definitions read like domain language; captured once at boot into plain data. One mental model shared with Predicate.

✓ Boot-time validation

Reject unknown activities, duplicates, and missing references at boot — before a single request is served.

✓ One canonical role/grant source

Reconcile the enum, the staff/assessor booleans, global roles, and membership roles into one model Permissify consumes. No competing truths.

✓ Separate gem repo

Built in StockLive-Group/permissify, consumed by the monolith at an immutable revision. The boundary is proven by independent boot, tests, explicit ports, and StockLive consumer contracts (ADR-0004).

✓ Observable decisions

Evaluation returns a structured decision with allowed/denied, reason code, rule ID, and trace ID. Explainability is part of the security contract, not optional debugging sugar.

Deferred — measure before adding
⏸ SHA-256 / TTL / LRU cache

Stale authorization is more dangerous than a slightly slower check. Add caching only if evaluation is a demonstrated bottleneck.

⏸ Generic action-name inference

:edit → :editable is convenient, but arbitrary "#{action}able" fallback must deny unless the activity is registered — never invent a permission name.

✕ Invisible superuser bypass

A global superuser_check recreates the role bypass the design removes. Break-glass access belongs to StockLive as a named, expiring, logged capability.

✕ Generic injected state hash

Dumping every attribute plus private actor keys into an untyped hash creates hidden coupling. The baseline uses an explicit actor/resource decision context.

⏸ Combinators · Predicate adapter · engine plugins

Add all_of/any_of and a Predicate adapter only when real repeated rules justify them.

⏸ Versioned gem releases

The repo exists from day one but is pinned by git SHA during active development. A real release/version cadence waits until the API stabilises.

Honest naming

A permission file is still a policy in the architectural sense — so this is "one policy per domain, not one class per action," not "no policies." And permission to :approve is not proof the record is valid to approve — authorization and domain invariants stay separate concerns.

08 — optional add-on

Predicate isn't a fact backend. It's the domain layer beneath authorization.

The default is zero Predicate — every fact above is plain Ruby. The tempting pattern is to plug Predicate in as Permissify's FactSource. That is usually the wrong seam. A truth like content_complete is needed in many places — the submit form, the save command, a "ready" badge, a background job — not only when asking "may this user publish?". So it belongs to the domain, computed once and exposed as a method. Permissify reads that result as an ordinary fact and never runs Predicate itself.

Predicate · domain layervalidates stable truth — complete? valid? eligible? — memoized, reused app-wide
→
Permissify · authz layerreads that truth as a plain fact + fresh authz facts (roles, grants, ownership) → Decision

Where Predicate wins: the checks Pundit policies polluted

Today those domain checks are smeared through Pundit policies — the same "is it complete / valid / eligible" logic recomputed inline across policies, views and commands. That is the pollution. Predicate's real payoff is to lift those checks out into one memoized domain fact, computed once per request and reused everywhere, while authorization only composes it.

Before → after — extract the domain check, memoize it, compose it

the Predicate win
# BEFORE — the Pundit policy pollutes authorization with a domain check,
# recomputed every call and duplicated wherever "complete?" is needed.
class ArticlePolicy
  def publish?
    user.editor? &&
      record.title.present? && record.body.present? &&
      record.media.any? && record.reviewed_at.present?   # domain truth, misplaced
  end
end

# AFTER — the domain truth is one Predicate fact, reused app-wide.
# app/predicates/article_predicate.rb  (state hash + is_present? helper)
Predicate.define(:article) do
  content_complete { |s| is_present?(s[:title]) && is_present?(s[:body]) &&
                         s[:media_ids].any? && is_present?(s[:reviewed_at]) }
end
# the domain calls Predicate with a state hash; Permissify reads the boolean:
class Article
  def content_complete?
    Predicate.for(:article).call(:content_complete,
      title:, body:, media_ids:, reviewed_at:)
  end
end

# Permissify composes the memoized domain truth with FRESH authz facts.
Permissify.define(:article) do
  fact(:complete) { |ctx| ctx.resource.content_complete? } # memoized domain truth
  fact(:may_edit) { |ctx| ctx.actor.editor? }             # volatile → always fresh
  permission(:publishable) { |ctx| ctx.all?(:complete, :may_edit) }
  action :publish, maps_to: :publishable
end

The boundary: what lives where

Fact kindHomeFreshnessWhy
Grants, roles, membership, ownership, revocation, tenant scopePlain Ruby, inside PermissifyAlways fresh — never memoizedAuthorization-specific and volatile; a stale value hands back access that was revoked.
Completeness, validity, eligibility, lifecycle statePredicate (domain layer), read by Permissify as a plain factSafely memoized per request / resource versionStable within a request and reused across the app; here Predicate's mandatory memoization is a feature, not a hazard.

The caching inversion

  • Predicate v1.2.0 always memoizes — dangerous for volatile authz inputs.
  • But domain truths are exactly the stable facts memoization is safe for.
  • So Predicate's "flaw" fits its right layer, and never touches grants or revocation.

Permissify still never runs Predicate

  • It reads content_complete? — a domain method that may use Predicate.
  • No coupling: the permissify gemspec has no Predicate dependency.
  • The same truth serves forms, commands, jobs and UI — not only the auth path.

The FactSource adapter — rare, secondary

  • Wiring Predicate directly as a FactSource is justified only for a stable, resource-only fact needed nowhere else.
  • Even then a plain domain query is usually cleaner.
  • If used, unknown/errored facts return Missing → default-deny.
09 — how we get there safely

Migrate by evidence, in waves. Remove Pundit last.

Permissify runs alongside Pundit, proven on one real path, then extended. Security comes first — literally Wave 0. Pundit is removed only when Permissify demonstrably covers the behaviour and rollback is no longer needed.

  1. Wave 0 · Secure the baseline. Rotate the exposed OAuth secret; inventory protected actions & current Pundit outcomes; reconcile role/organisation sources; add a test for every policy and scope; replace unsafe scope.all defaults.
  2. Wave 1 · Minimal isolated gem core. In StockLive-Group/permissify: can?/cannot?, explicitly registered activities, default deny, typed actor/resource/context, and a structured decision result. Prove pure-Ruby boot and tests; no cache, optional adapters, or release cadence yet.
  3. Wave 2 · Rails enforcement. authorize!, authorized ActiveRecord scopes, missing-authorization detection, correct HTML/Turbo/JSON denials, audit instrumentation without leaking sensitive facts.
  4. Wave 3 · One real migration. A single bounded Assessment workflow: evaluate Pundit + Permissify in parallel, keep Pundit authoritative, record mismatches, prove owner/staff/org/status cases, switch authority only on equivalence.
  5. Wave 4 · Roles & grants. Make organisation membership roles canonical; add direct grants only if real use cases require; add expiry/revocation; test for privilege creep.
  6. Wave 5 · Optional optimization. Only after measurement: cache/version fingerprints, a Predicate adapter, and a versioned gem release cadence once the API stabilises (the repo already exists — see ADR-0004).

The before / after, on one path

Today · Pundit policy — a domain check polluting authorization
class ArticlePolicy
  def publish?
    user.editor? &&
      record.title.present? && record.body.present? &&
      record.media.any? && record.reviewed_at.present?   # domain truth, misplaced
  end
end
After · without Predicate
Permissify.define(:article) do
  fact(:complete) { |ctx|
    r = ctx.resource
    r.title.present? && r.body.present? &&
      r.media.any? && r.reviewed_at.present?
  }
  fact(:may_publish) { |ctx| ctx.actor.editor? }
  permission(:publishable) { |ctx| ctx.all?(:complete, :may_publish) }
  action :publish, maps_to: :publishable
end
After · with Predicate (domain fact extracted, memoized)
# completeness is one Predicate fact, reused app-wide:
class Article
  def content_complete?
    Predicate.for(:article).call(:content_complete, title:, body:, media_ids:, reviewed_at:)
  end
end

Permissify.define(:article) do
  fact(:complete)    { |ctx| ctx.resource.content_complete? }
  fact(:may_publish) { |ctx| ctx.actor.editor? }
  permission(:publishable) { |ctx| ctx.all?(:complete, :may_publish) }
  action :publish, maps_to: :publishable
end

Same permission, same callers. Without Predicate the completeness check is plain Ruby inside the fact; with Predicate it is lifted into one memoized domain truth reused app-wide (see §08). The authorization decision is identical either way — only the home of the domain fact differs.