guest@websec ~ % man r06-controllers
Controllers and the API Hierarchy
A controller turns one HTTP request into one JSON response. Ours are short because each layer of the class hierarchy takes one job off their hands.
A controller action should: load records (scoped to what the caller may see), pass whitelisted params to a model or service, and render a model's JSON shape. Auth, permissions and error formatting are inherited, not written in each controller.
The class hierarchy
ActionController::API
└── ApplicationController health check, paginate, sort, safe render
└── Api::AppController cookies + rescue_from → JSON errors
└── Api::V1::AppController version seam (empty today)
├── Api::V1::Admin::AppController cookie login + permission check
│ ├── Api::V1::Admin::RolesController
│ ├── Api::V1::Admin::UsersController
│ └── Api::V1::Admin::SessionsController (skips login for create)
├── Api::V1::Client::AppController X-App-Key + signed JWT
│ ├── Api::V1::Client::RolesController
│ └── Api::V1::Client::AuthController
└── Api::V1::Public::AppController no auth
└── Api::V1::Public::TwoFactorsControllerWhen you generate a controller, change its parent to the right
…::AppController immediately. A leaf controller inheriting ApplicationController is a security bug: no login, no permission check.Anatomy of a resource controller
class Api::V1::Admin::RolesController < Api::V1::Admin::AppController before_action :set_client_application # parent from the URL before_action :set_role, only: %i[ show update ] # the record, scoped to the parent # GET /api/v1/admin/client_applications/:client_application_id/roles def index result = @client_application.roles total_count = result.count key_mapping = { "created_at" => "created_at", } result = sort_with_mapping(result, key_mapping) if result.present? result, total_pages = paginate(result) render json: { roles: result.map(&:as_admin_json), total_pages:, total_count: } end def show render json: { role: @role.as_admin_json } end def create @role = Role.new(role_params) @role.save! # raises → rescue_from → 400 render json: { role: @role.as_admin_json }, status: :created end def update @role.update!(role_params) render json: { role: @role.as_admin_json } end private def set_client_application @client_application = ClientApplication.find(params[:client_application_id]) end def set_role @role = @client_application.roles.find(params[:id]) # not Role.find! end def role_params p = params.require(:role).permit(:name, :description, :status, permissions: []) p[:client_application_id] = @client_application.id if action_name == "create" p end end
| pattern | why |
|---|---|
set_* before_actions | load records once, before the action; find raises → 404 automatically |
@client_application.roles.find | scope through the parent: a role id from another app is a 404, not a leak (IDOR) |
save! / update! | no if/else; failures raise and become the standard 400 JSON |
require(:role).permit(…) | whitelist; anything else in the body is dropped (mass assignment) |
p[:client_application_id] = … | the parent comes from the URL the user was authorized for, never from the body |
as_admin_json | the model decides the JSON shape; the controller picks which one |
{ roles:, total_pages:, total_count: } | every list has the same envelope, so the front end has one table component |
See it respond
Params, briefly
params[:id] # from the path: /users/:id params[:page] # from the query string: ?page=2 params.require(:role) # JSON body {"role": {...}}; raises if missing .permit(:name, :status, permissions: [])# arrays need [] ; nested hashes need { } params.permit(:sort_field, :sort_order) # optional query params, no require params[:info].to_bool # query values are strings action_name # "create", "update", ...
Status codes we use
| status | when | comes from |
|---|---|---|
200 :ok | read / update succeeded | render json: |
201 :created | create succeeded | render json:, status: :created |
400 :bad_request | invalid data, missing param, bad state transition | AppError, RecordInvalid, ParameterMissing, AASM::InvalidTransition |
401 :unauthorized | not logged in / bad token | AppAuthenticationError, JWT errors |
403 :forbidden | logged in but not allowed | AppPermissionDenied |
404 :not_found | no such record (or not yours) | ActiveRecord::RecordNotFound |
Check yourself
A user calls GET /client_applications/A/roles/R where role R belongs to app B. What happens with our set_role?
@client_application.roles.find(id) adds WHERE client_application_id = A. With Role.find(id) it would be 200: an IDOR bug.
Where should the client_application_id of a new role come from?
The user was authorized for the parent in the URL. Permitting the id from the body would let them create roles in any app.