skip to content

In a Rails Action Cable channel, how do you stop a customer from streaming another customer's support-ticket chat, and what does reject actually do?

level: seniorimportance: should knowfreq 40%

answer

  1. params come from the client identifier
  2. scope the lookup through current_user
  3. stream_or_reject_for
  4. reject sets a flag, does not return
  5. rejected() fires; unsubscribed still runs

basics

~20 s

Treat params in subscribed as untrusted: load the ticket through current_user's own tickets and call stream_or_reject_for (or reject), never stream_from a name built from raw params. reject only marks the subscription; Rails then removes it and the browser's rejected() callback fires.

solid answer

~40 s

A subscription's `params` are the JSON identifier the browser sent with `consumer.subscriptions.create({channel: "TicketChatChannel", ticket_id: 42})`, so any user can send any `ticket_id`. `stream_from "ticket_chat_#{params[:ticket_id]}"` therefore lets anyone read any chat. Instead look the record up through the user, `current_user.support_tickets.find_by(id: params[:ticket_id])`, and call `stream_or_reject_for ticket`, which streams when it is present and calls `reject` otherwise. `reject` only sets a flag: the rest of `subscribed` still runs, so `return` after it if more code follows. When `subscribed` returns, Rails removes the subscription (running `unsubscribed` and stopping any streams) and sends `reject_subscription`, which fires the JavaScript `rejected()` callback instead of `connected()`. Unlike `reject_unauthorized_connection`, the socket and its other subscriptions stay up.

code

ruby · 15 lines
ruby
class TicketChatChannel < ApplicationCable::Channel
  def subscribed
    @ticket = current_user.support_tickets.find_by(id: params[:ticket_id])
    stream_or_reject_for @ticket
  end

  def unsubscribed
    # also runs for rejected subscriptions: @ticket may be nil here
  end

  def speak(data)
    return unless @ticket.open?
    TicketChatChannel.broadcast_to(@ticket, author: current_user.id, body: data["body"])
  end
end

go deeper

for a junior

Remember that a channel can refuse a subscription with reject, and that params in a channel come from the browser.

for a middle

Explain scoping the lookup through current_user, stream_or_reject_for, and how the client learns about rejection through rejected().

for a senior

Show you know reject's sharp edges: it does not return, unsubscribed still runs, stream_for nil streams the bare channel name, and long-lived channels need re-checks in actions.

for a principal

Set the team rule for real-time authorisation: per-subscription checks through the same policy objects as controllers, and a revocation path for subscriptions that outlive a permission change.

## Where channel params come from In Action Cable a **subscription** is identified by a JSON string the browser builds. `consumer.subscriptions.create({ channel: "TicketChatChannel", ticket_id: 42 }, {...})` sends a `subscribe` command whose identifier is `{"channel":"TicketChatChannel","ticket_id":42}`. On the server, `ActionCable::Connection::Subscriptions#add` decodes it, finds the channel class with `safe_constantize` (only subclasses of `ActionCable::Channel::Base` are accepted), and passes the decoded hash, with indifferent access, as the channel's `params`. So `params[:ticket_id]` is whatever the client chose. Authenticating the socket in `connect` tells you *who* is asking; it says nothing about *what* they may see. Each subscription needs its own authorisation, and in Rails that lives in `subscribed`. ## The vulnerable version and the fix ```ruby # Vulnerable: any signed-in user can stream any ticket's chat def subscribed stream_from "ticket_chat_#{params[:ticket_id]}" end # Fixed: the lookup is scoped to the user, and a miss is rejected def subscribed @ticket = current_user.support_tickets.find_by(id: params[:ticket_id]) stream_or_reject_for @ticket end ``` The fix has three parts: - **Scope the lookup** through an association or a policy, so a foreign or made-up id returns `nil` rather than another customer's ticket. - **Use `stream_or_reject_for`**, which calls `stream_for` when the model is present and `reject` when it is not. Plain `stream_for nil` does not reject: `broadcasting_for(nil)` yields the bare channel name, so the subscriber would be attached to `ticket_chat`. - **Prefer `stream_for` to string names**, so the broadcasting is derived from the record you authorised. ## What reject does, step by step 1. `reject` sets `@reject_subscription = true` and returns. It does **not** raise or return from `subscribed`, so code after it still runs. 2. After `subscribed` (and any `after_subscribe` callbacks) finish, `subscribe_to_channel` sees `subscription_rejected?`. 3. It calls `connection.subscriptions.remove_subscription`, which runs `unsubscribe_from_channel`: the `unsubscribed` method runs, and the built-in unsubscribe callback calls `stop_all_streams`. 4. It transmits `{identifier: ..., type: "reject_subscription"}`; no `confirm_subscription` is ever sent. 5. In the browser, `@rails/actioncable` forgets the subscription and calls its `rejected()` callback; `connected()` never fires. Two consequences catch people out: - `unsubscribed` runs for rejected subscriptions too, so cleanup code there (presence tracking, for instance) must not assume the subscription was ever confirmed. - `after_subscribe` callbacks run even after `reject`; the source suggests `after_subscribe :track, unless: :subscription_rejected?`. ## reject vs reject_unauthorized_connection | | `reject` | `reject_unauthorized_connection` | |---|---|---| | Called in | a channel's `subscribed` | the connection's `connect` | | Scope | one subscription | the whole socket | | Browser sees | `rejected()` on that subscription | a disconnect with reason `unauthorized` | | Other subscriptions | unaffected | gone | ## Authorisation after subscribe - A channel instance lives as long as the subscription, which can be hours. Data loaded in `subscribed` (such as `@ticket`) can go stale; actions that change data should re-check, for example that the ticket is still open or still assigned. - Actions callable by `perform` are the channel's public methods, so keep helpers `private`. - Removing access later means stopping the stream (`stop_stream_for @ticket`) from inside the channel, or disconnecting the user's sockets with `remote_connections`. ## A checklist for every channel 1. Find each record named in `params` through the current user's scope or a policy, never with a bare `find`. 2. Reject on a miss with `stream_or_reject_for` or `return reject unless ...`, before any stream starts. 3. Derive broadcasting names with `stream_for` from the authorised record, not from strings built out of params. 4. Keep every helper `private`, because each public method is an action any browser can call. 5. Re-check state that can change (ticket closed, agent reassigned) inside the actions that write. 6. Write channel tests for the rejected path as well as the happy one. ## Why Rails leaves this to you Action Cable has no authorisation DSL of its own. It gives you the primitives (identifiers delegated from the connection, `reject`, `stream_or_reject_for`, `stop_stream_for`) and expects `subscribed` to call the same scopes or policy objects your controllers use. That keeps one source of truth for "who may see ticket 42", whether the request arrives over HTTP or over the socket. An interviewer asking this question is usually checking one thing: whether the candidate knows that a successful `connect` is authentication only, and that a channel subscribed with client-chosen params is an insecure direct object reference unless `subscribed` checks it.

  • What happens if subscribed calls reject and then stream_for on the next line?
    Both run, because `reject` only sets a flag. Once `subscribed` returns, Rails removes the subscription, which runs `unsubscribed` and `stop_all_streams`, so the stream is torn down and the browser gets `rejected()`. It is still clearer and cheaper to `return reject unless ...` before starting streams.
  • Why does stream_for nil not protect you?
    `broadcasting_for(nil)` serialises to just the channel name, such as `ticket_chat`, so `stream_for nil` subscribes the user to a shared channel-wide broadcasting instead of rejecting. `stream_or_reject_for` exists for exactly this case: it streams only when the model is present.

  • Calling reject inside subscribed immediately stops the rest of the method.
  • A rejected subscription never runs the channel's unsubscribed callback.
  • reject closes the whole WebSocket, like reject_unauthorized_connection.
  • Once connect has authenticated the user, params[:ticket_id] can be trusted in subscribed.
  • stream_for nil rejects the subscription because there is no record to stream.