# A public API: API keys and tokens

What a product with a public API needs at its door: keys its people make
and take back, short tokens a back end signs and others check, the public
keys at `/.well-known/jwks.json`, turned over on a schedule; and a
`requires` that says which scope a call needs. The keys and tokens are the
back end's own (`auth.…`, [back-end.md](back-end.md#signing-in)); the
[jwt extension](../extensions/jwt/README.md) is the routes and fns around
them. Back to the [map](README.md).

```text
use "pkg:jwt/jwt.mote"

// What a key may be given here.
fn jwtScopes(user: string): string[] = ["orders:read", "orders:write"]

server route GET "/api/orders"(req) requires scope("orders:read")
  let me = auth.me()?
  return {json: (Order.find({owner: me?.id ?? "-"})?).map(o => o.item)}

server fn refund(order: string): bool requires scope("orders:write") && apiCall
  …
```

```sh
curl -H "Authorization: Bearer mk_3f9c0a1b2c3d_…" https://shop.example/api/orders
```

## Who a bearer is

A call that comes with `Authorization: Bearer <an API key or a token>` is
that key's or token's person, with its scopes, **only where its `requires`
names `scope(…)` or `apiCall`**. Everywhere else a bearer is nobody: a key
made for the API is not a way into the calls the app's own pages make
(`changePassword`, anything that says only `requires signedIn`). A request
with the session's cookie is the session's, bearer or not.

| In `requires` | True for |
|---|---|
| `scope("orders:read")` | A session (its person has every scope of their own), or a key or token that holds that scope (or `*`). |
| `apiCall` | A call that came with a key or a token, not a session. |
| `secondFactor(10)` | A session that showed a second factor in the last ten minutes; never a bearer ([second-factor.md](second-factor.md)). |

They join with `&&`, `||` and `!` as any test does, are asked at the door in
its order (a bearer that is no key or token is nobody: `401`; one without
the scope: `403`), and are not for a `rule` or a model's line (`H295`): they
are about the call, and a row is read with none. `auth.bearer()` in the fn
says how it came: `{key, token, scopes}`, or none for a session.

## API keys

| | |
|---|---|
| `auth.keyMake(userId, {name, scopes, days})` | A new key, `{id, key, prefix, name, scopes, made, last, until}`. `key` is the whole of it, `mk_<12 hex>_<64 hex>`, **and is never had again**: only its SHA-256 is kept. Show it once. |
| `auth.keys(userId)` | Their keys in this app, newest first: everything but the secret (`prefix` is what a list shows). `last` is when it was last used, to the minute. |
| `auth.keyRevoke(userId, id)` | The key is no good from the next call on. |

A key is this app's (several apps at [shared accounts](back-end.md#accounts-several-apps-share)
each have their own); its person must still have their account. A key
compares in constant time, and a key's secret is never in the log.

## Tokens this back end signs

| | |
|---|---|
| `auth.token(userId, {scopes, minutes, aud})` | An ES256 token: `iss` (`MOTE_TOKEN_ISSUER`, else `mote:<app>`), `sub` (their id), `aud` (this app unless said), `scope` (with spaces), `iat`, `exp` (60 minutes unless said, a day at most), `jti`. Nothing is kept of it: it cannot be taken back, only end. What must be taken back at once is a key. |
| `auth.jwks()` | `{keys}`: the public keys tokens are checked with, the one signing now first. |
| `auth.rotateKeys()` | A new key signs from now; the old one still checks for two days, then goes. |

The signing keys are made the first time and kept in the accounts'
database (`mote_auth.sqlite`, table `tokenkey`). A bearer token is checked
against them alone: its alg must be ES256 (so `none`, and an HS256 made
with the public key as its secret, are nobody), its `iss` and `aud` this
back end's, its times good (30 seconds' leeway).

## The jwt extension

| | |
|---|---|
| `GET /.well-known/jwks.json` | `auth.jwks()`, kept an hour by whoever reads it. |
| `server every` hour | Turns the keys over every `JWT_ROTATE_DAYS` days (30 unset; 0: never by itself). |
| `jwtKeys()`, `jwtKeyMake(name, scopes, days)`, `jwtKeyRevoke(id)` | `server fn`s for someone signed in, over their own keys. A scope must be one `jwtScopes(user)` gives (unsaid: none); someone with a second factor shows it first; fifty keys at most. |
| `POST /api/token` | With a key as the bearer and `{scopes}`: a token of fifteen minutes with those of the key's scopes, `{token, expires, scopes}`. For a client that would rather not send its key each time. |
| `jwtMake(key, claims, alg, minutes, kid)`, `jwtCheck(token, keys, iss, aud, algs)` | A token for some other party (a private key, or `{secret}` for HS256), with `iat`, `exp` and `jti` put in; another party's token checked by issuer, audience and alg. Over [`crypto.jwt`](data.md#signatures-with-a-key-pair). |

## Tested

`tests/all.sh real_identity_api`: a key and a token at a route and at
`server fn`s, a key's write without the scope, `apiCall` by a session, a
page's call with a key and no session (nobody), a key with its secret
changed, one nobody made, a token for a token, the token checked by Node
with the published key, `alg: none`, HS256 under the public key, claims
changed, a stranger's key with and without its own `kid`, rotation, a key
taken back, and no key's secret in the log. `real_identity_vectors` checks
`crypto.jwt.sign` and `verify` for every alg against RFC 7515 A.1 (HS256)
and A.3, RFC 8037 and keys OpenSSL made.

Source: `runtime/server/auth.mote` (keys, tokens, part `AUB` for the
bearer), `runtime/server/guard.mote` (`scope`, `apiCall`), `compiler/src/guard.rs`,
`extensions/jwt/jwt.mote`.
