# ScalPanel edge

URL: https://scalws.com/docs/guide/scalpanel-edge/
Source: `docs/guide/scalpanel-edge.md` in the ScalWS repository

ScalPanel's edge is the web server on each ScalPanel node that faces the internet: it
terminates TLS, blocks addresses and countries, protects images from hotlinking, serves
the panel's website preview under a path prefix and writes one access log per website.
ScalPanel's generator (`scalpanel-agent`, its ADR-0216) writes that edge as a ScalWS
configuration, so ScalWS can take nginx's place there.

This page is the contract between the generator and ScalWS: which keys the generator may
write, what they do, and where ScalWS differs from nginx. Inside each website's container
ScalWS runs in [ScalPanel mode](https://scalws.com/docs/guide/scalpanel/) instead; that is a different setup. The
design record is [ADR-0054](https://scalws.com/docs/adr/0054-edge-features-for-scalpanel/).

## The version line

`scalwsd --version` names the edge features of the build:

```text
scalwsd 1.1.1
site-json: 1
site-json-fields: front_controller,compression,cache,runtime
edge-features: access_log affinity_key backup_members forwarded_for gzip max_upgraded networks peer_tls pools prefix_proxy read_only referer remove_cookies replica respond_file route_order sticky upstream_health
mime-table: 1
```

The `edge-features:` tokens are separated by spaces and in alphabetical order (the
`site-json-fields:` line uses commas, by an earlier decision). A token appears only once
its feature is complete; the line is printed even when it is empty. The generator writes
the tokens it needs in the header of its file
(`# edge-features needed: access_log ...`) and should refuse a ScalWS whose line lacks
one.

| Token | Keys |
|---|---|
| `access_log` | `access_log: {file, format}` on applications and routes |
| `affinity_key` | pool `hash: {by: cookie, key_file}` |
| `backup_members` | pool member `backup: true` ([load balancing](https://scalws.com/docs/guide/load-balancing/#pools-and-members)) |
| `forwarded_for` | proxy `forwarded_for: chain` or `client` |
| `gzip` | `server.compression.enabled`, `types`, `min_length` |
| `max_upgraded` | `server.security.per_ip.max_upgraded` |
| `networks` | `server.networks`, `server.geoip`, route `deny_networks` and `allow_networks` |
| `peer_tls` | listener `tls.client_ca_file` and `client_names`, pool `tls.client_cert_file` and `client_key_file` ([replicas](https://scalws.com/docs/guide/replicas/#the-node-link)) |
| `pools` | top-level `upstreams` pools, proxy `upstream: {pool}` and `backends` |
| `prefix_proxy` | proxy `rewrite_location`, `cookie.path_prefix`, `cookie.domain` |
| `read_only` | proxy `read_only` and `read_only_response` ([fencing](https://scalws.com/docs/guide/replicas/#fencing-with-read_only)) |
| `referer` | route `referer` |
| `remove_cookies` | route `request_headers.remove_cookies` |
| `replica` | `active_health`, `backends[].id`, `balance`, `retry`, `write_backend`, route `listeners` ([replicas](https://scalws.com/docs/guide/replicas/)) |
| `respond_file` | `respond` `body_file` |
| `route_order` | application `route_order: nginx` |
| `sticky` | proxy `sticky: {cookie, ttl, key_file}` ([replicas](https://scalws.com/docs/guide/replicas/#sticky-sessions)) |
| `upstream_health` | runtime `type: upstream_status` ([replicas](https://scalws.com/docs/guide/replicas/#upstream_status)) |

## Checking the generator's output

```sh
scalwsctl --config /var/lib/scalpanel/edge/gen-42/edge.yaml check
```

The generator's sample (generation 42, in `tests/integration/fixtures/scalpanel-edge`)
passes with exit status 0 when its certificates file, network files and certificates
exist. One warning depends on where the check runs: the open-file warning ("raise
LimitNOFILE") compares `max_connections` + 256 + the access log files with the soft
open-file limit of the process that runs `check`, not with scalwsd's. From a login shell
with the common limit of 1024, the sample's `max_connections: 4096` prints it, while
`scalwsd.service` runs with `LimitNOFILE=1048576` and is not affected. Run the check under
the service's limit (`ulimit -n 1048576` first, as root) or treat that one warning as
information about the shell, not about the file. The file is a leading `#` comment block followed by one JSON document
(YAML 1.2 reads JSON). The contract test serves every scenario of the sample on both
HTTP/1 stacks.

## Keys, by feature

### Route order and prefix paths

* `route_order: nginx` on an application: exact routes, then regex routes in the order
  written, then prefix routes (longest first). The default `scalws` order is exact,
  prefix, regex. The generator writes `nginx` on every application.
* Write the hotlink regex route before any broader regex route: the first regex that
  matches wins. Regex routes see the client's path, not a path another route rewrote.
* A prefix path may end with `/`: `/sp-ab12/` matches `/sp-ab12/` and below, not
  `/sp-ab12` (answer that with an exact route). `rewrite.prefix: /` turns `/sp-ab12/x`
  into `/x`.
* `rewrite.path` may start with a capture: `$1` of `^/sp-ab12(/.*\.(?:jpg|png|gif))$`. A
  result that does not start with `/` answers 400; no `/` is added.
* Redirects with the Gateway fields (`scheme`, `host`, `port`, `path`, `prefix`) write an
  absolute `Location`, as nginx with `absolute_redirect on`: the exact route `/sp-ab12`
  redirects to `http://panel.example.org/sp-ab12/`. `keep_path: false` drops the query.

See [configuration.md](https://scalws.com/docs/guide/configuration/#route-matching).

### Network sets: `networks`

`server.networks.<NAME>: {file: <CIDR list>}` and route `deny_networks: [NAME]`. One
address or network per line, `#` comments; at most 32 MiB per file and 1 000 000 entries
in all. Files are read at start and on each reload; write each generation's files into a
new directory. Country sets (`countries` with `server.geoip`) are for standalone servers.
See [Network sets](https://scalws.com/docs/guide/network-sets/).

### Hotlink protection: `referer`

Route `referer: {allow_empty, allow_own, hosts, status}`, nginx `valid_referers` with
`none blocked server_names` and host names. `allow_own` admits the request's host and every
name in the application's `domains`; list extra hosts in `hosts`. A refusal answers
`status` with `Cache-Control: no-store`. See [Hotlink protection](https://scalws.com/docs/guide/hotlink-protection/).

### Cookies of the panel: `remove_cookies`

`request_headers.remove_cookies: [vpwm_session]` drops these cookies before the request
reaches the website.

* 1 to 64 cookie names, compared exactly (case-sensitive).
* Every `Cookie` line is rewritten (HTTP/2 and HTTP/3 send several). Pairs whose name is
  listed are dropped; the others keep their bytes and order, joined with `; `. A line left
  empty is removed. A pair without `=` is kept.
* The rewritten lines move to the end of the request's header list; their order among
  themselves is kept. Header order across different names carries no meaning in HTTP.
* It applies to every runtime and to upgrade (WebSocket) requests.
* `remove_cookies: null` is accepted and removes nothing, as if the key were absent. An
  empty list `[]` is an error. Write the key only with names in it.
* `response_headers.remove_cookies` is an error.

### Client address: `forwarded_for`

Proxy runtime `forwarded_for: client` sends the client address resolved through
`server.trusted_proxies` as the only `X-Forwarded-For` value, and the same value in
`X-Real-IP`. Values a client sent in either header never pass. The default `chain`
extends the received chain (behind a trusted proxy) or sends the client address, as 1.0
did. An unknown client is sent as `::`. Pools and `backends` follow it too. In both modes
an IPv4 client of a dual-stack `[::]` listener is sent as IPv4 (`203.0.113.5`, not
`::ffff:203.0.113.5`), as the logs and the address checks see it.

### Preview under a prefix: `prefix_proxy`

```yaml
routes:
  - path: /sp-ab12/
    rewrite: {prefix: /}
    runtime:
      type: proxy
      upstream: "http://192.0.2.40:8080"
      rewrite_location: true
      cookie: {path_prefix: /sp-ab12, domain: request_host}
```

* `rewrite_location: true` puts the prefix the route's rewrite removed in front of a
  response `Location` that is a path: `/wp-admin/` becomes `/sp-ab12/wp-admin/` (nginx
  `proxy_redirect / /sp-ab12/;`). Absolute URLs and other values are unchanged; `//x`
  becomes `/sp-ab12//x`, a path, never another host. `Refresh` is not rewritten.
* The removed prefix is inferred: when the rewritten path is a suffix of the client's
  path, the part in front is the prefix. A rewrite that removes nothing in front but
  happens to end the same way still counts: `rewrite.path: /index.php` for
  `/blog/index.php` makes `Location: /login` into `/blog/login`. The result is always a
  path on the same host. Use `rewrite_location` only on prefix routes.
* Without a route `rewrite` of the path, `rewrite_location` does nothing (a warning at
  load).
* `cookie.path_prefix: /sp-ab12` (an absolute path without a trailing `/`): in every
  `Set-Cookie`, a `Path` starting with `/` gets the prefix in front (`Path=/` becomes
  `Path=/sp-ab12/`). A cookie without `Path` is unchanged. A value that already starts
  with the prefix is prefixed again, as nginx does.
* `cookie.domain: request_host`: every non-empty `Domain` becomes the request's host
  (lower case, no port). A cookie without `Domain` stays host-only.
* The affinity cookie of an upstream pool (`hash: {by: cookie}`) is added after this
  rewriting and keeps its own path. Two prefixed previews on one host that use one pool
  share its affinity; that is harmless.
* Both apply to `101` answers and to declined upgrades too, before the route's
  `response_headers`.

### Tunnels per client: `max_upgraded`

`server.security.per_ip.max_upgraded` (1 to 1 000 000) limits the upgraded (WebSocket)
tunnels of one client address (IPv4 address or IPv6 `/64`). A handshake beyond it gets
`429` with `Retry-After: 1` without reaching the upstream, counted with
`reason="upgraded"`. A tunnel counts from its handshake until it closes; a handshake the
upstream does not answer with `101` gives its slot back. A full address table fails open,
as the other per-client limits do. The server-wide `limits.max_upgraded_connections`
stays.

Under scalws-controller each instance gets a share: `ceil(max_upgraded / instances)`, at
least 1. The kernel spreads connections over instances, not by address, so with
`max_upgraded: 1` and 4 instances one address may hold up to 4 tunnels, and with
`max_upgraded: 3` a client whose two tunnels land on one instance gets `429` at the
second. `requests_per_second`, `burst` and `max_connections` are shared the same way.

`burst: 0` is accepted: a bucket of one request (nginx `limit_req` without `burst`).
ScalWS's `burst` is the bucket size and nginx's counts requests above one, so nginx
`burst=N` is ScalWS `burst: N+1`.

### Access logs: `access_log`

`access_log: {file, format: scalpanel}` on an application and on routes. A route's file
replaces the application's for the requests it serves. The `scalpanel` format is
ScalPanel's nginx `log_format`, byte for byte. `scalwsctl reopen-logs` (or `SIGUSR1`)
reopens every file on every instance after a rotation. Keep the files in one directory
that exists at start (for example `/var/log/scalpanel/sites/`): with the sandbox on, a
reload cannot add a directory that was not writable at start. See
[Logging and metrics](https://scalws.com/docs/guide/logging-metrics/#access-log-files-of-applications-and-routes).

### Compression: `gzip`

```yaml
server:
  compression:
    enabled: true
    min_length: 1024
    types: [text/plain, text/css, text/xml, application/json, application/javascript, application/xml, image/svg+xml]
```

Every application without its own `compression` compresses these types and `text/html`,
with gzip or brotli as the client chooses. See
[configuration.md](https://scalws.com/docs/guide/configuration/#compression).

## Evaluation order

For a request on the edge:

1. ACME HTTP-01, loopback `/healthz`, client address (`trusted_proxies`), per-client
   rate, host lookup, strict SNI, denied paths, HTTPS redirect, `.htaccess`.
2. Route selection (`route_order`).
3. The route's `allow`, `deny`, `allow_networks`, `deny_networks` (403).
4. `referer` (its `status`).
5. CORS preflight, basic authentication, `max_body`, tenant quotas.
6. Rewrite, request header changes (`remove_cookies` included).
7. The runtime; `max_upgraded` at an upgrade.
8. Response header changes: `rewrite_location` and `cookie`, then the route's
   `response_headers`.
9. Compression, then the access log line.

As at nginx's edge, a plain-HTTP request from a denied address first gets the HTTPS
redirect, then `403` over HTTPS. The full list is in
[request-processing.md](https://scalws.com/docs/guide/request-processing/#request).

## Differences from nginx

| Id | Where | ScalWS 1.1 | nginx | Note |
|---|---|---|---|---|
| D1 | route order | `route_order: nginx` opt-in; default exact, prefix, regex | exact, regex, prefix | the generator writes `nginx` |
| D2 | `Referer` with a malformed `http(s)://` value | refused | refused | parity |
| D3 | `per_ip.burst` | bucket size; `0` is a bucket of one | requests above one | parity is nginx `burst` plus one |
| D4 | redirect `keep_path: false` with Gateway fields | query dropped | `return 302 https://$host:2096/` | parity (changed from 1.0) |
| D5 | `Server` of proxied responses | `scalws`; a `101` keeps the upstream's | upstream's hidden | changed from 1.0 |
| D6 | `request_headers.set` with `""` | header sent empty | header not sent | the client's value never passes either way |
| D7 | `preserve_host` | the client's authority as sent (case, `:port`) | `$host` (lower case, no port) | site containers route on `X-ScalPanel-Site` |
| D8 | `$time_iso8601` | always UTC (`+00:00`) | local time | the same on UTC hosts |
| D9 | `$status` when the client left early | the status ScalWS produced | `499` | ScalWS has no `499` |
| D10 | `rewrite_location` | `Location` only | also `Refresh` | |
| D11 | compression | gzip and brotli | gzip | the client chooses |
| D12 | `limits.max_connections` | excess waits in the kernel backlog | refused | |
| D13 | an encoded slash (`%2F`) in the path | 400 when the decoded path selects another route than the path as sent | the location of the decoded path | fails closed; `/api%2Fv2/x` with `/api` and `/api/v2` is refused (changed from 1.0) |

Not in scope: TCP proxying (database and mail relays stay in ScalPanel's agent) and ACME
at the edge (ScalPanel answers challenges with exact `respond` routes).

## See also

* [ScalPanel mode](https://scalws.com/docs/guide/scalpanel/): ScalWS inside each website's container.
* [Replicas](https://scalws.com/docs/guide/replicas/): a site on two nodes, with failover, sticky sessions and fencing.
* [Network sets](https://scalws.com/docs/guide/network-sets/), [Hotlink protection](https://scalws.com/docs/guide/hotlink-protection/).
* [Control panels: ScalPanel hosts](https://scalws.com/docs/guide/control-panels/#scalpanel-hosts).
