Add device: platform-aware one-liner installs from the Devices page #5
+19
-3
@@ -62,14 +62,30 @@ NATS_WS_PORT=19222
|
||||
PUBLIC_SERVER_URL=https://control.example.com
|
||||
|
||||
# ── Reverse proxy trust ────────────────────────────────────────────────────
|
||||
# At least one of TRUSTED_PROXIES / TRUSTED_NETWORKS is required when
|
||||
# TRUST_PROXY=1 outside development mode.
|
||||
# Forwarded headers are trusted BY DEFAULT from private address space
|
||||
# (loopback, RFC1918, CGNAT), so no configuration is needed behind a typical
|
||||
# cloud or LAN reverse proxy. Setting TRUSTED_PROXIES / TRUSTED_NETWORKS
|
||||
# replaces those defaults with an explicit allow-list — narrow this when
|
||||
# untrusted peers share your private network. TRUST_PROXY=0 disables
|
||||
# forwarded-header processing entirely.
|
||||
TRUST_PROXY=1
|
||||
TRUSTED_PROXIES=
|
||||
TRUSTED_NETWORKS=172.16.0.0/12
|
||||
TRUSTED_NETWORKS=
|
||||
TRUSTED_HOSTS=control.example.com
|
||||
FORWARD_LIMIT=1
|
||||
|
||||
# ── Built-in encryption (self-signed) ──────────────────────────────────────
|
||||
# TLS_SELF_SIGNED=1 makes the backend serve HTTPS with a chain it manages
|
||||
# itself (root > intermediate > leaf, auto-renewed). Reverse proxies then
|
||||
# either SKIP verification — not insecure: the hop is still encrypted, the
|
||||
# roots simply are not distributed — or import root.crt + intermediate.crt
|
||||
# to establish trust (re-import when they rotate at expiry). Always follow
|
||||
# your organization's security standards. The chain is PEM files under
|
||||
# <data>/tls (TLS_CERT_DIR overrides; keep it on a persisted volume, and
|
||||
# switch the proxy upstream + health checks to https accordingly).
|
||||
TLS_SELF_SIGNED=0
|
||||
TLS_CERT_DIR=
|
||||
|
||||
# ── Initial local admin (first startup only) ───────────────────────────────
|
||||
INITIAL_ADMIN_USERNAME=admin
|
||||
# Generate: openssl rand -base64 24
|
||||
|
||||
@@ -1,10 +1,34 @@
|
||||
name: CI
|
||||
|
||||
# Runs only when something buildable changes — docs-only commits (README,
|
||||
# docs/, compose examples) skip the queue entirely.
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'src/**'
|
||||
- 'tests/**'
|
||||
- 'scripts/**'
|
||||
- 'assets/**'
|
||||
- '.gitea/workflows/**'
|
||||
- 'ExecuteR.slnx'
|
||||
- 'Directory.Build.props'
|
||||
- 'Directory.Packages.props'
|
||||
- 'global.json'
|
||||
- 'dotnet-tools.json'
|
||||
push:
|
||||
branches: [dev, main]
|
||||
paths:
|
||||
- 'src/**'
|
||||
- 'tests/**'
|
||||
- 'scripts/**'
|
||||
- 'assets/**'
|
||||
- '.gitea/workflows/**'
|
||||
- 'ExecuteR.slnx'
|
||||
- 'Directory.Build.props'
|
||||
- 'Directory.Packages.props'
|
||||
- 'global.json'
|
||||
- 'dotnet-tools.json'
|
||||
|
||||
jobs:
|
||||
build-test:
|
||||
@@ -92,6 +116,10 @@ jobs:
|
||||
$zip = "artifacts/Agent-${{ steps.ver.outputs.version }}-win-x64.zip"
|
||||
if (Test-Path $msi) { Copy-Item $msi "$stage/Agent.msi" }
|
||||
if (Test-Path $zip) { Copy-Item $zip "$stage/Agent.zip" }
|
||||
foreach ($rid in 'linux-x64','linux-arm64','osx-x64','osx-arm64') {
|
||||
$unix = "artifacts/Agent-${{ steps.ver.outputs.version }}-$rid.zip"
|
||||
if (Test-Path $unix) { Copy-Item $unix "$stage/Agent-$rid.zip" }
|
||||
}
|
||||
'${{ steps.ver.outputs.version }}' | Set-Content "$stage/VERSION" -NoNewline
|
||||
Get-ChildItem $stage | Select-Object Name, Length
|
||||
|
||||
|
||||
@@ -1,8 +1,21 @@
|
||||
name: Release
|
||||
|
||||
# Docs-only merges to main skip the release build the same way CI skips
|
||||
# docs-only commits — a release only makes sense when shippable bits changed.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'src/**'
|
||||
- 'tests/**'
|
||||
- 'scripts/**'
|
||||
- 'assets/**'
|
||||
- '.gitea/workflows/**'
|
||||
- 'ExecuteR.slnx'
|
||||
- 'Directory.Build.props'
|
||||
- 'Directory.Packages.props'
|
||||
- 'global.json'
|
||||
- 'dotnet-tools.json'
|
||||
|
||||
jobs:
|
||||
agent-artifacts:
|
||||
|
||||
@@ -35,25 +35,25 @@ updates with **no SignalR, SSE, or polling**.
|
||||
7. [Generating local secrets](#generating-local-secrets)
|
||||
8. [Docker Compose](#docker-compose)
|
||||
9. [Standalone server binary](#standalone-server-binary)
|
||||
10. [Reverse proxy routes](#reverse-proxy-routes)
|
||||
11. [Agent foreground mode and service lifecycle](#agent-foreground-mode-and-service-lifecycle)
|
||||
12. [MSI public properties](#msi-public-properties)
|
||||
13. [Registry paths and GPO precedence](#registry-paths-and-gpo-precedence)
|
||||
14. [Bootstrap and URL install](#bootstrap-and-url-install)
|
||||
15. [Local login and OIDC](#local-login-and-oidc)
|
||||
16. [Custom roles and permissions](#custom-roles-and-permissions)
|
||||
17. [Typed script parameters and Functions](#typed-script-parameters-and-functions)
|
||||
18. [Script engines](#script-engines)
|
||||
19. [Secrets providers and $Secrets](#secrets-providers-and-secrets)
|
||||
20. [Device groups and script triggers](#device-groups-and-script-triggers)
|
||||
21. [Group runs and schedules](#group-runs-and-schedules)
|
||||
22. [Database providers](#database-providers)
|
||||
23. [Logging](#logging)
|
||||
24. [Device lifecycle: reconnect or orphan](#device-lifecycle-reconnect-or-orphan)
|
||||
25. [S3 file delivery](#s3-file-delivery)
|
||||
26. [CI/CD and GITEA_* variables](#cicd-and-gitea_-variables)
|
||||
27. [Versioning](#versioning)
|
||||
28. [MVP demo sequence](#mvp-demo-sequence)
|
||||
10. [Networking and TLS](#networking-and-tls)
|
||||
11. [Reverse proxy routes](#reverse-proxy-routes)
|
||||
12. [Agent foreground mode and service lifecycle](#agent-foreground-mode-and-service-lifecycle)
|
||||
13. [MSI public properties](#msi-public-properties)
|
||||
14. [Registry paths and GPO precedence](#registry-paths-and-gpo-precedence)
|
||||
15. [Bootstrap and URL install](#bootstrap-and-url-install)
|
||||
16. [Local login and OIDC](#local-login-and-oidc)
|
||||
17. [Custom roles and permissions](#custom-roles-and-permissions)
|
||||
18. [Typed script parameters and Functions](#typed-script-parameters-and-functions)
|
||||
19. [Script engines](#script-engines)
|
||||
20. [Secrets providers and $Secrets](#secrets-providers-and-secrets)
|
||||
21. [Device groups and script triggers](#device-groups-and-script-triggers)
|
||||
22. [Group runs and schedules](#group-runs-and-schedules)
|
||||
23. [Database providers](#database-providers)
|
||||
24. [Logging](#logging)
|
||||
25. [Device lifecycle: reconnect or orphan](#device-lifecycle-reconnect-or-orphan)
|
||||
26. [S3 file delivery](#s3-file-delivery)
|
||||
27. [CI/CD and GITEA_* variables](#cicd-and-gitea_-variables)
|
||||
28. [Versioning](#versioning)
|
||||
29. [Troubleshooting](#troubleshooting)
|
||||
|
||||
---
|
||||
@@ -348,16 +348,120 @@ the same reset.
|
||||
|
||||

|
||||
|
||||
The **Windows MSI** wraps the same flow: an Administrator account page in the
|
||||
wizard (defaults admin / admin; `ADMINUSERNAME=… ADMINPASSWORD=…` for silent
|
||||
installs) then the binary's own `setup` + `service install`. Upgrades never
|
||||
overwrite existing configuration, and uninstall stops and removes the service.
|
||||
The **Windows MSI** wraps the same flow with two wizard pages — the
|
||||
Administrator account (defaults admin / admin) and **Network settings**: bind
|
||||
address (0.0.0.0 default, explained inline), the HTTP port (9080), the
|
||||
three loopback-only NATS ports, and an **Enable Self-Signed TLS** checkbox,
|
||||
checked by default (see [Networking and TLS](#networking-and-tls) — proxies
|
||||
skip verification or import the exported roots), each described in place so
|
||||
a next-next-next install just works. Silent installs pass the same values
|
||||
as properties (`ADMINUSERNAME ADMINPASSWORD BINDADDRESS HTTPPORT NATSPORT
|
||||
NATSWSPORT NATSMONITORPORT ENABLETLS`), then the binary's own `setup` +
|
||||
`service install` run.
|
||||
The finish page offers to **open the console in the browser** (checked by
|
||||
default) — a wildcard bind (`0.0.0.0` / `::`) opens `http://localhost:<port>`,
|
||||
a specific bind address opens that address directly.
|
||||
Upgrades never overwrite existing configuration, and uninstall stops and
|
||||
removes the service. The MSI installs exactly one instance — multi-instance
|
||||
boxes use the ZIP with distinct ports and service names.
|
||||
|
||||
Bundles ship the **agent installers** (`agent-package/` with `Agent.msi`,
|
||||
`Agent.zip`, `VERSION`), so the URL install command works immediately — no
|
||||
seeding, no S3. Agents enroll against the same base URL. Put a TLS-terminating
|
||||
reverse proxy in front for production use; the compose stack remains the
|
||||
recommended deployment for anything long-lived.
|
||||
`Agent.zip`, the unix zips and `VERSION`), so the URL install command works
|
||||
immediately — no seeding, no S3. Agents enroll against the same base URL. Put
|
||||
a TLS-terminating reverse proxy in front for production use; the compose stack
|
||||
remains the recommended deployment for anything long-lived.
|
||||
|
||||
The standalone binary is configured through **flat keys in the generated
|
||||
`appsettings.json`** next to the binary, or the same names as **environment
|
||||
variables** (env wins). It honors the default proxy trust (loopback / RFC1918
|
||||
/ CGNAT), so it works behind a typical reverse proxy untouched; `setup`
|
||||
pre-writes the optional knobs — `TLS_SELF_SIGNED`, `TLS_CERT_DIR`,
|
||||
`PUBLIC_SERVER_URL`, `TRUSTED_NETWORKS`, `TRUSTED_HOSTS`, `TRUST_PROXY` — as
|
||||
placeholders ready to fill.
|
||||
|
||||
**Multiple instances on one box**: one directory per instance, distinct ports
|
||||
at setup, distinct service names at install:
|
||||
|
||||
```text
|
||||
ExecuteR-Server setup --http-port 9081 --nats-port 4223 --nats-ws-port 9223 --nats-monitor-port 8223
|
||||
ExecuteR-Server service install --name ExecuteRServer2
|
||||
```
|
||||
|
||||
`--bind <ip>` controls the HTTP bind address (default `0.0.0.0`; e.g.
|
||||
`--bind 127.0.0.1` to serve only to a local reverse proxy). The NATS sidecar
|
||||
always binds loopback — its ports are never exposed. Ports and bind land in
|
||||
`appsettings.json` (`Urls`), so they can also be edited there afterwards.
|
||||
|
||||
Everything an instance owns — config, database, keys, NATS state, agent
|
||||
packages — lives inside its own directory, so instances never share state.
|
||||
|
||||
---
|
||||
|
||||
## Networking and TLS
|
||||
|
||||
ExecuteR serves **plain HTTP only — SSL/TLS termination is not supported in
|
||||
the service itself and will not be added**. Terminating TLS inside every
|
||||
application is yesterday's pattern; the state of the art is a dedicated edge
|
||||
appliance or service that terminates TLS once, renews certificates
|
||||
automatically (ACME/Let's Encrypt) and gives you layer-7 visibility — access
|
||||
logs, request metrics, rate limiting, WAF hooks — for everything behind it:
|
||||
|
||||
| Edge | Notes |
|
||||
|------|-------|
|
||||
| [Caddy](https://caddyserver.com) | Automatic HTTPS out of the box; single binary, runs fine on **Windows** or Linux |
|
||||
| [nginx](https://nginx.org) + [Nginx UI](https://nginxui.com) | The classic; Nginx UI adds a web console with ACME renewal and also installs on **Windows** |
|
||||
| [HAProxy](https://www.haproxy.org) | High-throughput L4/L7 balancing and fine-grained traffic policy |
|
||||
| [Zoraxy](https://zoraxy.aroz.org) | All-in-one reverse proxy with a friendly UI |
|
||||
|
||||
Put any of these in front on `:443` and forward to ExecuteR over HTTP.
|
||||
Because forwarded headers are trusted from private address space by default
|
||||
(next section), this works with zero ExecuteR-side configuration — the edge
|
||||
handles certificates and encryption, ExecuteR handles the rest. For the
|
||||
standalone Windows server the shortest path is installing Caddy (or Nginx UI
|
||||
if you want a console) on the same host and proxying `localhost:9080`.
|
||||
|
||||
### Self-Signed TLS (on by default)
|
||||
|
||||
The server encrypts its own listener **by default**: HTTPS with a chain it
|
||||
manages itself — root CA → intermediate → leaf, issued on first boot and
|
||||
**auto-renewed** in the background (leaf yearly, re-issued 30 days early and
|
||||
hot-swapped without a restart). Opt out with `TLS_SELF_SIGNED=0`, `setup
|
||||
--tls 0`, or by unchecking **Enable Self-Signed TLS** in the server MSI
|
||||
wizard (`ENABLETLS=""` silently).
|
||||
|
||||
The reverse proxy then has two equally valid options — **pick per your
|
||||
organization's security standards**:
|
||||
|
||||
- **Skip verification** (nginx `proxy_ssl_verify off`, Caddy
|
||||
`tls_insecure_skip_verify`, HAProxy `ssl verify none`). This is **not
|
||||
insecure**: the traffic on the hop is still fully encrypted — the
|
||||
self-signed roots simply are not distributed, so there is nothing for the
|
||||
proxy to verify against.
|
||||
- **Establish trust**: import the root and intermediate certificates into
|
||||
the proxy's trust store (`fullchain.crt` sits next to the PEMs for
|
||||
pinning). Be aware this adds a rotation duty — when the chain rotates at
|
||||
expiry, the proxy needs the new roots re-imported.
|
||||
|
||||
On **Windows** the chain lives in the machine certificate stores exactly
|
||||
where each link belongs — root in *Trusted Root Certification Authorities*,
|
||||
intermediate in *Intermediate Certification Authorities*, leaf in
|
||||
*Personal* — so browsers on the server itself trust it with no warning.
|
||||
The same chain is **also mirrored as PEM files** (certs, keys and
|
||||
`fullchain.crt` under `<data>/tls`), refreshed on every renewal, so a local
|
||||
Caddy / Nginx UI / nginx can bind or trust the files directly and stay
|
||||
current. On **Linux/macOS/containers** the PEM files are the primary store
|
||||
(`TLS_CERT_DIR` overrides; keep it on a persisted volume in containers).
|
||||
|
||||
**Agents** follow automatically: when the server serves the self-signed
|
||||
chain directly (no proxy in between), the Add-Device one-liners and install
|
||||
scripts include TLS skip-verify and set the agent's `TlsSkipVerify` registry
|
||||
value (`/etc/executer/agent.json` on unix) so enrollment and the persistent
|
||||
connection work out of the box — still fully encrypted. The value is
|
||||
GPO-manageable (`Skip TLS certificate verification` in the ADMX template,
|
||||
policy key beats local config), `configure --skip-tls-verify` sets it by
|
||||
hand, and the agent MSI wizard has a matching checkbox — unchecked by
|
||||
default (`SKIPTLSVERIFY=1` silently). Behind a proxy with a real
|
||||
certificate none of this engages — agents validate normally.
|
||||
|
||||
---
|
||||
|
||||
@@ -375,14 +479,30 @@ and forwarding to the host ports above:
|
||||
|
||||
The proxy must preserve the WebSocket upgrade and send `X-Forwarded-For`,
|
||||
`X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Forwarded-Prefix`. The backend
|
||||
processes forwarded headers before auth and trusts them only from configured
|
||||
`TRUSTED_PROXIES` / `TRUSTED_NETWORKS`. If path-based proxying conflicts with
|
||||
your NATS WebSocket config, use dedicated hostnames behind the same `:443` edge.
|
||||
processes forwarded headers before auth and **trusts them by default from
|
||||
private address space** — loopback, RFC1918 (10/8, 172.16/12, 192.168/16) and
|
||||
CGNAT (100.64/10) — so dropping the stack behind a cloud or LAN reverse proxy
|
||||
needs zero trust configuration. Setting `TRUSTED_PROXIES` /
|
||||
`TRUSTED_NETWORKS` **replaces** those defaults with an explicit allow-list
|
||||
(narrow this when untrusted peers share your private network), and
|
||||
`TRUST_PROXY=0` disables forwarded-header processing entirely. If path-based
|
||||
proxying conflicts with your NATS WebSocket config, use dedicated hostnames
|
||||
behind the same `:443` edge.
|
||||
|
||||
A ready-to-adapt single-file nginx site (nginx-ui style, edge rate limiting,
|
||||
long-lived WebSocket timeouts and commented IP allow-lists) is in
|
||||
[src/Infra/nginx](src/Infra/nginx). The OIDC callback (`/api/auth/oidc/callback`)
|
||||
rides the `/api/*` location — no extra route is needed.
|
||||
Ready-to-adapt single-file edge samples ship for all three common choices —
|
||||
each with the same shape: banner header, BEFORE-USE placeholders, forwarded
|
||||
headers, WebSocket handling, commented IP allow-lists and the self-signed
|
||||
upstream variant:
|
||||
|
||||
- [src/Infra/nginx](src/Infra/nginx) — nginx-ui friendly site with edge rate
|
||||
limiting and long-lived WebSocket timeouts
|
||||
- [src/Infra/caddy](src/Infra/caddy) — automatic HTTPS via ACME, runs on
|
||||
Windows too
|
||||
- [src/Infra/haproxy](src/Infra/haproxy) — stick-table rate limits and
|
||||
tunnel timeouts for the WebSocket sessions
|
||||
|
||||
The OIDC callback (`/api/auth/oidc/callback`) rides the `/api/*` route in
|
||||
all of them — no extra route is needed.
|
||||
|
||||
---
|
||||
|
||||
@@ -429,6 +549,7 @@ msiexec /i Agent.msi /qn SERVERURL=https://control.example.com BOOTSTRAPTOKEN=<t
|
||||
| `LOGLEVEL` | `LogLevel` |
|
||||
| `ALLOWREMOTESHELL` | `AllowRemoteShell` |
|
||||
| `ALLOWSCRIPTEXECUTION` | `AllowScriptExecution` |
|
||||
| `SKIPTLSVERIFY` | `TlsSkipVerify` (self-signed servers; hop stays encrypted) |
|
||||
|
||||
The installer never overwrites a non-blank existing value with a blank property,
|
||||
preserves configuration on upgrade, and removes runtime credentials only on a
|
||||
@@ -454,26 +575,41 @@ Group Policy templates live in
|
||||
|
||||
## Bootstrap and URL install
|
||||
|
||||
1. Sign in as admin, open **Settings**, and generate a one-time bootstrap token.
|
||||
2. Deploy the agent one of two ways.
|
||||
The fastest path is **Devices → + Add device**: pick the platform
|
||||
(Windows / Linux / macOS), choose a single-use token or a multi-use one with
|
||||
any use count up to 9999 — or unlimited (24-hour expiry either way) — and
|
||||
**Generate command** issues the token and builds the paste-ready one-liner.
|
||||
Nothing is created until you confirm, and Esc / click-outside / Cancel
|
||||
dismisses without side effects:
|
||||
|
||||
MSI:
|
||||
```powershell
|
||||
# Windows (elevated PowerShell)
|
||||
iwr 'https://control.example.com/api/enrollment/install?token=<token>' -UseBasicParsing | iex
|
||||
```
|
||||
|
||||
```bash
|
||||
# Linux
|
||||
curl -fsSL 'https://control.example.com/api/enrollment/install?token=<token>&type=linux' | sudo bash
|
||||
# macOS
|
||||
curl -fsSL 'https://control.example.com/api/enrollment/install?token=<token>&type=osx' | sudo bash
|
||||
```
|
||||
|
||||
The unix script detects the architecture (x64/arm64), downloads the matching
|
||||
agent zip from the same origin, unpacks to `/opt/executer/agent`, configures
|
||||
enrollment through the agent's own `configure --url --token` CLI and registers
|
||||
the systemd unit / launchd daemon. Tokens can also be minted under
|
||||
**Settings**, and the MSI installs directly:
|
||||
|
||||
```text
|
||||
msiexec /i Agent.msi /qn SERVERURL=https://control.example.com BOOTSTRAPTOKEN=<token>
|
||||
```
|
||||
|
||||
URL one-liner (elevated PowerShell on the target; requires `Agent.msi` in the
|
||||
backend's `AGENT_PACKAGE_PATH`):
|
||||
|
||||
```powershell
|
||||
iwr https://control.example.com/api/enrollment/install?token=<token> -UseBasicParsing | iex
|
||||
```
|
||||
|
||||
The agent generates its NKey locally (the private seed never leaves the device),
|
||||
bootstraps over HTTPS, receives a scoped NATS JWT, erases the token, and
|
||||
connects over WSS. The device appears in the UI within seconds.
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## Local login and OIDC
|
||||
@@ -1064,22 +1200,6 @@ metadata), and the frontend build metadata.
|
||||
|
||||
---
|
||||
|
||||
## MVP demo sequence
|
||||
|
||||
1. `docker compose up -d` — backend, NATS and WebUI become healthy.
|
||||
2. Sign in locally as the initial admin.
|
||||
3. Generate a one-time bootstrap token (Settings).
|
||||
4. Install the agent (`SERVERURL`, `BOOTSTRAPTOKEN`) via MSI or the URL one-liner.
|
||||
5. The device appears within seconds; presence keeps status live without refresh.
|
||||
6. Inventory populates the device detail tabs.
|
||||
7. Author/save a PowerShell script; select the device; run.
|
||||
8. Job state goes Running, output and a progress bar advance live; job Succeeds.
|
||||
9. Open the remote shell; run `hostname`, `whoami`, `Get-Process | Select -First 5`.
|
||||
10. Resize and disconnect cleanly; restart the service — it reconnects without a
|
||||
token; rerun and verify no duplicate execution from redelivery.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Check |
|
||||
|
||||
@@ -111,6 +111,8 @@ services:
|
||||
TRUSTED_PROXIES: '${TRUSTED_PROXIES:-}'
|
||||
TRUSTED_NETWORKS: '${TRUSTED_NETWORKS:-}'
|
||||
TRUSTED_HOSTS: '${TRUSTED_HOSTS:-}'
|
||||
TLS_SELF_SIGNED: '${TLS_SELF_SIGNED:-0}'
|
||||
TLS_CERT_DIR: '${TLS_CERT_DIR:-}'
|
||||
FORWARD_LIMIT: '${FORWARD_LIMIT:-1}'
|
||||
PUBLIC_SERVER_URL: '${PUBLIC_SERVER_URL:-}'
|
||||
INITIAL_ADMIN_USERNAME: '${INITIAL_ADMIN_USERNAME:-}'
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 195 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 141 KiB After Width: | Height: | Size: 142 KiB |
@@ -82,6 +82,10 @@ foreach ($rid in $Runtimes) {
|
||||
$staged = $false
|
||||
if (Test-Path $agentMsi) { Copy-Item $agentMsi (Join-Path $agentStage 'Agent.msi'); $staged = $true }
|
||||
if (Test-Path $agentZip) { Copy-Item $agentZip (Join-Path $agentStage 'Agent.zip'); $staged = $true }
|
||||
foreach ($unixRid in 'linux-x64', 'linux-arm64', 'osx-x64', 'osx-arm64') {
|
||||
$unixZip = Join-Path $artifacts "Agent-$Version-$unixRid.zip"
|
||||
if (Test-Path $unixZip) { Copy-Item $unixZip (Join-Path $agentStage "Agent-$unixRid.zip"); $staged = $true }
|
||||
}
|
||||
if ($staged) {
|
||||
$Version | Set-Content (Join-Path $agentStage 'VERSION') -NoNewline
|
||||
}
|
||||
@@ -130,7 +134,17 @@ ExecuteR standalone server $Version ($rid)
|
||||
1. $exeName setup
|
||||
Generates NATS keys, the sidecar config and appsettings.json with
|
||||
the admin/admin sign-in (override with --admin-user/--admin-password;
|
||||
change the password after the first sign-in either way).
|
||||
change the password after the first sign-in either way). For extra
|
||||
instances on the same box use one directory each with distinct ports
|
||||
(--http-port/--nats-port/--nats-ws-port/--nats-monitor-port) and
|
||||
`service install --name <name>`.
|
||||
Self-Signed TLS is ON by default: the server serves HTTPS with a
|
||||
managed, auto-renewed chain so this hop is encrypted (--tls 0 opts
|
||||
out). Reverse proxies either skip verification (not insecure — the
|
||||
roots simply are not distributed, the traffic is still encrypted) or
|
||||
import the root and intermediate to establish trust, re-importing when
|
||||
they rotate at expiry. Follow your organization's security standards.
|
||||
Install commands generated by the UI configure agents accordingly.
|
||||
2. $exeName
|
||||
Serves the UI + API on http://0.0.0.0:9080 with the NATS sidecar.
|
||||
...or run in the background:
|
||||
@@ -140,6 +154,15 @@ ExecuteR standalone server $Version ($rid)
|
||||
Agent installers ship in ./agent-package, so the URL install command
|
||||
works immediately. Put a TLS-terminating reverse proxy in front for
|
||||
production use; agents enroll against the same base URL.
|
||||
|
||||
Configuration = flat keys in appsettings.json next to the binary, or
|
||||
environment variables (either works; env wins). Forwarded headers are
|
||||
trusted by default from private networks (loopback/RFC1918/CGNAT) —
|
||||
behind a typical proxy nothing needs setting. Optional keys generated
|
||||
for you: TLS_SELF_SIGNED (built-in hop encryption, on by default — 0
|
||||
disables), TLS_CERT_DIR, PUBLIC_SERVER_URL (pin the public base URL),
|
||||
TRUSTED_NETWORKS (replace the default trust with an allow-list),
|
||||
TRUSTED_HOSTS, TRUST_PROXY=0 to disable.
|
||||
"@
|
||||
|
||||
# ── Zip it ───────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -65,6 +65,12 @@ public static class AgentCli
|
||||
case "status":
|
||||
return Lifecycle.Status();
|
||||
|
||||
// Cross-platform enrollment configuration (registry on Windows,
|
||||
// /etc/executer/agent.json elsewhere) — what the MSI does via
|
||||
// properties, expressed as a CLI for the unix install scripts.
|
||||
case "configure":
|
||||
return Configure(args[1..]);
|
||||
|
||||
case "ensure-pwsh":
|
||||
await Agent.PowerShell.PwshBootstrap.EnsureInstalledAsync(
|
||||
Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance,
|
||||
@@ -107,6 +113,52 @@ public static class AgentCli
|
||||
#endif
|
||||
}
|
||||
|
||||
private static int Configure(string[] args)
|
||||
{
|
||||
string? url = null;
|
||||
string? token = null;
|
||||
for (var i = 0; i < args.Length - 1; i++)
|
||||
{
|
||||
switch (args[i])
|
||||
{
|
||||
case "--url":
|
||||
url = args[++i];
|
||||
break;
|
||||
case "--token":
|
||||
token = args[++i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var skipTlsVerify = args.Contains("--skip-tls-verify");
|
||||
if (url is null && token is null && !skipTlsVerify)
|
||||
{
|
||||
Console.Error.WriteLine("Usage: configure --url <server-url> [--token <bootstrap-token>] [--skip-tls-verify]");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var registry = Agent.Platform.PlatformServices.CreateRegistryStore();
|
||||
if (url is not null)
|
||||
{
|
||||
registry.WriteString(Branding.AgentRegistryKey, Agent.Configuration.AgentConfigurationKeys.ServerUrl, url);
|
||||
}
|
||||
|
||||
if (token is not null)
|
||||
{
|
||||
registry.WriteString(Branding.AgentRegistryKey, Agent.Configuration.AgentConfigurationKeys.BootstrapToken, token);
|
||||
}
|
||||
|
||||
if (skipTlsVerify)
|
||||
{
|
||||
// For servers on the managed self-signed chain without a proxy:
|
||||
// the connection stays TLS-encrypted, validation is skipped.
|
||||
registry.WriteDword(Branding.AgentRegistryKey, Agent.Configuration.AgentConfigurationKeys.TlsSkipVerify, 1);
|
||||
}
|
||||
|
||||
Console.WriteLine("Configuration saved. The agent enrolls on next start (`initialize`).");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int PurgeCredentials()
|
||||
{
|
||||
var runtimeState = new Storage.RuntimeStateStore(Platform.PlatformServices.CreateRegistryStore());
|
||||
|
||||
@@ -18,6 +18,7 @@ public sealed class AgentConfiguration
|
||||
public required ConfigurationValue<TimeSpan> ReconnectMaxDelay { get; init; }
|
||||
public required ConfigurationValue<bool> AllowRemoteShell { get; init; }
|
||||
public required ConfigurationValue<bool> AllowScriptExecution { get; init; }
|
||||
public required ConfigurationValue<bool> TlsSkipVerify { get; init; }
|
||||
|
||||
/// <summary>Parsed ServerURL; null when unset or invalid.</summary>
|
||||
public ServerUrl? ServerUrl =>
|
||||
@@ -46,6 +47,7 @@ public sealed class AgentConfigurationLoader(IRegistryStore registry, bool allow
|
||||
ReconnectMaxDelay = ResolveTimeSpan(AgentConfigurationKeys.ReconnectMaxDelay, ProtocolDefaults.ReconnectMaxDelay),
|
||||
AllowRemoteShell = ResolveBool(AgentConfigurationKeys.AllowRemoteShell, defaultValue: false),
|
||||
AllowScriptExecution = ResolveBool(AgentConfigurationKeys.AllowScriptExecution, defaultValue: true),
|
||||
TlsSkipVerify = ResolveBool(AgentConfigurationKeys.TlsSkipVerify, defaultValue: false),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,14 @@ public static class AgentConfigurationKeys
|
||||
public const string AllowRemoteShell = "AllowRemoteShell";
|
||||
public const string AllowScriptExecution = "AllowScriptExecution";
|
||||
|
||||
/// <summary>
|
||||
/// DWORD 1: accept the server's certificate without validation — for
|
||||
/// servers running the managed self-signed chain without a proxy. The
|
||||
/// connection is still TLS-encrypted; the roots just aren't distributed.
|
||||
/// GPO (policy key) overrides the normal value like every other setting.
|
||||
/// </summary>
|
||||
public const string TlsSkipVerify = "TlsSkipVerify";
|
||||
|
||||
/// <summary>Development-only environment variable names (never override GPO).</summary>
|
||||
public static class EnvironmentNames
|
||||
{
|
||||
|
||||
@@ -62,6 +62,18 @@ public sealed class FileRegistryStore(string? path = null) : IRegistryStore
|
||||
}
|
||||
}
|
||||
|
||||
public void WriteDword(string keyPath, string valueName, int value)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
var root = Load();
|
||||
var section = Section(root, keyPath) ?? new JsonObject();
|
||||
section[valueName] = value;
|
||||
root[Normalize(keyPath)] = section;
|
||||
Save(root);
|
||||
}
|
||||
}
|
||||
|
||||
public void DeleteValue(string keyPath, string valueName)
|
||||
{
|
||||
lock (gate)
|
||||
|
||||
@@ -14,6 +14,7 @@ public interface IRegistryStore
|
||||
string? ReadString(string keyPath, string valueName);
|
||||
int? ReadDword(string keyPath, string valueName);
|
||||
void WriteString(string keyPath, string valueName, string value);
|
||||
void WriteDword(string keyPath, string valueName, int value);
|
||||
void DeleteValue(string keyPath, string valueName);
|
||||
void DeleteKeyTree(string keyPath);
|
||||
}
|
||||
@@ -40,6 +41,12 @@ public sealed class WindowsRegistryStore : IRegistryStore
|
||||
key.SetValue(valueName, value, RegistryValueKind.String);
|
||||
}
|
||||
|
||||
public void WriteDword(string keyPath, string valueName, int value)
|
||||
{
|
||||
using var key = Registry.LocalMachine.CreateSubKey(keyPath);
|
||||
key.SetValue(valueName, value, RegistryValueKind.DWord);
|
||||
}
|
||||
|
||||
public void DeleteValue(string keyPath, string valueName)
|
||||
{
|
||||
using var key = Registry.LocalMachine.OpenSubKey(keyPath, writable: true);
|
||||
|
||||
@@ -80,7 +80,16 @@ public sealed class EnrollmentService(
|
||||
AgentVersion: BuildVersion.Resolve(typeof(EnrollmentService).Assembly),
|
||||
Device: ReadDeviceInfo());
|
||||
|
||||
using var http = new HttpClient();
|
||||
// TlsSkipVerify (registry/GPO): servers on the managed self-signed
|
||||
// chain without a proxy — the connection stays TLS-encrypted.
|
||||
using var handler = new HttpClientHandler();
|
||||
if (configuration.TlsSkipVerify.Value)
|
||||
{
|
||||
handler.ServerCertificateCustomValidationCallback =
|
||||
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
|
||||
}
|
||||
|
||||
using var http = new HttpClient(handler);
|
||||
var endpoint = serverUrl.ApiEndpoint(ApiRoutes.Bootstrap);
|
||||
logger.LogInformation("Bootstrapping client {ClientId} against {Endpoint}", clientId, endpoint);
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ public static class AgentNatsOptionsFactory
|
||||
AgentConfiguration configuration,
|
||||
ILoggerFactory loggerFactory)
|
||||
{
|
||||
return NatsOpts.Default with
|
||||
var options = NatsOpts.Default with
|
||||
{
|
||||
Url = serverUrl.AgentWebSocketEndpoint.ToString(),
|
||||
Name = $"agent-{credentials.ClientId}",
|
||||
@@ -36,5 +36,25 @@ public static class AgentNatsOptionsFactory
|
||||
DrainSubscriptionsOnDispose = true,
|
||||
LoggerFactory = loggerFactory,
|
||||
};
|
||||
|
||||
// TlsSkipVerify (registry/GPO): accept the managed self-signed chain
|
||||
// on the wss connection — the traffic stays TLS-encrypted.
|
||||
if (configuration.TlsSkipVerify.Value)
|
||||
{
|
||||
options = options with
|
||||
{
|
||||
TlsOpts = NatsTlsOpts.Default with { InsecureSkipVerify = true },
|
||||
WebSocketOpts = NatsWebSocketOpts.Default with
|
||||
{
|
||||
ConfigureClientWebSocketOptions = (_, clientOptions, _) =>
|
||||
{
|
||||
clientOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true;
|
||||
return ValueTask.CompletedTask;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,14 @@ public static class BootstrapTokenEndpoints
|
||||
var lifetime = request?.ValidMinutes is > 0
|
||||
? TimeSpan.FromMinutes(request.ValidMinutes.Value)
|
||||
: ProtocolDefaults.BootstrapTokenDefaultLifetime;
|
||||
var maxUses = request?.MaxUses is > 0 ? request.MaxUses.Value : ProtocolDefaults.BootstrapTokenDefaultMaxUses;
|
||||
|
||||
// 0 means unlimited uses (expiry and revocation still apply).
|
||||
if (request?.MaxUses is < 0 or > 9999)
|
||||
{
|
||||
return Results.BadRequest(new { error = "maxUses must be between 0 (unlimited) and 9999." });
|
||||
}
|
||||
|
||||
var maxUses = request?.MaxUses ?? ProtocolDefaults.BootstrapTokenDefaultMaxUses;
|
||||
|
||||
// Plaintext exists exactly once: in this response. Only the hash is stored.
|
||||
var token = TokenGenerator.CreateUrlSafeToken(ProtocolDefaults.BootstrapTokenEntropyBytes);
|
||||
|
||||
@@ -70,7 +70,9 @@ public static class EnrollmentEndpoints
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
var token = await db.BootstrapTokens.SingleOrDefaultAsync(t => t.TokenHash == tokenHash, cancellationToken);
|
||||
if (token is null || token.Revoked || token.ExpiresUtc <= now || token.Uses >= token.MaxUses)
|
||||
// MaxUses 0 = unlimited (expiry and revocation still gate it).
|
||||
if (token is null || token.Revoked || token.ExpiresUtc <= now
|
||||
|| (token.MaxUses > 0 && token.Uses >= token.MaxUses))
|
||||
{
|
||||
await audit.LogAsync(AuditCategories.Enrollment, "bootstrap-rejected",
|
||||
clientId: request.ClientId, detail: "invalid, expired or consumed token", remoteIp: remoteIp,
|
||||
|
||||
@@ -26,7 +26,8 @@ public static class InstallEndpoints
|
||||
.AllowAnonymous();
|
||||
}
|
||||
|
||||
private static IResult GetInstallScript(HttpContext context, IConfiguration configuration, string? token, string? type)
|
||||
private static IResult GetInstallScript(
|
||||
HttpContext context, IConfiguration configuration, Backend.Tls.TlsSettings tls, string? token, string? type)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
@@ -34,14 +35,21 @@ public static class InstallEndpoints
|
||||
}
|
||||
|
||||
var baseUrl = ResolveBaseUrl(context, configuration);
|
||||
var packageType = type?.ToLowerInvariant() == "zip" ? "zip" : "msi";
|
||||
var packageUrl = $"{baseUrl}{ApiRoutes.AgentPackage}?type={packageType}";
|
||||
|
||||
// Direct self-signed serving: the roots aren't distributed, so the
|
||||
// installer must skip verification and configure the agent to do the
|
||||
// same (TlsSkipVerify — the hop stays encrypted either way).
|
||||
var skipVerify = tls.IsSelfSignedDirect(context);
|
||||
|
||||
// Token is embedded so the operator can paste one command; knowledge of a
|
||||
// valid token is itself the enrollment gate.
|
||||
var script = packageType == "zip"
|
||||
? BuildZipScript(baseUrl, token!, packageUrl)
|
||||
: BuildMsiScript(baseUrl, token!, packageUrl);
|
||||
var script = type?.ToLowerInvariant() switch
|
||||
{
|
||||
"linux" => BuildUnixScript(baseUrl, token!, "linux", skipVerify),
|
||||
"osx" or "mac" or "macos" or "darwin" => BuildUnixScript(baseUrl, token!, "osx", skipVerify),
|
||||
"zip" => BuildZipScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=zip", skipVerify),
|
||||
_ => BuildMsiScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=msi", skipVerify),
|
||||
};
|
||||
|
||||
return Results.Text(script, "text/plain; charset=utf-8");
|
||||
}
|
||||
@@ -50,7 +58,7 @@ public static class InstallEndpoints
|
||||
Files.AgentPackageService packages, string? type, CancellationToken cancellationToken)
|
||||
{
|
||||
var packageType = Files.AgentPackageService.NormalizeType(type);
|
||||
var fileName = packageType == "zip" ? "Agent.zip" : "Agent.msi";
|
||||
var fileName = Files.AgentPackageService.FileNameFor(packageType);
|
||||
|
||||
// When S3 offload is on, hand the endpoint a presigned URL so the
|
||||
// transfer never touches the control plane. Falls through to local
|
||||
@@ -72,7 +80,7 @@ public static class InstallEndpoints
|
||||
});
|
||||
}
|
||||
|
||||
var contentType = packageType == "zip" ? "application/zip" : "application/x-msi";
|
||||
var contentType = packageType == "msi" ? "application/x-msi" : "application/zip";
|
||||
var stream = File.OpenRead(path);
|
||||
return Results.Stream(stream, contentType, fileDownloadName: fileName, enableRangeProcessing: true);
|
||||
}
|
||||
@@ -80,17 +88,23 @@ public static class InstallEndpoints
|
||||
private static string ResolveBaseUrl(HttpContext context, IConfiguration configuration)
|
||||
=> Backend.Proxy.PublicUrl.Resolve(context, configuration);
|
||||
|
||||
// The PS5.1-safe global callback is used instead of -SkipCertificateCheck
|
||||
// (PowerShell 7 only) so the same script works everywhere.
|
||||
private const string PsSkipVerify =
|
||||
"[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }";
|
||||
|
||||
// NOTE: $$""" — interpolations are {{ }}, single braces are literal PowerShell.
|
||||
private static string BuildMsiScript(string baseUrl, string token, string packageUrl) => $$"""
|
||||
private static string BuildMsiScript(string baseUrl, string token, string packageUrl, bool skipVerify) => $$"""
|
||||
#Requires -RunAsAdministrator
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Write-Host 'Installing ExecuteR Agent...'
|
||||
{{(skipVerify ? PsSkipVerify : "")}}
|
||||
$server = '{{baseUrl}}'
|
||||
$token = '{{token}}'
|
||||
$msi = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.msi')
|
||||
try {
|
||||
Invoke-WebRequest -Uri '{{packageUrl}}' -OutFile $msi -UseBasicParsing
|
||||
$arguments = @('/i', ('"' + $msi + '"'), '/qn', "SERVERURL=$server", "BOOTSTRAPTOKEN=$token")
|
||||
$arguments = @('/i', ('"' + $msi + '"'), '/qn', "SERVERURL=$server", "BOOTSTRAPTOKEN=$token"{{(skipVerify ? ", 'SKIPTLSVERIFY=1'" : "")}})
|
||||
$p = Start-Process msiexec.exe -ArgumentList $arguments -Wait -PassThru
|
||||
if ($p.ExitCode -ne 0) { throw "msiexec exited with $($p.ExitCode)" }
|
||||
Write-Host 'ExecuteR Agent installed. It will enroll and start automatically.'
|
||||
@@ -100,10 +114,45 @@ public static class InstallEndpoints
|
||||
}
|
||||
""";
|
||||
|
||||
private static string BuildZipScript(string baseUrl, string token, string packageUrl) => $$"""
|
||||
/// <summary>
|
||||
/// linux/macOS installer: detects the architecture, downloads the matching
|
||||
/// agent zip, unpacks to /opt/executer/agent, configures enrollment via
|
||||
/// the agent's own CLI and registers the systemd unit / launchd daemon.
|
||||
/// </summary>
|
||||
private static string BuildUnixScript(string baseUrl, string token, string os, bool skipVerify) => $$"""
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
if [ "$(id -u)" -ne 0 ]; then echo 'Run with sudo/root.' >&2; exit 1; fi
|
||||
server='{{baseUrl}}'
|
||||
token='{{token}}'
|
||||
case "$(uname -m)" in
|
||||
x86_64|amd64) arch=x64 ;;
|
||||
aarch64|arm64) arch=arm64 ;;
|
||||
*) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
|
||||
esac
|
||||
pkg="{{baseUrl}}{{ApiRoutes.AgentPackage}}?type={{os}}-${arch}"
|
||||
dest=/opt/executer/agent
|
||||
tmp=$(mktemp -d)
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
echo "Installing ExecuteR Agent ({{os}}-${arch})..."
|
||||
curl -fsSL{{(skipVerify ? "k" : "")}} "$pkg" -o "$tmp/agent.zip"
|
||||
mkdir -p "$dest"
|
||||
if command -v unzip >/dev/null 2>&1; then
|
||||
unzip -oq "$tmp/agent.zip" -d "$dest"
|
||||
else
|
||||
python3 -m zipfile -e "$tmp/agent.zip" "$dest"
|
||||
fi
|
||||
chmod +x "$dest/executer-agent"
|
||||
"$dest/executer-agent" configure --url "$server" --token "$token"{{(skipVerify ? " --skip-tls-verify" : "")}}
|
||||
"$dest/executer-agent" initialize
|
||||
echo 'ExecuteR Agent installed. It will enroll and start automatically.'
|
||||
""";
|
||||
|
||||
private static string BuildZipScript(string baseUrl, string token, string packageUrl, bool skipVerify) => $$"""
|
||||
#Requires -RunAsAdministrator
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Write-Host 'Installing ExecuteR Agent (portable)...'
|
||||
{{(skipVerify ? PsSkipVerify : "")}}
|
||||
$server = '{{baseUrl}}'
|
||||
$token = '{{token}}'
|
||||
$dest = Join-Path $env:ProgramFiles 'ExecuteR Agent'
|
||||
@@ -117,6 +166,7 @@ public static class InstallEndpoints
|
||||
New-Item -Path 'HKLM:\SOFTWARE\ExecuteR' -Force | Out-Null
|
||||
Set-ItemProperty -Path 'HKLM:\SOFTWARE\ExecuteR' -Name 'ServerURL' -Value $server
|
||||
Set-ItemProperty -Path 'HKLM:\SOFTWARE\ExecuteR' -Name 'BootstrapToken' -Value $token
|
||||
{{(skipVerify ? "Set-ItemProperty -Path 'HKLM:\\SOFTWARE\\ExecuteR' -Name 'TlsSkipVerify' -Value 1 -Type DWord" : "")}}
|
||||
& $exe initialize
|
||||
Write-Host 'ExecuteR Agent installed and starting.'
|
||||
}
|
||||
|
||||
@@ -28,10 +28,19 @@ public sealed class AgentPackageService(
|
||||
public const string BakedInPath = "/opt/executer/agent";
|
||||
public const string SeededPath = "/data/agent";
|
||||
|
||||
private static string FileNameFor(string packageType) => packageType == "zip" ? "Agent.zip" : "Agent.msi";
|
||||
public static string FileNameFor(string packageType) => packageType switch
|
||||
{
|
||||
"zip" => "Agent.zip",
|
||||
"linux-x64" or "linux-arm64" or "osx-x64" or "osx-arm64" => $"Agent-{packageType}.zip",
|
||||
_ => "Agent.msi",
|
||||
};
|
||||
|
||||
public static string NormalizeType(string? type)
|
||||
=> string.Equals(type, "zip", StringComparison.OrdinalIgnoreCase) ? "zip" : "msi";
|
||||
public static string NormalizeType(string? type) => type?.ToLowerInvariant() switch
|
||||
{
|
||||
"zip" => "zip",
|
||||
"linux-x64" or "linux-arm64" or "osx-x64" or "osx-arm64" => type.ToLowerInvariant(),
|
||||
_ => "msi",
|
||||
};
|
||||
|
||||
/// <summary>Directories searched, most specific first.</summary>
|
||||
private IEnumerable<string> CandidateDirectories()
|
||||
|
||||
+47
-7
@@ -13,6 +13,7 @@ using Backend.Scripts;
|
||||
using Backend.Security;
|
||||
using Backend.Settings;
|
||||
using Backend.Shell;
|
||||
using Backend.Tls;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -81,6 +82,28 @@ builder.Services.ConfigureHttpJsonOptions(options =>
|
||||
var proxySettings = ProxySettings.FromConfiguration(builder.Configuration);
|
||||
builder.Services.AddSingleton(proxySettings);
|
||||
|
||||
// ── Built-in encryption (self-signed, on by default) ─────────────────────
|
||||
// The listener serves HTTPS with a locally managed chain (root >
|
||||
// intermediate > leaf, auto-renewed, hot-swapped) so the proxy-to-server
|
||||
// hop cannot be sniffed; TLS_SELF_SIGNED=0 opts out. Proxies either skip
|
||||
// verification (the hop is still encrypted — the roots just aren't
|
||||
// distributed) or import root+intermediate. Public TLS stays at the edge.
|
||||
var tlsSettings = TlsSettings.FromConfiguration(builder.Configuration);
|
||||
builder.Services.AddSingleton(tlsSettings);
|
||||
SelfSignedTlsManager? tlsManager = null;
|
||||
if (tlsSettings.Enabled)
|
||||
{
|
||||
tlsManager = new SelfSignedTlsManager(tlsSettings);
|
||||
builder.Services.AddSingleton(tlsManager);
|
||||
builder.Services.AddHostedService<TlsRenewalService>();
|
||||
builder.WebHost.ConfigureKestrel(kestrel => kestrel.ConfigureHttpsDefaults(https =>
|
||||
https.ServerCertificateSelector = (_, _) => tlsManager.ServerCertificate));
|
||||
var listenUrls = builder.Configuration["urls"] is { Length: > 0 } configured
|
||||
? configured
|
||||
: "http://0.0.0.0:8080";
|
||||
builder.WebHost.UseUrls(listenUrls.Replace("http://", "https://", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
// ── Persistence ──────────────────────────────────────────────────────────
|
||||
// SQLite by default; Postgres and SQL Server are selected with
|
||||
// DATABASE_PROVIDER + DATABASE_CONNECTION_STRING. Each provider carries its
|
||||
@@ -174,6 +197,23 @@ builder.Services.AddRateLimiter(options =>
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// The chain must exist before Kestrel accepts the first TLS handshake.
|
||||
if (tlsManager is not null)
|
||||
{
|
||||
tlsManager.EnsureChain(app.Logger);
|
||||
if (tlsManager.UsesWindowsStore)
|
||||
{
|
||||
app.Logger.LogInformation(
|
||||
"Built-in TLS: serving HTTPS with the managed self-signed chain from the Windows certificate stores (proxies: skip verification or import the root+intermediate)");
|
||||
}
|
||||
else
|
||||
{
|
||||
app.Logger.LogInformation(
|
||||
"Built-in TLS: serving HTTPS with the managed self-signed chain in {Directory} (proxies: skip verification or pin fullchain.crt)",
|
||||
tlsSettings.CertificateDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
// Apply EF migrations at startup; seed the demo script in development.
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
@@ -227,16 +267,16 @@ using (var scope = app.Services.CreateScope())
|
||||
}
|
||||
|
||||
// Forwarded headers must run before anything that inspects scheme/host/IP.
|
||||
// Trust defaults to private address space (loopback/RFC1918/CGNAT) so the
|
||||
// stack drops behind any reverse proxy with zero configuration; explicit
|
||||
// TRUSTED_PROXIES/TRUSTED_NETWORKS narrows it, TRUST_PROXY=0 disables.
|
||||
if (proxySettings.TrustProxy)
|
||||
{
|
||||
if (!proxySettings.HasExplicitTrustSources && !app.Environment.IsDevelopment())
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"TRUST_PROXY=1 requires TRUSTED_PROXIES or TRUSTED_NETWORKS outside development mode. " +
|
||||
"Refusing to trust X-Forwarded-* headers from anywhere.");
|
||||
}
|
||||
|
||||
app.UseForwardedHeaders(proxySettings.ToForwardedHeadersOptions());
|
||||
app.Logger.LogInformation(
|
||||
proxySettings.HasExplicitTrustSources
|
||||
? "Forwarded headers trusted from the configured proxies/networks"
|
||||
: "Forwarded headers trusted from private networks (loopback, RFC1918, CGNAT) — set TRUSTED_NETWORKS to narrow");
|
||||
}
|
||||
|
||||
// Structured request logging: one line per request, enriched with the
|
||||
|
||||
@@ -4,12 +4,26 @@ using Microsoft.AspNetCore.HttpOverrides;
|
||||
namespace Backend.Proxy;
|
||||
|
||||
/// <summary>
|
||||
/// Reverse-proxy trust configuration. TRUST_PROXY=1 alone is not enough:
|
||||
/// outside development mode at least one trusted proxy or network must be
|
||||
/// configured, otherwise forwarded headers are ignored.
|
||||
/// Reverse-proxy trust configuration. Forwarded headers are trusted BY DEFAULT
|
||||
/// from private address space — loopback, RFC1918 and CGNAT — so slapping the
|
||||
/// stack behind a reverse proxy (cloud or LAN) needs zero configuration.
|
||||
/// Setting TRUSTED_PROXIES / TRUSTED_NETWORKS replaces those defaults with an
|
||||
/// explicit allow-list (narrow this on networks where peers are untrusted),
|
||||
/// and TRUST_PROXY=0 disables forwarded-header processing entirely.
|
||||
/// </summary>
|
||||
public sealed class ProxySettings
|
||||
{
|
||||
/// <summary>Private ranges a reverse proxy realistically lives in.</summary>
|
||||
public static readonly IReadOnlyList<(IPAddress Prefix, int PrefixLength)> DefaultTrustedNetworks =
|
||||
[
|
||||
(IPAddress.Parse("127.0.0.0"), 8), // loopback
|
||||
(IPAddress.IPv6Loopback, 128), // ::1
|
||||
(IPAddress.Parse("10.0.0.0"), 8), // RFC1918
|
||||
(IPAddress.Parse("172.16.0.0"), 12), // RFC1918
|
||||
(IPAddress.Parse("192.168.0.0"), 16), // RFC1918
|
||||
(IPAddress.Parse("100.64.0.0"), 10), // CGNAT (RFC6598)
|
||||
];
|
||||
|
||||
public bool TrustProxy { get; init; }
|
||||
public IReadOnlyList<IPAddress> TrustedProxies { get; init; } = [];
|
||||
public IReadOnlyList<(IPAddress Prefix, int PrefixLength)> TrustedNetworks { get; init; } = [];
|
||||
@@ -18,9 +32,14 @@ public sealed class ProxySettings
|
||||
|
||||
public bool HasExplicitTrustSources => TrustedProxies.Count > 0 || TrustedNetworks.Count > 0;
|
||||
|
||||
/// <summary>The networks actually applied: explicit config, or the private-range defaults.</summary>
|
||||
public IReadOnlyList<(IPAddress Prefix, int PrefixLength)> EffectiveNetworks
|
||||
=> HasExplicitTrustSources ? TrustedNetworks : DefaultTrustedNetworks;
|
||||
|
||||
public static ProxySettings FromConfiguration(IConfiguration configuration)
|
||||
{
|
||||
var trustProxy = configuration["TRUST_PROXY"] == "1";
|
||||
// Trust is the default; TRUST_PROXY=0 opts out entirely.
|
||||
var trustProxy = configuration["TRUST_PROXY"] != "0";
|
||||
|
||||
var proxies = SplitList(configuration["TRUSTED_PROXIES"])
|
||||
.Select(value => IPAddress.TryParse(value, out var ip) ? ip : null)
|
||||
@@ -63,7 +82,9 @@ public sealed class ProxySettings
|
||||
ForwardLimit = ForwardLimit,
|
||||
};
|
||||
|
||||
// Do NOT trust every source: clear defaults, add configured ones only.
|
||||
// Never trust every source: clear the framework defaults, then apply
|
||||
// the explicit allow-list — or the private-range defaults when none
|
||||
// was configured.
|
||||
options.KnownProxies.Clear();
|
||||
options.KnownIPNetworks.Clear();
|
||||
foreach (var proxy in TrustedProxies)
|
||||
@@ -71,7 +92,7 @@ public sealed class ProxySettings
|
||||
options.KnownProxies.Add(proxy);
|
||||
}
|
||||
|
||||
foreach (var (prefix, length) in TrustedNetworks)
|
||||
foreach (var (prefix, length) in EffectiveNetworks)
|
||||
{
|
||||
options.KnownIPNetworks.Add(new System.Net.IPNetwork(prefix, length));
|
||||
}
|
||||
|
||||
@@ -28,11 +28,14 @@ public static class SettingsEndpoints
|
||||
/// The externally reachable base URL for display and generated commands:
|
||||
/// PUBLIC_SERVER_URL when set, else derived from trusted forwarded headers.
|
||||
/// </summary>
|
||||
private static IResult GetServerInfo(HttpContext context, IConfiguration configuration)
|
||||
private static IResult GetServerInfo(HttpContext context, IConfiguration configuration, Backend.Tls.TlsSettings tls)
|
||||
=> Results.Ok(new
|
||||
{
|
||||
baseUrl = Backend.Proxy.PublicUrl.Resolve(context, configuration),
|
||||
fromEnvironment = Backend.Proxy.PublicUrl.IsConfigured(configuration),
|
||||
// Direct self-signed serving: generated commands must skip TLS
|
||||
// verification (the hop is still encrypted).
|
||||
selfSignedDirect = tls.IsSelfSignedDirect(context),
|
||||
});
|
||||
|
||||
private static async Task<IResult> GetS3Async(S3SettingsService settings, CancellationToken cancellationToken)
|
||||
|
||||
@@ -144,12 +144,16 @@ public sealed class NatsSidecar(IConfiguration configuration, ILogger<NatsSideca
|
||||
/// <summary>Polls the monitor endpoint so callers connect to a live server.</summary>
|
||||
private async Task WaitForReadyAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var monitor = configuration["NATS_MONITOR_URL"] is { Length: > 0 } url
|
||||
? url.TrimEnd('/')
|
||||
: "http://127.0.0.1:8222";
|
||||
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(2) };
|
||||
for (var attempt = 0; attempt < 40; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await http.GetAsync("http://127.0.0.1:8222/healthz", cancellationToken);
|
||||
var response = await http.GetAsync($"{monitor}/healthz", cancellationToken);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
logger.LogInformation("NATS sidecar is ready");
|
||||
|
||||
@@ -9,7 +9,7 @@ namespace Backend.Standalone;
|
||||
/// <summary>
|
||||
/// Standalone-server commands for the combined single-binary deployment:
|
||||
///
|
||||
/// setup [--admin-user U] [--admin-password P]
|
||||
/// setup [--admin-user U] [--admin-password P] [--tls 0]
|
||||
/// — generate NATS keys + sidecar config + appsettings,
|
||||
/// downloading nats-server for this platform if absent
|
||||
/// service install — register as a Windows service / systemd unit
|
||||
@@ -29,14 +29,50 @@ public static class ServerCli
|
||||
{
|
||||
// Bare `setup` fully configures the server: admin/admin unless the
|
||||
// flags override — and the defaulted password forces a reset prompt
|
||||
// on the first sign-in.
|
||||
// on the first sign-in. Port flags let several instances share a box
|
||||
// (one directory per instance; pair with `service install --name`).
|
||||
var adminUser = "admin";
|
||||
var adminPassword = "admin";
|
||||
var passwordDefaulted = true;
|
||||
var httpPort = 9080;
|
||||
var bindAddress = "0.0.0.0";
|
||||
var natsPort = 4222;
|
||||
var natsWsPort = 9222;
|
||||
var natsMonitorPort = 8222;
|
||||
// Self-signed TLS is on by default; --tls 0 (or an unchecked MSI
|
||||
// checkbox, which passes an empty value) opts out.
|
||||
var selfSignedTls = true;
|
||||
for (var i = 0; i < args.Length - 1; i++)
|
||||
{
|
||||
switch (args[i])
|
||||
{
|
||||
case "--tls":
|
||||
// The MSI always passes a value ("" unchecked, "1"
|
||||
// checked); humans may use the bare flag or --tls 0.
|
||||
var tlsValue = args[++i];
|
||||
if (tlsValue.StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
selfSignedTls = true;
|
||||
i--;
|
||||
}
|
||||
else
|
||||
{
|
||||
selfSignedTls = tlsValue == "1";
|
||||
}
|
||||
|
||||
break;
|
||||
case "--bind":
|
||||
var candidate = args[++i];
|
||||
if (!System.Net.IPAddress.TryParse(candidate, out var parsed))
|
||||
{
|
||||
throw new ArgumentException($"--bind must be an IP address (got '{candidate}').");
|
||||
}
|
||||
|
||||
// IPv6 literals need brackets in the Urls syntax.
|
||||
bindAddress = parsed.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6
|
||||
? $"[{parsed}]"
|
||||
: parsed.ToString();
|
||||
break;
|
||||
case "--admin-user":
|
||||
adminUser = args[++i];
|
||||
break;
|
||||
@@ -46,9 +82,32 @@ public static class ServerCli
|
||||
// kept: a literal "admin" password always forces the reset.
|
||||
passwordDefaulted = adminPassword == "admin";
|
||||
break;
|
||||
// Short aliases keep the MSI's custom-action command inside
|
||||
// the 255-character CustomAction table column (ICE03).
|
||||
case "--http-port":
|
||||
case "--http":
|
||||
httpPort = ParsePort(args[++i], "--http-port");
|
||||
break;
|
||||
case "--nats-port":
|
||||
case "--nats":
|
||||
natsPort = ParsePort(args[++i], "--nats-port");
|
||||
break;
|
||||
case "--nats-ws-port":
|
||||
case "--ws":
|
||||
natsWsPort = ParsePort(args[++i], "--nats-ws-port");
|
||||
break;
|
||||
case "--nats-monitor-port":
|
||||
case "--monitor":
|
||||
natsMonitorPort = ParsePort(args[++i], "--nats-monitor-port");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (args.Length > 0 && args[^1] == "--tls")
|
||||
{
|
||||
selfSignedTls = true;
|
||||
}
|
||||
|
||||
var baseDir = AppContext.BaseDirectory;
|
||||
var natsDir = Path.Combine(baseDir, "nats");
|
||||
var secretsDir = Path.Combine(baseDir, "secrets", "nats");
|
||||
@@ -85,21 +144,21 @@ public static class ServerCli
|
||||
{
|
||||
// Paths are RELATIVE to the config file: nats-server mangles
|
||||
// Windows drive-letter absolutes in `include` directives.
|
||||
File.WriteAllText(natsConf, """
|
||||
File.WriteAllText(natsConf, $$"""
|
||||
# Generated by `setup` for the standalone ExecuteR server.
|
||||
server_name: executer-standalone
|
||||
|
||||
# Local-only listeners: the server binary proxies /messaging/*
|
||||
# to the websocket port; nothing here is exposed publicly.
|
||||
listen: 127.0.0.1:4222
|
||||
http: 127.0.0.1:8222
|
||||
listen: 127.0.0.1:{{natsPort}}
|
||||
http: 127.0.0.1:{{natsMonitorPort}}
|
||||
|
||||
jetstream {
|
||||
store_dir: "../data/jetstream"
|
||||
}
|
||||
|
||||
websocket {
|
||||
listen: 127.0.0.1:9222
|
||||
listen: 127.0.0.1:{{natsWsPort}}
|
||||
no_tls: true
|
||||
}
|
||||
|
||||
@@ -107,6 +166,10 @@ public static class ServerCli
|
||||
""");
|
||||
Console.WriteLine($"Wrote {natsConf}");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"Existing {natsConf} kept — delete it and appsettings.json to apply new ports.");
|
||||
}
|
||||
|
||||
// Server settings: the default configuration for standalone mode.
|
||||
var appsettings = Path.Combine(baseDir, "appsettings.json");
|
||||
@@ -116,19 +179,27 @@ public static class ServerCli
|
||||
var accountPublic = File.ReadAllText(Path.Combine(secretsDir, "account.pub")).Trim();
|
||||
File.WriteAllText(appsettings, $$"""
|
||||
{
|
||||
"Urls": "http://0.0.0.0:9080",
|
||||
"Urls": "http://{{bindAddress}}:{{httpPort}}",
|
||||
"DATABASE_PATH": "{{Path.Combine(dataDir, "app.db").Replace('\\', '/')}}",
|
||||
"DATAPROTECTION_PATH": "{{Path.Combine(dataDir, "keys").Replace('\\', '/')}}",
|
||||
"LOG_PATH": "{{Path.Combine(dataDir, "logs").Replace('\\', '/')}}",
|
||||
"AGENT_PACKAGE_PATH": "{{Path.Combine(baseDir, "agent-package").Replace('\\', '/')}}",
|
||||
"NATS_URL": "nats://127.0.0.1:4222",
|
||||
"NATS_URL": "nats://127.0.0.1:{{natsPort}}",
|
||||
"NATS_SIDECAR": "1",
|
||||
"NATS_WS_PROXY": "ws://127.0.0.1:9222",
|
||||
"NATS_WS_PROXY": "ws://127.0.0.1:{{natsWsPort}}",
|
||||
"NATS_MONITOR_URL": "http://127.0.0.1:{{natsMonitorPort}}",
|
||||
"NATS_ACCOUNT_SIGNING_SEED": "{{signingSeed}}",
|
||||
"NATS_ACCOUNT_PUBLIC_KEY": "{{accountPublic}}",
|
||||
"INITIAL_ADMIN_USERNAME": "{{adminUser}}",
|
||||
"INITIAL_ADMIN_PASSWORD": "{{adminPassword}}",
|
||||
"INITIAL_ADMIN_MUST_CHANGE": "{{(passwordDefaulted ? "1" : "0")}}"
|
||||
"INITIAL_ADMIN_MUST_CHANGE": "{{(passwordDefaulted ? "1" : "0")}}",
|
||||
|
||||
"TLS_SELF_SIGNED": "{{(selfSignedTls ? "1" : "0")}}",
|
||||
"TLS_CERT_DIR": "",
|
||||
"PUBLIC_SERVER_URL": "",
|
||||
"TRUST_PROXY": "1",
|
||||
"TRUSTED_NETWORKS": "",
|
||||
"TRUSTED_HOSTS": ""
|
||||
}
|
||||
""");
|
||||
Console.WriteLine($"Wrote {appsettings}");
|
||||
@@ -139,11 +210,26 @@ public static class ServerCli
|
||||
Console.WriteLine(passwordDefaulted
|
||||
? $" - First sign-in: {adminUser} / admin — a new password is required immediately."
|
||||
: $" - First sign-in: {adminUser} / <your password>.");
|
||||
Console.WriteLine(" - Run the binary directly, or `service install` to run in the background.");
|
||||
var scheme = selfSignedTls ? "https" : "http";
|
||||
Console.WriteLine($" - UI + API on {scheme}://{bindAddress}:{httpPort} (NATS local-only on {natsPort}/{natsWsPort}/{natsMonitorPort}).");
|
||||
if (selfSignedTls)
|
||||
{
|
||||
Console.WriteLine(" - Self-signed TLS: the hop is encrypted; reverse proxies either skip");
|
||||
Console.WriteLine(" verification (not insecure — the roots just aren't distributed) or");
|
||||
Console.WriteLine(" import the root+intermediate to establish trust (re-import when they");
|
||||
Console.WriteLine(" rotate at expiry). Follow your organization's security standards.");
|
||||
}
|
||||
|
||||
Console.WriteLine(" - Run the binary directly, or `service install` (add --name for extra instances).");
|
||||
Console.WriteLine(" - Put a TLS-terminating proxy in front for production use.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int ParsePort(string value, string flag)
|
||||
=> int.TryParse(value, out var port) && port is >= 1 and <= 65535
|
||||
? port
|
||||
: throw new ArgumentException($"{flag} must be a port between 1 and 65535.");
|
||||
|
||||
/// <summary>
|
||||
/// Downloads and unpacks nats-server for the current OS/architecture when
|
||||
/// it is not already next to the binary. Idempotent; packaged bundles ship
|
||||
@@ -243,45 +329,61 @@ public static class ServerCli
|
||||
{
|
||||
if (args.Length == 0)
|
||||
{
|
||||
Console.Error.WriteLine("Usage: service install|uninstall");
|
||||
Console.Error.WriteLine("Usage: service install|uninstall [--name <service-name>]");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var exe = Environment.ProcessPath
|
||||
?? throw new InvalidOperationException("Cannot determine the executable path.");
|
||||
|
||||
// --name lets several instances (one directory each, distinct ports
|
||||
// from `setup`) register side by side on the same box.
|
||||
var name = OperatingSystem.IsWindows() ? WindowsServiceName : SystemdUnitName;
|
||||
for (var i = 1; i < args.Length - 1; i++)
|
||||
{
|
||||
if (args[i] == "--name" && args[i + 1] is { Length: > 0 } custom)
|
||||
{
|
||||
if (!System.Text.RegularExpressions.Regex.IsMatch(custom, "^[A-Za-z0-9._-]+$"))
|
||||
{
|
||||
return Fail("--name may only contain letters, digits, dot, underscore and dash.");
|
||||
}
|
||||
|
||||
name = custom;
|
||||
}
|
||||
}
|
||||
|
||||
return args[0] switch
|
||||
{
|
||||
"install" => OperatingSystem.IsWindows() ? InstallWindows(exe) : InstallSystemd(exe),
|
||||
"uninstall" => OperatingSystem.IsWindows() ? UninstallWindows() : UninstallSystemd(),
|
||||
"install" => OperatingSystem.IsWindows() ? InstallWindows(exe, name) : InstallSystemd(exe, name),
|
||||
"uninstall" => OperatingSystem.IsWindows() ? UninstallWindows(name) : UninstallSystemd(name),
|
||||
_ => Fail($"Unknown service command '{args[0]}'."),
|
||||
};
|
||||
}
|
||||
|
||||
private static int InstallWindows(string exe)
|
||||
private static int InstallWindows(string exe, string name)
|
||||
{
|
||||
// Idempotent: create may fail when the service exists (repair or MSI
|
||||
// upgrade); config then points it at the current binary either way.
|
||||
Run("sc.exe", $"create {WindowsServiceName} binPath= \"\\\"{exe}\\\"\" start= delayed-auto DisplayName= \"ExecuteR Server\"", ignoreErrors: true);
|
||||
Run("sc.exe", $"config {WindowsServiceName} binPath= \"\\\"{exe}\\\"\" start= delayed-auto");
|
||||
Run("sc.exe", $"description {WindowsServiceName} \"ExecuteR control plane (UI, API, messaging).\"");
|
||||
Run("sc.exe", $"failure {WindowsServiceName} reset= 86400 actions= restart/30000/restart/30000/restart/30000");
|
||||
Run("sc.exe", $"start {WindowsServiceName}", ignoreErrors: true);
|
||||
Console.WriteLine($"Service {WindowsServiceName} installed and started.");
|
||||
Run("sc.exe", $"create {name} binPath= \"\\\"{exe}\\\"\" start= delayed-auto DisplayName= \"ExecuteR Server ({name})\"", ignoreErrors: true);
|
||||
Run("sc.exe", $"config {name} binPath= \"\\\"{exe}\\\"\" start= delayed-auto");
|
||||
Run("sc.exe", $"description {name} \"ExecuteR control plane (UI, API, messaging).\"");
|
||||
Run("sc.exe", $"failure {name} reset= 86400 actions= restart/30000/restart/30000/restart/30000");
|
||||
Run("sc.exe", $"start {name}", ignoreErrors: true);
|
||||
Console.WriteLine($"Service {name} installed and started.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int UninstallWindows()
|
||||
private static int UninstallWindows(string name)
|
||||
{
|
||||
Run("sc.exe", $"stop {WindowsServiceName}", ignoreErrors: true);
|
||||
Run("sc.exe", $"delete {WindowsServiceName}");
|
||||
Console.WriteLine($"Service {WindowsServiceName} stopped and removed.");
|
||||
Run("sc.exe", $"stop {name}", ignoreErrors: true);
|
||||
Run("sc.exe", $"delete {name}");
|
||||
Console.WriteLine($"Service {name} stopped and removed.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int InstallSystemd(string exe)
|
||||
private static int InstallSystemd(string exe, string name)
|
||||
{
|
||||
var unit = $"/etc/systemd/system/{SystemdUnitName}.service";
|
||||
var unit = $"/etc/systemd/system/{name}.service";
|
||||
File.WriteAllText(unit, $"""
|
||||
[Unit]
|
||||
Description=ExecuteR Server (control plane: UI, API, messaging)
|
||||
@@ -299,22 +401,22 @@ public static class ServerCli
|
||||
WantedBy=multi-user.target
|
||||
""");
|
||||
Run("systemctl", "daemon-reload");
|
||||
Run("systemctl", $"enable --now {SystemdUnitName}");
|
||||
Console.WriteLine($"systemd unit {SystemdUnitName} installed and started.");
|
||||
Run("systemctl", $"enable --now {name}");
|
||||
Console.WriteLine($"systemd unit {name} installed and started.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int UninstallSystemd()
|
||||
private static int UninstallSystemd(string name)
|
||||
{
|
||||
Run("systemctl", $"disable --now {SystemdUnitName}", ignoreErrors: true);
|
||||
var unit = $"/etc/systemd/system/{SystemdUnitName}.service";
|
||||
Run("systemctl", $"disable --now {name}", ignoreErrors: true);
|
||||
var unit = $"/etc/systemd/system/{name}.service";
|
||||
if (File.Exists(unit))
|
||||
{
|
||||
File.Delete(unit);
|
||||
}
|
||||
|
||||
Run("systemctl", "daemon-reload");
|
||||
Console.WriteLine($"systemd unit {SystemdUnitName} stopped and removed.");
|
||||
Console.WriteLine($"systemd unit {name} stopped and removed.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
namespace Backend.Tls;
|
||||
|
||||
/// <summary>Chain lifetimes and how early each link is re-issued.</summary>
|
||||
public sealed record TlsLifetimes(
|
||||
TimeSpan Root,
|
||||
TimeSpan Intermediate,
|
||||
TimeSpan Leaf,
|
||||
TimeSpan RootRenewalMargin,
|
||||
TimeSpan IntermediateRenewalMargin,
|
||||
TimeSpan LeafRenewalMargin)
|
||||
{
|
||||
public static readonly TlsLifetimes Default = new(
|
||||
Root: TimeSpan.FromDays(3650),
|
||||
Intermediate: TimeSpan.FromDays(1825),
|
||||
Leaf: TimeSpan.FromDays(365),
|
||||
RootRenewalMargin: TimeSpan.FromDays(365),
|
||||
IntermediateRenewalMargin: TimeSpan.FromDays(180),
|
||||
LeafRenewalMargin: TimeSpan.FromDays(30));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Owns the managed self-signed chain: ECDSA root > intermediate > leaf,
|
||||
/// created on first boot, re-issued ahead of expiry, hot-swapped into the
|
||||
/// live listener through <see cref="ServerCertificate"/> (Kestrel's
|
||||
/// certificate selector reads it on every handshake — renewals need no
|
||||
/// restart). Windows persists to the machine certificate stores; everywhere
|
||||
/// else (or with TLS_CERT_DIR set) the chain is PEM files.
|
||||
/// </summary>
|
||||
public sealed class SelfSignedTlsManager
|
||||
{
|
||||
private readonly Lock gate = new();
|
||||
private readonly TlsSettings settings;
|
||||
private readonly TlsLifetimes lifetimes;
|
||||
private readonly ITlsPersistence persistence;
|
||||
private X509Certificate2? leaf;
|
||||
|
||||
public SelfSignedTlsManager(TlsSettings settings, TlsLifetimes? lifetimes = null)
|
||||
{
|
||||
this.settings = settings;
|
||||
this.lifetimes = lifetimes ?? TlsLifetimes.Default;
|
||||
persistence = CreatePersistence(settings);
|
||||
}
|
||||
|
||||
private static ITlsPersistence CreatePersistence(TlsSettings settings)
|
||||
{
|
||||
if (OperatingSystem.IsWindows() && settings.UseWindowsStore && WindowsStoreTlsPersistence.IsAvailable())
|
||||
{
|
||||
return new WindowsStoreTlsPersistence(settings.CertificateDirectory);
|
||||
}
|
||||
|
||||
return new FileTlsPersistence(settings.CertificateDirectory);
|
||||
}
|
||||
|
||||
public bool UsesWindowsStore => persistence is WindowsStoreTlsPersistence;
|
||||
|
||||
/// <summary>The current server certificate; null until the first EnsureChain.</summary>
|
||||
public X509Certificate2? ServerCertificate => Volatile.Read(ref leaf);
|
||||
|
||||
/// <summary>
|
||||
/// Creates or re-issues whatever links are missing, expiring, or no
|
||||
/// longer signed by the current parent (a rotated root cascades down).
|
||||
/// Idempotent; returns true when anything was issued.
|
||||
/// </summary>
|
||||
public bool EnsureChain(ILogger logger)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var changed = false;
|
||||
|
||||
var root = persistence.Load(TlsRole.Root);
|
||||
if (!IsUsable(root, now, lifetimes.RootRenewalMargin))
|
||||
{
|
||||
root = persistence.Save(TlsRole.Root, CreateRoot(now));
|
||||
logger.LogInformation(
|
||||
"Self-signed TLS: issued a new root CA (valid to {NotAfter:u})",
|
||||
root.NotAfter.ToUniversalTime());
|
||||
changed = true;
|
||||
}
|
||||
|
||||
var intermediate = persistence.Load(TlsRole.Intermediate);
|
||||
if (!IsUsable(intermediate, now, lifetimes.IntermediateRenewalMargin)
|
||||
|| !IsIssuedBy(intermediate, root))
|
||||
{
|
||||
intermediate = persistence.Save(TlsRole.Intermediate, CreateIntermediate(root, now));
|
||||
logger.LogInformation(
|
||||
"Self-signed TLS: issued a new intermediate CA (valid to {NotAfter:u})",
|
||||
intermediate.NotAfter.ToUniversalTime());
|
||||
changed = true;
|
||||
}
|
||||
|
||||
var current = persistence.Load(TlsRole.Leaf);
|
||||
if (!IsUsable(current, now, lifetimes.LeafRenewalMargin)
|
||||
|| !IsIssuedBy(current, root, intermediate))
|
||||
{
|
||||
current = persistence.Save(TlsRole.Leaf, CreateLeaf(intermediate, now));
|
||||
logger.LogInformation(
|
||||
"Self-signed TLS: issued a new server certificate for {DnsNames} (valid to {NotAfter:u})",
|
||||
string.Join(", ", settings.DnsNames), current.NotAfter.ToUniversalTime());
|
||||
changed = true;
|
||||
}
|
||||
|
||||
persistence.Complete(root, intermediate, current);
|
||||
Volatile.Write(ref leaf, current);
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsUsable(
|
||||
[NotNullWhen(true)] X509Certificate2? certificate, DateTimeOffset now, TimeSpan renewalMargin)
|
||||
=> certificate is not null
|
||||
&& certificate.HasPrivateKey
|
||||
&& certificate.NotBefore.ToUniversalTime() <= now.AddMinutes(5)
|
||||
&& certificate.NotAfter.ToUniversalTime() > now + renewalMargin;
|
||||
|
||||
/// <summary>Real signature validation, so a rotated parent re-issues the children.</summary>
|
||||
private static bool IsIssuedBy(X509Certificate2 child, X509Certificate2 root, X509Certificate2? intermediate = null)
|
||||
{
|
||||
using var chain = new X509Chain();
|
||||
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
|
||||
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
||||
chain.ChainPolicy.CustomTrustStore.Add(root);
|
||||
if (intermediate is not null)
|
||||
{
|
||||
chain.ChainPolicy.ExtraStore.Add(intermediate);
|
||||
}
|
||||
|
||||
return chain.Build(child);
|
||||
}
|
||||
|
||||
private X509Certificate2 CreateRoot(DateTimeOffset now)
|
||||
{
|
||||
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP384);
|
||||
var request = new CertificateRequest(TlsSubjects.Root, key, HashAlgorithmName.SHA384);
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(
|
||||
certificateAuthority: true, hasPathLengthConstraint: true, pathLengthConstraint: 1, critical: true));
|
||||
request.CertificateExtensions.Add(new X509KeyUsageExtension(
|
||||
X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, critical: true));
|
||||
request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false));
|
||||
return request.CreateSelfSigned(now.AddMinutes(-5), now + lifetimes.Root);
|
||||
}
|
||||
|
||||
private X509Certificate2 CreateIntermediate(X509Certificate2 root, DateTimeOffset now)
|
||||
{
|
||||
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP384);
|
||||
var request = new CertificateRequest(TlsSubjects.Intermediate, key, HashAlgorithmName.SHA384);
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(
|
||||
certificateAuthority: true, hasPathLengthConstraint: true, pathLengthConstraint: 0, critical: true));
|
||||
request.CertificateExtensions.Add(new X509KeyUsageExtension(
|
||||
X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, critical: true));
|
||||
request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false));
|
||||
request.CertificateExtensions.Add(
|
||||
X509AuthorityKeyIdentifierExtension.CreateFromCertificate(
|
||||
root, includeKeyIdentifier: true, includeIssuerAndSerial: false));
|
||||
using var issued = request.Create(root, now.AddMinutes(-5), NotAfter(now + lifetimes.Intermediate, root), Serial());
|
||||
return issued.CopyWithPrivateKey(key);
|
||||
}
|
||||
|
||||
private X509Certificate2 CreateLeaf(X509Certificate2 intermediate, DateTimeOffset now)
|
||||
{
|
||||
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
||||
var request = new CertificateRequest(TlsSubjects.Leaf, key, HashAlgorithmName.SHA256);
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(
|
||||
certificateAuthority: false, hasPathLengthConstraint: false, pathLengthConstraint: 0, critical: true));
|
||||
request.CertificateExtensions.Add(new X509KeyUsageExtension(
|
||||
X509KeyUsageFlags.DigitalSignature, critical: true));
|
||||
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(
|
||||
[new Oid("1.3.6.1.5.5.7.3.1")], critical: false)); // TLS server authentication
|
||||
|
||||
var san = new SubjectAlternativeNameBuilder();
|
||||
foreach (var name in settings.DnsNames)
|
||||
{
|
||||
san.AddDnsName(name);
|
||||
}
|
||||
|
||||
foreach (var address in settings.IpAddresses)
|
||||
{
|
||||
san.AddIpAddress(address);
|
||||
}
|
||||
|
||||
request.CertificateExtensions.Add(san.Build());
|
||||
request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false));
|
||||
request.CertificateExtensions.Add(
|
||||
X509AuthorityKeyIdentifierExtension.CreateFromCertificate(
|
||||
intermediate, includeKeyIdentifier: true, includeIssuerAndSerial: false));
|
||||
using var issued = request.Create(
|
||||
intermediate, now.AddMinutes(-5), NotAfter(now + lifetimes.Leaf, intermediate), Serial());
|
||||
return issued.CopyWithPrivateKey(key);
|
||||
}
|
||||
|
||||
/// <summary>A child must not outlive its issuer.</summary>
|
||||
private static DateTimeOffset NotAfter(DateTimeOffset requested, X509Certificate2 issuer)
|
||||
{
|
||||
var issuerNotAfter = new DateTimeOffset(issuer.NotAfter).AddMinutes(-1);
|
||||
return requested < issuerNotAfter ? requested : issuerNotAfter;
|
||||
}
|
||||
|
||||
private static byte[] Serial()
|
||||
{
|
||||
var serial = RandomNumberGenerator.GetBytes(16);
|
||||
serial[0] &= 0x7F;
|
||||
return serial;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
namespace Backend.Tls;
|
||||
|
||||
internal enum TlsRole
|
||||
{
|
||||
Root,
|
||||
Intermediate,
|
||||
Leaf,
|
||||
}
|
||||
|
||||
internal static class TlsSubjects
|
||||
{
|
||||
public const string Root = "CN=ExecuteR Self-Signed Root CA";
|
||||
public const string Intermediate = "CN=ExecuteR Self-Signed Intermediate CA";
|
||||
public const string Leaf = "CN=ExecuteR Server";
|
||||
|
||||
public static string For(TlsRole role) => role switch
|
||||
{
|
||||
TlsRole.Root => Root,
|
||||
TlsRole.Intermediate => Intermediate,
|
||||
_ => Leaf,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where the managed chain lives. Save replaces any previous certificate for
|
||||
/// the role and returns the instance to keep using (backends may need to
|
||||
/// re-import the key into an OS-appropriate container).
|
||||
/// </summary>
|
||||
internal interface ITlsPersistence
|
||||
{
|
||||
X509Certificate2? Load(TlsRole role);
|
||||
|
||||
X509Certificate2 Save(TlsRole role, X509Certificate2 fresh);
|
||||
|
||||
/// <summary>Called after the chain settles so backends can write derived material.</summary>
|
||||
void Complete(X509Certificate2 root, X509Certificate2 intermediate, X509Certificate2 leaf);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PEM files (root/intermediate/server .crt + .key, keys chmod 600 on unix)
|
||||
/// — the mode for Linux, macOS, containers, and TLS_CERT_DIR overrides.
|
||||
/// </summary>
|
||||
internal sealed class FileTlsPersistence(string directory) : ITlsPersistence
|
||||
{
|
||||
private static readonly Dictionary<TlsRole, (string Cert, string Key)> Names = new()
|
||||
{
|
||||
[TlsRole.Root] = ("root.crt", "root.key"),
|
||||
[TlsRole.Intermediate] = ("intermediate.crt", "intermediate.key"),
|
||||
[TlsRole.Leaf] = ("server.crt", "server.key"),
|
||||
};
|
||||
|
||||
public X509Certificate2? Load(TlsRole role)
|
||||
{
|
||||
var (certName, keyName) = Names[role];
|
||||
var certPath = Path.Combine(directory, certName);
|
||||
var keyPath = Path.Combine(directory, keyName);
|
||||
if (!File.Exists(certPath) || !File.Exists(keyPath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var pem = X509Certificate2.CreateFromPemFile(certPath, keyPath);
|
||||
return WithUsableKey(pem);
|
||||
}
|
||||
catch (CryptographicException)
|
||||
{
|
||||
// Corrupt or mismatched pair: treat as absent and regenerate.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public X509Certificate2 Save(TlsRole role, X509Certificate2 fresh)
|
||||
{
|
||||
WritePem(role, fresh);
|
||||
return WithUsableKey(fresh);
|
||||
}
|
||||
|
||||
/// <summary>Writes the cert (and its key when exportable) as PEM.</summary>
|
||||
public void WritePem(TlsRole role, X509Certificate2 certificate)
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
var (certName, keyName) = Names[role];
|
||||
using var key = certificate.GetECDsaPrivateKey();
|
||||
if (key is not null)
|
||||
{
|
||||
WriteSecret(Path.Combine(directory, keyName), key.ExportPkcs8PrivateKeyPem());
|
||||
}
|
||||
|
||||
File.WriteAllText(Path.Combine(directory, certName), certificate.ExportCertificatePem());
|
||||
}
|
||||
|
||||
public void Complete(X509Certificate2 root, X509Certificate2 intermediate, X509Certificate2 leaf)
|
||||
{
|
||||
// For proxies that prefer pinning the chain over skipping verification.
|
||||
File.WriteAllText(Path.Combine(directory, "fullchain.crt"),
|
||||
leaf.ExportCertificatePem() + '\n'
|
||||
+ intermediate.ExportCertificatePem() + '\n'
|
||||
+ root.ExportCertificatePem() + '\n');
|
||||
}
|
||||
|
||||
/// <summary>SChannel rejects ephemeral PEM keys; round-trip through PFX on Windows.</summary>
|
||||
private static X509Certificate2 WithUsableKey(X509Certificate2 certificate)
|
||||
=> OperatingSystem.IsWindows()
|
||||
? X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pfx), null)
|
||||
: certificate;
|
||||
|
||||
private static void WriteSecret(string path, string content)
|
||||
{
|
||||
File.WriteAllText(path, content);
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Windows machine certificate stores: root in Trusted Root Certification
|
||||
/// Authorities, intermediate in Intermediate Certification Authorities, leaf
|
||||
/// in Personal — each with its private key persisted in the machine key set
|
||||
/// so renewal can re-sign without files on disk. Browsers on the server
|
||||
/// itself trust the chain automatically. The stores stay authoritative, but
|
||||
/// every chain settle also mirrors the PEM files (certs + keys + fullchain)
|
||||
/// to the certificate directory so a local proxy — Caddy, Nginx UI, nginx —
|
||||
/// can bind or trust them, and renewals keep that mirror current.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
internal sealed class WindowsStoreTlsPersistence(string mirrorDirectory) : ITlsPersistence
|
||||
{
|
||||
private readonly FileTlsPersistence mirror = new(mirrorDirectory);
|
||||
|
||||
private static StoreName StoreFor(TlsRole role) => role switch
|
||||
{
|
||||
TlsRole.Root => StoreName.Root,
|
||||
TlsRole.Intermediate => StoreName.CertificateAuthority,
|
||||
_ => StoreName.My,
|
||||
};
|
||||
|
||||
/// <summary>Machine stores need elevation; unelevated runs fall back to files.</summary>
|
||||
public static bool IsAvailable()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
|
||||
store.Open(OpenFlags.ReadWrite);
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public X509Certificate2? Load(TlsRole role)
|
||||
{
|
||||
using var store = new X509Store(StoreFor(role), StoreLocation.LocalMachine);
|
||||
store.Open(OpenFlags.ReadOnly);
|
||||
return store.Certificates
|
||||
.Find(X509FindType.FindBySubjectDistinguishedName, TlsSubjects.For(role), validOnly: false)
|
||||
.Where(certificate => certificate.HasPrivateKey)
|
||||
.MaxBy(certificate => certificate.NotAfter);
|
||||
}
|
||||
|
||||
public X509Certificate2 Save(TlsRole role, X509Certificate2 fresh)
|
||||
{
|
||||
// Exportable keeps the PEM mirror refreshable from the store alone.
|
||||
var persisted = X509CertificateLoader.LoadPkcs12(
|
||||
fresh.Export(X509ContentType.Pfx), null,
|
||||
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
|
||||
| X509KeyStorageFlags.Exportable);
|
||||
persisted.FriendlyName = "ExecuteR self-signed (managed)";
|
||||
|
||||
using var store = new X509Store(StoreFor(role), StoreLocation.LocalMachine);
|
||||
store.Open(OpenFlags.ReadWrite);
|
||||
foreach (var existing in store.Certificates.Find(
|
||||
X509FindType.FindBySubjectDistinguishedName, TlsSubjects.For(role), validOnly: false))
|
||||
{
|
||||
store.Remove(existing);
|
||||
}
|
||||
|
||||
store.Add(persisted);
|
||||
return persisted;
|
||||
}
|
||||
|
||||
public void Complete(X509Certificate2 root, X509Certificate2 intermediate, X509Certificate2 leaf)
|
||||
{
|
||||
// SChannel serves the chain from the stores; the PEM mirror exists
|
||||
// for local proxies. Keys from a pre-Exportable install cannot be
|
||||
// exported — certs still mirror so trust-by-import keeps working.
|
||||
foreach (var (role, certificate) in new[]
|
||||
{
|
||||
(TlsRole.Root, root), (TlsRole.Intermediate, intermediate), (TlsRole.Leaf, leaf),
|
||||
})
|
||||
{
|
||||
try
|
||||
{
|
||||
mirror.WritePem(role, certificate);
|
||||
}
|
||||
catch (CryptographicException)
|
||||
{
|
||||
Directory.CreateDirectory(mirrorDirectory);
|
||||
File.WriteAllText(
|
||||
Path.Combine(mirrorDirectory, role switch
|
||||
{
|
||||
TlsRole.Root => "root.crt",
|
||||
TlsRole.Intermediate => "intermediate.crt",
|
||||
_ => "server.crt",
|
||||
}),
|
||||
certificate.ExportCertificatePem());
|
||||
}
|
||||
}
|
||||
|
||||
mirror.Complete(root, intermediate, leaf);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace Backend.Tls;
|
||||
|
||||
/// <summary>
|
||||
/// Background renewal for the managed self-signed chain: re-runs the
|
||||
/// idempotent EnsureChain periodically so the leaf (and eventually the CAs)
|
||||
/// are re-issued well before expiry and hot-swapped without a restart.
|
||||
/// </summary>
|
||||
public sealed class TlsRenewalService(SelfSignedTlsManager manager, ILogger<TlsRenewalService> logger)
|
||||
: BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromHours(6));
|
||||
try
|
||||
{
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken))
|
||||
{
|
||||
try
|
||||
{
|
||||
manager.EnsureChain(logger);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Self-signed TLS renewal check failed; will retry");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Shutdown.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using System.Net;
|
||||
|
||||
namespace Backend.Tls;
|
||||
|
||||
/// <summary>
|
||||
/// Built-in encryption, ON by default (opt out with TLS_SELF_SIGNED=0): the
|
||||
/// listener serves HTTPS with a locally managed self-signed chain (root >
|
||||
/// intermediate > leaf, auto-renewed) so the hop between the reverse proxy
|
||||
/// and the server cannot be sniffed. This is NOT public TLS termination —
|
||||
/// that stays at the edge; proxies connect with verification off or import
|
||||
/// the exported root+intermediate.
|
||||
/// </summary>
|
||||
public sealed class TlsSettings
|
||||
{
|
||||
public bool Enabled { get; init; }
|
||||
|
||||
/// <summary>PEM storage directory (file mode). Defaults to <data>/tls.</summary>
|
||||
public required string CertificateDirectory { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Persist the chain in the Windows machine certificate stores (root in
|
||||
/// Trusted Roots, intermediate in Intermediate CAs, leaf in Personal)
|
||||
/// instead of PEM files. Setting TLS_CERT_DIR forces file mode anywhere.
|
||||
/// </summary>
|
||||
public bool UseWindowsStore { get; init; }
|
||||
|
||||
public IReadOnlyList<string> DnsNames { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<IPAddress> IpAddresses { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// True when this request reached the self-signed listener directly —
|
||||
/// HTTPS served here with no forwarded headers consumed (a proxied
|
||||
/// request carries X-Original-* after UseForwardedHeaders). Generated
|
||||
/// install commands then include TLS skip-verify so enrollment works
|
||||
/// against the undistributed roots.
|
||||
/// </summary>
|
||||
public bool IsSelfSignedDirect(HttpContext context)
|
||||
=> Enabled
|
||||
&& context.Request.IsHttps
|
||||
&& !context.Request.Headers.ContainsKey("X-Original-Proto")
|
||||
&& !context.Request.Headers.ContainsKey("X-Original-For");
|
||||
|
||||
public static TlsSettings FromConfiguration(IConfiguration configuration)
|
||||
{
|
||||
var certDir = configuration["TLS_CERT_DIR"];
|
||||
var dataDir = Path.GetDirectoryName(Path.GetFullPath(
|
||||
configuration["DATABASE_PATH"] is { Length: > 0 } db ? db : "data/app.db")) ?? "data";
|
||||
|
||||
var dnsNames = new List<string> { "localhost" };
|
||||
var ipAddresses = new List<IPAddress> { IPAddress.Loopback, IPAddress.IPv6Loopback };
|
||||
|
||||
// Verification is off at the proxy, so the SAN set only needs to be
|
||||
// friendly for direct browsing: hostname, FQDN and the bind address.
|
||||
try
|
||||
{
|
||||
var host = Dns.GetHostName();
|
||||
AddDns(dnsNames, host);
|
||||
try
|
||||
{
|
||||
AddDns(dnsNames, Dns.GetHostEntry(host).HostName);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// No resolvable FQDN — hostname and localhost suffice.
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Hostname unavailable; localhost suffices.
|
||||
}
|
||||
|
||||
foreach (var url in (configuration["urls"] ?? string.Empty)
|
||||
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
// Kestrel wildcard hosts (*, +) are not valid URI hosts.
|
||||
if (!Uri.TryCreate(url.Replace("//*", "//wildcard").Replace("//+", "//wildcard"),
|
||||
UriKind.Absolute, out var uri))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (IPAddress.TryParse(uri.Host, out var ip))
|
||||
{
|
||||
if (!ip.Equals(IPAddress.Any) && !ip.Equals(IPAddress.IPv6Any)
|
||||
&& !ipAddresses.Contains(ip))
|
||||
{
|
||||
ipAddresses.Add(ip);
|
||||
}
|
||||
}
|
||||
else if (uri.Host != "wildcard")
|
||||
{
|
||||
AddDns(dnsNames, uri.Host);
|
||||
}
|
||||
}
|
||||
|
||||
return new TlsSettings
|
||||
{
|
||||
Enabled = configuration["TLS_SELF_SIGNED"] != "0",
|
||||
CertificateDirectory = certDir is { Length: > 0 } ? certDir : Path.Combine(dataDir, "tls"),
|
||||
UseWindowsStore = OperatingSystem.IsWindows() && certDir is not { Length: > 0 },
|
||||
DnsNames = dnsNames,
|
||||
IpAddresses = ipAddresses,
|
||||
};
|
||||
}
|
||||
|
||||
private static void AddDns(List<string> names, string candidate)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(candidate)
|
||||
&& !names.Contains(candidate, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
names.Add(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
#=============================================================================
|
||||
# ExecuteR - Caddy site (single self-contained Caddyfile)
|
||||
#=============================================================================
|
||||
#
|
||||
# Fronts the three stack services on one public TLS edge:
|
||||
# / -> WebUI (host port 13080)
|
||||
# /api/ -> Backend API (host port 19080)
|
||||
# /messaging/agent -> NATS WebSocket (host port 19222)
|
||||
# /messaging/browser -> NATS WebSocket (host port 19222)
|
||||
#
|
||||
# BEFORE USE, replace:
|
||||
# control.example.com your public hostname
|
||||
# 10.0.0.10 the Docker host running the ExecuteR stack
|
||||
#
|
||||
# Caddy terminates TLS itself: certificates are obtained and renewed
|
||||
# automatically via ACME - no certificate paths to manage. The :80 listener
|
||||
# (redirect + ACME challenge) is automatic as well. Runs on Windows and
|
||||
# Linux alike: https://caddyserver.com/docs/install
|
||||
#
|
||||
# Standalone server instead of the compose stack? Point all three handles
|
||||
# at the single binary (default https://10.0.0.10:9080 with the
|
||||
# skip-verify transport shown at the bottom).
|
||||
#=============================================================================
|
||||
|
||||
control.example.com {
|
||||
|
||||
# --- Forwarded headers ---------------------------------------------------
|
||||
# Caddy sends X-Forwarded-For / -Proto / -Host on its own. The backend
|
||||
# only honors them from trusted proxy addresses (private networks by
|
||||
# default), so make sure THIS host is covered by TRUSTED_PROXIES /
|
||||
# TRUSTED_NETWORKS. Change the prefix only when mounting under a
|
||||
# sub-path instead of the site root.
|
||||
request_header X-Forwarded-Prefix /
|
||||
|
||||
# Security headers (the app is same-origin; adjust if you embed it).
|
||||
header {
|
||||
X-Content-Type-Options "nosniff"
|
||||
X-Frame-Options "SAMEORIGIN"
|
||||
Referrer-Policy "same-origin"
|
||||
Strict-Transport-Security "max-age=31536000"
|
||||
}
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Optional: restrict the whole site to known networks.
|
||||
# Uncomment and edit, then reload Caddy.
|
||||
# ----------------------------------------------------------------------
|
||||
# @outside {
|
||||
# not remote_ip 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 203.0.113.0/24
|
||||
# }
|
||||
# respond @outside 403
|
||||
|
||||
# ── NATS WebSocket: agents and browsers ───────────────────────────────
|
||||
# WebSocket upgrades pass through reverse_proxy automatically and are
|
||||
# not timed out mid-stream.
|
||||
handle /messaging/* {
|
||||
reverse_proxy 10.0.0.10:19222
|
||||
}
|
||||
|
||||
# ── Backend API (enrollment, sign-in, OIDC callback included) ─────────
|
||||
# Edge rate limiting needs the caddy-ratelimit plugin
|
||||
# (github.com/mholt/caddy-ratelimit); the backend rate limits
|
||||
# enrollment and sign-in itself, so the edge layer is optional here.
|
||||
handle /api/* {
|
||||
reverse_proxy 10.0.0.10:19080
|
||||
}
|
||||
|
||||
# ── WebUI (everything else) ───────────────────────────────────────────
|
||||
handle {
|
||||
reverse_proxy 10.0.0.10:13080
|
||||
}
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Backend running with TLS_SELF_SIGNED=1? Proxy the API upstream over
|
||||
# https instead - the hop stays encrypted; the self-signed roots simply
|
||||
# are not distributed. Either skip verification:
|
||||
#
|
||||
# handle /api/* {
|
||||
# reverse_proxy https://10.0.0.10:19080 {
|
||||
# transport http {
|
||||
# tls
|
||||
# tls_insecure_skip_verify
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
#
|
||||
# ...or import root.crt + intermediate.crt from <data>/tls and pin them
|
||||
# (transport http > tls_trust_pool file ...), re-importing when the
|
||||
# chain rotates at expiry. Follow your organization's security
|
||||
# standards.
|
||||
# ----------------------------------------------------------------------
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
#=============================================================================
|
||||
# ExecuteR - HAProxy edge (single self-contained file)
|
||||
#=============================================================================
|
||||
#
|
||||
# Fronts the three stack services on one public TLS edge:
|
||||
# / -> WebUI (host port 13080)
|
||||
# /api/ -> Backend API (host port 19080)
|
||||
# /messaging/agent -> NATS WebSocket (host port 19222)
|
||||
# /messaging/browser -> NATS WebSocket (host port 19222)
|
||||
#
|
||||
# BEFORE USE, replace:
|
||||
# control.example.com your public hostname
|
||||
# 10.0.0.10 the Docker host running the stack
|
||||
# /etc/haproxy/certs/control.example.com.pem full chain + key in ONE pem
|
||||
#
|
||||
# HAProxy does not obtain certificates itself - renew with your ACME tooling
|
||||
# (acme.sh, certbot) and reload. The :80 frontend passes HTTP-01 challenges
|
||||
# through un-redirected for that.
|
||||
#=============================================================================
|
||||
|
||||
global
|
||||
log stdout format raw local0
|
||||
maxconn 4096
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
option forwardfor
|
||||
timeout connect 5s
|
||||
timeout client 60s
|
||||
timeout server 120s
|
||||
# WebSockets are long-lived; after the upgrade the tunnel timeout
|
||||
# governs them - do not let the edge cut agent sessions.
|
||||
timeout tunnel 1h
|
||||
|
||||
# --- HTTP: ACME passthrough + redirect to HTTPS ------------------------------
|
||||
frontend http_in
|
||||
bind :80
|
||||
acl acme path_beg /.well-known/acme-challenge/
|
||||
use_backend acme_challenge if acme
|
||||
http-request redirect scheme https code 301 unless acme
|
||||
|
||||
backend acme_challenge
|
||||
# Point at wherever your ACME client serves webroot challenges.
|
||||
server acme 127.0.0.1:8402
|
||||
|
||||
# --- HTTPS -------------------------------------------------------------------
|
||||
frontend https_in
|
||||
bind :443 ssl crt /etc/haproxy/certs/control.example.com.pem alpn h2,http/1.1
|
||||
|
||||
# --- Forwarded headers ---------------------------------------------------
|
||||
# option forwardfor (defaults) adds X-Forwarded-For. The backend only
|
||||
# honors forwarded headers from trusted proxy addresses (private
|
||||
# networks by default), so make sure THIS host is covered by
|
||||
# TRUSTED_PROXIES / TRUSTED_NETWORKS.
|
||||
http-request set-header X-Forwarded-Proto https
|
||||
http-request set-header X-Forwarded-Host %[req.hdr(host)]
|
||||
http-request set-header X-Forwarded-Port 443
|
||||
# Change only when mounting under a sub-path instead of the site root.
|
||||
http-request set-header X-Forwarded-Prefix /
|
||||
|
||||
# Security headers (the app is same-origin; adjust if you embed it).
|
||||
http-response set-header X-Content-Type-Options "nosniff"
|
||||
http-response set-header X-Frame-Options "SAMEORIGIN"
|
||||
http-response set-header Referrer-Policy "same-origin"
|
||||
http-response set-header Strict-Transport-Security "max-age=31536000"
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Optional: restrict the whole site to known networks.
|
||||
# Uncomment and edit, then reload HAProxy.
|
||||
# ----------------------------------------------------------------------
|
||||
# acl internal src 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 203.0.113.0/24
|
||||
# http-request deny unless internal
|
||||
|
||||
# --- Edge rate limits: enrollment and sign-in ------------------------
|
||||
stick-table type ip size 100k expire 10m store http_req_rate(1m)
|
||||
acl enroll_path path_beg /api/enrollment/
|
||||
acl auth_path path_beg /api/auth/
|
||||
http-request track-sc0 src if enroll_path or auth_path
|
||||
http-request deny deny_status 429 if enroll_path { sc_http_req_rate(0) gt 10 }
|
||||
http-request deny deny_status 429 if auth_path { sc_http_req_rate(0) gt 20 }
|
||||
|
||||
# --- Routing ----------------------------------------------------------
|
||||
acl messaging path /messaging/agent /messaging/browser
|
||||
acl api path_beg /api/
|
||||
|
||||
use_backend executer_nats if messaging
|
||||
use_backend executer_api if api
|
||||
default_backend executer_webui
|
||||
|
||||
# --- Upstreams ----------------------------------------------------------------
|
||||
# Backend running with TLS_SELF_SIGNED=1? Switch the executer_api server
|
||||
# line to ssl - the hop stays encrypted; the self-signed roots simply are
|
||||
# not distributed. Either skip verification:
|
||||
# server api 10.0.0.10:19080 ssl verify none
|
||||
# ...or import root.crt + intermediate.crt from <data>/tls and pin them:
|
||||
# server api 10.0.0.10:19080 ssl verify required ca-file /etc/haproxy/executer-roots.pem
|
||||
# re-importing when the chain rotates at expiry. Follow your organization's
|
||||
# security standards.
|
||||
|
||||
backend executer_webui
|
||||
server webui 10.0.0.10:13080 check
|
||||
|
||||
backend executer_api
|
||||
# Agent packages can be tens of MB; give downloads room.
|
||||
timeout server 300s
|
||||
server api 10.0.0.10:19080 check
|
||||
|
||||
backend executer_nats
|
||||
server nats 10.0.0.10:19222 check
|
||||
@@ -0,0 +1,23 @@
|
||||
#=============================================================================
|
||||
# ExecuteR - http{}-level companion to executer.conf
|
||||
#=============================================================================
|
||||
#
|
||||
# The WebSocket upgrade map MUST be included at http{} level, NOT inside a
|
||||
# site:
|
||||
#
|
||||
# plain nginx: drop this file in /etc/nginx/conf.d/ (the stock nginx.conf
|
||||
# includes conf.d/*.conf at http level)
|
||||
# Nginx UI: Manage Configs -> create conf.d/executer-http.conf with
|
||||
# this content. Do NOT paste it into the site under Manage
|
||||
# Sites.
|
||||
#
|
||||
# The rate-limit zones live in executer.conf itself - they are fine in a
|
||||
# site file. If your nginx.conf already defines this map, delete the
|
||||
# duplicate here or nginx will refuse to start.
|
||||
#=============================================================================
|
||||
|
||||
# "upgrade" for WebSocket requests, "close" otherwise.
|
||||
map $http_upgrade $connection_upgrade {
|
||||
default upgrade;
|
||||
'' close;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
#=============================================================================
|
||||
# ExecuteR - nginx site (single self-contained file, nginx-ui friendly)
|
||||
# ExecuteR - nginx site (nginx-ui friendly)
|
||||
#=============================================================================
|
||||
#
|
||||
# Fronts the three stack services on one public TLS edge:
|
||||
@@ -13,23 +13,23 @@
|
||||
# 10.0.0.10 the Docker host running the ExecuteR stack
|
||||
# /etc/nginx/ssl/... your certificate paths
|
||||
#
|
||||
# Self-contained: no include/snippet files required.
|
||||
# COMPANION FILE: executer-http.conf carries the WebSocket upgrade map,
|
||||
# which must be included at http{} level - conf.d/ on plain nginx, Manage
|
||||
# Configs in Nginx UI. Everything else, including the rate-limit zones
|
||||
# below, lives right here in the site.
|
||||
#=============================================================================
|
||||
|
||||
# --- http{} level directives ------------------------------------------------
|
||||
# These three must live at http{} level. If your nginx.conf already defines
|
||||
# any of them, delete the duplicate here or nginx will refuse to start.
|
||||
|
||||
# --- Rate-limit zones -------------------------------------------------------
|
||||
limit_req_zone $binary_remote_addr zone=executer_enroll:10m rate=10r/m;
|
||||
limit_req_zone $binary_remote_addr zone=executer_auth:10m rate=20r/m;
|
||||
|
||||
# "upgrade" for WebSocket requests, "close" otherwise.
|
||||
map $http_upgrade $connection_upgrade {
|
||||
default upgrade;
|
||||
'' close;
|
||||
}
|
||||
|
||||
# --- Upstreams --------------------------------------------------------------
|
||||
# If the backend runs with TLS_SELF_SIGNED=1, switch its proxy_pass to
|
||||
# https:// and add `proxy_ssl_verify off;` (the hop stays encrypted; the
|
||||
# self-signed roots simply are not distributed) — or import the exported
|
||||
# root+intermediate and use proxy_ssl_trusted_certificate + proxy_ssl_verify
|
||||
# on, re-importing when the chain rotates at expiry. Follow your
|
||||
# organization's security standards.
|
||||
upstream executer_webui {
|
||||
server 10.0.0.10:13080;
|
||||
keepalive 16;
|
||||
@@ -112,6 +112,7 @@ server {
|
||||
# allow 10.0.0.0/8; # RFC1918 - internal
|
||||
# allow 172.16.0.0/12; # RFC1918 - internal
|
||||
# allow 192.168.0.0/16; # RFC1918 - internal
|
||||
# allow 100.64.0.0/10; # CGNAT - carrier / overlay networks
|
||||
# allow 203.0.113.0/24; # office egress
|
||||
# allow 2001:db8::/32; # office egress (IPv6)
|
||||
# deny all;
|
||||
@@ -128,6 +129,7 @@ server {
|
||||
|
||||
# Optional: agents only from trusted networks.
|
||||
# allow 10.0.0.0/8;
|
||||
# allow 100.64.0.0/10; # CGNAT
|
||||
# deny all;
|
||||
}
|
||||
|
||||
@@ -153,6 +155,7 @@ server {
|
||||
|
||||
# Optional: only let known networks enroll.
|
||||
# allow 10.0.0.0/8;
|
||||
# allow 100.64.0.0/10; # CGNAT
|
||||
# deny all;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,10 +6,14 @@
|
||||
ExecuteR Server MSI: the standalone combined server (UI + API + messaging
|
||||
relay + NATS sidecar) as a Windows service.
|
||||
|
||||
Public properties (uppercase): ADMINUSERNAME ADMINPASSWORD — the initial
|
||||
admin created on first start (defaults Admin/Admin; interactive installs
|
||||
edit them on the account page). After the files land, the installer runs
|
||||
the binary's own cross-platform init:
|
||||
Public properties (uppercase): ADMINUSERNAME ADMINPASSWORD BINDADDRESS
|
||||
HTTPPORT NATSPORT NATSWSPORT NATSMONITORPORT ENABLETLS — the initial
|
||||
admin account plus the listen configuration, all defaulted so a
|
||||
next-next-next install works. ENABLETLS defaults to 1 (Self-Signed TLS
|
||||
on; the Network page checkbox) — silent opt-out passes ENABLETLS="".
|
||||
Interactive installs edit them on the Account and Network pages; silent
|
||||
installs pass them as properties. After the files land, the installer
|
||||
runs the binary's own cross-platform init:
|
||||
|
||||
ExecuteR-Server.exe setup (with the admin user/password flags)
|
||||
ExecuteR-Server.exe service install
|
||||
@@ -43,6 +47,31 @@
|
||||
<Property Id="ADMINUSERNAME" Value="admin" />
|
||||
<Property Id="ADMINPASSWORD" Value="admin" Hidden="yes" />
|
||||
|
||||
<!-- Listen configuration (single-instance defaults). Multiple instances
|
||||
on one machine use the ZIP bundle with distinct ports and custom
|
||||
service names; the MSI installs exactly one. -->
|
||||
<Property Id="BINDADDRESS" Value="0.0.0.0" />
|
||||
<Property Id="HTTPPORT" Value="9080" />
|
||||
<Property Id="NATSPORT" Value="4222" />
|
||||
<Property Id="NATSWSPORT" Value="9222" />
|
||||
<Property Id="NATSMONITORPORT" Value="8222" />
|
||||
|
||||
<!-- Self-Signed TLS is on by default; unchecking the Network page
|
||||
checkbox (or ENABLETLS="" on the command line) opts out. -->
|
||||
<Property Id="ENABLETLS" Value="1" />
|
||||
|
||||
<!-- Finish page: open the UI in the browser (checked by default). The
|
||||
URL resolves at Finish time — wildcard binds become localhost, a
|
||||
concrete bind address is used as typed. -->
|
||||
<Property Id="WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT" Value="Open ExecuteR in the browser" />
|
||||
<Property Id="WIXUI_EXITDIALOGOPTIONALCHECKBOX" Value="1" />
|
||||
<CustomAction Id="LaunchBrowser"
|
||||
BinaryRef="Wix4UtilCA_X64"
|
||||
DllEntry="WixShellExec"
|
||||
Execute="immediate"
|
||||
Impersonate="yes"
|
||||
Return="ignore" />
|
||||
|
||||
<StandardDirectory Id="ProgramFiles64Folder">
|
||||
<Directory Id="INSTALLFOLDER" Name="ExecuteR Server" />
|
||||
</StandardDirectory>
|
||||
@@ -58,8 +87,11 @@
|
||||
</Feature>
|
||||
|
||||
<!-- First-boot init through the binary's own cross-platform CLI. -->
|
||||
<!-- Short port aliases keep this inside the 255-char CA column (ICE03);
|
||||
the quotes around ENABLETLS are load-bearing: unchecked formats to
|
||||
an empty quoted argument, which setup reads as off. -->
|
||||
<SetProperty Id="RunServerSetup"
|
||||
Value=""[INSTALLFOLDER]ExecuteR-Server.exe" setup --admin-user "[ADMINUSERNAME]" --admin-password "[ADMINPASSWORD]""
|
||||
Value=""[INSTALLFOLDER]ExecuteR-Server.exe" setup --admin-user "[ADMINUSERNAME]" --admin-password "[ADMINPASSWORD]" --bind "[BINDADDRESS]" --http [HTTPPORT] --nats [NATSPORT] --ws [NATSWSPORT] --monitor [NATSMONITORPORT] --tls "[ENABLETLS]""
|
||||
Sequence="execute"
|
||||
Before="RunServerSetup" />
|
||||
<CustomAction Id="RunServerSetup"
|
||||
@@ -134,13 +166,84 @@
|
||||
</Control>
|
||||
</Dialog>
|
||||
|
||||
<!-- Splice the page in: overrides outrank the stock set's publishes. -->
|
||||
<Dialog Id="ServerNetworkDlg" Width="370" Height="270" Title="ExecuteR Server Setup">
|
||||
<Control Id="BannerBitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="44"
|
||||
TabSkip="no" Text="!(loc.InstallDirDlgBannerBitmap)" />
|
||||
<Control Id="Title" Type="Text" X="15" Y="6" Width="330" Height="15"
|
||||
Transparent="yes" NoPrefix="yes"
|
||||
Text="{\WixUI_Font_Title}Network settings" />
|
||||
<Control Id="Description" Type="Text" X="25" Y="23" Width="330" Height="15"
|
||||
Transparent="yes" NoPrefix="yes"
|
||||
Text="Where the server listens. The defaults suit most installs." />
|
||||
<Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
|
||||
|
||||
<Control Id="BindLabel" Type="Text" X="20" Y="54" Width="330" Height="12" NoPrefix="yes"
|
||||
Text="&Bind address — 0.0.0.0 listens on every interface; 127.0.0.1 serves only a local reverse proxy:" />
|
||||
<Control Id="BindEdit" Type="Edit" X="20" Y="67" Width="140" Height="16"
|
||||
Property="BINDADDRESS" />
|
||||
|
||||
<Control Id="HttpLabel" Type="Text" X="20" Y="91" Width="330" Height="12" NoPrefix="yes"
|
||||
Text="&HTTP port — serves the UI, the API and enrolling agents:" />
|
||||
<Control Id="HttpEdit" Type="Edit" X="20" Y="104" Width="70" Height="16"
|
||||
Property="HTTPPORT" />
|
||||
|
||||
<Control Id="NatsLabel" Type="Text" X="20" Y="126" Width="330" Height="20" NoPrefix="yes"
|
||||
Text="Internal messaging (NATS) ports — always bound to 127.0.0.1 and never exposed. Change them only if another application already uses one:" />
|
||||
<Control Id="NatsCoreLabel" Type="Text" X="20" Y="147" Width="70" Height="10" NoPrefix="yes" Text="Core" />
|
||||
<Control Id="NatsCoreEdit" Type="Edit" X="20" Y="158" Width="70" Height="16" Property="NATSPORT" />
|
||||
<Control Id="NatsWsLabel" Type="Text" X="110" Y="147" Width="70" Height="10" NoPrefix="yes" Text="WebSocket" />
|
||||
<Control Id="NatsWsEdit" Type="Edit" X="110" Y="158" Width="70" Height="16" Property="NATSWSPORT" />
|
||||
<Control Id="NatsMonLabel" Type="Text" X="200" Y="147" Width="70" Height="10" NoPrefix="yes" Text="Monitor" />
|
||||
<Control Id="NatsMonEdit" Type="Edit" X="200" Y="158" Width="70" Height="16" Property="NATSMONITORPORT" />
|
||||
|
||||
<Control Id="TlsCheck" Type="CheckBox" X="20" Y="178" Width="330" Height="12"
|
||||
Property="ENABLETLS" CheckBoxValue="1"
|
||||
Text="Enable Self-Signed TLS (encrypts this server's traffic; auto-renewed)" />
|
||||
<Control Id="TlsNote" Type="Text" X="32" Y="191" Width="318" Height="24" NoPrefix="yes"
|
||||
Text="Reverse proxies: skip TLS verification (still encrypted — the roots simply are not distributed), or import the root and intermediate to establish trust and re-import when they rotate at expiry. Follow your organization's security standards." />
|
||||
|
||||
<Control Id="Note" Type="Text" X="20" Y="217" Width="330" Height="16" NoPrefix="yes"
|
||||
Text="Everything lands in appsettings.json next to the binary (restart the service to apply). Several instances on one machine: use the ZIP bundle instead." />
|
||||
|
||||
<Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
|
||||
<Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17"
|
||||
Text="!(loc.WixUIBack)" />
|
||||
<Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17"
|
||||
Default="yes" Text="!(loc.WixUINext)" />
|
||||
<Control Id="Cancel" Type="PushButton" X="304" Y="243" Width="56" Height="17"
|
||||
Cancel="yes" Text="!(loc.WixUICancel)">
|
||||
<Publish Event="SpawnDialog" Value="CancelDlg" />
|
||||
</Control>
|
||||
</Dialog>
|
||||
|
||||
<!-- Splice the pages in: overrides outrank the stock set's publishes. -->
|
||||
<Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="ServerConfigDlg"
|
||||
Order="99" Condition="NOT Installed" />
|
||||
<Publish Dialog="ServerConfigDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg" />
|
||||
<Publish Dialog="ServerConfigDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg" />
|
||||
<Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="ServerConfigDlg"
|
||||
<Publish Dialog="ServerConfigDlg" Control="Next" Event="NewDialog" Value="ServerNetworkDlg" />
|
||||
<Publish Dialog="ServerNetworkDlg" Control="Back" Event="NewDialog" Value="ServerConfigDlg" />
|
||||
<Publish Dialog="ServerNetworkDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg" />
|
||||
<Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="ServerNetworkDlg"
|
||||
Order="99" Condition="NOT Installed" />
|
||||
|
||||
<!-- Open the UI on Finish: wildcard binds resolve to localhost and the
|
||||
scheme follows the Self-Signed TLS checkbox. With TLS on, the
|
||||
chain sits in the machine stores, so local browsers trust it. -->
|
||||
<Publish Dialog="ExitDialog" Control="Finish"
|
||||
Property="WixShellExecTarget" Value="http://localhost:[HTTPPORT]/" Order="1"
|
||||
Condition="WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 AND NOT Installed AND ENABLETLS <> "1" AND (BINDADDRESS = "0.0.0.0" OR BINDADDRESS = "::" OR BINDADDRESS = "[::]")" />
|
||||
<Publish Dialog="ExitDialog" Control="Finish"
|
||||
Property="WixShellExecTarget" Value="http://[BINDADDRESS]:[HTTPPORT]/" Order="2"
|
||||
Condition="WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 AND NOT Installed AND ENABLETLS <> "1" AND NOT (BINDADDRESS = "0.0.0.0" OR BINDADDRESS = "::" OR BINDADDRESS = "[::]")" />
|
||||
<Publish Dialog="ExitDialog" Control="Finish"
|
||||
Property="WixShellExecTarget" Value="https://localhost:[HTTPPORT]/" Order="3"
|
||||
Condition="WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 AND NOT Installed AND ENABLETLS = "1" AND (BINDADDRESS = "0.0.0.0" OR BINDADDRESS = "::" OR BINDADDRESS = "[::]")" />
|
||||
<Publish Dialog="ExitDialog" Control="Finish"
|
||||
Property="WixShellExecTarget" Value="https://[BINDADDRESS]:[HTTPPORT]/" Order="4"
|
||||
Condition="WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 AND NOT Installed AND ENABLETLS = "1" AND NOT (BINDADDRESS = "0.0.0.0" OR BINDADDRESS = "::" OR BINDADDRESS = "[::]")" />
|
||||
<Publish Dialog="ExitDialog" Control="Finish"
|
||||
Event="DoAction" Value="LaunchBrowser" Order="5"
|
||||
Condition="WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 AND NOT Installed" />
|
||||
</UI>
|
||||
|
||||
<InstallExecuteSequence>
|
||||
|
||||
@@ -119,5 +119,16 @@
|
||||
<enabledValue><decimal value="1" /></enabledValue>
|
||||
<disabledValue><decimal value="0" /></disabledValue>
|
||||
</policy>
|
||||
|
||||
<!-- TlsSkipVerify (REG_DWORD) -->
|
||||
<policy name="TlsSkipVerify" class="Machine" displayName="$(string.TlsSkipVerify)"
|
||||
explainText="$(string.TlsSkipVerify_Help)"
|
||||
key="SOFTWARE\Policies\ExecuteR"
|
||||
valueName="TlsSkipVerify">
|
||||
<parentCategory ref="ExecuteR" />
|
||||
<supportedOn ref="SUPPORTED_ExecuteR_1_0" />
|
||||
<enabledValue><decimal value="1" /></enabledValue>
|
||||
<disabledValue><decimal value="0" /></disabledValue>
|
||||
</policy>
|
||||
</policies>
|
||||
</policyDefinitions>
|
||||
|
||||
@@ -100,6 +100,17 @@ If you do not configure this policy, the agent uses the locally configured value
|
||||
|
||||
Use Disabled as a hard opt-out for sensitive machines that should be visible in inventory but never remotely scripted.
|
||||
|
||||
The agent reads configuration at service start; restart the "ExecuteR Agent" service (ExecuteRAgent) to apply a change immediately.</string>
|
||||
|
||||
<string id="TlsSkipVerify">Skip TLS certificate verification (self-signed servers)</string>
|
||||
<string id="TlsSkipVerify_Help">Accepts the ExecuteR server's certificate without validation. Intended for servers running the built-in managed self-signed chain without a reverse proxy in front: the connection is still fully TLS-encrypted — the self-signed roots simply are not distributed to the devices, so there is nothing to validate against.
|
||||
|
||||
If you enable this policy, the agent connects to HTTPS servers without validating the certificate chain (enrollment and the persistent messaging connection alike).
|
||||
|
||||
If you disable or do not configure this policy, the agent uses the locally configured value, or full certificate validation by default.
|
||||
|
||||
Do not enable this for servers reached through a proxy with a publicly trusted certificate — leave validation on there. Always follow your organization's security standards.
|
||||
|
||||
The agent reads configuration at service start; restart the "ExecuteR Agent" service (ExecuteRAgent) to apply a change immediately.</string>
|
||||
</stringTable>
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<!--
|
||||
ExecuteR Agent MSI.
|
||||
Public properties (uppercase): SERVERURL BOOTSTRAPTOKEN LOGLEVEL
|
||||
ALLOWREMOTESHELL ALLOWSCRIPTEXECUTION.
|
||||
ALLOWREMOTESHELL ALLOWSCRIPTEXECUTION SKIPTLSVERIFY.
|
||||
Remember-property pattern: existing registry values are read back into
|
||||
the properties at install start, so blank properties never overwrite
|
||||
configured values and upgrades preserve configuration.
|
||||
@@ -64,6 +64,12 @@
|
||||
<RegistrySearch Id="ExistingAllowScriptExecution" Root="HKLM"
|
||||
Key="$(var.AgentRegKey)" Name="AllowScriptExecution" Type="raw" />
|
||||
</Property>
|
||||
<!-- SKIPTLSVERIFY=1: accept the server's managed self-signed chain (the
|
||||
connection stays TLS-encrypted; the roots just aren't distributed). -->
|
||||
<Property Id="SKIPTLSVERIFY">
|
||||
<RegistrySearch Id="ExistingTlsSkipVerify" Root="HKLM"
|
||||
Key="$(var.AgentRegKey)" Name="TlsSkipVerify" Type="raw" />
|
||||
</Property>
|
||||
|
||||
<StandardDirectory Id="ProgramFiles64Folder">
|
||||
<Directory Id="INSTALLFOLDER" Name="ExecuteR Agent">
|
||||
@@ -127,6 +133,10 @@
|
||||
<RegistryValue Root="HKLM" Key="$(var.AgentRegKey)"
|
||||
Name="AllowScriptExecution" Type="integer" Value="[ALLOWSCRIPTEXECUTION]" KeyPath="yes" />
|
||||
</Component>
|
||||
<Component Id="RegTlsSkipVerify" Guid="6b8e4a1d-9c02-47e3-b7a4-2e1f83c5d907" Condition="SKIPTLSVERIFY">
|
||||
<RegistryValue Root="HKLM" Key="$(var.AgentRegKey)"
|
||||
Name="TlsSkipVerify" Type="integer" Value="[SKIPTLSVERIFY]" KeyPath="yes" />
|
||||
</Component>
|
||||
|
||||
</ComponentGroup>
|
||||
|
||||
@@ -199,6 +209,11 @@
|
||||
<Control Id="Note" Type="Text" X="20" Y="142" Width="330" Height="48" NoPrefix="yes"
|
||||
Text="Leave blank to keep values already configured on this machine (upgrades), or to configure later via registry or Group Policy. The service enrolls automatically at start once both values are present. Command-line properties (SERVERURL=… BOOTSTRAPTOKEN=…) set the same fields and are the way to install silently." />
|
||||
|
||||
<!-- Unchecked by default; prefilled from the registry on upgrades. -->
|
||||
<Control Id="SkipTlsCheck" Type="CheckBox" X="20" Y="194" Width="330" Height="14"
|
||||
Property="SKIPTLSVERIFY" CheckBoxValue="1"
|
||||
Text="Skip TLS certificate verification (self-signed server — traffic stays encrypted)" />
|
||||
|
||||
<Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
|
||||
<Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17"
|
||||
Text="!(loc.WixUIBack)" />
|
||||
|
||||
@@ -324,6 +324,7 @@ public sealed record AgentPackageStatusDto(
|
||||
/// <summary>POST /api/admin/bootstrap-tokens request body.</summary>
|
||||
public sealed record CreateBootstrapTokenRequest(
|
||||
int? ValidMinutes,
|
||||
// 1-9999, or 0 for unlimited uses (expiry and revocation still apply).
|
||||
int? MaxUses,
|
||||
string? Note);
|
||||
|
||||
|
||||
@@ -362,6 +362,12 @@ export interface SchedulePreviewDto {
|
||||
export interface ServerInfoDto {
|
||||
baseUrl: string;
|
||||
fromEnvironment: boolean;
|
||||
/**
|
||||
* The server is serving its managed self-signed chain directly (no proxy
|
||||
* in between), so generated commands must skip TLS verification — the
|
||||
* traffic is still encrypted; the roots just aren't distributed.
|
||||
*/
|
||||
selfSignedDirect: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { api } from '$lib/api/client';
|
||||
import CopyChip from '$lib/components/CopyChip.svelte';
|
||||
|
||||
let { close }: { close: () => void } = $props();
|
||||
|
||||
type Platform = 'windows' | 'linux' | 'macos';
|
||||
type Scope = 'single' | 'multi';
|
||||
|
||||
let platform = $state<Platform>('windows');
|
||||
let scope = $state<Scope>('single');
|
||||
let multiUses = $state(1);
|
||||
let unlimited = $state(false);
|
||||
let token = $state('');
|
||||
let tokenId = $state('');
|
||||
let baseUrl = $state('');
|
||||
let selfSignedDirect = $state(false);
|
||||
let errorText = $state('');
|
||||
let busy = $state(false);
|
||||
let regenTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const platforms: { id: Platform; label: string }[] = [
|
||||
{ id: 'windows', label: 'Windows' },
|
||||
{ id: 'linux', label: 'Linux' },
|
||||
{ id: 'macos', label: 'macOS' }
|
||||
];
|
||||
|
||||
onMount(() => {
|
||||
void api
|
||||
.serverInfo()
|
||||
.then((info) => {
|
||||
baseUrl = info.baseUrl ?? location.origin;
|
||||
selfSignedDirect = info.selfSignedDirect ?? false;
|
||||
})
|
||||
.catch(() => (baseUrl = location.origin));
|
||||
|
||||
// A pending debounce firing after dismissal would mint an orphan token.
|
||||
return () => clearTimeout(regenTimer);
|
||||
});
|
||||
|
||||
const effectiveUses = $derived(
|
||||
scope === 'single' ? 1 : unlimited ? 0 : Math.min(9999, Math.max(1, Math.floor(multiUses || 1)))
|
||||
);
|
||||
|
||||
/** Confirm: nothing is created until this issues the bootstrap token. */
|
||||
async function generate() {
|
||||
busy = true;
|
||||
errorText = '';
|
||||
try {
|
||||
// A superseded token would otherwise stay live for 24 hours.
|
||||
if (tokenId) {
|
||||
await api.revokeBootstrapToken(tokenId).catch(() => undefined);
|
||||
tokenId = '';
|
||||
}
|
||||
|
||||
const created = await api.createBootstrapToken({
|
||||
validMinutes: 24 * 60,
|
||||
maxUses: effectiveUses,
|
||||
note:
|
||||
scope === 'single'
|
||||
? 'Add device (single use)'
|
||||
: `Add device (${unlimited ? 'unlimited uses' : `${effectiveUses} uses`})`
|
||||
});
|
||||
token = created.token ?? '';
|
||||
tokenId = created.id;
|
||||
} catch (e) {
|
||||
errorText = e instanceof Error ? e.message : 'Could not create a bootstrap token.';
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Limits are properties of the token. Before the first Generate, changes
|
||||
* just update the form; afterwards they re-issue live (debounced, with the
|
||||
* superseded token revoked).
|
||||
*/
|
||||
function limitsChanged() {
|
||||
if (!token && !busy) return;
|
||||
clearTimeout(regenTimer);
|
||||
regenTimer = setTimeout(() => void generate(), 600);
|
||||
}
|
||||
|
||||
function setScope(next: Scope) {
|
||||
if (scope === next) return;
|
||||
scope = next;
|
||||
limitsChanged();
|
||||
}
|
||||
|
||||
const command = $derived.by(() => {
|
||||
if (!token || !baseUrl) return '';
|
||||
const install = `${baseUrl}/api/enrollment/install?token=${token}`;
|
||||
// Self-signed direct serving: the fetch itself must skip verification
|
||||
// (the install script then configures the agent the same way). The
|
||||
// hop is still encrypted — the roots just aren't distributed.
|
||||
const curl = selfSignedDirect ? 'curl -fsSLk' : 'curl -fsSL';
|
||||
const psPrefix = selfSignedDirect
|
||||
? '[Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }; '
|
||||
: '';
|
||||
switch (platform) {
|
||||
case 'windows':
|
||||
return `${psPrefix}iwr '${install}' -UseBasicParsing | iex`;
|
||||
case 'linux':
|
||||
return `${curl} '${install}&type=linux' | sudo bash`;
|
||||
case 'macos':
|
||||
return `${curl} '${install}&type=osx' | sudo bash`;
|
||||
}
|
||||
});
|
||||
|
||||
const shellHint = $derived(
|
||||
platform === 'windows'
|
||||
? 'Run in an elevated PowerShell on the device.'
|
||||
: 'Run in a terminal on the device (needs sudo).'
|
||||
);
|
||||
</script>
|
||||
|
||||
<svelte:window
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Escape') close();
|
||||
}}
|
||||
/>
|
||||
|
||||
<div
|
||||
class="backdrop"
|
||||
role="presentation"
|
||||
onclick={(e) => {
|
||||
if (e.target === e.currentTarget) close();
|
||||
}}
|
||||
>
|
||||
<div class="modal card" role="dialog" aria-modal="true" aria-label="Add device">
|
||||
<div class="head">
|
||||
<h2>Add device</h2>
|
||||
<button class="btn icon" onclick={close} aria-label="Close">✕</button>
|
||||
</div>
|
||||
|
||||
<div class="platforms" role="tablist" aria-label="Platform">
|
||||
{#each platforms as p (p.id)}
|
||||
<button
|
||||
class="platform"
|
||||
class:active={platform === p.id}
|
||||
role="tab"
|
||||
aria-selected={platform === p.id}
|
||||
onclick={() => (platform = p.id)}
|
||||
>
|
||||
{p.label}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<div class="scope">
|
||||
<label class="radio">
|
||||
<input type="radio" checked={scope === 'single'} onchange={() => setScope('single')} />
|
||||
Single device <span class="faint">(one-time token)</span>
|
||||
</label>
|
||||
<label class="radio">
|
||||
<input type="radio" checked={scope === 'multi'} onchange={() => setScope('multi')} />
|
||||
Multiple devices
|
||||
</label>
|
||||
{#if scope === 'multi'}
|
||||
<div class="multi-opts">
|
||||
<input
|
||||
class="input uses"
|
||||
type="number"
|
||||
min="1"
|
||||
max="9999"
|
||||
bind:value={multiUses}
|
||||
oninput={limitsChanged}
|
||||
disabled={unlimited}
|
||||
aria-label="Maximum uses"
|
||||
/>
|
||||
<span class="faint">uses</span>
|
||||
<label class="radio">
|
||||
<input type="checkbox" bind:checked={unlimited} onchange={limitsChanged} />
|
||||
Unlimited
|
||||
</label>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if errorText}
|
||||
<p class="warn small">{errorText}</p>
|
||||
{/if}
|
||||
|
||||
{#if command}
|
||||
<div class="command-wrap" class:updating={busy}>
|
||||
<CopyChip value={command} label="Install command" />
|
||||
</div>
|
||||
<p class="muted small">
|
||||
{#if busy}Updating the token…{:else}
|
||||
{shellHint} The token expires in 24 hours; the agent downloads from this server,
|
||||
installs as a {platform === 'windows' ? 'Windows service' : platform === 'linux' ? 'systemd unit' : 'launchd daemon'}
|
||||
and enrolls automatically.
|
||||
{/if}
|
||||
</p>
|
||||
{:else}
|
||||
<p class="muted small">
|
||||
Generating issues a bootstrap token ({scope === 'single'
|
||||
? 'one use'
|
||||
: unlimited
|
||||
? 'unlimited uses'
|
||||
: `up to ${effectiveUses} use${effectiveUses === 1 ? '' : 's'}`}, 24-hour expiry)
|
||||
and builds the paste-ready install command for the selected platform.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<div class="actions">
|
||||
<button class="btn" onclick={close}>Cancel</button>
|
||||
{#if command}
|
||||
<button class="btn primary" onclick={close}>Done</button>
|
||||
{:else}
|
||||
<button class="btn primary" onclick={generate} disabled={busy || !baseUrl}>
|
||||
{busy ? 'Generating…' : 'Generate command'}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 200;
|
||||
background: rgb(0 0 0 / 55%);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: var(--space-4);
|
||||
}
|
||||
|
||||
.modal {
|
||||
width: 640px;
|
||||
max-width: 100%;
|
||||
padding: var(--space-5);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.head h2 {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.icon {
|
||||
padding: 4px 10px;
|
||||
}
|
||||
|
||||
.platforms {
|
||||
display: flex;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.platform {
|
||||
flex: 1;
|
||||
background: none;
|
||||
border: none;
|
||||
border-right: 1px solid var(--border);
|
||||
padding: 9px 0;
|
||||
font: inherit;
|
||||
font-weight: 500;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.platform:last-child {
|
||||
border-right: none;
|
||||
}
|
||||
|
||||
.platform.active {
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.scope {
|
||||
display: flex;
|
||||
gap: var(--space-5);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.radio {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.multi-opts {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.uses {
|
||||
width: 90px;
|
||||
}
|
||||
|
||||
.command-wrap {
|
||||
display: flex;
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
|
||||
.command-wrap.updating {
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
.command-wrap :global(.chip) {
|
||||
width: 100%;
|
||||
justify-content: space-between;
|
||||
padding: 9px 12px;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.small {
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
.warn {
|
||||
color: var(--warning);
|
||||
}
|
||||
</style>
|
||||
@@ -4,11 +4,16 @@
|
||||
import { api } from '$lib/api/client';
|
||||
import type { DeviceDto } from '$lib/api/types';
|
||||
import { nats } from '$lib/messaging/nats';
|
||||
import { session, hasPermission } from '$lib/auth/session';
|
||||
import StatusBadge from '$lib/components/StatusBadge.svelte';
|
||||
import RelativeTime from '$lib/components/RelativeTime.svelte';
|
||||
import EmptyState from '$lib/components/EmptyState.svelte';
|
||||
import AddDeviceModal from '$lib/components/AddDeviceModal.svelte';
|
||||
|
||||
let devices = $state<DeviceDto[] | null>(null);
|
||||
let showAddDevice = $state(false);
|
||||
// Token creation sits behind settings.manage.
|
||||
const canAddDevice = $derived(hasPermission($session, 'settings.manage'));
|
||||
let search = $state('');
|
||||
let statusFilter = $state<'all' | 'online' | 'offline'>('all');
|
||||
let sortKey = $state<'hostname' | 'lastSeenUtc' | 'osCaption'>('hostname');
|
||||
@@ -75,9 +80,16 @@
|
||||
<option value="online">Online</option>
|
||||
<option value="offline">Offline / stale</option>
|
||||
</select>
|
||||
{#if canAddDevice}
|
||||
<button class="btn primary" onclick={() => (showAddDevice = true)}>+ Add device</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if showAddDevice}
|
||||
<AddDeviceModal close={() => (showAddDevice = false)} />
|
||||
{/if}
|
||||
|
||||
<div class="card table-wrap">
|
||||
{#if devices === null}
|
||||
<div class="loading">
|
||||
|
||||
@@ -20,10 +20,11 @@
|
||||
|
||||
// PUBLIC_SERVER_URL (or trusted forwarded headers) beats the browser's own
|
||||
// origin, so the command works even when the admin browses via an internal
|
||||
// hostname the target devices cannot reach.
|
||||
// hostname the target devices cannot reach. Direct self-signed serving
|
||||
// prefixes a PS5-safe skip-verify (the hop is still encrypted).
|
||||
const installCommand = $derived(
|
||||
newToken?.token
|
||||
? `iwr ${serverInfo?.baseUrl ?? location.origin}/api/enrollment/install?token=${newToken.token} -UseBasicParsing | iex`
|
||||
? `${serverInfo?.selfSignedDirect ? '[Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }; ' : ''}iwr ${serverInfo?.baseUrl ?? location.origin}/api/enrollment/install?token=${newToken.token} -UseBasicParsing | iex`
|
||||
: ''
|
||||
);
|
||||
|
||||
@@ -109,8 +110,8 @@
|
||||
<input class="input" type="number" min="5" bind:value={validMinutes} />
|
||||
</label>
|
||||
<label>
|
||||
<span class="muted">Max uses</span>
|
||||
<input class="input" type="number" min="1" bind:value={maxUses} />
|
||||
<span class="muted">Max uses (0 = unlimited)</span>
|
||||
<input class="input" type="number" min="0" max="9999" bind:value={maxUses} />
|
||||
</label>
|
||||
<label class="grow">
|
||||
<span class="muted">Note</span>
|
||||
@@ -156,21 +157,21 @@
|
||||
<tr>
|
||||
<td class="muted">{new Date(token.createdUtc).toLocaleString()}</td>
|
||||
<td class="muted">{new Date(token.expiresUtc).toLocaleString()}</td>
|
||||
<td>{token.uses} / {token.maxUses}</td>
|
||||
<td>{token.uses} / {token.maxUses === 0 ? '∞' : token.maxUses}</td>
|
||||
<td class="muted">{token.note ?? '—'}</td>
|
||||
<td>
|
||||
{#if token.revoked}
|
||||
<span class="muted">Revoked</span>
|
||||
{:else if new Date(token.expiresUtc) < new Date()}
|
||||
<span class="muted">Expired</span>
|
||||
{:else if token.uses >= token.maxUses}
|
||||
{:else if token.maxUses > 0 && token.uses >= token.maxUses}
|
||||
<span class="muted">Consumed</span>
|
||||
{:else}
|
||||
<span style="color: var(--success)">Active</span>
|
||||
{/if}
|
||||
</td>
|
||||
<td>
|
||||
{#if !token.revoked && token.uses < token.maxUses && new Date(token.expiresUtc) > new Date()}
|
||||
{#if !token.revoked && (token.maxUses === 0 || token.uses < token.maxUses) && new Date(token.expiresUtc) > new Date()}
|
||||
<button class="btn danger" onclick={() => revoke(token.id)}>Revoke</button>
|
||||
{/if}
|
||||
</td>
|
||||
|
||||
@@ -81,9 +81,24 @@ public class AgentConfigurationTests
|
||||
Assert.Equal(ProtocolDefaults.ReconnectMaxDelay, config.ReconnectMaxDelay.Value);
|
||||
Assert.False(config.AllowRemoteShell.Value);
|
||||
Assert.True(config.AllowScriptExecution.Value);
|
||||
Assert.False(config.TlsSkipVerify.Value);
|
||||
Assert.Equal("Information", config.LogLevel.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TlsSkipVerifyFollowsDwordPrecedence()
|
||||
{
|
||||
registry.SetDword(Branding.AgentRegistryKey, AgentConfigurationKeys.TlsSkipVerify, 1);
|
||||
var local = new AgentConfigurationLoader(registry, allowEnvironment: false).Load();
|
||||
Assert.True(local.TlsSkipVerify.Value);
|
||||
|
||||
// GPO wins over the locally configured value.
|
||||
registry.SetDword(Branding.AgentPolicyRegistryKey, AgentConfigurationKeys.TlsSkipVerify, 0);
|
||||
var policy = new AgentConfigurationLoader(registry, allowEnvironment: false).Load();
|
||||
Assert.False(policy.TlsSkipVerify.Value);
|
||||
Assert.True(policy.TlsSkipVerify.IsPolicyControlled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IntervalAcceptsSecondsAndTimeSpanFormats()
|
||||
{
|
||||
|
||||
@@ -28,6 +28,9 @@ public sealed class InMemoryRegistryStore : IRegistryStore
|
||||
public void WriteString(string keyPath, string valueName, string value)
|
||||
=> values[(keyPath, valueName)] = value;
|
||||
|
||||
public void WriteDword(string keyPath, string valueName, int value)
|
||||
=> values[(keyPath, valueName)] = value;
|
||||
|
||||
public void DeleteValue(string keyPath, string valueName)
|
||||
=> values.Remove((keyPath, valueName));
|
||||
|
||||
|
||||
@@ -27,6 +27,9 @@ public sealed class BackendTestFixture : WebApplicationFactory<Program>
|
||||
// Tests drive schedule sweeps manually; the background worker would
|
||||
// race them (fire-and-advance between seeding steps).
|
||||
builder.UseSetting("SCHEDULE_WORKER", "0");
|
||||
// TestServer never terminates TLS; skip chain generation (and its
|
||||
// file writes, which would race across parallel fixtures).
|
||||
builder.UseSetting("TLS_SELF_SIGNED", "0");
|
||||
builder.UseEnvironment("Development");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Backend.Data;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shared.Contracts.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace Backend.Tests;
|
||||
|
||||
public class InstallScriptTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(0, 0)] // unlimited sentinel round-trips
|
||||
[InlineData(1, 1)]
|
||||
[InlineData(9999, 9999)]
|
||||
public async Task TokenUseLimitsAcceptZeroThroughMax(int requested, int expected)
|
||||
{
|
||||
using var client = await AdminClientAsync();
|
||||
var response = await client.PostAsJsonAsync(
|
||||
"/api/admin/bootstrap-tokens", new { maxUses = requested, validMinutes = 60 });
|
||||
|
||||
response.EnsureSuccessStatusCode();
|
||||
using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal(expected, body.RootElement.GetProperty("maxUses").GetInt32());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(10000)]
|
||||
[InlineData(-1)]
|
||||
public async Task TokenUseLimitsRejectOutOfRange(int requested)
|
||||
{
|
||||
using var client = await AdminClientAsync();
|
||||
var response = await client.PostAsJsonAsync(
|
||||
"/api/admin/bootstrap-tokens", new { maxUses = requested, validMinutes = 60 });
|
||||
|
||||
Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
private async Task<HttpClient> AdminClientAsync()
|
||||
{
|
||||
await fixture.WithDbAsync(async db =>
|
||||
{
|
||||
if (await db.Users.AnyAsync(u => u.Username == "token-admin"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var role = await db.Roles.SingleAsync(r => r.IsSystem && r.Name == "Admin");
|
||||
var user = new UserEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = "token-admin",
|
||||
DisplayName = "token-admin",
|
||||
Role = UserRole.Admin,
|
||||
RoleId = role.Id,
|
||||
AuthProvider = "local",
|
||||
CreatedUtc = DateTimeOffset.UtcNow,
|
||||
};
|
||||
user.PasswordHash = new Microsoft.AspNetCore.Identity.PasswordHasher<UserEntity>()
|
||||
.HashPassword(user, "token-admin-pass");
|
||||
db.Users.Add(user);
|
||||
await db.SaveChangesAsync();
|
||||
});
|
||||
|
||||
var client = fixture.CreateClient();
|
||||
var login = await client.PostAsJsonAsync(
|
||||
"/api/auth/login", new { username = "token-admin", password = "token-admin-pass" });
|
||||
login.EnsureSuccessStatusCode();
|
||||
|
||||
// Cookie-authenticated POSTs require the double-submit CSRF header.
|
||||
if (login.Headers.TryGetValues("Set-Cookie", out var cookies))
|
||||
{
|
||||
var csrf = cookies
|
||||
.Select(c => c.Split(';')[0])
|
||||
.FirstOrDefault(c => c.StartsWith("csrf_token=", StringComparison.Ordinal));
|
||||
if (csrf is not null)
|
||||
{
|
||||
client.DefaultRequestHeaders.Add("X-CSRF-Token", csrf["csrf_token=".Length..]);
|
||||
}
|
||||
}
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, "msiexec")]
|
||||
[InlineData("msi", "msiexec")]
|
||||
[InlineData("zip", "Expand-Archive")]
|
||||
public async Task WindowsVariantsReturnPowerShell(string? type, string marker)
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var url = "/api/enrollment/install?token=test-token" + (type is null ? "" : $"&type={type}");
|
||||
var response = await client.GetAsync(url);
|
||||
|
||||
response.EnsureSuccessStatusCode();
|
||||
var script = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains(marker, script);
|
||||
Assert.Contains("test-token", script);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("linux", "type=linux-${arch}")]
|
||||
[InlineData("osx", "type=osx-${arch}")]
|
||||
[InlineData("macos", "type=osx-${arch}")]
|
||||
public async Task UnixVariantsReturnBashWithArchDetection(string type, string packageMarker)
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var response = await client.GetAsync($"/api/enrollment/install?token=test-token&type={type}");
|
||||
|
||||
response.EnsureSuccessStatusCode();
|
||||
var script = await response.Content.ReadAsStringAsync();
|
||||
Assert.StartsWith("#!/usr/bin/env bash", script);
|
||||
Assert.Contains("uname -m", script);
|
||||
Assert.Contains(packageMarker, script);
|
||||
Assert.Contains("configure --url", script);
|
||||
Assert.Contains("initialize", script);
|
||||
Assert.Contains("test-token", script);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MissingTokenIsRefused()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var response = await client.GetAsync("/api/enrollment/install");
|
||||
Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DirectSelfSignedServingAddsSkipVerifyEverywhere()
|
||||
{
|
||||
// HTTPS with TLS_SELF_SIGNED on and no forwarded headers = an agent
|
||||
// talking straight to the self-signed listener: every install path
|
||||
// must skip verification and configure the agent to keep doing so.
|
||||
var certDir = Path.Combine(
|
||||
Path.GetTempPath(), "executer-tls-tests", Guid.NewGuid().ToString("N"));
|
||||
await using var factory = fixture.WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseSetting("TLS_SELF_SIGNED", "1");
|
||||
builder.UseSetting("TLS_CERT_DIR", certDir);
|
||||
});
|
||||
using var client = factory.CreateClient(
|
||||
new WebApplicationFactoryClientOptions { BaseAddress = new Uri("https://localhost") });
|
||||
|
||||
var msi = await (await client.GetAsync("/api/enrollment/install?token=t")).Content.ReadAsStringAsync();
|
||||
Assert.Contains("ServerCertificateValidationCallback", msi);
|
||||
Assert.Contains("SKIPTLSVERIFY=1", msi);
|
||||
|
||||
var zip = await (await client.GetAsync("/api/enrollment/install?token=t&type=zip")).Content.ReadAsStringAsync();
|
||||
Assert.Contains("ServerCertificateValidationCallback", zip);
|
||||
Assert.Contains("TlsSkipVerify", zip);
|
||||
|
||||
var bash = await (await client.GetAsync("/api/enrollment/install?token=t&type=linux")).Content.ReadAsStringAsync();
|
||||
Assert.Contains("curl -fsSLk", bash);
|
||||
Assert.Contains("--skip-tls-verify", bash);
|
||||
|
||||
// Plain HTTP (the fixture default) stays clean.
|
||||
using var plain = fixture.CreateClient();
|
||||
var script = await (await plain.GetAsync("/api/enrollment/install?token=t")).Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("ServerCertificateValidationCallback", script);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using System.Net;
|
||||
using Backend.Proxy;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Xunit;
|
||||
|
||||
namespace Backend.Tests;
|
||||
|
||||
public class ProxySettingsTests
|
||||
{
|
||||
private static ProxySettings Load(params (string Key, string Value)[] values)
|
||||
=> ProxySettings.FromConfiguration(new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(values.ToDictionary(v => v.Key, v => (string?)v.Value))
|
||||
.Build());
|
||||
|
||||
[Fact]
|
||||
public void TrustIsOnByDefaultWithPrivateNetworkDefaults()
|
||||
{
|
||||
var settings = Load();
|
||||
|
||||
Assert.True(settings.TrustProxy);
|
||||
Assert.False(settings.HasExplicitTrustSources);
|
||||
|
||||
var networks = settings.EffectiveNetworks;
|
||||
Assert.Contains(networks, n => n.Prefix.Equals(IPAddress.Parse("10.0.0.0")) && n.PrefixLength == 8);
|
||||
Assert.Contains(networks, n => n.Prefix.Equals(IPAddress.Parse("172.16.0.0")) && n.PrefixLength == 12);
|
||||
Assert.Contains(networks, n => n.Prefix.Equals(IPAddress.Parse("192.168.0.0")) && n.PrefixLength == 16);
|
||||
Assert.Contains(networks, n => n.Prefix.Equals(IPAddress.Parse("100.64.0.0")) && n.PrefixLength == 10);
|
||||
Assert.Contains(networks, n => n.Prefix.Equals(IPAddress.Parse("127.0.0.0")) && n.PrefixLength == 8);
|
||||
Assert.Contains(networks, n => n.Prefix.Equals(IPAddress.IPv6Loopback) && n.PrefixLength == 128);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExplicitNetworksReplaceTheDefaults()
|
||||
{
|
||||
var settings = Load(("TRUSTED_NETWORKS", "203.0.113.0/24"));
|
||||
|
||||
Assert.True(settings.HasExplicitTrustSources);
|
||||
var networks = settings.EffectiveNetworks;
|
||||
Assert.Single(networks);
|
||||
Assert.Equal(IPAddress.Parse("203.0.113.0"), networks[0].Prefix);
|
||||
Assert.DoesNotContain(networks, n => n.Prefix.Equals(IPAddress.Parse("10.0.0.0")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExplicitProxiesAloneAlsoReplaceTheNetworkDefaults()
|
||||
{
|
||||
var settings = Load(("TRUSTED_PROXIES", "203.0.113.10"));
|
||||
|
||||
Assert.True(settings.HasExplicitTrustSources);
|
||||
Assert.Empty(settings.EffectiveNetworks);
|
||||
Assert.Single(settings.TrustedProxies);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrustProxyZeroOptsOutEntirely()
|
||||
{
|
||||
Assert.False(Load(("TRUST_PROXY", "0")).TrustProxy);
|
||||
Assert.True(Load(("TRUST_PROXY", "1")).TrustProxy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ForwardedHeaderOptionsCarryTheEffectiveNetworks()
|
||||
{
|
||||
var options = Load().ToForwardedHeadersOptions();
|
||||
Assert.Empty(options.KnownProxies);
|
||||
Assert.Equal(ProxySettings.DefaultTrustedNetworks.Count, options.KnownIPNetworks.Count);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Backend.Tls;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Xunit;
|
||||
|
||||
namespace Backend.Tests;
|
||||
|
||||
public sealed class SelfSignedTlsTests : IDisposable
|
||||
{
|
||||
private readonly string directory = Path.Combine(
|
||||
Path.GetTempPath(), "executer-tls-tests", Guid.NewGuid().ToString("N"));
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private TlsSettings Settings => new()
|
||||
{
|
||||
Enabled = true,
|
||||
CertificateDirectory = directory,
|
||||
UseWindowsStore = false,
|
||||
DnsNames = ["localhost", "unit-test-host"],
|
||||
IpAddresses = [IPAddress.Loopback, IPAddress.IPv6Loopback],
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void EnsureChain_CreatesRootIntermediateAndLeaf()
|
||||
{
|
||||
var manager = new SelfSignedTlsManager(Settings);
|
||||
var changed = manager.EnsureChain(NullLogger.Instance);
|
||||
|
||||
Assert.True(changed);
|
||||
foreach (var file in new[]
|
||||
{
|
||||
"root.crt", "root.key", "intermediate.crt", "intermediate.key",
|
||||
"server.crt", "server.key", "fullchain.crt",
|
||||
})
|
||||
{
|
||||
Assert.True(File.Exists(Path.Combine(directory, file)), $"{file} missing");
|
||||
}
|
||||
|
||||
var leaf = manager.ServerCertificate;
|
||||
Assert.NotNull(leaf);
|
||||
Assert.True(leaf.HasPrivateKey);
|
||||
Assert.Equal("CN=ExecuteR Server", leaf.Subject);
|
||||
Assert.Equal("CN=ExecuteR Self-Signed Intermediate CA", leaf.Issuer);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnsureChain_LeafValidatesToRootThroughIntermediate()
|
||||
{
|
||||
var manager = new SelfSignedTlsManager(Settings);
|
||||
manager.EnsureChain(NullLogger.Instance);
|
||||
|
||||
using var root = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(directory, "root.crt"));
|
||||
using var intermediate = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(directory, "intermediate.crt"));
|
||||
using var chain = new X509Chain();
|
||||
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
|
||||
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
||||
chain.ChainPolicy.CustomTrustStore.Add(root);
|
||||
chain.ChainPolicy.ExtraStore.Add(intermediate);
|
||||
|
||||
Assert.True(chain.Build(manager.ServerCertificate!));
|
||||
Assert.Equal(3, chain.ChainElements.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnsureChain_SecondRunIsStable()
|
||||
{
|
||||
var first = new SelfSignedTlsManager(Settings);
|
||||
first.EnsureChain(NullLogger.Instance);
|
||||
var thumbprint = first.ServerCertificate!.Thumbprint;
|
||||
|
||||
var second = new SelfSignedTlsManager(Settings);
|
||||
var changed = second.EnsureChain(NullLogger.Instance);
|
||||
|
||||
Assert.False(changed);
|
||||
Assert.Equal(thumbprint, second.ServerCertificate!.Thumbprint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnsureChain_RenewsLeafInsideTheRenewalMargin()
|
||||
{
|
||||
var lifetimes = TlsLifetimes.Default with { Leaf = TimeSpan.FromDays(45) };
|
||||
var initial = new SelfSignedTlsManager(Settings, lifetimes);
|
||||
initial.EnsureChain(NullLogger.Instance);
|
||||
var oldLeaf = initial.ServerCertificate!.Thumbprint;
|
||||
var oldRoot = File.ReadAllText(Path.Combine(directory, "root.crt"));
|
||||
|
||||
// A margin wider than the leaf's remaining life forces re-issue; the
|
||||
// CAs are untouched and the renewed leaf still chains to them.
|
||||
var renewing = new SelfSignedTlsManager(
|
||||
Settings, lifetimes with { LeafRenewalMargin = TimeSpan.FromDays(60) });
|
||||
var changed = renewing.EnsureChain(NullLogger.Instance);
|
||||
|
||||
Assert.True(changed);
|
||||
Assert.NotEqual(oldLeaf, renewing.ServerCertificate!.Thumbprint);
|
||||
Assert.Equal(oldRoot, File.ReadAllText(Path.Combine(directory, "root.crt")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnsureChain_RotatedRootCascadesToTheWholeChain()
|
||||
{
|
||||
var manager = new SelfSignedTlsManager(Settings);
|
||||
manager.EnsureChain(NullLogger.Instance);
|
||||
var oldIntermediate = File.ReadAllText(Path.Combine(directory, "intermediate.crt"));
|
||||
var oldLeaf = manager.ServerCertificate!.Thumbprint;
|
||||
|
||||
// Simulate root loss/rotation: the old intermediate no longer chains
|
||||
// to the new root, so signature validation re-issues everything.
|
||||
File.Delete(Path.Combine(directory, "root.crt"));
|
||||
File.Delete(Path.Combine(directory, "root.key"));
|
||||
var rotated = new SelfSignedTlsManager(Settings);
|
||||
var changed = rotated.EnsureChain(NullLogger.Instance);
|
||||
|
||||
Assert.True(changed);
|
||||
Assert.NotEqual(oldIntermediate, File.ReadAllText(Path.Combine(directory, "intermediate.crt")));
|
||||
Assert.NotEqual(oldLeaf, rotated.ServerCertificate!.Thumbprint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnsureChain_LeafCarriesConfiguredSansAndServerAuthEku()
|
||||
{
|
||||
var manager = new SelfSignedTlsManager(Settings);
|
||||
manager.EnsureChain(NullLogger.Instance);
|
||||
var leaf = manager.ServerCertificate!;
|
||||
|
||||
var san = leaf.Extensions.OfType<X509SubjectAlternativeNameExtension>().Single();
|
||||
var dnsNames = san.EnumerateDnsNames().ToArray();
|
||||
Assert.Contains("localhost", dnsNames);
|
||||
Assert.Contains("unit-test-host", dnsNames);
|
||||
Assert.Contains(IPAddress.Loopback, san.EnumerateIPAddresses());
|
||||
|
||||
var eku = leaf.Extensions.OfType<X509EnhancedKeyUsageExtension>().Single();
|
||||
Assert.Contains("1.3.6.1.5.5.7.3.1", eku.EnhancedKeyUsages.Cast<Oid>().Select(oid => oid.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FromConfiguration_ReadsFlagsDirectoryAndBindSans()
|
||||
{
|
||||
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["TLS_SELF_SIGNED"] = "1",
|
||||
["TLS_CERT_DIR"] = directory,
|
||||
["urls"] = "https://192.0.2.10:9080",
|
||||
}).Build();
|
||||
|
||||
var settings = TlsSettings.FromConfiguration(configuration);
|
||||
|
||||
Assert.True(settings.Enabled);
|
||||
Assert.Equal(directory, settings.CertificateDirectory);
|
||||
Assert.False(settings.UseWindowsStore); // TLS_CERT_DIR forces file mode
|
||||
Assert.Contains(IPAddress.Parse("192.0.2.10"), settings.IpAddresses);
|
||||
Assert.Contains("localhost", settings.DnsNames);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FromConfiguration_IsOnByDefaultAndZeroOptsOut()
|
||||
{
|
||||
var defaulted = TlsSettings.FromConfiguration(
|
||||
new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>()).Build());
|
||||
Assert.True(defaulted.Enabled);
|
||||
|
||||
var optedOut = TlsSettings.FromConfiguration(
|
||||
new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["TLS_SELF_SIGNED"] = "0",
|
||||
}).Build());
|
||||
Assert.False(optedOut.Enabled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FromConfiguration_WildcardBindsAddNoSans()
|
||||
{
|
||||
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["TLS_SELF_SIGNED"] = "1",
|
||||
["TLS_CERT_DIR"] = directory,
|
||||
["urls"] = "http://0.0.0.0:9080;http://[::]:9081;http://*:9082",
|
||||
}).Build();
|
||||
|
||||
var settings = TlsSettings.FromConfiguration(configuration);
|
||||
|
||||
Assert.DoesNotContain(IPAddress.Any, settings.IpAddresses);
|
||||
Assert.DoesNotContain(IPAddress.IPv6Any, settings.IpAddresses);
|
||||
Assert.DoesNotContain("wildcard", settings.DnsNames);
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,7 @@ public class JobPipelineIntegrationTests
|
||||
ReconnectMaxDelay = new(TimeSpan.FromSeconds(60), ConfigurationSource.Default),
|
||||
AllowRemoteShell = new(false, ConfigurationSource.Default),
|
||||
AllowScriptExecution = new(true, ConfigurationSource.Default),
|
||||
TlsSkipVerify = new(false, ConfigurationSource.Default),
|
||||
};
|
||||
|
||||
private sealed class FixedIdentity : IHardwareIdentitySource
|
||||
|
||||
Reference in New Issue
Block a user