# Security

> API keys and roles, tenants, console sessions, single sign-on, request identity, TLS and outbound request policy for self-hosted cairnflow.

Source: https://cairnflow.dev/docs/self-hosting/security

## Authentication is on by default

Every route except `GET /health` requires `Authorization: Bearer <key>`. A missing or wrong key
gets `401`; a key whose role does not allow the route gets `403`.

A node with no key configured refuses to start. `--no-auth` turns keys off and treats every request
as `cluster-admin` of tenant `default`: use it on a development machine only.

Wrong keys are rate-limited per client IP (taken from `X-Forwarded-For` only behind `--trust-proxy`):
a burst of 100 failed attempts, then one per second. Past that, a wrong key gets
`429 auth_failures_limited` with `Retry-After`. A correct key is never limited, so clients behind
the same NAT as a prober are not locked out.

## Keys that live in the environment

| Variable | Gives |
|---|---|
| `CAIRNFLOW_ADMIN_KEY` | The bootstrap key: role `cluster-admin`, tenant `default`. Never written anywhere. |
| `CAIRNFLOW_ADMIN_KEY_SHA256` | The same, but the node only holds the SHA-256 of the key; the key itself stays in your break-glass store. |
| `CAIRNFLOW_PROVISION_KEY_SHA256` | A `provision` key for tenant `default`, by hash. Enough for a node to start without any `cluster-admin` key. |
| `CAIRNFLOW_METRICS_KEY` | A token that can call `GET /metrics` and nothing else, for Prometheus. |

Generate keys with enough randomness, and hash them without a trailing newline:

```sh
KEY="cf_$(openssl rand -hex 24)"
printf %s "$KEY" | sha256sum
```

The node refuses to start if `CAIRNFLOW_ADMIN_KEY` is shorter than 32 bytes, if a hash is not 64
hex digits, if both `CAIRNFLOW_ADMIN_KEY` and its `_SHA256` variant are set, if the metrics token is
shorter than 32 bytes, or if two roles share the same secret. These keys cannot be revoked through the API: to rotate one, set the new value on every
node and restart the nodes one by one.

## Roles

Each key belongs to one **tenant** and has one **role**.

| Role | Can |
|---|---|
| `invoke` | Call handlers and workflows, resolve promises and awakeables, send signals, cooperative cancel (`?mode=signal`), read an invocation by id, attach to it, read its user streams and artifacts, manage schedules of its tenant. |
| `view` | Read everything in its tenant: invocations, journals, logs and spans, deployments, services, archive, stats, metering, SQL queries. Cannot call or change anything. |
| `admin` | Everything `view` and `invoke` can do, plus: register and remove deployments, move service revisions, hard cancel, purge, resume, restart, migrate, batch operations. |
| `provision` | Control-plane work without access to run data: create and revoke `invoke`, `view` and `admin` keys, tenant settings and state, SSO configuration, cluster version. Cannot read invocations, journals, state, queries, archive, artifacts or streams, and cannot sign in to the console. |
| `cluster-admin` | Everything, across all tenants: flow-control rules, range split and merge, `/cluster`, `/metrics`, all `/admin` routes, and `?tenant=` on tenant routes. |
| `metrics` | `GET /metrics` only. Exists only through `CAIRNFLOW_METRICS_KEY`. |

A `provision` key can grant and revoke only `invoke`, `view` and `admin` keys, so a leaked
`provision` key cannot mint a peer or a `cluster-admin` key.

:::note
On a cluster first created by an older binary, `view` and `provision` keys stored in the bucket are
behind a one-way gate. Once every node runs the new binary, enable it with
`cairn-ctl cluster enable-key-roles --apply`. Until then, creating such a key returns
`409 key_roles_disabled`. Clusters created by a current binary have it enabled.
:::

## Managing keys

```sh
cairn keys create default invoke      # prints the secret once
cairn keys                            # lists stored keys, never secrets
cairn keys rm <id>                    # revokes
cairn keys check <id>                 # is the key still accepted anywhere?
```

The secret (`cf_...`) appears only in the response that creates the key; the bucket keeps its
SHA-256. The same operations are available at `/admin/keys` (see
[HTTP API](/docs/reference/http-api#keys-identity-and-tenant)).

Revocation is synchronous. `cairn keys rm` returns `204` only when every live node has confirmed it
stopped accepting the key. Nodes that did not confirm in time are listed in a `202` response with
`pending`; they pick up the change within one `--deploy-refresh-ms` interval. After a `202`, or a
revocation whose outcome you did not see, ask any node with `cairn keys check <id>`
(`GET /admin/keys/{id}/revocation`): `confirmed: true` means no live node accepts the key. An id
that is not in the key book, including a typo, also reports `revoked: true`, so check the id with
`cairn keys` first.

A node that cannot confirm its key book is fresh for more than two refresh intervals answers `503`
to requests authenticated with stored keys until it can. The bootstrap key keeps working.

`cairn-ctl keys create <tenant> <role> --apply` writes a key directly to the bucket, without a
running node, for example to bootstrap the first `provision` key.

## Tenants

The tenant of a request is the tenant of its key, never a path segment or a header. Service names,
state, promises, idempotency keys, workflow ids and virtual-object keys are all scoped by tenant:
`Cart/x` in two tenants is two objects. Another tenant's invocation answers `404`, as if it did not
exist. A self-hosted node with one team typically uses only tenant `default`.

## Console sessions

The web console is served at `/ui`. Its static files need no key; all data goes through the API.
The browser never stores your API key: the console exchanges it once at `POST /ui/session` for an
`HttpOnly`, `SameSite=Strict` cookie that lasts 12 hours, without sliding renewal. The cookie
carries the key id, not the key, and every request looks the key id up again, so revoking a key ends
its console sessions too. Changing `CAIRNFLOW_ADMIN_KEY` ends every bootstrap session.

Unsafe requests made with the cookie (`POST`, `PUT`, `DELETE`) must come from the same origin
(`Sec-Fetch-Site: same-origin`, or a matching `Origin`), otherwise `403`. Requests with an
`Authorization` header ignore the cookie.

The cookie gets the `Secure` attribute by default unless `--host` is a loopback address; control it
with `--ui-cookie-secure on|off`.

Signing out revokes the session on the server, for key sessions and SSO sessions alike: only that
session ends, and other sessions of the same person or key keep working. Other nodes see the
revocation within a few seconds. Each tenant can hold at most 200 signed-out sessions that have not
expired yet; past that, signing out answers `429` (the browser still drops the cookie, but the
session lives until it expires; revoke the key to end it at once). Sign-outs are also rate-limited
per client IP and per tenant. Cookies issued by binaries from before this behaviour are refused
after an upgrade, so console users sign in again once.

## Single sign-on (OIDC)

A node can be an OpenID Connect relying party for one issuer (Keycloak, Authentik, Okta and
similar). There are no flags: the configuration is stored in the bucket and set through the API
with a `provision` or `cluster-admin` key. Without it, the console offers key sign-in only, which
always remains available.

```sh
curl -X PUT -H "Authorization: Bearer $KEY" https://cairn.example.com/admin/oidc \
  -d '{"issuer":"https://idp.example.com/realms/ops","sessionTtlMs":3600000,"displayName":"Keycloak"}'

# one client per hostname: requests to that hostname sign in to that tenant
curl -X PUT -H "Authorization: Bearer $KEY" https://cairn.example.com/admin/oidc/clients/cairn-prod \
  -d '{"hostname":"cairn.example.com","tenant":"default","maxRole":"admin"}'
```

At the identity provider:

- a **public** client (no secret) with PKCE `S256`;
- redirect URI `https://<hostname>/ui/login/oidc/callback` (adjust for `--ui-base-path`);
- scopes `openid email profile`;
- an ID token signed with `RS256`, `PS256`, `ES256` or `EdDSA`, carrying `sub` and a `cairn_role`
  claim of `admin`, `view` or `invoke`. A missing or unknown role is refused.

The tenant comes from the client configuration, not from a claim, and the role is capped at the
client's `maxRole`. `cluster-admin` is never available through SSO. Session TTL defaults to one
hour (60 seconds to 24 hours).

The SSO cookie uses the `__Host-` prefix, which browsers accept only over HTTPS or on `localhost`.
Behind a TLS proxy, set `--ui-cookie-secure on` or `--trust-proxy` so the node knows requests
arrive over HTTPS. Removing a client, changing the issuer or lowering `maxRole` takes effect on the
next request. To end one person's sessions, `POST /admin/oidc/revoked` with
`{"client", "sub", "beforeMs"}`.

## Request identity: signed calls to your services

Set `CAIRNFLOW_IDENTITY_MASTER` (32 bytes or more, the same on every node, kept outside the bucket)
and every request the runtime sends to your services carries a short-lived signed token, derived
per tenant. Get the public key with `GET /identity` and verify in the SDK:

```ts
await serve({ services: [greeter], identityKeys: ["publickeyv1_..."] });
```

Requests without a valid signature, for another path, expired, or for another invocation get `401`
and the handler does not run. Your service's clock must be within 60 seconds of the nodes.

`--deploy-require-identity` makes `POST /deployments` refuse services that do not verify
signatures (`400 identity_required`).

Rotate a tenant's key in four steps, each recorded in the bucket's audit trail:

1. `cairn-ctl identity publish <tenant> --apply`: publishes a new key; signing still uses the old one.
2. Add the new key id to `identityKeys` and deploy your service.
3. `cairn-ctl identity activate <tenant> --apply`: signing switches to the new key.
4. `cairn-ctl identity retire <tenant> --apply`, then remove the old key id from your service.

Changing the master secret changes every tenant's key at once.

## TLS

Cairnflow has no built-in TLS. Put a TLS-terminating proxy or load balancer in front of the client
port; without it, API keys travel in clear text. Tell the node which proxies to trust with
`--trust-proxy`, so it can use `X-Forwarded-*` for origin checks, the `Secure` cookie flag and
per-IP sign-in limits.

The internal port is signed but not encrypted. Keep traffic between nodes on a private network. A
captured internal request could be replayed within 60 seconds; internal requests are idempotent.

## Outbound requests

Registering a deployment makes the node send requests to a URL chosen by the caller. If people you
do not fully trust can hold `admin` keys, restrict where those requests can go:

```sh
cairnflow ... --egress-deny-private --egress-deny-cidr 203.0.113.10/32
```

`--egress-deny-private` blocks loopback, private networks, link-local and cloud metadata
addresses, CGNAT, other special ranges and IPv6 addresses that embed IPv4. Checks apply to the URL,
to every address DNS returns and to the actual peer of the socket. Use `--egress-deny-cidr` for the
public address of your own load balancer, and `--egress-allow-cidr` for a private network you do
want to reach. A refused endpoint gets `400 egress_denied`. These requests never follow redirects
and ignore `HTTP_PROXY` and `HTTPS_PROXY`.

## SQL queries run in a child process

SQL sent to `POST /query` (and the console's SQL screen) is planned without memory or time limits,
so a crafted query could exhaust a node. By default (`--query-isolation auto`) each query runs in a
separate `cairn-query-worker` process when that binary sits next to `cairnflow`; without it, queries
run inside the node and startup logs a warning. Ship both binaries together, or point at the worker
with `--query-worker PATH`.

The child gets no cluster secret, environment variables, store credentials or direct access to
ranges: the node serves its reads and enforces the tenant, the ranges and the read budget itself.
The child has its own memory limit (`--query-worker-memory-mb`, default 512), no file writes and a
small file-descriptor limit; on Linux it is also non-dumpable and runs under a seccomp filter that
blocks the network, starting programs, signalling other processes, tracing and opening files. On
macOS only the resource limits apply. A query over its memory limit or deadline kills the child and
gets `422 query_budget`; the node is unaffected. The child still runs as the same user as the node.

`--query-isolation process` requires the worker and refuses to start without it;
`--query-isolation inline` runs every query inside the node, for very small machines where only
trusted people hold keys.

## Hardened profile

`--profile saas` is meant for a cluster shared by tenants who do not trust each other. It mostly
turns on protections that also exist as separate flags, and refuses to start, listing everything
that is missing, when a requirement is not met:

- **Turns on:** `--egress-deny-private`, `--egress-require-https`, `--ui-cookie-secure on`,
  `--no-user-otlp`, `--deploy-require-identity`, `--deploy-https-request-response`,
  `--deploy-require-compression`, and `--query-isolation process`. On Linux it also makes the node
  process non-dumpable, so other processes of the same user, query workers included, cannot read
  its environment (cluster secret, store credentials) or trace it.
- **Sets defaults** where you gave none: `--query-worker-memory-mb 256`, `--key-rate 1000/1`,
  `--max-turns-per-tenant` at a quarter of `--max-concurrent-turns`, `--inactivity-timeout-max-ms`
  at most 15 minutes, and a default for every per-tenant resource limit a tenant's settings leave
  empty.
- **Requires** `CAIRNFLOW_CLUSTER_SECRET` (which is then never stored in the bucket),
  `CAIRNFLOW_IDENTITY_MASTER`, and at least one `--egress-deny-cidr` for the cluster's own public
  addresses.
- **Refuses** `--no-auth`, `--ui-cookie-secure off`, `--inactivity-timeout-ms 0` and
  `--query-isolation inline`.

Without the profile, the same protections can be turned on one flag at a time. If people outside
your organisation can register deployments or hold keys on your cluster, set at least
`CAIRNFLOW_CLUSTER_SECRET`, `CAIRNFLOW_IDENTITY_MASTER` with `--deploy-require-identity`, the egress
flags above, `--trust-proxy`, `--key-rate` and `--max-turns-per-tenant`.

## What to protect most

The S3 credentials are the most sensitive secret of a deployment. Anyone holding them can read the
cluster secret stored in the bucket and change journals. Give bucket credentials, and the
`cairn-ctl` tool, only to people who need them.

## Reporting a security issue

If you find a vulnerability in cairnflow, the SDK or Cairnflow Cloud, write to
[security@cairnflow.dev](mailto:security@cairnflow.dev).
