skip to content

In Rails, when would you hand out record.signed_id(expires_in:, purpose:) instead of a generates_token_for token, and why can't you revoke one early?

level: seniorimportance: should knowfreq 25%

answer

  1. only the id, a purpose, an expiry
  2. purpose prefixed with the model name
  3. find_signed nil, find_signed! raises
  4. no record state to compare
  5. a new purpose retires every old link

basics

~20 s

signed_id signs only the record's id with an optional expiry and purpose, so it suits short-lived links that need no revocation; with no record state in it, a leaked one works until it expires unless every link's purpose changes.

solid answer

~40 s

`endpoint.signed_id(expires_in: 15.minutes, purpose: :delivery_preview)` returns a tamper-proof string carrying the id, the expiry and the purpose, which Rails prefixes with the model name (`webhook_endpoint/delivery_preview`), so it cannot be replayed against another model or purpose. `WebhookEndpoint.find_signed(sid, purpose: :delivery_preview)` returns the record or `nil`; `find_signed!` raises `ActiveSupport::MessageVerifier::InvalidSignature`, or `ActiveRecord::RecordNotFound` if the row is gone. Nothing is stored, and unlike `generates_token_for` no record state is embedded, so you cannot kill one link early, only every link at once, by requiring a new purpose or rotating the verifier. Choose `signed_id` for short links where reuse is harmless, such as a preview or a download; choose `generates_token_for` with a block for actions that must work once, such as an email change. Both are readable, not encrypted.

code

ruby · 13 lines
ruby
# app/controllers/delivery_previews_controller.rb
class DeliveryPreviewsController < ApplicationController
  def create
    endpoint = current_account.webhook_endpoints.find(params[:endpoint_id])
    sid = endpoint.signed_id(expires_in: 15.minutes, purpose: :delivery_preview)
    redirect_to delivery_preview_path(sid)
  end

  def show
    @endpoint = WebhookEndpoint.find_signed(params[:id], purpose: :delivery_preview)
    head :not_found unless @endpoint
  end
end

go deeper

for a junior

Recall that signed_id gives a tamper-proof string for a saved record, and that find_signed turns it back into the record or returns nil.

for a middle

Explain expires_in, expires_at and purpose, the model-name prefix on the purpose, and the difference between find_signed and find_signed!.

for a senior

Show you choose by revocability: signed ids die only by expiry or a purpose change, so single-use actions belong to generates_token_for with a block.

for a principal

Weigh stateless links against stored tokens across the product, and plan verifier rotation and the 8.1 signed-id verifier migration without breaking links in flight.

## What a signed id is `signed_id` is an Active Record instance method that returns the record's primary key wrapped in a **signed message**: anyone can decode it, nobody can alter it without the signature failing. On a webhooks relay, an account owner can open a 15-minute preview of the next delivery for one endpoint without signing in: ```ruby sid = endpoint.signed_id(expires_in: 15.minutes, purpose: :delivery_preview) WebhookEndpoint.find_signed(sid, purpose: :delivery_preview) # => endpoint ``` It is defined only for saved records; calling it on a new one raises `ArgumentError`. ## Generating and finding | Call | Result | |---|---| | `endpoint.signed_id` | never expires, no purpose | | `endpoint.signed_id(expires_in: 15.minutes, purpose: :delivery_preview)` | expires, bound to that purpose | | `endpoint.signed_id(expires_at: Date.tomorrow.end_of_day)` | expires at a fixed time | | `WebhookEndpoint.find_signed(sid, purpose: :delivery_preview)` | the record, or `nil` | | `WebhookEndpoint.find_signed!(sid, purpose: :delivery_preview)` | the record, or raises | `find_signed!` raises `ActiveSupport::MessageVerifier::InvalidSignature` for a tampered, expired or wrong-purpose id and `ActiveRecord::RecordNotFound` when the id is valid but the row is gone. Both finders also work on a relation, so `account.webhook_endpoints.find_signed(sid, purpose: :delivery_preview)` only finds an endpoint of that account. ## The purpose is namespaced Rails combines the purpose with the model's base class name, so the verifier sees `webhook_endpoint/delivery_preview`. A signed id made for one model never finds a row of another model with the same id, and one made without a purpose does not match a lookup that names one. Under single-table inheritance the base class name is used, so subclasses share signed ids. ## Why early revocation is impossible 1. The payload holds the id, the purpose and the expiry; nothing about the record's state. 2. Verification checks only the signature, the purpose and the clock, then loads the row. 3. Nothing you change on the record (`touch`, a new column value) alters any of those three. The only levers are coarse: **require a new purpose** (`purpose: :delivery_preview_v2`) in every `find_signed`, which retires all outstanding links, rotate the verifier's secret, or delete the record. `generates_token_for` exists largely to fix this: its block value is embedded and compared again, so changing the record kills that record's tokens alone. ## Choosing among Rails' token tools | Tool | Stored where | Revoke one early | Typical use | |---|---|---|---| | `has_secure_token` | raw value in a column | yes, `regenerate_*` | long-lived API keys | | `generates_token_for` + block | nothing | yes, change the block's value | email change, password reset, magic links | | `signed_id` | nothing | no, purpose change only | short previews, downloads, idempotent links | The first stores a usable secret; the other two store nothing and are readable, so none of them should carry data you would not put in a URL. ## The Rails 8.1 verifier change Signed ids now come from `Rails.application.message_verifiers["active_record/signed_id"]`, and `ActiveRecord::Base.signed_id_verifier_secret` is deprecated, to be removed in 8.2. `config.active_record.use_legacy_signed_id_verifier` defaults to `:generate_and_verify`, which keeps generating and verifying with the pre-8.1 verifier options so links already sent keep working; `:verify` accepts old links while new ones use the new settings. A per-model verifier is set with `Model.signed_id_verifier=`. ## Common misreadings - **"It hides the id."** The id is readable to anyone holding the string; only tampering is prevented. - **"It expires on its own."** Without `expires_in:` or `expires_at:` a signed id is valid forever. - **"Updating the record retires its links."** Nothing about the record is in the payload. - **"find_signed raises on a bad id."** It returns `nil`; only `find_signed!` raises. - **"Purposes are global."** They are namespaced by model, so the same purpose on two models never collides. ## Testing expiry `travel 16.minutes` from Active Support's time helpers moves the clock past a 15-minute signed id, after which `find_signed` returns `nil`; `travel_back` restores it. Pair that with a test that a wrong purpose also returns `nil`, and the two coarse controls signed ids offer are both covered.

  • What changed for signed ids in Rails 8.1?
    Signed ids now come from `Rails.application.message_verifiers["active_record/signed_id"]`, and `ActiveRecord::Base.signed_id_verifier_secret` is deprecated for removal in 8.2. `config.active_record.use_legacy_signed_id_verifier` defaults to `:generate_and_verify`, so ids are still made and checked with the pre-8.1 options and old links keep working; `:verify` accepts old links while issuing new-style ones.
  • Can a signed id be limited to one account's records?
    Yes. `find_signed` and `find_signed!` are also relation methods that run inside the relation's scope, so `account.webhook_endpoints.find_signed(sid, purpose: :delivery_preview)` returns `nil` for an endpoint that belongs to another account, even with a valid signature.

  • A signed_id is encrypted, so the record id inside it stays secret.
  • Touching or updating the record invalidates its outstanding signed ids.
  • signed_id links expire after 15 minutes unless told otherwise.
  • A User signed id with the same purpose can load an Account with that id.
  • find_signed raises an exception when the signed id has expired.

Assumes Rails 8.1, where signed ids use Rails.application.message_verifiers["active_record/signed_id"] and ActiveRecord::Base.signed_id_verifier_secret is deprecated for removal in 8.2.