guest@websec ~ % man r08-where-code-goes
Controllers, Models or Services?
Most code-review comments in a Rails app are about where code lives, not whether it works. Here is how we decide.
Controllers speak HTTP (params, scoping, status codes), models own data rules and JSON shapes, services wrap external systems or stateless algorithms (
DirectoryService, TokenService), and jobs handle slow or retryable side effects.| layer | owns | must not |
|---|---|---|
| controller | HTTP: params, who is calling, which records they may touch, status code, which JSON shape | business rules, SQL beyond simple finds, calling external systems |
| model | data rules: validations, associations, state, derived values, JSON shapes, record-level behaviour | read params, cookies or the request; call external services directly |
| service | the outside world (company directory, JWT, payment, S3) or a stateless algorithm, behind a small API | own a table; know about HTTP requests |
| job | slow or retryable side effects: webhooks, emails, syncs | be required for the response to be correct |
| concern | behaviour shared by several models or controllers (SoftDeletable) | be a dumping ground for one model's code |
One feature, three layers
Admin login checks the password against the company directory, syncs the user, verifies 2FA and sets a cookie. Here is the same feature written badly, then the way it actually is:
def create client = SomeDirectoryGem::Client.new(host: ENV["DIRECTORY_HOST"], password: ENV["DIRECTORY_PASSWORD"]) entry = client.login(params[:username], params[:password]) # raw client, raw errors, no timeout return render json: { error: "bad login" }, status: 401 unless entry user = User.find_or_initialize_by(username: entry["name"].downcase) user.email = entry["mail"] user.save # failure silently ignored if !user.is_admin then return render json: { error: "no" }, status: 401 end totp = ROTP::TOTP.new(user.otp_secret) return render json: { error: "bad otp" }, status: 401 unless totp.verify(params[:otp]) cookies.encrypted[:bearer] = JWT.encode({ ... }, Rails.application.credentials.user_jwt_secret) render json: { success: true } end
# controller: HTTP only def create user = User.authenticate_and_sync!(username, password) # model raise AppAuthenticationError.new("user not admin") unless user.is_admin? raise AppAuthenticationError.new("401: Invalid 2FA code") unless user.verify_otp(otp) user.reset_authentication_token update_cookies(:bearer, user.jwt("bearer")) # inherited helper render json: { success: true }, status: :created end # model: what a User is and does def self.authenticate_and_sync!(username, password) entry = DirectoryService.authenticate!(username, password) # service sync_from_directory!(entry) end def verify_otp(code) = !totp.verify(code.to_s.strip, drift_behind: 1).nil? # service: the only code that talks to the directory class DirectoryService def self.authenticate!(username, password) entry = client.login(username, password) # host, timeouts, secrets: in here only raise AppError.new("401: Invalid credentials") unless entry { username: entry["name"], email: entry["mail"], display_name: entry["display"] } # plain hash out rescue SomeDirectoryGem::Error => e raise AppError.new("Directory unavailable") # our error, no internals leaked end end
Why services?
- One door to the outside world. Connection settings, timeouts, credentials and error translation for the directory live in
DirectoryServiceonly. When the directory changes, one file changes. - Errors in our language. Network errors from a client gem or
JWT::DecodeErrorbecomeAppError, which the API already knows how to render. - Easy to fake in tests.
DirectoryService.stub :authenticate!, entry do … end: model and controller tests run without the real directory. - Reusable. The same service method runs from a controller, a job,
bin/rails runneror the console. - Models stay about data. Loading a model never opens a socket.
Our service style
class TokenService HMAC_SECRET = Rails.application.credentials.dig(:token_service_jwt_secret) # config read once def self.encode(hmac_secret, payload, exp = 8.hours.from_now) # class methods, raise AppError.new("HMAC secret is missing") if hmac_secret.blank? # no instance state data = payload.deep_dup data[:exp] = exp.to_i data[:iat] = Time.current.to_i JWT.encode(data, hmac_secret, "HS256") end def self.decode(hmac_secret, token) raise AppError.new("HMAC secret is missing") if hmac_secret.blank? JWT.decode(token, hmac_secret, true, { algorithm: "HS256" }).first.with_indifferent_access # pin the algorithm rescue JWT::DecodeError => e raise AppError.new("Invalid token: #{e.message}") # translate errors end end # the model offers a friendly method that uses its own secret class ClientApplication < ApplicationRecord def encode_payload(payload) = TokenService.encode(api_secret, payload) def decode_payload(token) = TokenService.decode(api_secret, token) end
Services are classes with
self. methods and a …Service name, one per external system or algorithm. No UserService grab-bags: logic about a user's own data is a User method.Jobs for side effects
class ClientApplicationWebhookJob < ApplicationJob queue_as :webhooks retry_on StandardError, wait: :polynomially_longer, attempts: 5 # network fails; try again def perform(client_application_id, event_name, payload) # pass ids, not objects client_app = ClientApplication.find_by(id: client_application_id) return if client_app.nil? || client_app.webhook_url.blank? token = JWT.encode({ iss: client_app.app_key, aud: client_app.webhook_url, exp: 10.minutes.from_now.to_i, event: event_name, data: payload }, client_app.api_secret, "HS256") Faraday.post(client_app.webhook_url) { |req| req.headers["Authorization"] = "Bearer #{token}"; req.body = { token:, event: event_name }.to_json } end end
The model’s after_commit only calls notify_webhook, which calls perform_later. The API responds immediately; slow or failing receivers never slow down or break our endpoint.