authorization.md
| source_url | https://github.com/nuke-on-rails/nuke-on-rails/blob/67c72332e6eea2a2897f3ed72a061ac8fc175140/arsenal/authorization.md |
|---|
Weapon: Authorization & IDOR
The territory Brakeman cannot reach: whether the code checks who is allowed to do what. Brakeman parses for injection and unsafe APIs; it cannot know that Order.find(params[:id]) should have been current_user.orders.find(params[:id]). That judgment — reading the code with the app's domain in mind — is this weapon.
Apply it to every controller that touches user-owned or money-related data, plus the routes file. This weapon covers authorization; it does not guarantee it — say so in the report.
Methodology
- Map the attack surface first. Read
config/routes.rband list every reachable action. Blanketresources :ordersexposes seven actions — flag routes for actions that don't exist in the controller or were never meant to be public. Generated apps almost never restrict withonly:. A legacy catch-all route (match ':controller(/:action(/:id))') exposes every public method as an action — flag it outright. For authorization errors on guessable resources, returning 403 (vs 404) confirms the record exists — prefer 404 to avoid enumeration. - Identify the authorization layer. Pundit, CanCanCan, action_policy, or nothing? If a library is present, the question becomes "where is it skipped?" (
authorizemissing in an action, noverify_authorizedhook,skip_authorizationsprinkled around). If nothing is present, every controller action is hand-audited. - For each sensitive action ask three questions: Who can reach this? What records can it load? Is the record scoped to the requester?
What to Flag Aggressively
IDOR — the number one finding in unreviewed Rails apps:
-
Model.find(params[:id])on user-owned data, instead of scoping through ownership:current_user.orders.find(...). The canonical critical case: a payments/orders/invoices controller where changing the URL id reads someone else's record.@invoice = Invoice.find(params[:id]) # Problem — any logged-in user reads any invoice by id @invoice = current_user.invoices.find(params[:id]) # Fix — scoped to the owner; an unowned id 404s -
Scoping on
showbut not onupdate/destroy(or vice versa) — auditors check the read path and forget the write path.def update = Order.find(params[:id]).update(order_params) # Problem — write path unscoped def update = current_user.orders.find(params[:id]).update(order_params) # Fix — scope every action alike -
IDOR in nested or non-obvious params:
params[:order_id]inside a different controller, ids accepted in POST bodies, ids in API serializer links.LineItem.find(params[:line_item_id]) # Problem — id in a nested/POST param, unscoped current_user.orders.find(params[:order_id]).line_items.find(params[:line_item_id]) # Fix — via the owner -
Sequential integer ids make IDOR trivially discoverable; UUIDs reduce discoverability but do not fix the vulnerability — never accept "we use UUIDs" as the remedy.
Missing or bypassed authorization:
-
Actions with authentication (
authenticate_user!) but no authorization — logged-in is not allowed-to.authenticate_user!; Post.find(params[:id]).destroy # Problem — logged in ≠ allowed; anyone deletes any post authorize(@post = Post.find(params[:id])); @post.destroy # Fix — Pundit checks PostPolicy#destroy? -
Admin functionality guarded only by obscurity: an
/adminnamespace with no role check, or abefore_actioncheckingparamsinstead of the session user.namespace(:admin) { resources :users } # Problem — /admin reachable by anyone, no role check authenticate(:user, ->(u) { u.admin? }) { namespace(:admin) { resources :users } } # Fix — gate on role -
Records leaked through form helpers: a
collection_select/dropdown populated withCategory.allinstead ofpolicy_scope(Category)(orcurrent_user.categories) exposes every record's existence right in the rendered page — an authorization leak no static scanner sees. Check select boxes and association pickers on user-facing forms.collection_select :category_id, Category.all # Problem — exposes every category's existence collection_select :category_id, policy_scope(Category) # Fix — only what the user may see -
Cache keys not scoped to the requester:
Rails.cache.fetch("dashboard") { current_user.dashboard }, or a fragment<% cache "sidebar" %>wrapping per-user content, serves the first user's data to everyone who hits it next — a cross-user leak no scanner sees. Any cache (fragment or low-level) around user-specific data must include the user/account in the key ([current_user, ...]).Rails.cache.fetch("dashboard") { current_user.dashboard } # Problem — one user's data to everyone Rails.cache.fetch([current_user, :dashboard]) { current_user.dashboard } # Fix — keyed per user -
Turbo Stream broadcasts rendered for the wrong audience:
broadcasts_torenders the partial once, with no request context (nocurrent_user), and sends the same HTML to every subscriber of the stream. A partial with viewer-specific content — an owner-only Edit/Delete button, another user's private fields — either breaks or leaks to everyone subscribed. Onlyturbo_stream_froma stream on pages where the viewer may receive every future broadcast to it.broadcasts_to ->(comment) { [comment.post, :comments] } # Problem — one partial (no current_user) to all subscribers # Fix — broadcast only what every subscriber may see; keep per-viewer controls out of the partial # (render them client-side, or use a per-recipient stream) — never current_user-dependent markup -
ActionCable channels that subscribe without ownership scoping: a
Channel#subscribedthat doesstream_for Room.find(params[:id])lets any authenticated user subscribe to any room's stream by id and receive every broadcast to it — IDOR over the websocket (messages, presence) on a resource they don't belong to. Scope the lookup through the requester; authenticateConnection#connectwith the same identity resolution as HTTP.def subscribed; stream_for Room.find(params[:id]); end # Problem — any user streams any room by id def subscribed; stream_for current_user.rooms.find(params[:id]); end # Fix — scoped to the subscriber's rooms -
Attachments served without per-request authorization: Active Storage's default URLs (
url_for(doc.file),rails_blob_path) are signed (unguessable) but not scoped to a user — they're bearer URLs, valid to anyone who obtains them (a leaked Referer, a shared link, a log line) and effectively permanent. For private or tenant-owned files (invoices, IDs, contracts) the access control becomes "knows the URL", not "is authorized" — an IDOR on attachments. Serve sensitive files through a controller that authorizes via the owning record.<%= url_for(document.file) %> <%# Problem — signed but unauthorized; a leaked URL grants anyone access %># Fix — authorize through ownership, then serve (short-TTL URL or send_data) def show; @doc = current_user.documents.find(params[:id]); redirect_to @doc.file.url(expires_in: 5.minutes); end -
Authorization enforced in the view (hiding the button) but not in the controller — the request still works via curl.
# Problem — the view hides the button, but `def destroy = @post.destroy` still runs via curl # Fix — enforce in the controller too: `authorize @post` before destroying -
Role/permission fields reachable through mass assignment:
permit(:role),permit!, orupdate(params[:user])on a model withadmin/rolecolumns. Brakeman flags some of this; confirm the semantic cases it can't.params.require(:user).permit(:email, :role) # Problem — user can set role: "admin" params.require(:user).permit(:email) # Fix — never permit privilege columns from params -
Value/state fields reachable through mass assignment — the same flaw, but the leaked column isn't a privilege bit, it's economic or trust state:
credits/balance/wallet(money),plan/subscription_status/tier(paid entitlement),verified/approved/kyc_status(trust),stripe_customer_id(billing-identity hijack). These are server-authority columns — they may only change via server logic (a payment webhook, an admin action), never from a user-facingpermit. This case is the one reviewers miss, because auth and ownership both pass and it still leaks: a valid token on a correctly ownership-scoped update (current_user.update(...)) hands the attacker free credits if the field is permitted. Don't pattern-match only onrole/admin; scan everypermit/update/assign_attributesfor any column the user shouldn't be able to set the value of.current_user.update(params.permit(:name, :credits)) # Problem — ownership checked, token valid, STILL leaks credits current_user.update(params.permit(:name)) # Fix — value/state columns never enter a user-facing permit; # credits change only in the payment webhook, server-side -
accepts_nested_attributes_forwithout ownership checks — nested params let a user update or delete child records by id (comments_attributes: [{id: 999, ...}]) without the controller ever verifying the child belongs to the parent they own. A classic IDOR-through-nesting that static analysis misses: confirm the parent is loaded throughcurrent_userand that permitted nested ids are re-scoped.Post.find(params[:id]).update(post_params) # Problem — nested comment ids unscoped to the owner current_user.posts.find(params[:id]).update(post_params) # Fix — load the parent through ownership -
Strong-parameters bypassed by a raw Hash —
User.new(JSON.parse(params[:user]))(or any.new/.updatefed a plain Hash built outsideActionController::Parameters) sidesteps permit entirely, re-opening mass assignment. Common in hand-written JSON API actions and AI-generated endpoints. Trace every.new/.update/.assign_attributeswhose argument isn't apermit-ed params object. On Rails 8, the idiomatic, type-safe remedy isparams.expect(user: [:name, :email])— it raises on the array/hash param-type tricks that slip pastrequire().permit().User.new(JSON.parse(params[:user])) # Problem — bypasses permit; mass assignment reopened params.expect(user: [:name, :email]) # Fix (Rails 8) — type-safe allowlist
Structural signals that raise suspicion:
-
skip_before_action :authenticate_user!(or pundit skips) with a longonly:/except:list — those lists drift out of date.skip_before_action :authenticate_user!, except: %i[show index] # Problem — list drifts; new actions ship public # Fix — default closed: authenticate globally, open only the few public actions explicitly (only:) -
Authorization logic duplicated inline across actions instead of centralized in policies — inconsistency is where the holes live.
redirect_to(root_path) unless @post.author == current_user # Problem — copy-pasted per action, drifts authorize @post # Fix — one PostPolicy#update?, enforced in one place -
Webhooks and internal/API endpoints exempted from CSRF and auth "because it's internal", with no signature verification in its place.
skip_before_action :verify_authenticity_token # Problem — "internal", no signature check in its place # Fix — verify the signature instead (see arsenal/api.md)
Multi-tenant isolation (cross-tenant IDOR)
In a multi-tenant app (SaaS with account/organization/workspace scoping) the worst finding isn't one user reading another user's row — it's one tenant reading another tenant's entire dataset. The signal is always the same: isolation that rests on developer discipline per query rather than a structural guarantee. One forgotten where(account_id:) is the whole breach.
-
Tenant resolved from a request-controlled value instead of the session. Tenant taken from
params, a request header, or aHost/subdomain the client sets —Current.tenant = Account.find(params[:account_id])— lets an attacker simply name someone else's tenant. The tenant must come from the authenticated session (current_user.account), never from input.ActsAsTenant.current_tenant = Account.find(params[:account_id]) # Problem — attacker names any account set_current_tenant(current_user.account) # Fix — tenant from the authenticated session -
Per-query scoping instead of a default guarantee. Hand-written
where(account: current_account)on every query is one missed call away from a leak — and the miss is invisible in review. Look for the absence of a structural guarantee (acts_as_tenant,ActsAsTenant.current_tenant, adefault_scope, or a multitenant gem) on tenant-owned models. A bareProject.find(params[:id])in a tenant app is a cross-tenant IDOR. Andacts_as_tenantonly fails closed whenrequire_tenant = true— without it (the default), a query that loses the tenant context silently returns every tenant's rows instead of raising, so the gem's mere presence is false confidence.Project.where(account_id: current_account.id).find(params[:id]) # Problem — one forgotten scope = leak Project.find(params[:id]) # Fix — acts_as_tenant scopes every query (set require_tenant = true so it fails closed) -
unscoped/default_scopeoverride on a reachable path.unscoped,Model.default_scoped(false), or awith_tenant/admin scope used inside a user-facing action defeats the isolation that exists elsewhere — grep for it and confirm none sit on a request path.Project.unscoped.find(params[:id]) # Problem — defeats tenant isolation on a request path current_account.projects.find(params[:id]) # Fix — stay within the tenant scope -
Child/join tables without their own tenant column. Scoping the parent (
current_account.projects) but loading a child directly (Task.find(params[:id]),comments_attributesby id) when the child carries noaccount_idof its own — the child is reachable across tenants even though the parent is locked down.Task.find(params[:id]) # Problem — child reachable cross-tenant (no account_id of its own) current_account.projects.find(params[:project_id]).tasks.find(params[:id]) # Fix — through the scoped parent -
Background jobs and callbacks that lose tenant context.
Current.tenant/ActsAsTenant.current_tenantis request-local; an ActiveJob/Sidekiq worker that doesn't re-establish it runs unscoped and can read or mutate every tenant's data. Confirm the tenant is passed as a job argument and re-set inperform, not assumed.def perform(id) = Project.find(id).archive! # Problem — runs unscoped, reaches every tenant's data def perform(account_id, id) # Fix — pass the tenant and re-establish it ActsAsTenant.with_tenant(Account.find(account_id)) { Project.find(id).archive! } end -
Global lookups that skip the tenant entirely —
find_by(email:)for login, token lookups, orfind_by!(slug:)that match across tenants when they should be scoped within one.User.find_by(email: params[:email]) # Problem — matches across all tenants current_account.users.find_by(email: params[:email]) # Fix — scoped within the tenant
State the blast radius explicitly in the report: cross-tenant access is "any customer can read/modify every other customer's data", which sits at the very top alongside IDOR on money paths.
Severity
Confirmed IDOR or missing authorization on money, PII, or account-takeover paths is the top of the entire report — above every CVE and every quality finding. For each confirmed finding, state the exploit in one sentence ("any logged-in user can read any other user's invoices by changing the id"). If you cannot demonstrate the unscoped path, it goes to "theoretical", never to "confirmed".
Untested authorization rules are a finding even when the code looks correct — they're one refactor away from silent failure (this overlaps with the quality weapon's test-coverage rule; report it on the security side).
Preferred Remedies
- Scope queries through ownership:
current_user.orders.find(params[:id])— the fix is usually one line. - Adopt one authorization library and enforce it globally (
verify_authorized/check_authorization) so a missing check fails loudly instead of silently allowing. - Restrict routes to the actions that exist:
resources :orders, only: [:index, :show]. - Replace per-query tenant discipline with a structural guarantee (default tenant scoping).
- Add a request spec per rule: "user A cannot see user B's record" — the cheapest regression insurance in the codebase.
Copyright (c) 2026 Nuke on Rails contributors License files are attached. MIT
MIT notice
MIT License
Copyright (c) 2026 Nuke on Rails contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Children
No children yet.
Like how this is organised?
Build your own Memory tree on knowen.md: notes, decisions and tasks in one connected markdown graph, shared with your team and your AI agents.