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.
Client mode
Section titled “Client mode”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.
-
Add the gem to your Gemfile:
gem "masks" -
Run the install generator:
Terminal window bin/rails generate masks:install --resource https://app.example.comThe generator mounts the engine at
/auth, or at the path you give with--mount. It writesconfig/initializers/masks.rband addsconfig/masks.jsonto.gitignore. Leave out--resourcewhen 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 -
Set
MASKS_ISSUERto the tenant you sign in against, such ashttps://acme.auth.example.com. -
Start the app.
-
Open
/auth/handshake.
The handshake
Section titled “The handshake”The handshake connects your app to the masks server:
- The handshake sends the browser to the masks server’s approval screen.
- You approve the app there.
- 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 = :adminconfig.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.
Signing in
Section titled “Signing in”Include Masks::Rails::Authentication in a controller and call masked!:
class ApplicationController < ActionController::Base include Masks::Rails::Authentication
masked!endTo 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 areHttpOnlyandSameSite=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. |
Signing out
Section titled “Signing out”To sign out, send DELETE /auth/logout. This revokes the refresh token and clears the session.
- With
config.sign_out_of_issuer = true, oreverywherein 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 toafter_sign_out. - A request for JSON gets the masks address as
logout_url. - A sign-out of any method is refused with
403when itsSec-Fetch-Siteheader is anything other thansame-originornone, or itsOriginheader names another origin. APOSTorDELETEthat sends neither header is refused the same way. - A
GETsign-out signs out at once when itsSec-Fetch-Siteheader issame-originornone, or itsOriginheader names the app. AGETwith neither header, as older browsers send, does not sign out. A browser gets a page with a Sign out button that posts to/auth/logoutwith the app’s authenticity token and keepseverywhere. A JSON request gets403. So a link on another site cannot sign anybody out.
Masks::Rails lists every method and setting.
Back-channel logout
Section titled “Back-channel logout”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_outhears each logout as well. It is a callable that takes aMasks::Client::Logout, or the request and the logout.
Running several processes
Section titled “Running several processes”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"])endThe 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 })Organizations
Section titled “Organizations”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.
Privileges
Section titled “Privileges”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: [...] }. roletakes one role or several. Any one of them is enough.organizationlimits 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.
Accepting tokens
Section titled “Accepting tokens”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.resourceis the audience that tokens must name. The audience is the app a token is meant for.config.resource_scopeslists 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 } endendmasked! 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
403andinsufficient_scope,insufficient_role, orinsufficient_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
Authorizationheader 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:
-
Route the path to the controller above:
get "/.well-known/oauth-protected-resource", to: "api#metadata" -
Return
masks_resource_metadatafrom that action:def metadatarender json: masks_resource_metadataend
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.