StockLive · authorization architecture
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.
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.
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.
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.
The app is conventional, policies remain easy to find, user + record is sufficient, and plain Ruby locality matters more than a global registry.
Many surfaces must share named activities, tenant and relationship facts, reason codes, validation, tracing, and migration evidence as one contract.
Only if a reusable boolean fact already exists. Permissify decides fully without it — see the optional Predicate section.
| Question | Pundit | Permissify |
|---|---|---|
| Primary unit | One policy class per record type, with query methods such as update?. | One registered entity with named activities, checks, references, and metadata. |
| Public question | authorize post, policy(post).update?. | decide(actor:, activity:, resource:, tenant:); can? is the boolean convenience. |
| Context | Intentionally user + record; wrap them when more context is truly required. | A typed, immutable context makes actor, resource, tenant and resolved facts first-class. |
| Discovery | Ruby 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. |
| Result | A 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. |
| Collections | Mature Policy::Scope#resolve convention and policy_scope helpers. | Must provide an explicit host-owned database scope contract; booleans never filter rows in memory. |
| Completeness | verify_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. |
| Auditability | Excellent 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 cost | Established ecosystem, familiar debugging, low conceptual overhead. | A bespoke security kernel, metaprogramming, migration cost, independent releases and a larger proof burden. |
ContactPolicyclass 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.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.
The core requires only its own registry, context, evaluator and decision objects. Rails support is a thin adapter. Pundit may run beside it during migration, but it is not called to reach a decision. Predicate may supply facts, but the same facts can be read or calculated by ordinary Ruby.
# app/permissions/article_permissions.rb — no Predicate, no Rails
Permissify.define(:article) do
fact(:draft) { |ctx| ctx.resource.status == "draft" }
fact(:owned) { |ctx| ctx.resource.user_id == ctx.actor.id }
permission(:editable) { |ctx| ctx.all?(:draft, :owned) }
action :edit, maps_to: :editable
end
decision = Permissify.decide(
actor: current_user,
action: :edit,
resource: article,
resource_key: :article
)
decision.allowed? # boolean convenience
decision.reason # :allowed
An unknown entity, activity, tenant or rule denies. It never asks Pundit and never guesses a method name after registration.
The pure-Ruby core accepts objects satisfying the public context ports. Active Record and Action Controller live only in adapters.
The host supplies explicit objects/facts. Permissify does not serialize every model attribute into a magic state hash.
permissify gemspec has no Pundit or Predicate dependency.draft, complete, owned.edit, publish.can_publish.# The port Permissify owns—not a Predicate-shaped API
FactSource.fetch(names:, context:)
# => FactsResult(values: { content_complete: true }, source: "predicate@04d2…")
# Controlled failures remain structured and fail closed
Decision.denied(
reason_code: :fact_source_error,
rule_id: "article.publishable.v1",
trace_id: trace_id,
error_class: :dependency_failure
)
Research basis: Pundit's official README (policy classes, scopes, verification and additional-context guidance); StockLive's locked Pundit 2.3.2 and Predicate 1.2.0 revision; Predicate's Registry/Core/DSL and cache implementation. The Predicate adapter shown here is a proposed port, not a claim that Permissify already exists.
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.
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?).
user.can? / cannot?. Entry point.app/permissions/<entity>_permissions.rb; adds ?-checks.authorize!, verify_authorized, can? view helper.method_missing captures each check.{ facts, permissions, actions }. Plain data.all_of/any_of, predicates. Added only when rules repeat.app/permissions/, reloads the Registry on to_prepare, runs boot-time validation.| File | Layer | Single responsibility |
|---|---|---|
| subject.rb | edge | User mixin — can?, cannot?. The question people ask. |
| resource.rb | edge | Model mixin — auto-load the entity's permission file; expose ?-checks. |
| controller.rb | edge | authorize! (raises NotAuthorized); verify_authorized catches actions that forgot. |
| authorization.rb | core | Action→activity map, build the typed decision context, deny by default on anything unknown. |
| core.rb | core | Look the permission up in the Registry and call its lambda. Evaluation only. |
| decision_context.rb | core | Immutable actor/resource/tenant/facts input. No generic host attribute dump. |
| decision.rb | core | Structured result: allowed, reason code, rule ID, trace ID, and safe error class. |
| configuration.rb | core | Action map and explicit ports. No implicit host constants or invisible bypass. |
| registry.rb | base | Store & fetch entity → { checks, sections }. No behaviour, just data. |
| dsl.rb | base | Builder/SectionBuilder — method_missing turns each block into a Registry entry. |
| railtie.rb | glue | Zeitwerk ignore, dev reload, boot-time validation of the whole Registry. |
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.
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.
The gem cannot casually reach into StockLive constants, models, helpers, or tables. Host knowledge enters only through public ports.
A pure-Ruby boot and isolated suite catch hidden coupling that namespace conventions and static checks miss.
Authorization mechanics have a compact review surface, stricter ownership, threat modelling, and focused adversarial tests.
can?, authorize!, scopes, decisions, and registration are deliberate contracts rather than application reach-ins.
StockLive pins an immutable revision, tests it as a consumer, and can restore the previous known-good revision without reverting unrelated app work.
The gem proves its supported Ruby and Rails combinations independently while StockLive proves the one combination it deploys.
Pundit and Permissify can evaluate the same requests in shadow mode, producing explicit mismatch evidence before authority changes.
A second trusted consumer can adopt the same mechanics without copying code or forcing StockLive business rules into the library.
The gem contains generic mechanics and examples. StockLive business permission files remain in StockLive. The gem never references a StockLive constant or owns StockLive persistence.
The gem runs in the same Ruby process and trust boundary. A repository cannot contain runtime failure or malicious code.
A tidy API can still hide decisions. Structured explanations, reason codes, tracing, and searchable declarations are required.
Independent history creates coordination cost. Immutable pins, consumer CI, changelogs, and an explicit upgrade owner contain it.
Do not invent adapters and abstractions for hypothetical consumers. StockLive's real migration drives the public API.
No invisible superuser lambda. Break-glass access is a named host capability with expiry, logging, alerts, and tests.
Boolean checks do not secure collections. Every list path needs a database-level scope contract and denial tests.
Never infer tenancy only from the actor or resource. Tenant is explicit, checked first, and applied to every database scope.
Fail-closed must not mean invisible failure. Adapter, rule, and source errors deny while emitting safe telemetry and alerts.
Approval and transition commands re-check authorization and domain invariants inside the write transaction when state can change concurrently.
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.
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
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.
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.
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.
Unknown entity, unregistered action, missing rule, or a raised error all resolve to false. Access is never the fallback.
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.
Authorized collections return an ActiveRecord::Relation scoped by organisation + ownership — safe by construction, never post-filtering loaded Ruby objects.
Definitions read like domain language; captured once at boot into plain data. One mental model shared with Predicate.
Reject unknown activities, duplicates, and missing references at boot — before a single request is served.
Reconcile the enum, the staff/assessor booleans, global roles, and membership roles into one model Permissify consumes. No competing truths.
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).
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.
Stale authorization is more dangerous than a slightly slower check. Add caching only if evaluation is a demonstrated bottleneck.
:edit → :editable is convenient, but arbitrary "#{action}able" fallback must deny unless the activity is registered — never invent a permission name.
A global superuser_check recreates the role bypass the design removes. Break-glass access belongs to StockLive as a named, expiring, logged capability.
Dumping every attribute plus private actor keys into an untyped hash creates hidden coupling. The baseline uses an explicit actor/resource decision context.
Add all_of/any_of and a Predicate adapter only when real repeated rules justify them.
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.
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.
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.
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 — 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
| Fact kind | Home | Freshness | Why |
|---|---|---|---|
| Grants, roles, membership, ownership, revocation, tenant scope | Plain Ruby, inside Permissify | Always fresh — never memoized | Authorization-specific and volatile; a stale value hands back access that was revoked. |
| Completeness, validity, eligibility, lifecycle state | Predicate (domain layer), read by Permissify as a plain fact | Safely memoized per request / resource version | Stable within a request and reused across the app; here Predicate's mandatory memoization is a feature, not a hazard. |
content_complete? — a domain method that may use Predicate.permissify gemspec has no Predicate dependency.FactSource is justified only for a stable, resource-only fact needed nowhere else.Missing → default-deny.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.
scope.all defaults.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.authorize!, authorized ActiveRecord scopes, missing-authorization detection, correct HTML/Turbo/JSON denials, audit instrumentation without leaking sensitive facts.class ArticlePolicy
def publish?
user.editor? &&
record.title.present? && record.body.present? &&
record.media.any? && record.reviewed_at.present? # domain truth, misplaced
end
end
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
# 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.