Skip to content

Rails apps

A Rails app can use masks in one of three modes.

Mode Gemfile What your app does
Client gem "masks" Signs people in against a masks server that runs somewhere else.
Server gem "masks-server" Is a masks server, and nothing else.
Engine gem "masks-server" Mounts masks inside itself. Signs its own people in through it.

Server mode and Engine mode use the same Rails engine, Masks::Server::Engine, and the same install generator. They mount it in different ways:

  • Server mode mounts it at the root. The container image is a Server-mode app.
  • Engine mode mounts it at a path or on a subdomain, and keeps masks apart from the app around it.

In Client mode, your app signs people in against a masks issuer. The issuer is the masks server, and the tenant on it, that signs people in and gives out tokens.

Masks::Rails is a Rails engine inside the masks gem. It adds the sign-in flow to your app, and you configure it in an initializer.

A scope is a named permission that a token holds. A claim is one piece of information inside a token, such as the person’s email address.

  1. Add the gem to your Gemfile:

    gem "masks"
  2. Run the install generator:

    Terminal window
    bin/rails generate masks:install --resource https://app.example.com

    The generator mounts the engine at /auth, or at the path you give with --mount. It writes config/initializers/masks.rb and adds config/masks.json to .gitignore. Leave out --resource when the app does not accept tokens of its own. The initializer looks like this:

    Masks::Rails.configure do |config|
    config.issuer = ENV.fetch("MASKS_ISSUER", "https://auth.example.com")
    config.resource = "https://app.example.com"
    config.resource_scopes = []
    config.after_sign_in = "/"
    config.after_sign_out = "/"
    end
  3. Set MASKS_ISSUER to the tenant you sign in against, such as https://acme.auth.example.com.

  4. Start the app.

  5. Open /auth/handshake.

The handshake connects your app to the masks server:

  1. The handshake sends the browser to the masks server’s approval screen.
  2. You approve the app there.
  3. A one-time token comes back. The engine redeems it by talking to the masks server directly, so the client secret never passes through the browser.

The handshake registers the app for config.resource, which must be an absolute https URL. If it is not set, /auth/handshake refuses. masks refuses the handshake unless every address it registers, such as /auth/callback, shares the resource’s origin.

Once the app is connected, only someone config.manages approves can reconnect or disconnect it. Set it to a privilege, or to a callable that takes the request, or the request and masked. If it is not set, the engine refuses everyone.

config.manages = :admin
config.manages = ->(request, masked) { masked.subject == ENV["OWNER_SUB"] }

The engine writes the credentials to config/masks.json, with file mode 600. A multi-tenant app keeps one row per tenant in place of the file:

config.credentials = ->(request) { Tenant.for(request).masks_credentials }
config.store = ->(request, registration) { Tenant.for(request).connect!(registration) }

Every setting that can change from one request to the next accepts a callable that takes the request.

Include Masks::Rails::Authentication in a controller and call masked!:

class ApplicationController < ActionController::Base
include Masks::Rails::Authentication
masked!
end

To include Authentication in every controller, set config.authenticate_everything = true.

The engine keeps the tokens and the person’s claims in their own cookies:

  • The cookies are encrypted with a key made from secret_key_base, and are HttpOnly and SameSite=Lax. Over https their name starts with __Host-.
  • A large session, such as one with a large access token, is split across up to eight cookies.
  • The Rails session holds only a random value that ties the cookies to it. When the app calls reset_session, the person is signed out of the app as well.
Method
masked! Sends a signed-out visitor to masks_login_url and stops the request. See privileges for more.
masked The signed-in person and what they hold, described below. Also a view helper.
masks_disconnect! Removes the connection. With the default store, it deletes config/masks.json. With a custom config.store, it calls config.forget, and returns false if config.forget is not set.

masked tells you everything about the sign-in:

signed_in? Whether there is a sign-in and its token has not expired.
subject, name, nickname, email, email_verified? Who signed in.
picture, avatars picture is the picture claim, then the photo, then the identicon. avatars holds each avatar URL.
tenant The tenant’s uuid, subdomain, and name.
organization, organizations, role?("owner") See organizations.
scopes, permits?("catalog:read") The scopes the token holds.
privileges, privilege?(:admin) See privileges.
access_token The token to send to a resource server.
masked["groups"] Any other claim.
to_h What GET /auth/session returns as JSON, for a single-page app.

To sign out, send DELETE /auth/logout. This revokes the refresh token and clears the session.

  • With config.sign_out_of_issuer = true, or everywhere in the request, the browser goes on to masks to end its session there. masks sends it back to /auth/logout/return, and the app sends it on to after_sign_out.
  • A request for JSON gets the masks address as logout_url.
  • A sign-out of any method is refused with 403 when its Sec-Fetch-Site header is anything other than same-origin or none, or its Origin header names another origin. A POST or DELETE that sends neither header is refused the same way.
  • A GET sign-out signs out at once when its Sec-Fetch-Site header is same-origin or none, or its Origin header names the app. A GET with neither header, as older browsers send, does not sign out. A browser gets a page with a Sign out button that posts to /auth/logout with the app’s authenticity token and keeps everywhere. A JSON request gets 403. So a link on another site cannot sign anybody out.

Masks::Rails lists every method and setting.

When masks ends a session itself, it sends a logout token to /auth/logout/backchannel. The handshake registers that address when the issuer says it sends logout tokens. The engine checks the token, then signs out the session it names, or every session of the person it names. The sign-out takes effect at that session’s next request.

  • A logout token must carry exp. Each one is accepted once.
  • The engine remembers each logout in config.cache, so it reaches every process that shares the cache.
  • config.logged_out hears each logout as well. It is a callable that takes a Masks::Client::Logout, or the request and the logout.

The engine keeps some things in config.cache:

  • the result of each token refresh, so requests that arrive together refresh once
  • the logouts masks sent, so a session ends in every process
  • the logout tokens and DPoP proofs already used

config.cache is Rails.cache by default. When Rails.cache is a :null_store, which keeps nothing, the engine uses its own memory in each process.

An app that runs as several processes, such as Puma with more than one worker, needs a cache they all share. Without one, two processes can refresh the same token at once. masks then treats the second refresh as a stolen token and revokes the tokens from both, so the person is signed out. :solid_cache_store, :redis_cache_store, and :mem_cache_store are shared. To use another cache than Rails.cache, set it:

Masks::Rails.configure do |config|
config.cache = ActiveSupport::Cache::RedisCacheStore.new(url: ENV["REDIS_URL"])
end

The cache holds no tokens anyone can read. Each key is a hash, and each refresh result is sealed with a key made from the old refresh token.

When the engine sees that the cache cannot be reached, it does not refresh tokens, and it answers 503 to a logout token, a DPoP proof, or a session it cannot check for a logout.

Rails.cache hides most errors. A failed read looks like an empty cache, so a logout check passes while the cache is down. To let the engine see every error, give the cache an error_handler that raises. :redis_cache_store and :solid_cache_store both take one:

config.cache = ActiveSupport::Cache::RedisCacheStore.new(
url: ENV["REDIS_URL"],
error_handler: ->(exception:, **) { raise exception }
)

When an app asks for the organization scope, a person signs in as a member of one organization. You can name the organization in two ways:

  • For every sign-in, with config.organization.
  • For one sign-in, with /auth?organization=acme.
Masks::Rails.configure do |config|
config.scope = %w[openid profile email offline_access organization]
config.organization = ->(request) { request.subdomain }
end
Method
masked.organization The organization signed in to, with its id, key, name, and role. nil if there is none.
masked.role?("owner", "billing") Whether the person holds one of those roles in it.
masked.organizations Every organization the person has joined. Each one includes the role held there.
masks_login_url(organization: "globex") Signs the person in again, naming another organization.

/auth/session returns the same information as organization and organizations.

The engine reads the organizations from userinfo at sign-in and at every refresh. Userinfo is the masks endpoint that describes the signed-in person. So when a person’s role changes, the app sees the change within the lifetime of one access token.

To let a person switch organizations, link each one to a new sign-in. A person who already belongs to that organization is not asked for anything more:

<% masked.organizations.each do |held| %>
<%= link_to held.name, masks_login_url(organization: held.key, return_to: request.path) %>
<% end %>

A privilege that names a role refuses a request with 403 in two cases:

  • The person signed in to no organization. The error is insufficient_organization.
  • The person holds another role. The error is insufficient_role.

A privilege is a name for what an action needs. It can ask for:

  • scopes the person holds in masks
  • a role in the organization they signed in to
  • both
Masks::Rails.configure do |config|
config.scope = %w[openid profile email offline_access organization catalog:read]
config.privileges = {
admin: %w[catalog:admin],
billing: { role: %w[owner billing] },
acme_admin: { scope: %w[catalog:admin], role: "owner", organization: "acme" }
}
end
  • A list is a short way to write { scope: [...] }.
  • role takes one role or several. Any one of them is enough.
  • organization limits the privilege to one organization, named by key or id.

masked! guards a controller. With no privilege, it needs only a sign-in:

class SettingsController < ApplicationController
masked!
masked! :admin, only: %i[create update destroy]
end
The sign-in holds the privilege The action runs.
A scope is missing The browser goes through masks once. It asks for the usual scopes and the privilege’s scopes, then comes back to the page it was on. A person already signed in to masks sees a consent screen at most. A JSON request gets 403 with privilege_required, the privileges, and the login_url to send the browser to.
masks did not grant the scope on that trip 403 insufficient_scope. The person does not hold the scope.
A role or organization does not match 403 insufficient_role or insufficient_organization. The browser does not go through masks.

An ordinary sign-in never asks for privilege scopes. Asking for them never gives anyone more access:

  • masks puts a scope in the token only for a person who already holds it.
  • A manager grants scopes in /manage.

The handshake registers the scopes of every privilege, so the issuer lets the app ask for them.

Method
masked!(*privileges, only:, except:) Guards a controller.
authorize_masks!(*privileges) The same check inside an action.
masked.privilege?(:admin) Whether the sign-in holds a privilege. Use it to show or hide a control.
masked.privileges Every privilege the sign-in holds. /auth/session returns it as privileges.
masks_login_url(privilege: :admin) Signs the person in again and asks for a privilege, the same as /auth?privilege=admin.

A name that config.privileges does not define raises ArgumentError in the app. In a URL, the engine ignores it.

A resource server is an app that accepts access tokens from other apps. If your app is also a resource server, it checks access tokens with Masks::Rails::ProtectedResource.

  • config.resource is the audience that tokens must name. The audience is the app a token is meant for.
  • config.resource_scopes lists the scopes your app accepts.
Masks::Rails.configure do |config|
config.privileges = { read: %w[catalog:read], write: %w[catalog:write] }
end
class ApiController < ActionController::Base
include Masks::Rails::ProtectedResource
masked! :read, except: :metadata
def show
render json: { subject: masked.subject }
end
end

masked! takes the same privileges as a controller that signs browsers in, including roles and organizations. It checks them against the bearer token, which is the token sent in the request’s Authorization header.

  • A token that lacks a privilege is refused with 403 and insufficient_scope, insufficient_role, or insufficient_organization.
  • A token cannot go through masks again, so there is no second trip.

A controller that includes both Authentication and ProtectedResource accepts both kinds of request:

  • A request with an Authorization header is checked as a token.
  • A request with no masks session in the browser is also checked as a token.
  • A request from a signed-in browser is checked against its session.

In each case, masked describes whoever sent the request.

A refusal carries an RFC 6750 challenge. Its resource_metadata points at /.well-known/oauth-protected-resource. The engine does not route that path. To serve it:

  1. Route the path to the controller above:

    get "/.well-known/oauth-protected-resource", to: "api#metadata"
  2. Return masks_resource_metadata from that action:

    def metadata
    render json: masks_resource_metadata
    end

A token can be bound to a key with DPoP. DPoP lets only the holder of a private key use the token. A bound token has a cnf.jkt claim.

The engine accepts a bound token only as Authorization: DPoP, with a DPoP proof that:

  • is signed by that key
  • names this request’s method, URL, and token
  • was made in the last 60 seconds, with 30 seconds of leeway for clock differences
  • has not been seen before

A bound token sent as Bearer is refused.

The engine remembers the proofs it has seen in config.cache.

Outside Rails, Masks::Client does the same without the engine.