Auth with your identity provider

Sign-in stays with a provider you already use. fennec-server checks the token it hands out, and a policy file decides, row by row and field by field, what that person may read and write.

A backend platform bundles three things: sign-in, rules about who may touch which rows, and a database. fennecdb is the last two. The provider (Clerk, Auth0, Supabase Auth, Amazon Cognito, Firebase, Cloudflare Access) signs a user in and issues a JSON Web Token. The app, or the browser, sends it to fennec-server as Authorization: Bearer. The server checks the signature against the provider's public keys, takes only the tokens made for your application (the issuer and audience it is given), and holds every statement the token sends to the policy.

Tell the server the issuer and the audience. A provider's keys sign far more than tokens for your database, and a server told neither takes every token they sign, from every other application the provider hosts. What the server checks, and what it does not says what it takes of a token; Holding a token to your application gives each provider's flags, and Rules that name a claim's value the rest. Each is run below, on a stand-in provider that signs tokens of the shapes the providers' documentation describes.

Try it with nothing to sign up for

Make a secret, start a server that takes tokens signed with it, and mint some. --mint-token prints a token for the claims it is given, signed with the secret (or the first oct key of a keys file) and good for an hour unless the claims say otherwise.

head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' > jwt.secret

fennec-server --file app.fennec --http 127.0.0.1:8080 --http-token "$ROOT" \
    --jwt-secret-file jwt.secret --policy policy.txt

fennec-server --jwt-secret-file jwt.secret --mint-token '{"sub":"alice"}'
fennec-server --jwt-secret-file jwt.secret --mint-token '{"sub":"carol","role":"admin"}'

The policy is one line a rule. It holds per-user rows, an admin role, fields that only their owner reads, and an audit trail nobody edits:

policy.txt
# collection  access                      rows                           role

# Per-user rows: a person reads and writes their own notes.
notes         read,write                  where owner = $jwt.sub

# An admin also reads every note, and changes none. `role` is a claim of the
# token (a text, or a list holding the role).
notes         read                                                       for admin

# Field read rules: every profile's name is public, the rest is its owner's.
profiles      read(name)
profiles      read,update(name, phone)    where owner = $jwt.sub

# An audit trail a person adds lines about themselves to, and nobody edits.
audit         read,insert                 where actor = $jwt.sub
audit         read                                                       for admin
audit         append-only

What the server answered alice, bob, an admin and a token that has lapsed, statement by statement. sh examples/recipes/auth.sh runs it from a clone, with a fennec-server built by cargo build -p fennec-server (or any binary, as FENNEC_SERVER=), and it needs Node, curl and jq; it also creates the collections of schema.fennecql. The scripts are in examples/recipes, and make recipes-test holds this page's outputs to what they print:

alice writes a note                        {"affected":1} [200]
alice writes a note as bob                 {"error":"the document is outside what this token may write to `notes`"} [403]
bob writes a note                          {"affected":1} [200]
alice reads notes                          [{"owner":"alice","title":"buy oat milk"}] [200]
bob reads notes                            [{"owner":"bob","title":"call the dentist"}] [200]
the admin reads notes                      [{"owner":"alice","title":"buy oat milk"},{"owner":"bob","title":"call the dentist"}] [200]
the admin deletes a note                   {"affected":0} [200]
everyone reads profiles                    [{"id":1,"owner":null,"name":"Alice","email":null,"phone":null},{"id":2,"owner":"bob","name":"Bob","email":"[email protected]","phone":"222"}] [200]
bob renames alice                          {"affected":0} [200]
bob changes his email                      {"error":"this token may not change `email` in `profiles`"} [403]
bob changes his phone                      {"affected":1} [200]
alice adds an audit line                   {"affected":1} [200]
alice deletes it                           {"error":"`audit` is append-only: a scoped token inserts into it, and neither updates nor deletes its rows"} [403]
a token that has lapsed                    {"error":"the token has expired","code":"token_expired"} [401]
no token                                   {"error":"invalid or missing token"} [401]
  • Rows. Alice's put that leaves out owner gets her sub in it; one naming bob is refused (403), as is any row that stops matching the filter after the write.
  • An admin who only reads. Carol reads every note. Her del writes {"affected":0}, not an error: the rows she may delete are none, because for admin grants read alone.
  • Fields. profiles read(name) shows every row's name and id; the rest of a row is null unless it is the reader's own. Bob changes his phone and is refused his email, which update(name, phone) does not list.
  • An audit trail. Alice adds a line about herself and cannot take it back, by any route, whatever her rules say.
  • Tokens that do not pass. A lapsed one and none at all are 401, and the body of the first says it has expired.

GET /_whoami shows what the server took a token for, rules and all:

-- /_whoami for alice
{"node":"single","tenant":null,"read_only":false,"kind":"scoped","sub":"alice","roles":[],"tenants":null,"unbound":false,"append_only":["audit"],"calls":[],"wakes":[],"rules":[{"collection":"notes","grants":["read","insert","update","delete"],"fields":null,"read_fields":null,"rows":"owner = $jwt.sub"},{"collection":"profiles","grants":["read"],"fields":null,"read_fields":["name"],"rows":null},{"collection":"profiles","grants":["read","update"],"fields":["name","phone"],"read_fields":null,"rows":"owner = $jwt.sub"},{"collection":"audit","grants":["read","insert"],"fields":null,"read_fields":null,"rows":"actor = $jwt.sub"}]}

calls lists the named statements the token may call, and wakes the statements bound to writes its writes may wake: a policy's paid_ledger wake for customer lets a customer's payment land the ledger line its statement writes, with no rule of the customer's on the ledger. Alice is granted none of either, and a write of hers that would wake one is refused (403), nothing landed.

What the server checks, and what it does not

This is the one place that says what the server takes of a token and what it leaves to you. The issuer, the audience and the client are checked when the server is given them with a flag; given none, it takes every token its keys sign.

 What the server does
CheckedThe signature: RS256 against an RSA key of 2048 to 8192 bits, ES256 against an EC key on P-256, HS256 against an oct key of at least 32 bytes. A key is used for its own algorithm alone, so a provider's public RSA key is never taken as an HMAC secret.
kid: a token that names one is checked against that key and no other. One that names none is tried against every key of its algorithm.
exp, which a token must have (401 otherwise; --jwt-require-exp off takes tokens without); --jwt-max-age <s> also refuses an exp further ahead than that. nbf too.
Checked when toldiss against --jwt-issuer, aud against --jwt-audience, and azp (or, where a token has none, client_id) against --jwt-client. Each flag is repeatable, any one of its values is taken, and each is asked of every token on every route, before a rule is read. A token refused is 401 naming the check, never the value it holds (Holding a token to your application). Given none of them the server takes any token its keys sign, which is right only where the keys are yours alone, and with --jwt-keys it says so on stderr as it starts.
Not checkedtoken_use: not read. Cognito's ID tokens and access tokens are told apart by the flags that name the client and the audience (below), or by a rule: $jwt.token_use = 'access'.
The kind of sub. RFC 7519 makes it a string, and only a string that is not empty names the token's subject. A token whose sub is a number, a bool, a list or an object is taken, and names none: an Idempotency-Key sent with it is refused (400, the token's `sub` claim must be a string (RFC 7519)), --request-rate and --call-rate count it with every token of its issuer that names no subject, and /_whoami answers "sub": null. Mint a numeric id as its decimal text: "sub": "42".
Revocation. A token is good until its exp (Expiry).
Not supportedA keys URL. --jwt-keys takes a path, read again when the file changes (Keys).
EdDSA, PS256, ES384, ES512, RS384 and RS512. Such a token is 401, only HS256, RS256 and ES256 tokens are accepted. Keys of any other kind in a JWKS (OKP, an EC key on P-384 or P-521) are skipped, and a file with no RSA, P-256 EC or oct key is refused at the start.
A claim by a path. $jwt.<name> is a claim at the top of the token, and a name of more than letters, digits and _ goes in double quotes: $jwt."cognito:groups". $jwt.app_metadata.role stops the server at startup, and so does lower($jwt.email): a claim is read as the token holds it.

The server reads the token from Authorization: Bearer and from no other header. A rule's for <role> reads the claim role, a text or a list holding the role, or the claim --jwt-role-claim <name> names.

How a checked token is kept, and what a missing claim does

A rule whose filter names a claim the token lacks does not apply, so a missing claim narrows what a token may do, never widens it. A claim held as null, as "", as an object, or as a list where the rule reads one value is a missing one: "sub": null is no subject, and owner = $jwt.sub does not become owner = null. A sub that is a number is no subject either, though a rule reads the claim as the token holds it: under "sub": 42, owner = $jwt.sub matches an owner stored as the number 42, and under "sub": "42" only one stored as the text. An app moving a numeric id into sub as text keeps the number in a claim of its own ($jwt.user) for the rules comparing it with a number field, or stores the field as text. A claim a rule compares by order admits only values of its own kind. A token that has been checked is kept by its text, up to 4 096 of them, and the kept ones are dropped whenever the keys change; exp and nbf are asked again on every request. A claim holding a list of more than 1 000 values is refused (401). The whole story of rules and claims is in HTTP security and scoped access.

Keys: the provider's JWKS, in a file kept fresh

Every provider publishes its public keys as a JWKS, a JSON document {"keys": [...]}. fennec-server reads one from a file. A job that fetches it every few minutes is the other half.

ProviderKeysSigns with
Clerkhttps://<Frontend API URL>/.well-known/jwks.jsonRS256
Auth0https://<your domain>/.well-known/jwks.jsonRS256 or HS256 per application; a JWKS publishes the RS256 keys
Supabase Authhttps://<project>.supabase.co/auth/v1/.well-known/jwks.jsonES256, RS256 or HS256 per signing key. An EC key on P-256 (ES256) and an RSA 2048 one are both taken; the legacy HS256 secret is not in the JWKS (below)
Amazon Cognitohttps://cognito-idp.<region>.amazonaws.com/<userPoolId>/.well-known/jwks.jsonRS256, one key pair for access tokens and another for ID tokens, both in the JWKS
Firebasehttps://www.googleapis.com/service_accounts/v1/jwk/[email protected] (a JWKS of the same keys, by kid, as the X.509 form the page names)RS256
Cloudflare Accesshttps://<team>.cloudflareaccess.com/cdn-cgi/access/certsRS256

How often a key changes, as each one's documentation says:

  • Auth0: one key signs at a time, and the endpoint may hold several during a rotation.
  • Supabase: a standby key is rotated in and the old one revoked once its tokens have expired. The edge caches the JWKS 10 minutes, and the docs say to wait at least 20 minutes after creating a standby key or revoking one.
  • Cognito: keys "might rotate"; cache by kid and refresh.
  • Firebase: the answer's Cache-Control: max-age says when to fetch again (the docs say to use it; it was about seven hours when this was written).
  • Cloudflare Access: every 6 weeks, and the previous key stays valid for 7 days.
  • Clerk: not said on the pages read.

The job below fetches the file beside the one in use and renames it over. The server looks at the file at most once a second and reads it again when its modification time has changed, so the rename is the rotation: no restart, and no half-written file to read. Replace the file by a rename, never by writing into it: a file read while it was being written does not parse, the keys read before stay, and it is read again as its time changes, or a minute later, until it does; two files written into it within the file system's time granularity can share a modification time, and the second is then read only that minute later. A file the server could not read at all — an error opening or reading it — is read again at the next look. A fetch that fails, or that returns a page with no RSA or P-256 key, leaves the file that works where it is. It takes https only, follows no redirect to anything else and takes no more than a megabyte (the stand-in provider below is plain http on localhost, which is what JWKS_PROTO='=http' is for).

refresh-jwks.sh
#!/bin/sh
# Keep the JWKS file fennec-server reads (--jwt-keys) as fresh as the provider's.
# fennec-server fetches no URL: it reads this file, and again whenever its
# modification time changes (at most once a second). Run this from cron or a
# systemd timer every few minutes.
#
#   refresh-jwks.sh https://acme.us.auth0.com/.well-known/jwks.json /etc/fennec/jwks.json [own-keys.json]
#
# The new file is written beside the old one and renamed over it, so the server
# never reads half of one, and only a file holding a key the server verifies
# with (an RSA one, or an EC one on P-256) replaces the one in use: an error
# page, an empty body or a provider that went EdDSA-only leaves the keys that
# work where they are, and the job fails for whoever watches it.
#
# A third argument is a JWKS of keys of your own -- the public halves of the
# keys your backend or Worker signs its short service tokens with -- which go
# into the file beside the provider's. Without it the file would hold only the
# provider's keys, and a service could not call the server.
#
# Only https, and no more than 1 MiB: a URL that redirects to http, or one that
# answers with a body of any size, is not a keys file. JWKS_PROTO='=http' lifts
# the first, for the stand-in provider of idp.mjs on localhost.
set -eu
url=$1
file=$2
own=${3:-}
tmp=$(mktemp "$file.XXXXXX")
trap 'rm -f "$tmp" "$tmp.merged"' EXIT
curl -fsS --proto "${JWKS_PROTO:-=https}" --proto-redir "${JWKS_PROTO:-=https}" --max-redirs 3 \
    --max-filesize 1048576 --max-time 10 "$url" -o "$tmp"
jq -e '[.keys[]? | select(.kty == "RSA" or (.kty == "EC" and .crv == "P-256"))] | length > 0' "$tmp" >/dev/null ||
    { echo "refresh-jwks: $url holds no RSA or P-256 key; $file left as it was" >&2; exit 1; }
if [ -n "$own" ]; then
    # A file of your own keys with none in it is a mistake that would drop them
    # from the server's file, and a kid on both sides is one key claiming
    # another's name: a token that names it is checked against both.
    jq -e '(.keys | type == "array") and (.keys | length > 0)' "$own" >/dev/null ||
        { echo "refresh-jwks: $own holds no key; $file left as it was" >&2; exit 1; }
    jq -s -e '([.[0].keys[].kid, .[1].keys[].kid] | map(select(. != null))) as $k | ($k | length) == ($k | unique | length)' \
        "$tmp" "$own" >/dev/null ||
        { echo "refresh-jwks: a kid is in both $url and $own; $file left as it was" >&2; exit 1; }
    jq -s '{keys: (.[0].keys + .[1].keys)}' "$tmp" "$own" >"$tmp.merged"
    mv "$tmp.merged" "$tmp"
fi
chmod 644 "$tmp"
mv "$tmp" "$file"
trap - EXIT
# crontab: every five minutes, well inside what any of them asks
*/5 * * * *  /usr/local/bin/refresh-jwks.sh https://acme.us.auth0.com/.well-known/jwks.json /etc/fennec/jwks.json /etc/fennec/service-jwks.json

fennec-server --file app.fennec --http 0.0.0.0:8080 --http-token "$ROOT" \
    --jwt-keys /etc/fennec/jwks.json --policy policy.txt \
    --jwt-issuer https://acme.us.auth0.com/ --jwt-issuer urn:fennec:services \
    --jwt-audience https://api.example.test

The two issuers are the provider's and your services' (below); the audience is the API's. Holding a token to your application has the flags of each provider.

A rotation as the server sees it, with the stand-in provider serving its JWKS over HTTP and a kid of idp-2 signing after the rotation:

-- the provider rotates: a new key signs, and the server's file has not heard
a token of the new key                     {"error":"no key has the token's kid"} [401]
-- the refresh job fetches the provider's file; no restart
the same token                             [{"title":"clerk note"}] [200]
-- a key of your own service goes into the file beside the provider's
["idp-1","idp-2","svc-1"]
the server's view of the service's token   {"kind":"scoped","sub":"files-backend"}
-- a key whose kid is the provider's, and a file of own keys with none in it, are refused
refresh-jwks: a kid is in both <provider>/.well-known/jwks.json and dup.json; jwks.json left as it was
refresh-jwks: none.json holds no key; jwks.json left as it was
-- the job asks for a page that is not there one night
curl: (22) The requested URL returned error: 404
(the job failed, rc 22)
the same token                             [{"title":"clerk note"}] [200]
-- and a file that is no JWKS, written over the keys by hand
the same token                             [{"title":"clerk note"}] [200]
jwks.json: a JWKS file is {"keys": [...]}; the keys read before stay, and the file is read again as it changes, or in a minute, until it parses
-- a provider that signs with EC keys (Supabase's ES256): its P-256 key comes with the next fetch
an ES256 token                             [{"title":"clerk note"}] [200]
an ES384 token                             {"error":"only HS256, RS256 and ES256 tokens are accepted"} [401]
  • Behind a rotation a token is 401 with no key has the token's kid until the next fetch. Cloudflare's overlap of seven days, Supabase's twenty minutes and Firebase's hours are all longer than a five-minute job.
  • A fetch that fails (the 404 above, a provider that is down) makes the job exit non-zero and touches nothing; the keys read last stay in use.
  • A file that no longer reads (written over by hand above) is logged, the keys read before stay, and the server goes on with the keys it has. A file with no usable key (here a single P-384 key, for ES384) is refused at the start: ec.json: no HS256, RS256 or ES256 key in the JWKS file.
  • ES256 is taken, ES384 is not. A key on P-256 in the file verifies ES256 tokens, which is what Supabase's EC signing keys sign, and the refresh job takes a file holding one. A token signed with ES384, or any other algorithm than the three, is 401 whatever the file holds.
  • Real files load. The JWKS Google publishes for Firebase (four RS256 keys) and the one of Auth0's public samples tenant (two) were fetched when this was written and the server started on each. The other providers' endpoints were not tried, for want of a project of one's own.
  • A token already checked is dropped from the server's memory when the keys change, so a key taken out takes its tokens with it.
  • Cloudflare Access answers with keys and, beside them, public_cert and public_certs in PEM. A file of that shape loads (tried here with a stand-in, not with Cloudflare's endpoint), and the job's filter looks at keys alone.

Tokens your own services call with

A backend or a Worker that calls fennec-server needs a token too, and the provider has none for it. --mint-token cannot make one: it signs with the first oct key of the file, and a file of a provider's RSA keys has none (an RSA key's private half is its owner's). A token minted by hand and kept would also be refused by --jwt-max-age, and by the default of --jwt-require-exp if it never expires. So the service has a key pair of its own. The public half is a JWK in a file of its own, which the refresh job's third argument puts into the keys file beside the provider's, and the private half is the service's secret, which signs a token of five minutes whenever one is wanted. The provider's JWKS never holds it, and a token naming its kid is checked against that key alone.

openssl genrsa -out svc-1.pem 2048
node idp.mjs jwk svc-1.pem svc-1 > service-jwks.json     # the public half as a JWKS, kid svc-1

refresh-jwks.sh https://acme.us.auth0.com/.well-known/jwks.json /etc/fennec/jwks.json /etc/fennec/service-jwks.json

# a Worker's secret is the same key as base64 of the PKCS#8 DER, on one line
openssl pkcs8 -topk8 -nocrypt -in svc-1.pem -outform DER | base64 | tr -d '\n'

The refresh job above ran it with a key made as shown, and the server took the service's token. The job refuses a kid that is on both sides and an own-keys file with no key in it, which would leave the server without the service's key at the next fetch:

-- a key of your own service goes into the file beside the provider's
["idp-1","idp-2","svc-1"]
the server's view of the service's token   {"kind":"scoped","sub":"files-backend"}
-- a key whose kid is the provider's, and a file of own keys with none in it, are refused
  • A service is an iss and a sub, never a role. A rule that means a service says $jwt.sub = 'files-backend' and $jwt.iss = 'urn:fennec:services' (Files and Functions use it). A sub alone is not enough: a provider assigns one, but a provider's token can say files-backend too (a Firebase project's owner picks the uid of a custom token), and a rule that asked for the sub only would take it for the service. No provider's token carries the issuer of your services. A role claim in the provider's namespace would be one the provider's settings, or a user's own attributes, might fill.
  • The server binds no key to an identity. Whoever holds a signing key the file holds, svc-1 or the provider's own, can sign any sub, iss or role a rule of the policy asks for: a Worker that leaked its key leaked every identity the policy has a rule for, not only its own. So the key is the secret: a Worker secret (wrangler secret put) or a file only its service reads, never in a repository or a .dev.vars that is committed; one key for each service, so that one can be dropped without the others. --jwt-issuer is the server's list of issuers, not a key's: it does not tie svc-1 to urn:fennec:services, and a key of the provider's could sign that issuer too. Binding a key to an issuer, so that a key signs only for its own, is a known gap and future work.
  • Rotating it: add svc-2 to service-jwks.json (the job puts both in the file), deploy the service with the new key and its kid, and once the tokens it signed with svc-1 have lapsed (five minutes) take svc-1 out of the file.
  • One form of the key to a service. The backend reads a PEM from a path (SERVICE_KEY_FILE), a Worker the PKCS#8 DER as base64 (SERVICE_KEY); the names differ so that the one is not given the other's form.

A server given --jwt-issuer and --jwt-audience (below) takes the service's token only if both list it: the issuer of your services goes beside the provider's, and the token names an audience the server takes. The lists admit the provider's tokens and the service's alike, so the rule that means a service still asks for $jwt.iss = 'urn:fennec:services'. serviceTokens({ pem, sub, aud }) in service-token.mjs signs the audience in:

-- your own service's token, beside the provider's: its issuer is one the server takes, and it names an audience
the service's token, no aud                {"error":"the token names no audience (aud) this server takes"}
the service's token, aud the API's         {"kind":"scoped","sub":"files-backend"}

A legacy HS256 secret

Supabase's JWKS does not hold its legacy shared secret, and its documentation recommends against verifying with it. If a project still signs with it, the secret goes into the keys file as an oct key, k the base64url of the bytes the provider signs with (which bytes those are is for you to check with a token and /_whoami). The same file then lets --mint-token make test tokens. A project's anon and service_role keys are JWTs of that project too: check what signs yours, and write no rule for those roles, since it would be a rule for whoever holds the key.

{"keys":[{"kty":"oct","kid":"legacy","alg":"HS256","k":"..."}]}
a token signed with the secret             [{"owner":"alice","title":"alice note"}] [200]

What each provider's token carries

The claim shapes below are taken from each provider's documentation and carried by the stand-in (examples/recipes/idp.mjs). For each: who the user is, where a role or a tenant can come from, and what a policy reaches only by a quoted name or not at all (the table above says why).

Never take a role from an attribute the user can write. Supabase's user_metadata is "can be updated by the authenticated user" and "not a good place to store authorization data" (its row level security guide); Clerk's unsafe_metadata is the one kind that can be set from the frontend (user metadata); a Cognito attribute an app client may write is the user's to change, which AWS says to take out of WriteAttributes of every app client before deciding by it (attribute permissions). A claim a policy trusts comes from something only your server or the provider's admin writes.

Clerk

  • sub is the user id, user_… (session token).
  • A role, a tenant: add role and tenant as claims of the session token (Dashboard, Sessions, Customize session token; shortcodes such as {{user.public_metadata.role}}, which only the backend sets). Up to 1.2 KB of custom claims fit the cookie.
  • azp is the origin the session was started on, left out where the request carried no Origin; Clerk's documentation asks a verifier to check it, which --jwt-client does, once for each origin the app is served from. A token without it is refused.
  • Out of reach: the active organization's role is o.rol, nested. A JWT template lives 60 seconds unless set otherwise.

Auth0

  • sub is the connection's name, a bar and the id: auth0|…, facebook|… (docs).
  • A role, a tenant: an access token for an API carries RBAC permissions as a list, when the API has "Add Permissions in the Access Token" turned on (docs), which a rule tests: 'read:notes' in $jwt.permissions. A login to an Organization carries org_id (docs): --jwt-tenant-claim org_id.
  • aud of an access token names the API. One tenant's keys sign every API's and every application's tokens, and the ID tokens too, whose aud is the application's client id: --jwt-audience is the API's identifier, --jwt-issuer the tenant's with its closing /.
  • A namespaced claim: custom claims in an access token for an API must be namespaced URLs (docs): such a token "cannot have private, non-namespaced custom claims". A rule names one in double quotes, $jwt."https://example.com/role", and --jwt-role-claim https://example.com/role makes it the role of for.

Supabase Auth

  • sub is the user's id (claims).
  • A role: role is authenticated for every signed-in user (anon and service_role are the others), so for authenticated admits every signed-in user and cannot single out an admin. An anonymous sign-in has role: authenticated too, and is_anonymous: true: a rule that means a person says $jwt.is_anonymous = false.
  • Out of reach: app_metadata and user_metadata are objects, so a role kept there has no name (and the second is the user's to write). Keep admins as rows (below).

Amazon Cognito

  • sub is the user's id. An access token has client_id and token_use: access, and no aud; an ID token has aud and token_use: id (docs). The pool's keys sign both. --jwt-client with the app client's id takes the access tokens and refuses the ID tokens, which name the client in aud alone; --jwt-audience with the same id takes the ID tokens.
  • A role, a tenant: add a plain claim (role, tenant) with a pre token generation trigger: version 1 for the ID token, 2 or 3 for access tokens, which needs the Essentials or Plus plan. The trigger may add any claim not in the pool's token schema.
  • Groups and attributes: cognito:groups is a list. --jwt-role-claim cognito:groups makes it the role of for editors, and 'editors' in $jwt."cognito:groups" tests it in a filter. A custom attribute is a claim named custom:<name>, and its name goes in double quotes too.

Firebase

  • sub is the user's uid; aud is the Firebase project's id and iss is https://securetoken.google.com/<project> (docs).
  • Google signs every project's tokens with the same keys, so a token for any Firebase project verifies unless the server is given both --jwt-issuer https://securetoken.google.com/<project> and --jwt-audience <project>.
  • A role: a custom claim, set "only from a privileged server environment by the Firebase Admin SDK", so not the user's to write (docs).

Cloudflare Access

  • sub is the user's id, unique to an email address per account; email is a claim too (docs).
  • A role: none of its own. Rows (below), or the email.
  • Out of reach: the token reaches the origin in Cf-Access-Jwt-Assertion, and fennec-server reads Authorization: Bearer alone: a Worker or proxy in front moves it. aud is a list holding the application's tag, and a team's applications are signed with the same keys: --jwt-audience is the tag.

The user's sub is what owner = $jwt.sub compares with, so a row's owner holds it exactly as the provider writes it. The same stand-in alice is five different people to five providers; a note written for each one's sub and read back with that one's token:

clerk: sub user_2xYzAbc                    [{"owner":"user_2xYzAbc","title":"clerk note"}] [200]
auth0: sub auth0|0123456789                [{"owner":"auth0|0123456789","title":"auth0 note"}] [200]
supabase: sub 7c9e6679-7425-40de-944b-e07fc1f90ae7 [{"owner":"7c9e6679-7425-40de-944b-e07fc1f90ae7","title":"supabase note"}] [200]
cognito: sub a1b2c3d4-5678-90ab-cdef-111111111111 [{"owner":"a1b2c3d4-5678-90ab-cdef-111111111111","title":"cognito note"}] [200]
access: sub 3d9a0f0e-5c1b-4a3e-8f61-2b7d9c4e1a55 [{"owner":"3d9a0f0e-5c1b-4a3e-8f61-2b7d9c4e1a55","title":"access note"}] [200]

When the claims a provider offers do not fit, there is a last way round that needs nothing from it: the app verifies the provider's token with the provider's own SDK and signs one of its own, short, with the role and tenant the policy reads (examples/saas does that, with RS256 and its own keys file).

Holding a token to your application

A provider's keys sign every token it issues, for every application it signs users in to: an Auth0 tenant's, a Cognito user pool's, a Cloudflare Access team's, and every Firebase project's with one set of keys. A good signature says who issued a token, not that it was issued for this database. Give the server the issuer and the audience (or the client), and it takes only the tokens made for it, on every route and before a rule is read, so no rule can forget the check:

ProviderFlagsWhat they refuse
Auth0--jwt-issuer https://<tenant>.us.auth0.com/ --jwt-audience <the API's identifier>Another API's token, and an ID token, whose aud is a client id.
Clerk--jwt-issuer <Frontend API URL> --jwt-client <each origin the app is served from>A session started on another origin, and one with no azp.
Cloudflare Access--jwt-issuer https://<team>.cloudflareaccess.com --jwt-audience <the application's AUD tag>The team's other applications.
Firebase--jwt-issuer https://securetoken.google.com/<project id> --jwt-audience <project id>Every other project, which Google's keys sign for as well.
Cognito--jwt-issuer https://cognito-idp.<region>.amazonaws.com/<pool id> --jwt-client <app client id>Another app client's tokens and the ID tokens (--jwt-audience takes those instead).
Supabase Auth--jwt-issuer https://<project ref>.supabase.co/auth/v1 --jwt-audience authenticatedAnother project: aud is the same for all, the issuer tells them apart.

Whom a token is for has the same table with each provider's source, and the issuers whose callers choose their own aud (Google's identity tokens, GitHub Actions' tokens), where the flags are not enough. Here is each provider's server given its flags, with a token made for it and one made for another application the same keys sign for, against policy.txt:

-- the flags of each provider: the keys sign other applications' tokens too (policy.txt)
auth0, a token for the API                 [{"title":"ada note"}] [200]
auth0, an ID token (aud is the client)     {"error":"the token names no audience (aud) this server takes"} [401]
auth0, a token for another API             {"error":"the token names no audience (aud) this server takes"} [401]
auth0, another tenant                      {"error":"the token names no issuer (iss) this server takes"} [401]
clerk, this origin                         [{"title":"ada note"}] [200]
clerk, another origin                      {"error":"the token names no client (azp, or client_id) this server takes"} [401]
clerk, a request with no origin            {"error":"the token names no client (azp, or client_id) this server takes"} [401]
access, this application                   [{"title":"ada note"}] [200]
access, another application of the team    {"error":"the token names no audience (aud) this server takes"} [401]
firebase, this project                     [{"title":"ada note"}] [200]
firebase, another project                  {"error":"the token names no issuer (iss) this server takes"} [401]
cognito, an access token of this client    [{"title":"ada note"}] [200]
cognito, an ID token                       {"error":"the token names no client (azp, or client_id) this server takes"} [401]
cognito, another app client                {"error":"the token names no client (azp, or client_id) this server takes"} [401]
supabase, this project                     [{"title":"ada note"}] [200]
supabase, another project                  {"error":"the token names no issuer (iss) this server takes"} [401]
supabase, an anonymous sign-in             [{"title":"ada note"}] [200]
  • Told by name. A refused token is 401 and the body names the check (the token names no audience (aud) this server takes), never the value the token holds. The audit log's refused line says the same in its reason.
  • The lists are not pairs. Each flag is repeatable and any one of its values is taken, so two issuers and two audiences take either issuer with either audience. A database has one provider; where it must serve two, the rules pin the pair ($jwt.iss = '…' and 'api-a' in $jwt.aud).
  • What the flags do not say. They say the token was made for this application, not which person it is for or what that person is. An anonymous sign-in of Supabase's passes above, with is_anonymous true, and a rule that means a person says so (below). A provider that names its client otherwise, such as Okta's cid, is pinned in the rule: where owner = $jwt.sub and $jwt.cid = "0oa1example".
  • Your own service's tokens have an issuer of their own, and an audience when the server is given one (above).

Rules that name a claim's value

A rule is a filter over a row, and a filter may hold a claim on its own side of a comparison. That reads what for <role> cannot, and it fails closed: a token without the claim does not meet the rule. With the flags above holding the token to the application, the rules name what only a claim can say: a list it holds, a flag the provider sets, a role under a name of its own. The server is given the provider's flags in each run.

policy-claims.txt
# Rules that name a claim's value. What pins a token to the application the
# database is for is not here: fennec-server is started with the provider's
# issuer and audience (--jwt-issuer, --jwt-audience, --jwt-client), and
# refuses a token made for another application, on every route, before a rule
# is read (docs/http-access, "Whom a token is for"). A rule names what only a claim
# can say: a list a token holds, a flag a provider sets, a role under a name
# of its own.
#
# A database has one provider, and so one of the sections below; they are
# together here to be tried against a server for each.

# ---- Auth0 (--jwt-issuer, --jwt-audience of the API)
# `permissions` is a list claim: RBAC's "Add Permissions in the Access Token".
notes         read                        where 'read:notes' in $jwt.permissions
# A custom claim of an access token is a URL, and a name that is not a word
# goes in double quotes.
notes         read,write                  where owner = $jwt.sub and $jwt."https://example.test/role" = 'member'
# Staff are rows. The inner get reads the token's own row of `staff` alone.
staff         read                        where user = $jwt.sub
notes         read                        where $jwt.sub in (get staff select user)

# ---- Amazon Cognito (--jwt-issuer, --jwt-client; --jwt-role-claim cognito:groups)
# With the flag, a rule's `for` reads the groups the token lists.
notes         read                                                       for editors

# ---- Supabase Auth (--jwt-issuer, --jwt-audience authenticated)
# An anonymous sign-in has role `authenticated` and is a user too; a rule that
# means a person says so.
notes         read,write                  where owner = $jwt.sub and $jwt.is_anonymous = false
-- rules that name a claim's value (policy-claims.txt); the flags above are what pin the application
auth0, holding read:notes                  [{"title":"ada note"},{"title":"bob note"}] [200]
auth0, a member, no permission             [{"title":"ada note"}] [200]
auth0, another role claim                  [] [200]
dana, in staff                             [{"title":"ada note"},{"title":"bob note"}] [200]
cognito, in the group editors              [{"title":"ada note"},{"title":"bob note"}] [200]
cognito, in no group                       [] [200]
supabase, a person                         [{"title":"ada note"}] [200]
supabase, an anonymous sign-in             [] [200]
  • The rules that mean a service are pinned on the issuer of your services (files-policy.txt, functions-policy.txt), since a provider's token can carry any sub, and the issuers the server is given include the services': see Tokens your own services call with.
  • A list claim is a test. 'read:notes' in $jwt.permissions is true or false for the whole token, and a rule holding it grants what it grants to the tokens for which it is true. permissions: [] is a list of none.
  • A name in quotes is a name. $jwt."https://example.test/role" is the claim of that name, the dots, colon and slashes in it just characters. --jwt-role-claim makes such a claim the role of for: with cognito:groups, for editors admits a token whose groups list editors, and role is then a claim like any other.
  • A person, not an anonymous sign-in. Supabase's anonymous users have role: authenticated too. $jwt.is_anonymous = false is true only of a token that says so, and a rule that asks it does not apply to one that says nothing.
  • Admins are rows. The staff rule asks a collection, and works with any provider because it asks nothing of the token but sub. staff read where user = $jwt.sub lets the inner get see the token's own row and no one else's; a rule's inner get reads what the token's own would (Rules that read another collection).
  • One provider to a database. The file above has every provider's section to be tried against a server for each; a database serves the one it trusts, and carries its section.

Expiry

A token is good until its exp and the server asks no one whether it was revoked. Keep tokens short, and for a person to turn away sooner, make it a row and let every rule that grants them anything ask for it:

policy-ban.txt
# A token is good until its `exp`, and the server asks no one whether it was
# revoked. A person to turn away sooner is a row, and every rule that grants
# them anything asks for it: they read `banned` for their own row alone, so
# the rule sees whether it is there.
notes         read,write                  where owner = $jwt.sub and $jwt.sub not in (get banned select user)
banned        read                        where user = $jwt.sub
bob reads                                  [{"title":"bob note"}] [200]
bob reads, banned, the same token          [] [200]
bob writes, banned                         {"error":"the document is outside what this token may write to `notes`"} [403]
alice reads                                [{"title":"alice note"}] [200]
  • Short tokens are normal. A Clerk JWT template lives 60 seconds by default. FennecHttp holds the token it was made with, so an app that gets a fresh one per request makes a client per token (connect opens no connection), and one that keeps a client makes a new one when its provider refreshes.
  • A stream ends at its token's exp, with event: error and {"error":"the token has expired","status":401,"code":"token_expired"}: the client fetches a fresh token and opens the stream again. A member taken off a team stops hearing the team no later than that.
  • An expiry is told by its code. A request whose token's exp has passed is answered 401 with "code":"token_expired", as the stream's end is; every other 401 -- a signature no key makes, a kid no key has, an issuer, audience or client the server does not take, a token not valid yet, none at all -- names no code. The code is told only of a token whose signature and audience checked out, so a forged token past its exp is refused for its signature.
  • A 401 is no sign-out by itself. The server keeps no list of revoked tokens: only the issuer knows that a session ended. So an app asks its issuer for a fresh token at every 401, whatever the code, and signs out where the issuer refuses to issue one. A fresh token cures an expiry, a token signed with a key the server has since dropped (a replica offline past a rotation), a request sent before any token was handed over, and every expiry from a server older than this release, which names no code. It does not cure a key the server has not fetched yet (no key has the token's kid, behind a rotation above, until the next fetch), a token whose nbf the server's clock has not reached, or an issuer, audience or client the server does not take: a token minted again at once is refused the same, and a replica's sync waits before it asks again, 1 s doubling to 60 s -- as it does for tokens that arrive expired, as every one does where the server's clock runs ahead of the issuer's by a token's lifetime. It hands its tokenProvider what it needs to tell these apart (Sync, mobile). A replica belongs to one account -- its file or persist key names the account, and it is never opened for another -- and signing out keeps it, for that account's next sign-in to send the writes the server has not taken; deleting it loses them.
  • --jwt-max-age <s> refuses a token whose exp lies further ahead than that: set to 3600, a provider configured for day-long tokens is refused, and the fix is at the provider, where the lifetime is set.
  • The ban is read at every statement, so it takes hold on the next one, whatever the token's age. It is the same for a subscription: a scoped one is bound again when the collection its rules read is written.

One database a tenant

On a --dir node (Tenants and sharding) a token reaches /t/<tenant>/ only when its tenant claim names the tenant, as a text or a list holding it. The policy is the node's, not a tenant's: owner = $jwt.sub would match the same user in every tenant's file, so a token that names none is refused on such a node, unless it is started with --jwt-unbound-tenants. --jwt-tenant-claim <name> reads another claim than tenant: Auth0's org_id below, a claim you add to Clerk's session token or Cognito's.

-- the claim `tenant`, which Clerk's session token carries once customized
alice, token for acme, asks acme               [{"title":"acme note"}] [200]
alice, token for acme, asks globex             {"error":"this token is for another tenant"} [403]
a token naming no tenant, asks acme            {"error":"this token names no tenant, and this node serves tenants"} [403]
-- --jwt-tenant-claim org_id, which Auth0 puts in a token for an organization
alice, token for org_acme, asks org_acme       [{"title":"org_acme note"}] [200]
alice, token for org_acme, asks org_globex     {"error":"this token is for another tenant"} [403]
a token naming no tenant, asks org_acme        {"error":"this token names no tenant, and this node serves tenants"} [403]
  • The tenant check comes before the tenant is looked up, so a refused token learns nothing of which tenants exist. It holds on every route under the prefix, streams and /_changes among them.
  • A tenant is the unit of isolation; rows inside it are the policy's. A person in two organisations carries both in a list.

Next: files in S3 or R2 with the same tokens, and functions and webhooks for reacting to writes.