HTTP security and scoped access

Who may ask: a bearer token and CORS, JSON Web Tokens held to a policy file down to the rows, and the keys that verify them. The routes are in the HTTP reference.

Security

Protect the endpoint with a bearer token, and serve it over HTTPS on an open network: --tls-cert and --tls-key (HTTPS).

fennec-server --file data.fennec --http 127.0.0.1:8080 \
         --http-cors 'http://localhost:8787' \
         --http-token "$TOKEN" \
         --http-read-only
--http-token <value>every request needs Authorization: Bearer <value>, compared in constant time; 32 bytes at least where the server listens past loopback (Security)
--http-cors <origin>sets Access-Control-Allow-Origin; without it no CORS header is sent at all. A browser’s preflight (OPTIONS) from that origin, or any with *, is answered 204 before a token is asked for -- the browser sends none with it -- on a single database and under /t/<tenant>/. Every answer exposes Fennec-Seq, X-Request-Id, Retry-After and a deprecated route's Deprecation, Sunset and Link (Compatibility), and lets Idempotency-Key in. Through fennec-shard, give the router the flag: it answers the preflight itself and puts its headers on its own answers and in place of the node's (Tenants and sharding)
--tls-cert <pem>, --tls-key <pem>the endpoint speaks HTTPS alone, with this certificate chain and private key; a plain HTTP request is answered 400, naming https://. Both or neither
--tls-ca <pem>not the endpoint's: the CAs the https:// URLs this server dials are held to (a primary, an OTLP collector), in place of Mozilla's roots (Dialing HTTPS)
--http-read-onlywrite endpoints return 403, and so does a call of a named statement whose body writes (one whose body only reads is answered); fennec-server's own path is unaffected
a replicaevery write returns 403, whatever the flags: its writes come from its primary
non-loopback addressrefuses to bind without a token, unless --insecure is given
no tokenanswers only under this machine's name, and a page only from its own origin or --http-cors's; every other request is refused 403 before it runs (below)

A server with no token

With neither --http-token nor JSON Web Tokens -- the Quickstart's server, a node given --admin-token alone -- whoever reaches the server reads and writes everything, and a browser reaches 127.0.0.1 from any page. So such a server holds every request to two checks before it runs anything, under --insecure too:

  • Its name. The Host a request names must be localhost, a name under it (app.localhost) or an IP address. A page whose DNS name was rebound to 127.0.0.1 sends its own name, and is refused (403) where it would have read every row. A server reached by another name -- a container's service name, a tunnel's, a LAN name -- needs a token: reach it as localhost or by its address, or give it --http-token, the refusal says.
  • The page's origin. A request carrying Origin must come from the server's own origin (the studio it serves) or the one --http-cors names (*: any). Another site's page, which could send a write without a preflight (mode: "no-cors"), is refused (403) before the write runs. Name your app's origin with --http-cors.

curl, the SDKs, Node's fetch and other servers send no Origin and pass on this machine's name. /_health and a preflight --http-cors lets in are answered under any name. A server with a token is held to neither check: a page holds no token, and sends none to another origin without the preflight CORS refuses. fennec-shard with no --token is held the same way (Tenants and sharding). Behind the router or a proxy, the server also asks the name the router or proxy was reached by, which they send in X-Forwarded-Host: a node with no data token answers only a client that reached the router under this machine's name (Behind a proxy), and nothing a router listening past loopback forwards it unless it runs --insecure: such a router's clients are the network's, and name whatever host they like (A node with no token behind a router).

TLS, unfiltered writes, body limits and what a shape leaks

The endpoint runs inside fennec-server and takes its TLS flags. Without them it speaks plain HTTP, and a token travels in the clear on an open network (HTTPS). A PATCH or DELETE without a filter is refused, and covering a whole collection needs a separate path rather than a flag — a key like ?all=true would collide with a field named all.

Limits are shared with fennec-server (--max-connections, --idle-timeout: a connection silent that long between requests is closed with nothing written, and one that went silent part way through a request is answered 408; --header-timeout: a request not come within 10 s of its first byte and a second more for each KiB that came -- slower than 1 KiB a second, head and body alike -- is answered 408 too; --write-timeout: a write of an answer waits 30 s at most for its client to take any of it, a client reading nothing let go within twice that); the body ceiling is 64 MiB and the header block 64 KiB. A body may come Transfer-Encoding: chunked, held to the same ceiling chunk by chunk (Request bodies). A field whose name matches a clause name (select, order, limit, offset, count, where, group) cannot be filtered over HTTP; the FennecQL and fennec-server paths are unaffected.

A shape alone is not a security boundary. Under the server's own token, which ids changed is visible to a subscriber even when the rows are not. Rows are hidden by a scoped token, below.

Scoped access

Give each user a JSON Web Token, and a policy file decides which collections and which rows that token can read or write. A browser can then talk to the database directly.

# collection   access         rows                                role
notes          read,write     where owner = $jwt.sub
posts          read           where published = true or author = $jwt.sub
posts          write          where author = $jwt.sub
messages       read,insert    where room in $jwt.rooms
journal        read,insert    where owner = $jwt.sub
journal        append-only
accounts       update(balance, held)                              for app
orders         update(status, run_at)  where customer = $jwt.sub and status = "ready" and new.status = "cancelled"
orders         read(pickup, run_at)    where run_at <= now()                    for courier
positions      read           where courier in (get orders select courier where customer = $jwt.sub)
transfer       call                                               for customer
paid_ledger    wake                                               for customer
*              read                                               for dashboard
  • Reads only see the rows the rule allows.
  • Fields. read(pickup, run_at) shows the rows it admits with those fields alone, and id: a row shows the fields of every read rule admitting it, the rest null. A courier sees a ready order's pickup, and the customer's door once the order is theirs.
  • Writes must stay inside the rule, or get 403. write grants insert, update and delete, and each can be granted alone; update(balance, held) grants an update of those fields and no other.
  • Transitions. new.status reads a row as the write leaves it, and a bare name as it stands: the orders rule above lets a customer cancel a ready order, and not take a cancelled one back.
  • returning answers rows the token may read as the write leaves them: a courier who reads the orders they carry claims a ready one and is answered it, claimed.
  • append-only collections take inserts from scoped tokens, and refuse every update and delete with 403.
  • A named statement is granted by name: transfer call lets the token call transfer, which runs with its own text's authority, and the token needs no rule on the collections it moves (Calling a named statement).
  • A statement bound to writes is granted by name too: paid_ledger wake lets the token's writes wake paid_ledger, whose ledger line lands with the write though the token has no rule on ledger (Waking a bound statement).
  • A list claim, such as "rooms": ["r1", "r2"], goes after in.
  • Another collection. in (get …) reads a rule's list from rows: the positions rule above lets a customer read where the courier carrying their order is, and nothing of the others.
  • The server's own collections — _idempotency, _consumers, _migrations, every name starting with _ — are out of every rule's reach: * grants nothing there, and a token is answered as if they were not there (below).
  • The server's own --http-token still has full access, but for changing the server's own collections, which it reads.

A whole product built on these rules is examples/saas: sign-up and sessions owned by the app, a tenant per organisation behind fennec-shard, roles and teams as grants and list claims, live boards and search under each person's token, with its threat model and the attacks its tests try.

Every rule of a scoped token

--http-token is everything or nothing. With --jwt-secret the endpoint also takes HS256 JSON Web Tokens, each held to the rules of a --policy file, collection by collection and down to the rows, so a browser can talk to the database directly with a token per user:

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

fennec-server --jwt-secret-file jwt.secret --mint-token '{"sub":"alice","exp":1893456000}'
  • Reads get the rule's filter ANDed in at every level: the collection's where, each lookup below it, a subscription's shape, a count. A collection no rule grants a token anything on does not exist for it: 404, and absent from the list.
  • Writes get it twice, as PostgreSQL's USING and WITH CHECK: a set or del touches only the rows the filter matches, and every document written — a put, or a row a set rewrote — has to match it afterwards, or the write is refused with 403. A put that leaves out a field the filter pins to a claim gets the claim's value, so {"title":"a"} is alice's. A scoped put names no id, which could overwrite a row the token cannot see — so PUT /<name>/<id>, which names one, is 403 whatever its preconditions; a scoped token holds a write to the row it read with PATCH or DELETE /<name>/<id> under If-Match (Writing over the row you read) — and a scoped token changes no schema and runs no maintenance.
  • returning answers what the write wrote, so the rows it answers are held to the read rules: a set's as it wrote them, a del's as they were. A row the read rules leave out by a field the write does not change is passed over, as a get passes it over; a set that would leave a row the token may not read is refused with 403 and writes nothing. PostgreSQL asks its SELECT policies of the row before an UPDATE … RETURNING as well as after, which is why a courier who reads the orders they carry, claiming a ready order, would take nothing there and be told nothing; here the terms over the fields the set writes are asked of the row it leaves, and the claim answers the order, claimed. Without returning a write's rows are those its own rules reach, read rules or not.
  • Grants are read, insert, update and delete, joined by commas, and write is the three writes. An insert is a put of new documents, held to the filters of the rules granting insert; an update is a set and a delete a del, of rows the token may read and the filters of the rules granting them, a set's rows checked again after. update(balance, held, status) names the fields an update may change: a write over a row — a set, a REST PATCH or PUT, a line of a /batch — is judged by the fields it changes, and each of them must be one rule's whose filter admits the row before and after, or it is refused with 403 naming a field (a batch holding it is put back whole). A field written with the value it holds is not changed. Rules widen each other, each with its fields and its rows: notes update where owner = $jwt.sub beside notes update(title) changes every field of the token's notes and the title of anyone's. A token may insert into a collection it cannot read, such as an event stream: its reads of it are refused with 403 and it is not listed. expired grants the rows past their @ttl, which expired() reads (the reaper): a statement asking it is held to the filters of the rules granting expired beside the ones its operation needs, and neither write nor * grants it — a lapsed hold is the reaper's, not a user's to see again.
  • Fields a read shows. read(pickup, run_at) grants the rows its filter admits with those fields and id; read grants every field. A row shows the fields of every read rule admitting it, and the rest answer null — in /query, /batch, REST, each lookup level by its own collection's rules, a write's returning, a subscription's seed and changes, and the MCP tools. Beside orders read where courier = $jwt.sub for courier, the rule above shows a courier every ready order's pickup and the whole of the orders they carry. A field no read rule grants is not there: select * leaves it out, describe, /collections and /_schema do not list it, and naming it is refused (403) as a name the collection lacks is.
    get orders where dropoff = $1                 -- no ready order matches, whatever its door
    get orders where not (dropoff = $1)           -- every ready order does: no door told from another
    get orders order dropoff                      -- 403: the order would tell the doors
    get orders where courier = $1 order dropoff   -- $1 their sub: every order reached shows it
    A field withheld from a row must not show through what a statement does with it either. A where term reading it holds only where the row shows it — dropoff = $1 is asked as (courier = $jwt.sub and dropoff = $1), the or of the filters of the rules granting dropoff — in a get, a set or del, a lookup level, a facet's and an inner get's; and stops at the first false, so the term is never worked out over a value it may not see. order, group, having, a facet, an aggregate, match, near, a highlight, a lookup key and a set's values read a field only where every row they reach shows it, and are refused with 403 naming it otherwise: when every read rule of the collection grants it, or when one rule granting it has no filter or one whose and terms are each a term of the statement's own where, parameters bound — as the last line above. A computed column over such a field is null where the row does not show it and never worked out there, and an inner get's column of one is listed from the rows showing it. A write reaches the rows it reached before; its returning is masked as a read's rows are. PostgreSQL's column privileges are a role's and the same on every row, and refuse a statement naming a column the role lacks, SELECT * included; a column shown on some rows is a view of CASE WHEN … THEN col END there, whose WHERE reads NULL on the rest where this reads the term as false. A token whose rules name no fields reads as before; one whose do loses the stored-bytes path of a plain get where a column is masked, and pays each rule that could show a row more, per row: over HTTP on loopback a row by id took 28.0 µs against 26.0 under the same two rules naming no fields, a page of twenty 39.5 against 34.4, about 0.13 µs a row of it in process (make policy-bench).
  • Transitions. A rule's filter reads the row as it stands, and new.<field> reads it as the write leaves it, as new. names the document in an upsert's else set. One filter asked of the row before and after cannot say which way a row may go: status = "ready" or status = "cancelled" lets a customer cancel an order and take a cancelled one back, and run_at granted lets them move it to the head of the queue. A rule naming new. is a transition, asked of the two rows together:
    # a customer cancels a ready order, out of the queue for good
    orders  update(status, run_at)  where customer = $jwt.sub and courier is null and status = "ready" and new.status = "cancelled" and new.run_at is null  for customer
    # a courier claims an order whose lease is out, for themselves, counting the attempt
    orders  update(status, run_at, courier, claim, attempts)  where run_at <= now() and new.status = "assigned" and new.courier = $jwt.sub and new.attempts = attempts + 1  for courier
    # and delivers only what they carry
    orders  update(status, delivered_at, run_at, claim)  where courier = $jwt.sub and (status = "assigned" or status = "picked") and new.status = "delivered" and new.run_at is null  for courier
    A write over a row is the token's when one rule granting update names every field it changes (or names none) and admits the change: a transition by being true of the row before and after together, any other rule by admitting each. Rules naming no fields and no new. widen each other as before, the row before one rule's and the row after another's, as PostgreSQL's permissive policies do; a transition lends neither half. A set picks the rows a transition reaches by what the row before can answer of it — status = "ready" of the first rule above — and each row it writes is then asked the whole rule, a refusal 403 and the statement (or the batch) put back. The row after is held to what the rule says of new. and nothing more: the field list keeps the rest where it was, so a transition with none should pin what must not move (new.customer = customer). A rule naming new. grants update alone — a read, an insert or a delete has no row after, or none before — and one granting more stops the server at startup. A scoped set of one row over HTTP on loopback took 5.0 µs more than the server token's 45 µs under a plain rule, 5.7–5.9 under a field list and 6.1–6.8 under a transition (make policy-bench).
  • append-only is a line of its own, journal append-only, with no filter and no role. No scoped token updates or deletes there, by any route — /query, REST, /batch — whatever its rules grant: write and * mean insert there, and a rule naming update or delete for the collection stops the server at startup. It binds JSON Web Tokens and not the server's own token: corrections, erasure and @ttl's sweep stay with whoever holds that, and an app server that should only append is given a scoped token of its own, a role for instance.
  • The server's own collections. A collection whose name starts with _ is the server's: _idempotency keeps each Idempotency-Key with the answer kept for it, _consumers the change stream's consumers, _migrations the migrations a schema declared in code ran, _follow what --follow follows, and a name starting with _ is kept for the next one. * reaches none of them, and a rule naming one, or reading one through in (get …), stops the server at startup. A JSON Web Token is answered 404 for each, by every route, word for word as for a collection no database holds, and none is listed to it — a REST request or a subscription naming any collection the token is granted nothing on, by its path or a lookup level, is answered so whatever its filter, select or the level's on names, and a subscription's in (get …) reads only what the token may, as a query's does. The server's own token reads them, and no statement of its creates, alters, drops, indexes, compacts or writes one (403), nor does a description or a migration still to run sent to /_schema/apply: the server makes and writes them itself, in their own shape. So the migrations a schema ran, recorded in _migrations, start over in a new file, or a new tenant. The change stream leaves them out.
  • Calling a named statement. A line grants calling by name, to a role or to every token. call stands alone on it:
    # statements       access  role
    transfer           call    for customer
    transfer, refund   call    for teller
    The statement is defined with the server's token, and a customer token calls it with no rule on accounts or entries:
    create statement transfer($from int, $to int, $amount int)
      claims (sub text)
      check $amount > 0 and $from != $to
    as begin
      get accounts select id where id = $from and owner = $jwt.sub
        limit 1 require 1 else 'not your account';
      set accounts {balance: balance - $amount} where id = $from and balance >= $amount
        require 1 else 'insufficient funds';
      set accounts {balance: balance + $amount} where id = $to
        require 1 else 'no such account';
      insert entries {src: $from, dst: $to, amount: $amount, by: $jwt.sub}
        returning id, amount
    end
    call transfer {from: 1, to: 2, amount: 300} — or POST /_call/transfer with {"params": {"from": 1, "to": 2, "amount": 300}} (Calling a named statement) — lands the debit, the credit and the entry as one block or not at all, and the token cannot send the debit alone. The caller reaches the body only as the claims it declares, read from the token: sub here, held to its declared type. A claim the token lacks, or holds as null, as "", as an empty list or as a value of another type, is a 403 and nothing runs. A scoped token calls as itself: as {…}, which gives the server's token the claims to call with, is a 403.
  • A grant is by name and nothing else. call beside another grant or a where stops the server at startup, and so does * call, since a statement defined later would be granted by a line no one reads again. A line naming a statement the database does not hold is logged as the server starts, as each tenant of a --dir node opens and after a drop takes one away: a typo grants nothing, silently, otherwise. A statement a token is not granted is the same 404 a statement the database lacks gets, so a name tried says nothing. On a tenant node the lines are the node's and the statements the tenant's: a tenant holding none by that name answers 404. The server's token calls every statement. /_whoami lists the statements a token can call as calls: those its lines grant that the database holds, never one bound to writes, scheduled or a webhook consumer, which run by themselves — at a tenant node's root, which asks no tenant, the names its lines grant; statements is refused it (403) and describe statement answers 404.
  • The body runs with its statement's authority. The caller's rules and field lists hold nothing in it, and the answer is not masked by them: the statement answers what it names, and one that wants the caller's rows says owner = $jwt.sub where it reads. append-only still binds: a body that updates or deletes in such a collection is refused (403) for a scoped caller. A scoped /batch holds one call and nothing beside it (400); the server's token runs any batch. A refusal tells a scoped caller the status and a guard's reason and nothing of the collections, fields and values the body met; the server's token is told the engine's words.
  • A call is answered in one order, and held to a rate. Each refusal comes before the next is asked: the token and its tenant, the rate (429), the grant (404), as (403), the claims (403), the arguments and check (400), append-only (403) and a broken statement (409). --call-rate holds a scoped token to 100 calls a second for each subject and issuer in each tenant, 0 for none, and answers 429 with Retry-After past it; the server's token is not held. A call is a request too: it is held to --request-rate first, then to --call-rate. --call-max-rows bounds the rows one call examines (Limits).
  • Waking a bound statement. A statement bound to a collection's writes (Statements bound to writes) runs in the block of the write that woke it, once a row. A scoped token's write wakes one only where a line grants it by name, to a role or to every token. wake stands alone on it, as call does:
    # statements       access  role
    paid_ledger        wake    for customer
    orders             read            where account in $jwt.accounts  for customer
    orders             insert          where account in $jwt.accounts and status = "open" and total > 0  for customer
    orders             update(status)  where account in $jwt.accounts and status = "open" and new.status = "paid"  for customer
    create statement paid_ledger
      after set orders where new.status = 'paid' and old.status = 'open'
    as begin
      get accounts select id where id = new.account limit 1 require 1 else 'no such account';
      insert ledger {order: new.id, account: new.account, amount: new.total, at: now()};
      set accounts {balance: balance - new.total} where id = new.account
    end
    A customer who sets an order's status to paid lands the ledger line and the debit with it, or nothing, with no rule on ledger or accounts: the statement's writes are its own text's, never the token's. The token's own write is judged by its rules first, so the policy over orders is the binding's guard — what a customer may write into new.account is what it debits. A bound statement runs with its definer's authority, as a SECURITY DEFINER function does, so every input the writer controls — each new. field it may write — must be held by the writer's rules: here an order is inserted open with a total above zero and only moves from open to paid, its total and account fixed. Without that, a customer inserting an order of a negative total and paying it would credit the account.
    • Asked as it wakes. The grant is asked of a write whose row passes the statement's condition: a courier moving an order's location wakes nothing and needs no line, and a write that would wake one not granted is refused (403), nothing landed — a bound statement never skips. Where the condition reads a field the token is not shown — one its read rules' field lists leave out, or any of a collection it may not read — the grant is asked of every write of its event, its rows passing the condition or not, so a 403 against a 200 tells the token nothing of that field. A call is asked before its body runs, of every bound statement its body's writes may wake.
    • append-only binds it. A bound statement that updates or deletes in an append-only collection is refused a scoped token's write (403), granted or not; the server's token's same write runs it.
    • Named to no token. The 403 names no statement, as an ungranted statement is no name to a token; the audit log's unwoken line (--audit) names it, with the path, for the operator writing the grant. A refusal the statement makes — a guard's require — tells a scoped writer the status and the guard's reason, in a write bound to it refused it, and the server's token the statement's name as binding and the engine's words. The audit log's bound line keeps both for the operator, with the method and the path (The audit log).
    • Held to --call-rate. Each run a scoped token's write wakes is charged to its subject's calls a second: past them 429 with Retry-After, the write put back; a request waking more runs than a second's worth at once is 400 and would never be let through. The server's token is not held.
    • Never called. A bound statement is run by the writes it binds alone: to a scoped token a call of one is the 404 a missing one is, and MCP lists no tool for it.
    • Checked at startup. * wake stops the server, with or without a role, since a statement bound later would run on a token's behalf by a line no one reads again; so do wake beside another grant and a where. A wake line naming a statement the database does not hold, or holds callable, and a call line naming a bound one, are logged as the server starts, as each tenant opens and after a drop, and grant nothing. /_whoami lists what a token may wake as wakes.
  • List claims. A claim that is a JSON array goes after in: room in $jwt.rooms matches the rooms it lists, room in [$jwt.rooms, "lobby"] those and one more, and a text claim there is a list of one. SQL's room = any($jwt.rooms) is the same rule, and room <> all($jwt.rooms) is not (room in $jwt.rooms). It holds reads, writes (WITH CHECK: a post into a room the list does not hold is 403) and subscriptions alike. A list holding a null, a "", a list or an object is no claim, and the rule naming it does not apply; [] is a list of none. A token whose list claim holds more than 1 000 values is refused (401). A role claim may be a list too, and a rule for a role applies when the list holds it. Membership kept in another collection is a rule's in (get …) (below).
  • Claim names. $jwt.<name> takes letters, digits and _; a claim named with anything else goes in double quotes, as its provider names it:
    teams  read   where team in $jwt."cognito:groups"
    posts  write  where author = $jwt."https://example.com/user_id"
    Inside the quotes a ., a :, a / or a # is part of the name, never a path or a comment, and $jwt."sub" is $jwt.sub. An unquoted name running into - or : ($jwt.x-hasura-user-id) stops the server at startup, saying to quote it: it would have been read as a subtraction. A claim is read from the top of the token alone: $jwt.app_metadata.role stops the server at startup too. Providers keep what a user may edit of themselves in nested objects (Supabase's and Auth0's user_metadata) beside what only the app may (app_metadata), and a path into the wrong one would let a user write their own grant; have the provider put the claim a rule reads at the top of the token, where it was told to sign it. A # outside quotes starts a comment.
  • Rules that read another collection. A rule's filter takes in (get …), its claims bound inside as anywhere else:
    # a customer follows the courier carrying their order
    positions  read  where courier in (get orders select courier where customer = $jwt.sub and (status = "assigned" or status = "picked"))  for customer
    # a member reads and posts in the rooms they belong to
    messages   read,insert  where room in (get members select room where user = $jwt.sub)
    The inner get reads the rows of its collection the token's own get would, held to the token's rules there; one no rule lets the token read gives none of its rows, as PostgreSQL's row security gives a policy's subquery none of a table no policy grants. The fields it reads are the policy's own: its list is never shown, only what it admits. It is answered before each statement, under the lock that runs it, as the in list it is: reads, a lookup level, a facet, a match and an agent's MCP tools see the list as it stands, and a write's WITH CHECK — an insert's document, an update's row before and after, a transition's pair, an upsert's row written over, returning's rows — is tested by it where no query could run. A rule naming the fields it shows may read another collection too, positions read(courier, at, loc) where courier in (get orders …): each row is shown the fields of the rules admitting it as their lists stand, in a read, a lookup level and a stream (Fields a read shows). A /batch answers it again for each statement: a courier's claim, then a read of the customer's door the claim lets them read, is one round trip. The list is held to a list claim's bound, 1 000 values, each counted once however many rows hold it, and a statement whose list would hold more is refused (400) rather than answered with a list cut short, the refusal naming the bound and the rule by its collection and its filter as the policy writes it. An inner get that selects one field and pages nothing is read whole, however many rows its filter holds, but for a nocase or json field, whose values a group would join where in tells them apart ("R2" and "r2"): that one, and one with a limit, an offset or a computed column, is read on past its first rows as far as a statement's own would be, 100 000 rows, and refused past them; one with a group as far as 100 000 groups, which bound the groups and not the rows read into them. A list read again to 100 000 rows costs its statement some 200 million instructions, about 11 ms, and one read whole or grouped costs the rows its filter holds, however few its values: a rule's inner get is best kept to the token's own few rows. The bound is not a statement's 100 000 because the list is made before every statement the token sends, and every row the statement reads is tested against it: a list of 1 000 values costs each statement some 2.8 million instructions, against 32 000 for one of two, and one of 100 000 would cost every statement what a statement's own list of that length costs once, 391 million. Past 1 000 the membership belongs in the rows — a collection a room, or a tenant — or in a statement's own in (get …). Rules that read each other's collections — positions reading orders whose rules read positions, at any depth, whatever their roles — stop the server at startup, since none of them could be answered first; so do a rule on * that reads a collection, a claim anywhere in the inner get but its where, an inner get standing anywhere but under and, or and not — (… in (get …)) = false, != true, any other comparison, arithmetic, a function's argument, a case — or anywhere in another inner get but its where, an inner get that ranks its rows — a match with neither an order nor an aggregate beside it, plain, fuzzy or prefix alike, a near, a fuse or a rerank — and what an inner get may not say anyway. The rules of the collection an inner get reads are bound for the nots it stands under, and a value has none to count: spelled (room in (get bans …)) = false, a deny list was bound as an allow list, and under bans read where sev >= $jwt.min a ban whose sev is "high" left the list, showing its room's messages, which not (room in (get bans …)) holds out. Write a deny list with not. A ranking answers a page of its best rows, at most 10 000, not every row its filter holds, and where the rule negates the list a list cut there would hold out less than the rule names; match beside an order or an aggregate is a filter, every row it scores above zero, and may stand there. A scoped subscription whose rules read another collection is bound again when that collection is written: the courier enters a customer's stream of positions as the order is claimed and leaves it, a deletion of the row it was sent, as it is delivered, with no write to positions between. It costs one inner get a statement — a @hash bucket's read, 1.8 to 2.1 µs in process and 4.3 to 4.7 µs over HTTP on loopback above a rule naming a claim — and a stream one at each write to the collection its rules read: beside 100 scoped streams a write took 1.89 ms of the server's CPU against 1.65 under a rule naming the courier as a claim, every scoped stream looking at every write either way. A token with no such rule runs as it did (make policy-bench, ARGS=streams).
  • match scores over the rows the token may read. BM25's statistics — how many documents, their mean length, how many hold each word — are taken over the rows the query's filter selects, the token's rules among them, not over the collection: there a user's own memo scored 9.87, then 4.79 once another user wrote 200 private memos holding the same word, which told the first how many of the second's held it. A score is what a collection holding the user's rows alone would give, and so is the order of match, rerank's candidates and fuse's text side. It costs the token's query its rows' lengths and each word's count among them: over 100 000 documents, a filter keeping 2.5% took 0.16 ms and takes 0.24, one keeping half 5.4 and 6.2. The server's own token scores over the collection, as before. Under @text(accents) the same rows decide whether a word typed with accents reads its spelling, in the ranking, its facets and its marks alike: a spelling only another user's rows write leaves the token's word read as every spelling.
  • The rules are asked first. A row meets the token's rules before any condition of the statement's own, in a where, a lookup level, an inner get, a set or del, REST's ?where= and a subscription's shape alike, so a condition that fails — a division by zero, a number past 64 bits — is never worked out over a row the token may not read: get notes where id = 17 and 1 / (case when body >= "m" then 0 else 1 end) = 1 is [] whatever another user's note 17 holds. A row past its @ttl is left out before either, so such a condition never meets one without the expired grant. An upsert's else set reads the row holding its value only once the token may update it, and is refused (403) before it reads one it may not. Conditions that cannot fail — a field compared with a value, an in list, like — may be tested in another order where that is faster; the answer is the same.
  • explain is the server token's. A scoped token's explain is refused (403, `explain` is the server token's: a plan counts rows this token's rules hide from it) through /query, /batch and MCP's query tool: a plan counts the rows an index found before the rules held them, and which index it names compares two such counts, so it would tell a user whether another user's row holds a value. A collection the token is granted nothing on is still answered 404, as for a get. The server's own token explains as before.
  • Subscriptions are told only of rows they were sent: a scoped subscriber hears of a row leaving its shape only if the row was in it, so the ids other users write never reach it — rows leaving as a rule that reads another collection moves among them. Where a rule names the fields it shows, a row written again that shows what it showed is not sent: a write to a field the subscriber does not see would tell it when.
  • Tokens are HS256, or RS256 and ES256 with --jwt-keys (below). The algorithm is the key's, not the token's, so alg: none is refused. Every token is checked against exp and nbf, and one with no exp is refused (401): it would be good for ever, and a token that leaked could only be outlived by rotating every key. --jwt-require-exp off takes such tokens again, and --jwt-max-age <s> also refuses one whose exp lies further ahead than that. --mint-token gives claims naming no exp one an hour away, or --jwt-max-age away where that is sooner. A server told an issuer or an audience takes only the tokens issued for it (Whom a token is for). A rule with for applies to tokens whose role claim names that role, or lists it: role, or the claim --jwt-role-claim <name> names, such as Cognito's cognito:groups. A role is the word after the rule's last for, so for platform-admins is that role; one of more than a word goes in double quotes, for "Account Admin". /_whoami answers the roles the server read, which the studio shows. Rules on one collection widen each other; a rule whose filter names a claim the token lacks does not apply, and grants nothing. Nor does one naming a claim the token holds as null, as "", as an object, or as a list where the rule reads one value: "sub": null is no subject, and owner = $jwt.sub does not become owner = null, which every row with no owner matches. A number and a bool are values like any other. A claim a rule compares by order (level <= $jwt.clearance) admits only values of its own kind, under a not too: given "top", no number is below it. A float's NaN is above every number, as PostgreSQL orders it (Collections and types): level <= $jwt.clearance admits no row holding one, and level > $jwt.floor admits every such row. A row with no value answers as the rule written out: not (level > $jwt.c) admits the rows with no level. A text claim that reads as a time, such as "2026-07-01T00:00:00Z", orders a time field by time (from year 0) and a text field as text. A rule reading another collection through not in (get ...) builds its list as the other collection's rules allow under that not, so a deny list holds out what it held out before; spelled as a value instead, (… in (get …)) = false, it has no not to build by and stops the server at startup. A claim inside a call or arithmetic (lower($jwt.email), $jwt.iat * 1000) and an ordered comparison with a claim used as a value stop the server at startup: mint the claim as the rule compares it. A claim as the pattern of like, ilike or not like (path like $jwt.home) is taken, as is its escape. A policy names its parameters by claim alone: one writing $1 or $3 of its own stops the server at startup too, as does anything after a rule's where but its role — a limit, an order, a match, a select list, a group — since a rule is its filter and applies none of them. A subscription is checked when it opens, and ended at its token's exp with event: error and {"error":"the token has expired","status":401,"code":"token_expired"}: the client takes it as a request refused for its token's expiry -- whose 401 names the same code, which no other refusal does -- fetches a fresh token and opens the stream again (FennecHttp.live, subscribe, the sync layer, Go's *Error and .NET's Event.Status). Without it a stream outlived its token, and a member taken off a team heard the team until the client went away. No other request is held open past its token, nor before it: a read, a subscription or a /_changes page sent with Fennec-After waits only once its token is taken — one the server refuses is answered 401 at once, never after the wait — and is checked again once its wait ends, a write held by Fennec-Wait asks its token again each time it runs, and /_changes takes no scoped token.
  • Refusals tell a scoped token only what it may read: a @unique clash (409) names the field, not the document holding the value nor the value, since that row is another user's.
  • Tenants. On a --dir node a token reaches /t/<t>/ only when its tenant claim names <t> (a text, or a list holding it), and is refused with 403 under every other tenant's prefix; one without the claim is refused there unless the node runs with --jwt-unbound-tenants, and one holding it as null, "" or anything else naming no tenant is refused even then (Tokens).
  • Requests a second. --request-rate holds each caller — a scoped token's subject and issuer — to 1 000 requests a second in each database, a tenant's apart, every route counted: a collection's reads and writes, /query, /batch, a call, /_whoami, MCP and a subscription as it opens, once however long it streams. Past it the request is answered 429 as its token is taken, before anything of it runs, with Retry-After in whole seconds and the body's retry_after and retry_after_ms, the wait to the millisecond; every SDK sends it again after that wait. A bucket holds a second's worth, so a page opening with fifty requests is never held; a write held by Fennec-Wait is one request however many times it runs. A call counts as a request and then as a call (--call-rate), an MCP tool call as a request and then against --mcp-calls-per-sec; a tenant's quotas are its own besides. A token naming no sub is counted with every other of its issuer's. The server's token, and a server asking for no token, is never held; --request-rate 0 holds no one. Past the requests of the server's own token, nothing is counted by address: a client with no token is the server's to keep out, and one in front of it to slow down. A backend that holds one scoped token for all its users is one caller: every user's request counts against that token's 1 000 a second. Give each user a token of their own, each its own caller held to its own rules, or raise --request-rate to what the backend asks at its peak (0 for none); fennec_request_rate_refused_total rising says the bound is biting.

The server's own --http-token keeps full access alongside.

Keys, rotation and identity providers

To accept tokens from Auth0, Clerk, Firebase or another identity provider, give --jwt-keys its published key file. Edit the file to rotate keys; no restart is needed. The server reads a file, not a URL: a job that fetches the provider's keys into it is yours, and Auth with your identity provider has one, with what Clerk, Auth0, Supabase Auth, Cognito and Cloudflare Access each sign with and carry, and what the server does not take. A provider's keys sign tokens for every application it hosts (Google's every Firebase project's, an Auth0 tenant's every API's, a Cloudflare Access team's every application's), so give the server the issuer and the audience of yours (Whom a token is for, below).

# the provider's public keys, as it publishes them
curl -s https://example.auth0.com/.well-known/jwks.json > jwks.json
fennec-server --file data.fennec --http 0.0.0.0:8080 --jwt-keys jwks.json --policy policy.txt
How keys, algorithms and token checks work, timed

--jwt-keys takes a JWKS file, {"keys": [...]}, in place of a secret. An oct key verifies HS256 tokens and needs at least 32 bytes. An RSA key whose modulus is 2048 to 8192 bits and whose exponent is odd, from 3, verifies RS256 tokens, which is what Auth0, Clerk, Firebase and most identity providers sign with. An EC key on the P-256 curve verifies ES256 tokens (ECDSA with SHA-256), as Supabase Auth's EC signing keys sign them; its x and y must be a point of the curve, or the whole file is refused, as it is for an RSA key outside those sizes. A file whose malformed P-256 key an earlier version skipped therefore no longer loads: at the start the server refuses it, and on a reload it keeps the keys it read last. Nor does a file holding an RSA key of 2041 to 2047 bits, which v0.1.7 to v0.2.0 took: they counted the modulus in whole bytes, where RFC 7518 asks 2048 bits. A token one of these providers issues is taken with its public keys alone. Keys of any other kind (OKP, an EC key on P-384 or P-521) are skipped, and a token signed with EdDSA, PS256, ES384, ES512, RS384 or RS512 is refused (401). A key is only used for its own algorithm: an RSA modulus is public, and taken as an HS256 secret it would let anyone sign. A token that names a kid is checked against that key only. A token without one is checked against each key of its algorithm.

The server looks at the file at most once a second and reads it again when it has changed, so keys rotate without a restart. To rotate:

  1. Add the new key to the file.
  2. Start signing with it.
  3. Once the tokens signed with the old key have expired, remove the old key.

If the file can no longer be read, the server keeps the keys it read last and logs why. --mint-token signs with the first oct key and names its kid.

A token that has already been verified is kept by its text, so that later requests with it skip the check. The server keeps up to 4 096 tokens, and the kept tokens are dropped whenever the keys change. Checking a token from that cache takes 0.3 to 0.5 µs, whatever its algorithm. Checking a new one takes 2.9 µs for HS256, 38 µs for RS256 over 2048 bits and 145 µs for ES256 (Apple M1, make jwt-bench). A client sends the same token for as long as it lives, so each token pays that once on each server.

Whom a token is for

A provider's keys sign every token it issues, for every app it signs users in to: an Auth0 tenant's, a Cognito user pool's, a Cloudflare Access team's. Firebase signs every project there is with one set of keys. A good signature says who issued a token, not that it was issued for this database. Given the issuer and the audience, the server takes only the tokens issued for it:

fennec-server --file data.fennec --http 0.0.0.0:8080 --jwt-keys jwks.json --policy policy.txt \
         --jwt-issuer https://acme.us.auth0.com/ --jwt-audience https://api.example.com
  • --jwt-issuer <iss>: the token's iss must be one of those given, compared as written. Copy it from the issuer of the provider's /.well-known/openid-configuration: Auth0's ends in /, Cloudflare Access's does not.
  • --jwt-audience <aud>: the token's aud, a text or a list, must hold one of those given; a token with no aud is refused.
  • --jwt-client <id>: the token's azp must be one of those given or, where it names no azp, its client_id. Cognito's access tokens carry the app client's id in client_id, and an aud only when the app asked for a token bound to a resource server. Clerk's session tokens name the page's origin in azp, and leave it out where the request carried no Origin: under --jwt-client such a token is refused. A provider naming its client otherwise, such as Okta's cid, is pinned in a rule, where owner = $jwt.sub and $jwt.cid = "0oa1example", which applies to no token lacking the claim or naming another.

Each flag is repeatable, any one of its values taken, and each is asked of every token on every route — /query, REST, /batch, a subscription, MCP, /_whoami — after its signature and before its rules. The lists are independent, not pairs: given two issuers and two audiences, the server takes either issuer with either audience. Where each provider must keep to its own, pin the pair in the rules: and $jwt.iss = "https://a.example/" and "api-a" in $jwt.aud. A token refused is answered 401 naming the check, {"error":"the token names no audience (aud) this server takes"}, never the value the token holds, and the audit log's refused line names it in its reason. --mint-token stamps the first issuer, audience and client given on claims naming none, so the server takes the tokens it mints. Told none of them, the server takes any token its keys sign, as it always did; with --jwt-keys it says so on stderr as it starts. Every --jwt-* flag but the keys' is refused at the start where no --jwt-secret or --jwt-keys is given. Behind fennec-shard the nodes check them; the router holds no keys and forwards the token as it came.

Where the issuer and the audience are required, and where they are not enough. Firebase signs every project's ID tokens with the same keys: without --jwt-issuer https://securetoken.google.com/<project id> and --jwt-audience <project id>, a token from anyone's project, whose claims its owner writes, is taken here. Some issuers let whoever asks for a token name its audience: Google's identity tokens (https://accounts.google.com, any account's, through gcloud auth print-identity-token --audiences), GitHub Actions' tokens (https://token.actions.githubusercontent.com, any workflow's, through core.getIDToken(audience)) and a Kubernetes cluster's projected service account tokens, whose pod names the audience. There the issuer and the audience say only that some account of that issuer asked for a token for this database: the rules must pin whose, by sub, azp or repository: deploys write where $jwt.repository = "acme/deploy".

Provider--jwt-issuerand
Auth0https://<your Auth0 domain>/, the tenant's or its custom domain, its / and all--jwt-audience the API's identifier, which an access token's aud lists; --jwt-client the application's client id
Clerkthe Frontend API URL: https://clerk.<your domain> in production, https://<slug>.clerk.accounts.dev in development--jwt-client each origin the app is served from: a session token names it in azp, where the request had an Origin, and carries no aud
Supabase Authhttps://<project ref>.supabase.co/auth/v1--jwt-audience authenticated, every project's alike: the issuer is what sets projects apart. An anonymous sign-in is authenticated too, with is_anonymous true: to keep those out, each rule adds and $jwt.is_anonymous = false
Amazon Cognitohttps://cognito-idp.<region>.amazonaws.com/<user pool id>, or on the updated issuer https://issuer-cognito-idp.<region>.amazonaws.com/<user pool id>Access tokens: --jwt-client the app client's id (or, for a token bound to a resource server, --jwt-audience its identifier). ID tokens: --jwt-audience the app client's id
Cloudflare Accesshttps://<team>.cloudflareaccess.com--jwt-audience the application's AUD tag: the team's keys sign for every one of its applications
Firebase Authhttps://securetoken.google.com/<project id>, required--jwt-audience the project id, required: the keys are every project's

A provider that names a user's roles in a claim of its own is read with --jwt-role-claim: with --jwt-role-claim cognito:groups a rule for editors applies to a token whose cognito:groups lists editors, and role is then a claim like any other. Its other claims go in a policy by their names, quoted where they hold more than letters, digits and _ (Claim names).