> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sailresearch.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Egress policy reference

> Every rule Sail applies to an egress policy document, and exactly what each entry allows

This page is the complete reference for the egress policy document. Read
[Egress policy](https://docs.sailresearch.com/sailboxes-egress-policy.md) first for what a policy is and how
to set one.

## Entries

Each entry in `allowlist` or `blocked` is one of:

* A hostname, such as `api.example.com`.
* A `*.` wildcard hostname. `*.example.com` matches every host below it at
  any depth, such as `api.example.com` and `a.b.example.com`. It does not
  match `example.com` itself.
* An IPv4 address, such as `203.0.113.7`.
* An IPv4 range in CIDR form, such as `203.0.113.0/24`. The range must start
  at its first address (`1.2.3.0/24`, not `1.2.3.5/24`).

Each list follows these rules:

* At most 128 entries. An empty `allowlist` means no egress; an empty
  `blocked` list is the same as leaving it out.
* An entry names a destination without a port. An allowed destination is
  reachable on every port, and an entry with a port is rejected.
* IPv6 entries are rejected, because a Sailbox does not reach the internet
  over IPv6.
* An address no Sailbox could ever reach, such as `127.0.0.1` or
  `169.254.0.0/16`, is rejected.
* A private range such as `10.0.0.0/8` is accepted but allows nothing,
  because a Sailbox cannot reach private addresses.
* Entries are stored lowercased, without a trailing dot or duplicates.

## What an entry allows

* A hostname entry allows connections that name the host, which HTTPS and
  plain HTTP do. It also allows a connection that names no host, such as SSH
  or a database connection, when one of the Sailbox's most recent name
  lookups resolved that hostname to the destination address. The remembered
  lookups stay with the Sailbox's memory through sleep, pauses, checkpoints,
  and forks. Resolve a name right before connecting.
* An address the Sailbox never resolved, such as one read from a config
  file, is reachable only through an address or range entry.
* Name resolution follows the allowlist. A name no hostname or wildcard entry
  covers does not resolve, so an allowlist of only addresses and ranges
  resolves nothing but Sail's own API host.
* A TLS connection that hides the server name with Encrypted Client Hello is
  closed under an allowlist. Turn that feature off in the client, or add the
  server's address to the allowlist.

Sail resolves an allowed hostname itself and connects to the result, so an
entry in the Sailbox's `/etc/hosts` cannot redirect the connection. Sail
checks only the name a connection announces, so an allowed server that also
serves other sites, as a shared CDN does, makes those sites reachable too.

Under an allowlist or a blocked entry, a connection the policy does not allow
opens and is then closed by Sail, so a program sees the failure on its first
read or write. Under no network the connection is refused before it opens.

## No egress and no network

* `{"allowlist": []}` is no egress. The Sailbox reaches nothing but Sail's
  own API host (below), and no other name resolves. Inbound connections are
  unaffected: exposed ports and SSH keep working, and the policy may be set
  on a Sailbox that exposes them. `blocked` and `rules` are rejected beside
  it, since nothing is left to block and no request is sent for a rule to
  act on.
* `{"no_network": true}` is no network. The Sailbox has no outbound
  connections, no name lookups, and no exposed ports or SSH. Exposing a port
  or enabling SSH is rejected, and the document cannot be set on a Sailbox
  that already exposes one. No other field may be set beside it; a document
  that tries is rejected, naming the field. Running commands, the shell, and
  mounted volumes still work.
* Sail's own API host, `sailbox-api.sailresearch.com`, stays reachable under
  no egress and under every allowlist, so a Sailbox can always call Sail
  about itself, for example to [`reboot`](https://docs.sailresearch.com/sailbox-sdk#reboot). Only no
  network removes it, and no [rule](#rules) applies to it.
* Setting either on a running Sailbox affects connections opened afterwards.
  Under no network, the connections the Sailbox already has open stall
  without closing and resume if a later policy restores network access.

## Blocked

`blocked` uses the same [entry forms](#entries) as `allowlist`, and an entry
only ever removes access. Every entry must be narrower than what covers it.

| Document | Accepted |
| - | - |
| With an allowlist | A hostname under a `*.` wildcard in the allowlist; an address or range inside a range in the allowlist. |
| No allowlist | Any address or range. |

Anything else is rejected, naming the entry: a wildcard, an entry that also
appears in the allowlist, a hostname on a document without an allowlist, and
any entry beside an empty allowlist or `no_network`.

A blocked entry cannot remove Sail's own API host,
`sailbox-api.sailresearch.com`: an entry that names it is rejected, and a
range that covers its address does not apply to it.

A hostname can be blocked only under an allowlist: a blocked name takes
effect on connections that name their host, and only an allowlist makes every
connection to a hostname do so. Without an allowlist, block the address or
range instead.

### What a blocked entry does

* A blocked hostname does not resolve, and a connection that announces it
  is refused. Other hosts under the wildcard connect normally. Sail checks
  the name a connection announces when it opens, so a server the blocked
  name shares with an allowed name or address stays reachable through that
  name or address; block the address to keep it off limits.
* A blocked address or range closes any connection to it, whether the
  Sailbox chose the address itself or an allowed hostname resolved to it.

## Rules

`rules` maps a host to an ordered list of rules for the HTTPS requests the
Sailbox sends to that host. Sail picks the most specific host entry for a
request, then the first rule under it that matches, and applies that rule. If
nothing matches, the request goes out unchanged. Rules act on HTTPS only;
plain HTTP and other traffic pass through untouched.

### Hosts

* Write a bare hostname: no `https://`, port, or path.
* `api.example.com` matches exactly that host. `*.example.com` matches every
  host below it at any depth, never `example.com` itself. `*` matches every
  host not named elsewhere. Sail picks an exact entry first, then the nearest
  wildcard (`*.api.example.com` before `*.example.com`), then `*`.
* No rule applies to Sail's own API host, `sailbox-api.sailresearch.com`, not
  even under `*`. A Sailbox's requests to Sail about itself go out unchanged.
* Use an exact host whenever a rule adds a credential: a wildcard sends the
  credential to every host it matches.

### Rules and the allowlist

* A rule does not make its host reachable. When the document has an
  `allowlist`, every host under `rules` other than `*`, and every host a
  rule forwards to, must be covered by the allowlist: an exact host by the
  same entry or by a wildcard that matches it, and a wildcard by the same
  wildcard entry or by a wildcard above it.
* No rules host or forward host may be a blocked hostname.
* A document that breaks either rule is rejected, naming the host.

### Matching

* Leave `match` out to cover every request to the host; such a rule must be
  last in its list.
* `method` is case-sensitive, so write `GET`; give one method or a list.
* `path`, `headers`, and `query` values accept a plain string or
  `{"equals": "..."}` for an exact match, `{"prefix": "..."}`, or
  `{"one_of": [...]}`.
* A header or query condition can also assert `"present": false`.
* Request bodies cannot be matched.
* A request to a host with rules is answered with status 400 and not sent
  on when its path contains a `.` or `..` segment, such as
  `/v1/../admin`. Encoded forms like `/v1/%2e%2e/admin` count too. The
  destination host, such as `api.example.com`, reads `/v1/../admin` as
  `/admin`. A rule matching the prefix `/v1/` would otherwise add its
  credential to a request the destination treats as `/admin`. Clients normally remove these segments before sending, so
  ordinary requests are unaffected.

### Actions

What a rule does is exactly one of:

| Key | What it does |
| - | - |
| `request` | `set`, `add`, or `remove` headers and query parameters, `set` the path or [body fields](#request-bodies), or [`replace`](#env) a placeholder with its secret. `${secrets.NAME}` works inside every `set` field but `path`. |
| `forward` | Send the request to another HTTPS `host` (and optional `port`). Combine with `request` to add a credential for that host. |
| `respond` | Answer the request yourself with `status`, `headers`, and `body`. The request is not sent on. Cannot be combined with the other two. |

* A `respond` rule answers requests and leaves the host reachable. Sail
  still connects to the host before the rule answers, so a `respond` rule
  cannot stand in for a host that is down or does not exist. To block a host,
  leave it out of the allowlist or add it to `blocked`.
* A `forward` host must be exact. If Sail cannot reach it, the request
  fails; nothing is sent to the original host.
* `request.set.headers`, `request.set.query`, `request.set.json`, and
  `request.set.form` are templates: every `$` in them must be part of
  `${secrets.NAME}` or `$$` (a literal dollar sign). In every other string
  `$` is plain text, except that an unescaped `${` is rejected because it
  looks like an unresolved reference.
* Only a saved policy may reference a secret, and the secret must exist
  before the policy is saved. [Credential injection](https://docs.sailresearch.com/sailboxes-credentials)
  covers storing and rotating secrets.
* Responses cannot be changed.
* When Sail cannot apply a rule's `request` change, for example because a
  secret it names was deleted or a body edit does not fit the request, the
  Sailbox gets status 502 and the request is not sent.

### Request bodies

`request.set.json` sets string values in a JSON request body. Each key is a
[JSON Pointer](https://www.rfc-editor.org/rfc/rfc6901) such as `/auth/token`
(write `~1` for a `/` inside a name and `~0` for a `~`). Missing parent
objects are created, so `/auth/token` works on the body `{}`. A pointer may
name an existing array element by index, but cannot add one.

```json theme={null}
{ "request": { "set": { "json": { "/api_key": "${secrets.EXAMPLE_KEY}" } } } }
```

`request.set.form` sets fields of a form-encoded body
(`application/x-www-form-urlencoded`), taking a string or a list of strings
like `set.query`. Other fields in the body are sent as they came.

* A JSON edit needs a request with a JSON body: Content-Type
  `application/json` or a type ending in `+json`. A form edit needs Content-Type
  `application/x-www-form-urlencoded`.
* The body must be at most 8 MiB and not compressed: no Content-Encoding
  other than `identity`.
* A request that does not meet these gets status 502 and is not sent. It
  never goes out without the edit.
* One rule edits a JSON body or a form body, not both. No pointer may sit
  inside another one in the same rule.
* Sail re-encodes an edited JSON body: the values are unchanged, but
  whitespace and key order may differ from what the Sailbox sent.

### `missing_alpn`

* Most clients announce their HTTP version during the TLS handshake (ALPN),
  and a rule applies to the version announced.
* A client that announces none on port 443 is handled as HTTP/1.1, so the
  host's rules apply. WebSocket libraries often connect this way. A client
  that announces none and then speaks something other than HTTP on port 443
  gets an HTTP 400.
* On any other port, such a connection passes through untouched and no rule
  runs, unless a top-level `missing_alpn` map names the exact host and the
  version to assume: `"missing_alpn": {"api.legacy.example": "http/1.1"}`.
* The host must have rules, and `"http/1.1"` is the only value.

## Environment variables

`env` gives every command in the Sailbox environment variables that hold a
**placeholder** for a secret, not the secret itself. Code inside uses the
variable as it would the real key. A `request.replace` entry names the request
fields where the placeholder may appear, and Sail sends the secret in its
place. Only a saved policy may set `env`.

```json theme={null}
{
  "env": { "OPENAI_API_KEY": "OPENAI_KEY" },
  "rules": {
    "api.openai.com": [
      {
        "request": {
          "replace": { "headers": { "authorization": "OPENAI_KEY" } }
        }
      }
    ]
  }
}
```

With this policy, `$OPENAI_API_KEY` inside the Sailbox reads like
`sail_ph_3kTq9...`. A request to `api.openai.com` with the header
`Authorization: Bearer $OPENAI_API_KEY` goes out with the real key.

* Each `env` value is a secret name, or
  `{"secret": "NAME", "placeholder_prefix": "sk-"}` to choose the text the
  placeholder starts with, for a client that checks the format of a key. The
  default prefix is `sail_ph_`. Every entry for one secret must use the same
  prefix.
* A placeholder is 32 characters, prefix included. It is the same in every
  Sailbox in your organization, and changes only if you change its prefix.
* Variable names start with a letter or `_` and use letters, digits, and `_`.
  Names starting with `SAILBOX_` are reserved.
* Commands get the variables whether they run through `exec` or a login
  shell. A variable you pass to a command yourself keeps your value.
* Setting the policy on a running Sailbox updates the variables for commands
  started after the call. Processes already running keep the environment they
  started with.

`request.replace` maps a field to the secret whose placeholder it may carry,
under `headers`, `query`, `json` (JSON Pointers into the body, as in
[Request bodies](#request-bodies)), or `form`.

* A field is replaced when its value is exactly the placeholder. A header
  value may also be a scheme followed by the placeholder, such as
  `Bearer <placeholder>`; the scheme is kept.
* A field that does not hold the placeholder is sent as it came.
* On a host with rules or [TLS settings](#tls-config), a request that carries
  a placeholder anywhere else gets status 502 and is not sent. Sail checks
  every header, the path, and the query. It checks the body only when a rule
  edits or replaces a body field, and then a placeholder in any other body
  field is refused. The check catches a placeholder sent where the policy does
  not swap it, which would otherwise reach the server in place of the secret.
* Every `env` secret must appear in some `request.replace`, and every
  `request.replace` secret must have an `env` entry.
* `replace` needs a named host. It cannot be used under `*`, where code in
  the Sailbox would choose which host gets the secret.

## Identity tokens

`oidc_identity_tokens` gives the Sailbox OpenID Connect identity tokens that
Sail signs. Each entry gives the token's audience and the file that holds
the token:

```json theme={null}
{
  "oidc_identity_tokens": [
    { "audience": "sts.amazonaws.com", "path": "/run/sailbox/oidc/aws" }
  ]
}
```

* `audience` is the token's `aud` claim: 1 to 512 printable characters with
  no spaces.
* `path` must be a file directly in `/run/sailbox/oidc/`, named with 1 to 64
  letters, digits, `.`, `_`, or `-`, starting with a letter or digit. No two
  entries may share a path. Sail rewrites the file before the token expires.
* A policy has at most 10 entries.
* Only a saved policy may set `oidc_identity_tokens`.

See [Identity tokens](https://docs.sailresearch.com/sailboxes-identity-tokens) for what a token says and
how to make a cloud account trust it.

## TLS settings

`tls_config` sets how Sail connects to a host over HTTPS: which certificate
authorities it trusts, and the client certificate it presents. Hosts are
written as under [`rules`](#hosts), and Sail picks the most specific entry the
same way.

```json theme={null}
{
  "tls_config": {
    "mtls.example.com": {
      "trusted_cas": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n",
      "client_certificate": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n",
      "client_key": "${secrets.DB_CLIENT_KEY}"
    }
  }
}
```

| Key | What it does |
| - | - |
| `trusted_cas` | PEM CA certificates. Sail trusts only these for the host, in place of the public CAs. |
| `client_certificate` | A PEM client certificate, leaf first, followed by any intermediates. Sail presents it when the host asks for one. |
| `client_key` | `${secrets.NAME}`, the secret holding the client certificate's PEM private key. Required with `client_certificate`. |

* Each entry needs `trusted_cas`, `client_certificate`, or both.
* The private key is always a secret, never written into the policy, so a
  policy with a client certificate must be saved.
* A host that asks for a client certificate when its entry has none fails the
  connection. So does a host whose certificate the entry's `trusted_cas` do
  not cover.
* Like `rules`, `tls_config` applies to HTTPS only and does not make a host
  reachable. Its hosts must be covered by the allowlist the same way, as
  described in [Rules and the allowlist](#rules-and-the-allowlist).
* The settings also apply when a `forward` rule sends a request to the host.

## Limits

* `allowlist` and `blocked` hold at most 128 entries each.
* `rules` names at most 100 hosts and holds at most 100 rules in total.
* `tls_config` names at most 100 hosts.
* `env` holds at most 100 variables.
* A request body a rule edits is at most 8 MiB.
* A document is at most 64 KiB.
* A saved policy's name is at most 128 characters with no control characters.

## Errors

* An invalid document fails the call with `InvalidArgumentError`
  (`SailError::InvalidArgument` in Rust), naming the part to fix. Nothing is
  created or changed.
* Setting `no_network` on a Sailbox that exposes ports or SSH fails with
  `ApiError` (`SailError::Api` in Rust).
* Setting a policy with `env` on a Sailbox created before `env` existed
  fails and asks you to upgrade the Sailbox first.
* Deleting a saved policy that a Sailbox still uses fails with
  `EgressPolicyInUseError` (`SailError::Api` in Rust).
