# Security model

This page lists what to protect in a Kite deployment, what each credential can
do and where it is stored, and what someone who controls a node can reach.
[Identity and access](/docs/identity/) says how RBAC decides what each
identity can do.

## What to protect

- **Edit access to the Worker.** Code that runs as the Worker can read every
  Worker secret. So anyone who can deploy to the Worker can read every Secret
  and act as the administrator. Treat this access as cluster-admin.
- **The settings file.** `~/.kite/deployments/<name>/deploy.env` contains the
  administrator token, the Cloudflare deploy token, and the audit bucket key.
- **Node hosts.** A host has the Secrets and ServiceAccount tokens of every pod
  scheduled on it.
- **The ingress namespace.** It contains a Secret with a Cloudflare API token.
  See [Ingress credentials](#ingress-credentials).

A deployment accepts only tokens that its own keys signed. A ServiceAccount
token or a node credential from one deployment does not work in any other
deployment.

## What each credential can do

### Cluster credentials

| Credential                  | Who uses it                                 | What it can do                                                                    | Where it is stored                                                 |
| --------------------------- | ------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| Administrator token         | Bootstrap and break-glass recovery          | Everything, as `system:masters`. Rotates the signing key.                         | Worker secret `KITE_ADMIN_TOKEN`, the settings file                |
| The admin user's OIDC token | A management plane                          | Everything as `system:masters`, except rotating the signing key                   | The client of the user that `KITE_OIDC_ADMIN_USER` sets            |
| Front proxy token           | A front proxy that you run                  | Set any user and groups, including `system:masters`, on a request that carries it | Worker secret `KITE_FRONT_PROXY_TOKEN`, the proxy                  |
| Shared bootstrap token      | A joining node                              | Join any node. Never expires.                                                     | Worker secret `KITE_BOOTSTRAP_TOKEN`, the settings file, each node |
| Bootstrap token             | A joining node                              | Join a node until it expires or runs out of uses                                  | Secret `bootstrap-token-<id>` in `kube-system`, the node it joined |
| Node credential             | The node agent                              | Connect as its own node, as `system:node:<name>`                                  | `/var/lib/kite/nodes/` on the node                                 |
| ServiceAccount token        | Pods                                        | What RBAC grants the account                                                      | The pod's projected volume                                         |
| Cloudflare Access assertion | Browser sign-in                             | What RBAC grants a person that Cloudflare Access authenticated                    | The person's client                                                |
| External OIDC token         | `kite login` on an OIDC cluster             | What RBAC grants a person that your OIDC issuer authenticated                     | The person's client                                                |
| Cluster-signed user token   | `kite login` on a Cloudflare Access cluster | What RBAC grants a person that Cloudflare Access signed in                        | The person's client                                                |

A node that joins with a token stores the token in `/etc/kite/node.env`.

### Cloud provider credentials

| Credential                    | What it can do                                                  | Where it is stored                                                                                                                        |
| ----------------------------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| Cloudflare provision token    | Create API tokens, use R2, read zones                           | Only the environment of `kite deploy credentials`, which deletes the token when it finishes                                               |
| Cloudflare deploy token       | Deploy Workers, manage Logpush, write DNS in the cluster's zone | The settings file                                                                                                                         |
| Audit bucket key              | Read and write the audit bucket                                 | The settings file, the Logpush job                                                                                                        |
| Ingress Cloudflare credential | Manage every tunnel in the account, and DNS in the zone         | The IngressClass Secret, and the cluster's Durable Object                                                                                 |
| Tunnel token                  | Serve one tunnel's hostnames from anywhere                      | Secret `<class>-tunnel-token`, each `cloudflared` pod                                                                                     |
| Node pool provider credential | Create and delete machines in the provider account              | A Secret, in `kube-system` by default, for a DigitalOcean token or a GCP key. None for AWS, or for GCP with workload identity federation. |

### Rotate the shared bootstrap token

Anyone who has the shared bootstrap token can join a node until you replace
it. Join nodes with `kite node add` instead, because it creates a token that
expires. To replace the shared token, delete the `KITE_BOOTSTRAP_TOKEN` line
from your settings file and run `kite deploy`. The deploy creates a new token,
writes it to the file and uploads it. See
[Back up and rotate credentials](/docs/configure/#back-up-and-rotate-credentials).
Node pool machines use neither token: they join with a provider identity
document or a one-time token.

### Ingress credentials

The ingress API token and the tunnel token are Secrets in the namespace that
the IngressClass parameters refer to. Anyone who can do any of these can read
the tokens:

- read Secrets in that namespace,
- create a pod in that namespace, or
- write the ConfigMap `<class>-tunnel-override`.

Grant those permissions only to people you trust with the Cloudflare API
token. [Expose a workload](/docs/expose/) lists the token's
permissions.

Use an API token that expires, and replace it in the Secret before it does. The
controller reads the Secret again when it changes, so the replacement needs no
other step. See [Credentials](/docs/ingress/#credentials).

## Encryption at rest

`KITE_STORAGE_KEY` encrypts every Secret, the cluster's signing key and its
refresh tokens with AES-256-GCM. `kite deploy` generates the key when the
settings file has none, and saves it there. The cluster stores other objects,
including ConfigMaps, in plaintext. When you set the key on a cluster that
already stores Secrets, the cluster encrypts them when it starts, before it
serves a request.

:::caution
Without `KITE_STORAGE_KEY`, Secrets are stored in plaintext. The key protects a
copy of the storage, not the API. Anyone whom RBAC allows to read a Secret can
still read its value.
:::

To change the key, follow [Rotate the storage key](/docs/configure/#rotate-the-storage-key).

## Pod Security

A namespace with no `pod-security.kubernetes.io/enforce` label enforces the
`baseline` level, where upstream Kubernetes enforces `privileged`. A pod that
needs access to its node runs in a namespace that you label:

```sh
kubectl label namespace <namespace> pod-security.kubernetes.io/enforce=privileged
```

`baseline` refuses a pod that sets any of these:

- a `hostPath` volume, `hostNetwork`, `hostPID` or `hostIPC`
- a privileged container, a `hostPort` or an unmasked `procMount`
- a capability outside upstream's baseline set, or a sysctl outside its
  namespaced list
- an AppArmor or seccomp profile other than `RuntimeDefault` or `Localhost`

`restricted` adds upstream's restricted controls. Upstream exempts a pod with
`hostUsers: false` from the controls on the user it runs as. Kite does not,
because the node creates no user namespace, so root in the pod is root on the
node.

When a controller's pod template breaks its namespace's level, the controller
creates no pod and its owner gets a `FailedCreate` event.

## What a compromised node can do

| The node                               | The attacker can                                                              | Until                                                                  |
| -------------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| Runs pods                              | Read the pods' Secrets, and call the API with the pods' ServiceAccount tokens | The node is removed and the tokens it took expire                      |
| Joined with the shared bootstrap token | Join more nodes with that token                                               | You [rotate the token](#rotate-the-shared-bootstrap-token)             |
| Runs a pod behind an APIService        | Act as any user on every aggregated API server                                | Five minutes after the last request for that API through the node      |
| Runs a pod behind a webhook Service    | Read each of that webhook's requests, and answer in the webhook's place       | The webhook's pod no longer runs on the node                           |
| Has its node credential                | Connect as the node                                                           | The real node reconnects twice, or 90 days after the cluster issued it |

The cluster sends an aggregated API's requests through the node, each with a
client certificate that every aggregated API server trusts. Each certificate
expires five minutes after the cluster issues it. The cluster sends a webhook
Service's requests through the node too, but calls a webhook at a URL itself,
never through a node.

:::note
On Cloudflare, every call to a webhook URL that sets `caBundle` fails, because a
Worker cannot check a certificate against a CA you supply. The webhook's
`failurePolicy` then decides the write.
:::

The attacker cannot read another node's pods or Secrets, use another node's
connection, or sign tokens.

### Remove a compromised node

A node credential is valid for 90 days, and the cluster replaces it each time
the node connects, so a stolen copy stops working after the real node
reconnects twice.

:::caution
Deleting the Node object does not lock out a stolen credential. Until the
credential expires, it can still connect, and the cluster registers the node
again.
:::

Follow [Leave and remove a node](/docs/manage-nodes/#leave-and-remove-a-node).

## Audit logs

With [audit logs](/docs/configure/#audit-logs) on, the Worker writes one
`audit.k8s.io/v1` Event at `Metadata` level for every API request, including
refused requests. It writes no Event for a user listed in
`KITE_AUDIT_OMIT_USERS`. Each Event records:

- the user and groups,
- the verb, the URI and the object,
- the source IP and the user agent,
- the response code, and the allow or forbid decision, and
- the annotations that a ValidatingAdmissionPolicy adds: its
  `auditAnnotations`, and each validation that fails under a binding with the
  `Audit` action.

No Event contains a request or response body. The Worker records an
unauthenticated request as `system:anonymous`.

:::note[Long Events]
Each Event is one line of at most 8,192 bytes. An `auditAnnotations` value
keeps its first 10,240 bytes, as in upstream Kubernetes. When an Event is
longer than a line, Kite marks it with the annotation
`audit.kiteplane.dev/reduced: "true"` and removes the user agent and the end
of the URI. Then, while the Event is still too long, it cuts the longest
annotations, drops the policies' annotations, and drops the groups. A list of
failed validations keeps its first records whole.
:::

### Controller deletes

The log also contains a `delete` Event for each object that Kite deletes on its
own, such as a Job past its `ttlSecondsAfterFinished` or an object whose owner
you deleted. The Event's user is the one that upstream Kubernetes records for
the same delete:

| Action                                                                                               | User recorded                                                     |
| ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| Delete a Job past its time to live                                                                   | `system:serviceaccount:kube-system:ttl-after-finished-controller` |
| Delete a preempted pod                                                                               | `system:kube-scheduler`                                           |
| Delete by Kite's node pool controller, ingress controller or local volume provisioner                | A user under `system:kite:`                                       |
| Change a replica count through the horizontal pod autoscaler, as an `update` of the target's `scale` | `system:serviceaccount:kube-system:horizontal-pod-autoscaler`     |

A ValidatingAdmissionPolicy decides a controller's delete as it decides
yours, and the delete's Event carries the same annotations that it adds to a
request's Event. A controller's create or update writes no Event, so a policy
that audits it records nothing.

## Who can call each endpoint

| Endpoint                                         | Who can call it                                        |
| ------------------------------------------------ | ------------------------------------------------------ |
| OIDC discovery, health checks, sign-in endpoints | Anyone                                                 |
| Node join, connect, agent download               | A bootstrap token or node credential                   |
| `/selfsubjecttoken`, `/authorize`                | A person signed in through Cloudflare Access or OIDC   |
| `selfsubjectreviews`                             | Any signed-in identity                                 |
| `/metrics`, `/metrics/slis`                      | An identity a ClusterRole grants via `nonResourceURLs` |
| Resources and discovery                          | Whoever RBAC allows                                    |
| `/node-updates`                                  | `system:masters`                                       |
| `/signingkeys`                                   | The administrator token                                |
| Any other path                                   | `system:masters`                                       |
