Self-hosting
masks comes as a container image, ghcr.io/masksrb/masks. It runs on its own, or with a Postgres
server of yours. It migrates its databases each time it boots.
One container
Section titled “One container”docker run --name masks -p 3000:3000 -v masks:/rails/storage ghcr.io/masksrb/masks- Run the command.
- Find the setup token in the output. It is on a line like
masks: masks is not set up. Its setup token is 7Hq2…. - Open
http://localhost:3000and follow the Set up screen.
The container runs its own Postgres. Its data and the master key live in the
masks volume, so the container can be removed and started again without losing anything.
masks answers plain HTTP only at localhost. To reach it from other computers, put a proxy that
serves HTTPS in front of it. This Compose file runs masks with Caddy, which gets the certificate:
services: masks: image: ghcr.io/masksrb/masks:0.12.0 volumes: - masks:/rails/storage logging: options: max-size: 10m max-file: "3"
caddy: image: caddy:2-alpine command: caddy reverse-proxy --from auth.example.com --to masks:3000 ports: - "443:443" - "80:80" volumes: - caddy:/data
volumes: masks: caddy:Open https://auth.example.com first. masks keeps the address the Set up screen was opened at.
See the public address.
What it runs
Section titled “What it runs”The image runs Puma, the web server, in front of Rails, on port 3000. It needs one Postgres server,
which holds three databases named from POSTGRES_DATABASE:
- the primary
- a cache
- a job queue
When POSTGRES_HOST is unset, the image runs Postgres 17 inside the container. It listens only on a
socket inside the container, and its files are in /rails/storage/postgres. When the server stops,
Postgres stops too.
- Background jobs, such as mail and retries, run in the web process by default. To move them to a
second container that runs
bin/jobs, setMASKS_JOBS_IN_WEB_SERVER=false. That needs a Postgres server of your own. - The job queue stays bounded. A daily prune removes finished jobs after 7 days and failed jobs
after 30 days.
MASKS_FINISHED_JOB_RETENTIONandMASKS_FAILED_JOB_RETENTIONchange those times, in seconds. A failed job is in/up/jobsand the logs until then. - The web process also serves LDAP for apps that sign people in only over LDAP.
CI times a first sign-in on every push. It starts the image with the command above, waits for /up,
then creates the first manager and signs in. The seconds for each step are in the build job’s
summary on GitHub Actions. ./dev first-sign-in runs the same check on your computer against any
image, and fails when the whole thing takes longer than 120 seconds.
Image tags
Section titled “Image tags”| Tag | Pushed on | Platforms |
|---|---|---|
:<version>, such as :0.12.0 |
A server release. | amd64, arm64 |
:latest |
A server release. Moved to that release’s version. | amd64, arm64 |
:main |
Every push to main. | amd64, and arm64 too on a server release |
:sha-<commit> |
Every push to main, named by the full commit hash. | amd64, and arm64 too on a server release |
Pin a version, as the examples do. Read CHANGELOG.md before you move to a new one.
Your own Postgres
Section titled “Your own Postgres”This Compose file runs masks with a Postgres server of its own and Caddy in front.
services: masks: image: ghcr.io/masksrb/masks:0.12.0 environment: POSTGRES_HOST: postgres POSTGRES_ADMIN_PASSWORD: ... POSTGRES_DATABASE: masks volumes: - masks:/rails/storage depends_on: - postgres logging: options: max-size: 10m max-file: "3"
postgres: image: postgres:17-alpine environment: POSTGRES_PASSWORD: ... volumes: - postgres:/var/lib/postgresql/data
caddy: image: caddy:2-alpine command: caddy reverse-proxy --from auth.example.com --to masks:3000 ports: - "443:443" - "80:80" volumes: - caddy:/data
volumes: masks: postgres: caddy:POSTGRES_ADMIN_PASSWORDis the password of thepostgressuperuser. The entrypoint uses it to create the two database roles masks connects as, and to set their passwords. UsePOSTGRES_ADMIN_USERfor another role that can create roles.- To create the roles yourself, leave
POSTGRES_ADMIN_PASSWORDunset and setPOSTGRES_USER,POSTGRES_PASSWORD,MASKS_MIGRATION_USER, andMASKS_MIGRATION_PASSWORD. - The
loggingoptions cap the masks container’s log, so a repeating fault cannot fill the disk. - Every variable the server reads is in ENV vars.
The public address
Section titled “The public address”The public address, or origin, is the scheme and host that apps and browsers use to reach masks. It is the issuer, and every link in an email starts with it.
Without MASKS_PUBLIC_ORIGIN_TEMPLATE, masks learns the address from the Set up screen:
- Before setup, masks answers at any address.
- When the first account is created, masks keeps the address the screen was opened at.
- After that, masks answers only there and at the tenant’s custom domains. Any other address gets a 404 that names the kept address.
To move masks to a new address, set MASKS_PUBLIC_ORIGIN_TEMPLATE to it, such as
https://id.example.com. The template wins over the kept address. To serve many tenants, each at
its own subdomain, use a template with %{subdomain}. See tenants.
Health checks
Section titled “Health checks”A health check is a request that a container runtime or a monitor makes again and again to see if a service works. masks answers two.
| Path | Answers |
|---|---|
/up |
up while the server can reach its database, job queue, and cache, a worker has reported in the last 5 minutes, and no job has waited more than 10 minutes to start. Otherwise a 503 that starts with down and says which of those is wrong. MASKS_WORKER_SILENCE and MASKS_QUEUE_WAIT set the two times. |
/up/jobs |
up while no background job has failed in the last day. Otherwise a 503 that names the job classes that failed, and the tenants each one failed for on its last run. |
- The image carries its own
HEALTHCHECKon/up, so a container runtime such as Docker or Podman marks the container unhealthy when its worker stops. The example sets the same check for runtimes that read the Compose file instead. - Point a monitor at
/up/jobs. Leave it out of the container’s health check, because restarting the server does not fix a failing job. - A job that fails for one tenant carries on with the rest, records a
job.failedevent in the tenant it failed for, and is named by/up/jobswith that tenant. - The errors themselves are in the logs.
- When a health check in the panel below is failing,
/upadds a second line that names it, such asfailing checks: mail (demo). The status code does not change.
The health panel
Section titled “The health panel”The overview in /manage has a Health panel. A job runs every check every 10 minutes and the
panel shows each result as a sentence, with what to do when something is wrong. Check now runs
them again.
| Check | Looks at |
|---|---|
| Background jobs | Whether a kind of job failed in the last day. |
| Worker | Whether a worker has reported within MASKS_WORKER_SILENCE. |
| Queue | Whether a job has waited longer than MASKS_QUEUE_WAIT to start. |
| LDAP | Whether the directory answers without TLS to the network. See LDAP. |
| Metrics | Whether MASKS_METRICS_TOKEN is set and at least 24 characters long. |
Whether the tenant’s SMTP server, or the one in MASKS_SMTP_ADDRESS, answers a connection. No mail is sent. |
|
| Public address | Whether requests reach this tenant at its public address. A proxy that drops X-Forwarded-Proto shows up here. |
| Domains | Whether every claimed domain still has its TXT record. |
| Signing keys | Whether the active key is older than the tenant’s rotation period, missing, or left to rotate by hand. |
| Reverse proxy | Whether forwarded headers came from an address outside MASKS_TRUSTED_PROXIES, whether a trusted proxy forwards plain HTTP, and whether every event in the last hour came from one private address. |
The first five are about the server and show the same result in every tenant. The rest are about
the tenant. A check that turns failing records a health.failing event, and health.recovered when
it is fine again.
A new release
Section titled “A new release”Set MASKS_RELEASE_CHECK to true and masks reads the list of releases from GitHub once a day. When
a newer server release is out, the overview says so and links to its notes. The request carries this
server’s version and nothing else, and nothing is sent without the variable.
A release whose notes have a line that starts with Operator: needs a step from you before or
after the upgrade. The overview says so, and the release.available event carries the flag.
Database roles
Section titled “Database roles”masks keeps tenants apart with row-level security in Postgres. Row-level security is a rule on each table that limits which rows a role can see. Two kinds of role can get around it:
- A superuser, or a role with
BYPASSRLS, skips it. - The role that owns a table can switch it off with one
ALTER TABLE.
So masks connects as two roles.
| Role | Variable | Holds |
|---|---|---|
masks_owner |
MASKS_MIGRATION_USER |
The databases and every table in them. CREATEDB, and nothing else. |
masks |
POSTGRES_USER |
SELECT, INSERT, UPDATE, and DELETE on the tables, and the sequences behind them. |
On every boot, the image’s entrypoint:
- Creates both roles, and sets their passwords, when it runs its own Postgres or holds
POSTGRES_ADMIN_PASSWORD. Their passwords are derived from the master key. - Runs
db:prepareandmasks:grantsas the migration role. - Runs
masks:tenants, which creates the declared tenants and prints the setup token of each one that is not set up yet. - Starts the server as the serving role.
Two checks stop a server that is set up wrong:
- The entrypoint refuses to start when
MASKS_MIGRATION_USERis unset or names the serving role. - The server refuses to answer a request while its role is a superuser, has
BYPASSRLS, or owns a table that row-level security protects.
Connection poolers
Section titled “Connection poolers”masks names the tenant on its Postgres connection with set_config, and row-level security reads
that name on every query. A pooler such as PgBouncer or PgCat keeps the name only in session mode,
where one client holds one server connection for as long as it is connected. In transaction mode,
each transaction may run on a different server connection, so the tenant named on one is missing
from the next, and a query would see no rows, or another tenant’s rows.
The first time it enters a tenant, masks checks which mode it is in. It names a value on one connection, uses another connection, and reads the value back. When the value is gone, masks refuses to go on, with an error that begins “this server reaches Postgres through a pooler”. Connect masks to Postgres directly, or run the pooler in session mode.
Inside a transaction, masks names the tenant for that transaction only, so work you wrap in one transaction is safe behind any pooler. A request is not one transaction, so this does not make transaction mode safe.
Encryption and secrets
Section titled “Encryption and secrets”For each tenant, the database holds accounts, sign-in factors, clients, tokens, signing keys, and activity.
Columns that hold secrets are also encrypted with Active Record Encryption (AES-256-GCM). To read them, someone needs the encryption keys as well as the database. These columns include:
- signing keys
- authenticator app secrets
- provider credentials and sending service credentials
- connected accounts’ tokens
- event stream secrets
The master key
Section titled “The master key”On first boot, the image’s entrypoint generates a master key and writes it to
/rails/storage/master.key. On every boot, it derives four secrets from that key:
SECRET_KEY_BASEsigns the session cookie. Anyone holding it can forge one.ENCRYPTION_PRIMARY_KEY,ENCRYPTION_DETERMINISTIC_KEY, andENCRYPTION_KEY_DERIVATION_SALTmake the keys for the encrypted columns.
What to know about the master key:
- Keep its path on a volume, as the examples do.
- A secret set as an environment variable takes precedence over the derived one.
- To keep the key elsewhere, use
MASKS_MASTER_KEYorMASKS_MASTER_KEY_FILE. See ENV vars.
Each tenant’s encrypted columns use a key made from the master key and that tenant’s own ID, so nothing else needs backing up. See tenant isolation.
Running more than one replica
Section titled “Running more than one replica”A replica is one of several copies of the server that share a database. Every replica needs the same master key. Do one of these:
- Set
MASKS_MASTER_KEYon each replica. - Mount one file at
MASKS_MASTER_KEY_FILEon all of them.
A replica that generates its own key cannot read the database’s encrypted columns. It refuses to start, with an error that says so. The same check stops a server whose database was restored with a different key.
The tasks a server runs at boot, such as applying MASKS_CONFIG, running MASKS_RECOVER, and
re-encrypting after a key change, run once when several replicas start together. The first replica
takes a database lock and does the task. The others wait for it, see it was done, and skip it. Each
replica’s log says which one did the task, so a recovery link is printed by one replica only. The
record lasts 10 minutes, so a replica that starts later runs the task again.
Rotating the master key
Section titled “Rotating the master key”- Set
MASKS_PREVIOUS_MASTER_KEYto the key in use now. - Put the new key in
MASKS_MASTER_KEYor its file, and restart. At boot, masks re-encrypts every encrypted column with keys derived from the new one and prints that it is done. - Remove
MASKS_PREVIOUS_MASTER_KEYand restart again.
A new SECRET_KEY_BASE comes with the new key, so everyone signs in again after the restart.
Metrics
Section titled “Metrics”masks can report figures to Prometheus, a tool that collects numbers from services over time.
-
Set
MASKS_METRICS_TOKEN. -
Point Prometheus at
/metrics, with that token as a bearer token:scrape_configs:- job_name: masksauthorization:credentials: the-value-of-MASKS_METRICS_TOKENstatic_configs:- targets: [masks:3000]
Without the variable, /metrics answers 404. It answers 30 requests from each IP address each
minute.
The gauges count from the database on each scrape, so their figures agree across replicas.
| Metric | Counts |
|---|---|
masks_tenants |
The tenants this server serves. |
masks_actors |
The tenant’s accounts. |
masks_sessions_live |
The tenant’s sessions that have not ended. |
masks_sign_ins_last_hour |
The tenant’s sign-ins in the last hour. |
masks_sign_ins_refused_last_hour |
The tenant’s refused sign-ins in the last hour. |
masks_access_tokens_last_hour |
The tenant’s access tokens issued in the last hour. |
masks_jobs_failed_last_day |
The kinds of background job that failed in the last day. |
masks_jobs_waiting |
The background jobs ready to run and not yet picked up. |
The metrics that count something in a tenant carry a tenant label with its subdomain.
Two more metrics time the requests the process answered since it started. Each replica reports its own figures, so scrape every replica.
| Metric | Reports |
|---|---|
masks_request_seconds |
A histogram of how long each request took, from 5 milliseconds to 10 seconds, by route. |
masks_requests_total |
The requests answered, by route and by status class: 2xx, 3xx, 4xx, or 5xx. |
The route label is authorize, token, userinfo, login, manage, discovery, or other.
authorize covers /authorize, /par, and /device_authorization. login covers /login and
/logout. discovery covers the .well-known documents and the key set. manage covers the
console and its API. Scrapes of /metrics and /up are not counted.
Backups, restores, and upgrades
Section titled “Backups, restores, and upgrades”Back up the primary database and the master key together.
- The primary holds every tenant’s accounts, clients, signing keys, and activity.
- The cache and queue databases hold rate limits, replay records, and pending jobs. They can be recreated empty.
Back up
Section titled “Back up”In one container, dump the primary database from inside it:
docker exec masks pg_dump --host=/rails/tmp/postgres --format=custom masks_production > masks.dumpWith your own Postgres:
-
Dump the primary database as a Postgres superuser. Row-level security stops every other role from reading all the rows, and the dump fails.
Terminal window pg_dump --username=postgres --format=custom --file=masks.dump masks -
Keep
master.key, or the value ofMASKS_MASTER_KEY, beside the dump.
A dump restored without its key cannot be read, and the server refuses to start.
Restore
Section titled “Restore”Restore as the migration role, so the migration role owns every table again.
-
Stop the server.
-
Create the database as the migration role, and load the dump as it:
Terminal window createdb --username=masks_owner maskspg_restore --username=masks_owner --dbname=masks --no-owner masks.dump -
Start the server with the same master key.
In one container, load the dump into the running container, then restart it:
docker exec -i masks pg_restore --host=/rails/tmp/postgres --dbname=masks_production \ --clean --if-exists --no-owner --role=masks_owner < masks.dumpdocker restart masksIts first boot creates the cache and queue databases and grants the serving role what it needs. Everyone keeps their passkeys and second factors. Sessions that were live at the time of the dump work again.
Upgrade
Section titled “Upgrade”- Take a backup. Migrations do not run backwards.
- Read the release notes for anything that needs a step of your own. A line that starts with
Operator:is one, and the health panel can tell you about it. - Change the image tag and restart.
Each boot runs the migrations that have not run yet, so you can skip versions.
With more than one replica:
- Start one replica on the new image.
- Wait for
/up. - Replace the rest.
Tenants
Section titled “Tenants”A tenant is a separate set of accounts, clients, and signing keys at its own subdomain. The
examples serve one tenant, masks. The image declares it when nothing else does.
To serve more tenants:
- Set
MASKS_PUBLIC_ORIGIN_TEMPLATEto a template with%{subdomain}, such ashttps://%{subdomain}.auth.example.com. - Name each tenant in
MASKS_TENANTS, such asacme,demo. WithMASKS_TENANTSunset, masks creates a tenant for each new subdomain that a request arrives at. - Point each host at the proxy. A wildcard host such as
*.auth.example.comneeds a DNS challenge, and a Caddy build with your DNS provider’s module.
See declaring tenants for each mode, and setting a tenant up for the setup token.
Custom domains
Section titled “Custom domains”A tenant can also serve sign-in from a host of its own, such as login.example.com.
- In
/manage, open Settings, then the General tab, then Domains. - Claim
example.com, and publish the TXT record it shows. masks checks the record every hour. - Point
login.example.comat the server with a CNAME or an address record. - Under Serve sign-in at, enter the host and choose Serve. Only an owner can do this, and the host must be within a domain the tenant has proven.
What happens next:
- The tenant answers at both its usual address and the host.
- Each is a separate issuer, so an app names the one it uses.
- A passkey works only on the address it was made on.
- When the proof lapses or the domain is released, masks stops serving the host.
Certificates on demand
Section titled “Certificates on demand”Caddy can issue each custom host a certificate on demand. Before it issues one, it asks
/tls/allowed?domain=. That path answers 200 only for a custom host that a tenant serves.
- Set
MASKS_ON_DEMAND_TLS=trueon the server. The path is closed until you do. - Point Caddy’s
askat the server’s own address:
{ on_demand_tls { ask http://masks:3000/tls/allowed }}
auth.example.com { reverse_proxy masks:3000}
https:// { tls { on_demand } reverse_proxy masks:3000}Declaring apps in a file
Section titled “Declaring apps in a file”When a server’s apps and groups live in a file, a rebuilt server comes back the same way. Mount the
file into the container and set MASKS_CONFIG to its path. Every boot applies it.
name: Homeaccent_color: "#3355aa"password_reset_lifetime: 3600
groups: admins: name: Admins members: [ada]
apps: grafana: preset: grafana url: https://grafana.example.com client_secret_env: GRAFANA_CLIENT_SECRET allowed_groups: [admins] dash: preset: proxy url: https://dash.example.com wiki: redirect_uris: [https://wiki.example.com/oauth/callback] scopes: [openid, profile, email, groups] refresh_token_lifetime: 604800name, accent_color |
The tenant’s name and color, as under Branding in /manage. |
invitation_lifetime, organization_invitation_lifetime, password_reset_lifetime, email_verification_lifetime |
Seconds each emailed link stays valid, as under Links in /manage. |
| An app’s key | Its client_id, unless client_id names another. The app’s own settings never have to change. |
preset, url, slug |
A known product, as Add client registers it. |
redirect_uris, scopes |
An app no preset covers. With neither scopes nor a preset, the app gets openid profile email. |
name under an app |
The app’s name. Without it, masks uses the preset’s name or the app’s key. |
client_secret_env |
The variable that holds the app’s secret. Without it, masks makes a secret the first time and prints it to the logs once. |
allowed_groups, access_token_lifetime, refresh_token_lifetime, refresh_token_absolute_lifetime |
As on a client’s Access and General tabs in /manage. Lifetimes are in seconds. |
groups |
Each group’s name, and the nicknames or emails of its members. A member must already have an account. |
limits |
Each rate limit by name, and its count. Applies to the whole server, so it sits at the top of the file, beside tenants:. |
- An app in the file is approved, and actors are not asked to consent to it.
- Applying the file adds and updates. It never removes an app, a group, or a member the file no longer names.
- A server with several tenants nests each one under
tenants:by subdomain. - A mistake stops the boot with an error that names the app or group it is in.
Getting back into a locked account
Section titled “Getting back into a locked account”Use this when nobody can sign in to reset an account. For example, the only manager lost their phone and backup codes.
-
Name the account in
MASKS_RECOVER:environment:MASKS_RECOVER: masks/owner -
Restart the server. At boot, masks removes that account’s authenticator app, backup codes, passkeys, and sign-in codes. It signs the account out everywhere and prints a link to the logs:
masks: masks: owner has no second factors now and every session is signed out. This link sets a new password once: https://auth.example.com/reset/... -
Open the link and choose a password.
-
Sign in and set up a new second factor. masks requires one of every manager.
-
Remove
MASKS_RECOVERand restart again. Every boot repeats the recovery while it is set.
Both the new password and the new second factor appear in the account’s activity.
Without a tenant prefix, such as owner alone, masks finds the account in every tenant that has one
by that nickname or email.
System requirements
Section titled “System requirements”masks has no fixed CPU or memory minimum. RAILS_MAX_THREADS sizes Puma’s threads, and
JOB_CONCURRENCY sizes the background job workers. Raise either one if requests or jobs queue up.
See processes.
Next steps
Section titled “Next steps”-
Read the tenant’s setup token in the server’s logs, open the tenant’s address, and create the first account. See setting a tenant up.
-
Fetch the tenant’s discovery document:
Terminal window curl https://auth.example.com/.well-known/openid-configurationIt confirms the tenant’s issuer, keys, and public origin.