Condition builder, built-in vault, script parameters from code, BYO TLS and a simpler server installer #22
+26
-5
@@ -3,7 +3,8 @@
|
||||
#=============================================================================
|
||||
#
|
||||
# CREDENTIALS:
|
||||
# Initial admin: INITIAL_ADMIN_USERNAME / INITIAL_ADMIN_PASSWORD (below)
|
||||
# Initial admin: generated at first start into /data/initial-admin-password.txt
|
||||
# (INITIAL_ADMIN_PASSWORD below sets one instead)
|
||||
# NATS seeds: generated into secrets/nats by scripts/New-LocalSecrets.ps1
|
||||
#
|
||||
# ACCESS URL: set PUBLIC_SERVER_URL to the public https URL served by your
|
||||
@@ -11,7 +12,7 @@
|
||||
#
|
||||
# PRODUCTION SETUP:
|
||||
# 1. cp .env.example .env (or run scripts/New-LocalSecrets.ps1)
|
||||
# 2. Fill INITIAL_ADMIN_PASSWORD and NATS_ACCOUNT_SIGNING_SEED
|
||||
# 2. Fill NATS_ACCOUNT_SIGNING_SEED (and INITIAL_ADMIN_PASSWORD only to choose it)
|
||||
# 3. docker compose -f IaC/compose/docker-compose.yml up -d --build (or ./scripts/deploy.sh)
|
||||
#
|
||||
#=============================================================================
|
||||
@@ -95,19 +96,39 @@ FORWARD_LIMIT=1
|
||||
# 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).
|
||||
# The root and intermediate alone (no keys) are also written to
|
||||
# <data>/ca-certificates as .cer and .pem, for Group Policy or a proxy.
|
||||
TLS_SELF_SIGNED=0
|
||||
TLS_CERT_DIR=
|
||||
|
||||
# Your own certificate instead (turns HTTPS on by itself; hot-reloaded within
|
||||
# a minute when the file is replaced): TLS_CERT_SOURCE=file with
|
||||
# TLS_CERT_FILE a PFX/P12 (TLS_CERT_PASSWORD) or a PEM (a fullchain PEM
|
||||
# brings its intermediates) with TLS_CERT_KEY_FILE, mounted read-only into the
|
||||
# container. On Windows, TLS_CERT_SOURCE=store + TLS_CERT_THUMBPRINT serves a
|
||||
# LocalMachine\My certificate. When its chain is not publicly trusted (an
|
||||
# enterprise CA) agents are handed that chain, pinned to the token, as with the
|
||||
# self-signed one; TLS_DISTRIBUTE_CA=1/0 overrides that decision.
|
||||
TLS_CERT_SOURCE=
|
||||
TLS_CERT_FILE=
|
||||
TLS_CERT_KEY_FILE=
|
||||
TLS_CERT_PASSWORD=
|
||||
TLS_DISTRIBUTE_CA=
|
||||
|
||||
# ── Execution history ──────────────────────────────────────────────────────
|
||||
# Newest jobs kept per device (older jobs and their stored output are
|
||||
# pruned). 0 disables pruning.
|
||||
JOB_HISTORY_LIMIT=200
|
||||
|
||||
# ── Break-glass account (first startup only) ───────────────────────────────
|
||||
# The one recovery built-in account. Left empty, a one-time password is
|
||||
# generated and written once to the server log. Recover with `auth-reset`.
|
||||
# The one recovery built-in account. Left empty (the default), a one-time
|
||||
# password is generated at the first start and written to
|
||||
# /data/initial-admin-password.txt (mode 600, never the log); it must be
|
||||
# changed at the first sign-in, and the file goes once it is. Read it with
|
||||
# docker exec EXECUTER-API-00001 cat /data/initial-admin-password.txt
|
||||
# Locked out or lost: docker exec EXECUTER-API-00001 dotnet Backend.dll reset-admin
|
||||
# Set a password here only to choose it yourself (existing deployments keep theirs).
|
||||
INITIAL_ADMIN_USERNAME=admin
|
||||
# Generate: openssl rand -base64 24
|
||||
INITIAL_ADMIN_PASSWORD=
|
||||
|
||||
# ── Sign-in ────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -23,8 +23,8 @@
|
||||
<InformationalVersion Condition="'$(GitCommitShort)' != ''">$(UnifiedVersion)+$(GitCommitShort)</InformationalVersion>
|
||||
<InformationalVersion Condition="'$(GitCommitShort)' == ''">$(UnifiedVersion)</InformationalVersion>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<Company>ExecuteR</Company>
|
||||
<Copyright>Copyright (c) 2026 Grace Solutions. All rights reserved.</Copyright>
|
||||
<Company>Endexa Solutions</Company>
|
||||
<Copyright>Copyright (c) 2026 Endexa Solutions. All rights reserved.</Copyright>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
|
||||
@@ -41,6 +41,8 @@
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.10" />
|
||||
<PackageVersion Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="8.22.0" />
|
||||
<PackageVersion Include="System.DirectoryServices.Protocols" Version="10.0.12" />
|
||||
<!-- PowerShell's parser for script param() import; the same line as the agent's SDK. -->
|
||||
<PackageVersion Include="System.Management.Automation" Version="7.6.4" />
|
||||
|
||||
<!-- Agent -->
|
||||
<PackageVersion Include="Microsoft.PowerShell.SDK" Version="7.6.4" />
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
#=============================================================================
|
||||
#
|
||||
# CREDENTIALS:
|
||||
# Initial admin: INITIAL_ADMIN_USERNAME / INITIAL_ADMIN_PASSWORD (.env)
|
||||
# Initial admin: generated at first start into /data/initial-admin-password.txt
|
||||
# (or INITIAL_ADMIN_USERNAME / INITIAL_ADMIN_PASSWORD in .env)
|
||||
# NATS decentralized auth: seeds generated by scripts/New-LocalSecrets.ps1
|
||||
#
|
||||
# PRODUCTION SETUP:
|
||||
@@ -117,6 +118,12 @@ services:
|
||||
TRUSTED_HOSTS: '${TRUSTED_HOSTS:-}'
|
||||
TLS_SELF_SIGNED: '${TLS_SELF_SIGNED:-0}'
|
||||
TLS_CERT_DIR: '${TLS_CERT_DIR:-}'
|
||||
# Your own certificate (file only in a container): mount it read-only and point TLS_CERT_FILE at it.
|
||||
TLS_CERT_SOURCE: '${TLS_CERT_SOURCE:-}'
|
||||
TLS_CERT_FILE: '${TLS_CERT_FILE:-}'
|
||||
TLS_CERT_KEY_FILE: '${TLS_CERT_KEY_FILE:-}'
|
||||
TLS_CERT_PASSWORD: '${TLS_CERT_PASSWORD:-}'
|
||||
TLS_DISTRIBUTE_CA: '${TLS_DISTRIBUTE_CA:-}'
|
||||
FORWARD_LIMIT: '${FORWARD_LIMIT:-1}'
|
||||
PUBLIC_SERVER_URL: '${PUBLIC_SERVER_URL:-}'
|
||||
INITIAL_ADMIN_USERNAME: '${INITIAL_ADMIN_USERNAME:-}'
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
Copyright (c) 2026 Grace Solutions. All rights reserved.
|
||||
Copyright (c) 2026 Endexa Solutions. All rights reserved.
|
||||
|
||||
This software and its source code, documentation and associated files (the "Software") are proprietary to Grace
|
||||
This software and its source code, documentation and associated files (the "Software") are proprietary to Endexa
|
||||
Solutions and are provided under licence only.
|
||||
|
||||
No part of the Software may be copied, modified, distributed, sublicensed, sold or made available to any third
|
||||
party, in source or binary form, except as permitted by a written licence agreement with Grace Solutions.
|
||||
party, in source or binary form, except as permitted by a written licence agreement with Endexa Solutions.
|
||||
|
||||
The Software includes third-party components that remain under their own licences; see THIRD-PARTY-NOTICES.md.
|
||||
The web console is built on a commercial user-interface template licensed to Grace Solutions for use in this product
|
||||
The web console is built on a commercial user-interface template licensed to Endexa Solutions for use in this product
|
||||
only; its source may not be extracted or redistributed on its own.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
||||
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL GRACE SOLUTIONS
|
||||
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ENDEXA SOLUTIONS
|
||||
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
@@ -275,7 +275,7 @@ Never commit generated secrets (enforced by `.gitignore`).
|
||||
|
||||
| Secret | Purpose |
|
||||
|--------|---------|
|
||||
| `INITIAL_ADMIN_PASSWORD` | First-boot local admin password |
|
||||
| `INITIAL_ADMIN_PASSWORD` | Optional first-boot admin password; empty generates one into `<data>/initial-admin-password.txt` |
|
||||
| `NATS_OPERATOR_SEED` | NATS operator identity |
|
||||
| `NATS_ACCOUNT_SEED` | Application account identity |
|
||||
| `NATS_ACCOUNT_SIGNING_SEED` | Backend signs user JWTs with this |
|
||||
@@ -349,42 +349,73 @@ relay, and supervises a `nats-server` sidecar. CI publishes
|
||||
|
||||
```text
|
||||
ExecuteR-Server setup
|
||||
Generates NATS keys, the sidecar config and appsettings.json with the
|
||||
admin/admin sign-in (override with --admin-user/--admin-password) — and
|
||||
Generates NATS keys, the sidecar config and appsettings.json — and
|
||||
downloads nats-server for this OS/architecture if it is not bundled.
|
||||
ExecuteR-Server run in the foreground on http://0.0.0.0:9080
|
||||
TLS: the managed self-signed chain by default; --tls-source store
|
||||
--tls-thumbprint <hex> (Windows) or --tls-source file --tls-cert-file
|
||||
<pfx|pem> [--tls-key-file <pem>] [--tls-password <pw>] serves your own
|
||||
(checked here, so a wrong path or password fails setup); --tls 0 for HTTP.
|
||||
ExecuteR-Server run in the foreground on https://0.0.0.0:9080
|
||||
ExecuteR-Server service install Windows service / systemd unit
|
||||
ExecuteR-Server service uninstall
|
||||
ExecuteR-Server reset-admin [--user <name>] [--password <pw>]
|
||||
Lockout recovery, run elevated on the server (service running or not)
|
||||
```
|
||||
|
||||
When the password was left at the default, the **first sign-in demands a new
|
||||
password** before any session is issued — valid credentials return a
|
||||
must-change signal, and the sign-in page walks straight into a set-new-password
|
||||
form. Choosing a literal `admin` password (CLI flag or MSI wizard) triggers
|
||||
the same reset.
|
||||
**No administrator password is asked for.** At its first start the server
|
||||
creates the built-in `admin` account with a **generated one-time password**
|
||||
and writes it to `data\initial-admin-password.txt` (beside the binary;
|
||||
`/data/initial-admin-password.txt` in the container). Only Administrators,
|
||||
SYSTEM and the account the server runs as can open that file (inheritance
|
||||
off; mode 600 off Windows), and the log only says where it is — logs are
|
||||
shipped and bundled far more widely than the data folder, so the password
|
||||
never goes there. The **first sign-in demands a new password** before any
|
||||
session is issued, and the file is deleted once it has been changed.
|
||||
`--admin-user` / `--admin-password` (MSI `ADMINUSERNAME` / `ADMINPASSWORD`)
|
||||
still set one for scripted installs; a literal `admin` forces the same reset.
|
||||
|
||||

|
||||
|
||||
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.
|
||||
**Locked out, or the file is gone?** From an elevated prompt on the server:
|
||||
|
||||
```text
|
||||
ExecuteR-Server reset-admin new one-time password for the break-glass account, printed here
|
||||
ExecuteR-Server reset-admin --user jdoe that built-in account instead
|
||||
ExecuteR-Server reset-admin --password '<pw>' that password (still changed at the next sign-in)
|
||||
```
|
||||
|
||||
It reads the same `appsettings.json` as the server, so it reaches the same
|
||||
database whether the service is running or stopped; it turns the account
|
||||
back on, clears its sign-in back-off, ends its sessions, turns Built-In
|
||||
sign-in back on (OIDC redirect off), and is audited
|
||||
(`identity.break-glass.reset`). No restart is needed. In a container:
|
||||
`docker exec EXECUTER-API-00001 dotnet Backend.dll reset-admin`.
|
||||
`auth-reset` is the same verb.
|
||||
|
||||
The **Windows MSI** wraps the same flow with two wizard pages, each label
|
||||
short with the detail in its tooltip: **Server Address** — the port (9080),
|
||||
Listen On (All Addresses, This Machine Only, or a specific address) and the
|
||||
three NATS ports with the WebSocket bind — and **Certificate** —
|
||||
**Self-Signed** (the default, managed and auto-renewed), **Certificate Store**
|
||||
(a thumbprint from Local Computer › Personal), **File** (a PFX with its
|
||||
password, or a PEM certificate and key) or **None (HTTP Only)**. A
|
||||
next-next-next install just works. Silent installs pass the same values as
|
||||
properties (`BINDADDRESS HTTPPORT NATSPORT NATSWSPORT NATSMONITORPORT
|
||||
NATSBIND ENABLETLS TLSSOURCE=selfsigned|store|file TLSTHUMBPRINT TLSCERTFILE
|
||||
TLSKEYFILE TLSCERTPASSWORD`, plus the optional `ADMINUSERNAME ADMINPASSWORD`;
|
||||
the passwords are hidden from the installer log), then the binary's own
|
||||
`setup` + `service install` run. The finish page says where the one-time
|
||||
password is and offers to **open the console in the browser** (checked by
|
||||
default) — a wildcard bind (`0.0.0.0` / `::`) opens `https://localhost:<port>`,
|
||||
a specific bind address opens that address directly. An upgrade goes straight
|
||||
from Welcome to Ready to Install: it keeps the configuration in effect.
|
||||
Upgrades never overwrite existing configuration, and uninstall stops and
|
||||
removes the service. By default a plain uninstall **keeps** the generated
|
||||
data, sign-in and self-signed chain so a reinstall resumes where it left
|
||||
off (the managed chain is located in the machine certificate stores by
|
||||
subject and reused when still valid). For a fully clean removal, tick
|
||||
**Also remove all data, keys and self-signed certificates** on the
|
||||
uninstall page — or pass `PURGEDATA=1` to a silent uninstall. That deletes
|
||||
**Remove All Data, Keys and Self-Signed Certificates** on the Remove Data
|
||||
page — or pass `PURGEDATA=1` to a silent uninstall. That deletes
|
||||
`appsettings.json`, `data`, `logs` and `secrets` and removes the
|
||||
self-signed root/intermediate/leaf from the Windows stores. The same
|
||||
cleanup is available directly as `ExecuteR-Server.exe purge`. The MSI
|
||||
@@ -401,9 +432,13 @@ 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`,
|
||||
pre-writes the optional knobs — `TLS_SELF_SIGNED`, `TLS_CERT_SOURCE`,
|
||||
`TLS_CERT_THUMBPRINT`, `TLS_CERT_FILE`, `TLS_CERT_KEY_FILE`,
|
||||
`TLS_CERT_PASSWORD`, `TLS_DISTRIBUTE_CA`, `TLS_CERT_DIR`,
|
||||
`PUBLIC_SERVER_URL`, `TRUSTED_NETWORKS`, `TRUSTED_HOSTS`, `TRUST_PROXY` — as
|
||||
placeholders ready to fill.
|
||||
placeholders ready to fill. Because it carries the NATS signing seed and any
|
||||
certificate password, `setup` restricts `appsettings.json` to Administrators,
|
||||
SYSTEM and the account that ran it.
|
||||
|
||||
**Multiple instances on one box**: one directory per instance, distinct ports
|
||||
at setup, distinct service names at install:
|
||||
@@ -447,8 +482,8 @@ 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).
|
||||
--tls 0`, or **None (HTTP Only)** on the server MSI's Certificate page
|
||||
(`ENABLETLS=""` silently).
|
||||
|
||||
The reverse proxy then has two equally valid options — **pick per your
|
||||
organization's security standards**:
|
||||
@@ -473,20 +508,123 @@ 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 trust a direct self-signed server automatically — without pinning.**
|
||||
When the server serves its chain directly, the Add-Device modal (and
|
||||
Settings token panel) pre-select **Trust self-signed certificate**, which
|
||||
sets `ServerCaAutoInstall`. The agent then fetches the CA from
|
||||
`/api/enrollment/ca` and **installs it into the OS trust store**, and a
|
||||
background service keeps it current as the server rotates its chain — so
|
||||
ordinary system validation trusts the server and renewals never lapse. It
|
||||
is deliberately *not* pinned or forced: if a reverse proxy with a real
|
||||
certificate is added later, that certificate validates normally and the
|
||||
installed self-signed CA simply goes unused — nothing to break. The setting
|
||||
is GPO-manageable (ADMX `Install the server's self-signed CA`),
|
||||
`configure --install-server-ca` sets it by hand, and the agent MSI accepts
|
||||
`CAINSTALL=1`. For an accept-any escape hatch (no validation), `insecure` /
|
||||
`TlsSkipVerify=1` remains.
|
||||
**For distribution**, the root and intermediate alone — never the leaf,
|
||||
never a key — are also written to **`<data>/ca-certificates`**
|
||||
(`root-ca.cer`/`.pem`, `intermediate-ca.cer`/`.pem`, `ca-chain.pem`) and
|
||||
rewritten on every renewal, so an administrator can push them by Group
|
||||
Policy (*Computer Configuration › Windows Settings › Security Settings ›
|
||||
Public Key Policies*: the root into Trusted Root Certification Authorities,
|
||||
the intermediate into Intermediate Certification Authorities) or to a proxy.
|
||||
|
||||
### Your own certificate
|
||||
|
||||
Instead of the managed chain, the listener can serve a certificate you
|
||||
provide — from the **Windows certificate store** or a **file** — with the
|
||||
managed chain staying the default:
|
||||
|
||||
| Setting | `setup` flag | MSI property | |
|
||||
|---|---|---|---|
|
||||
| `TLS_CERT_SOURCE` | `--tls-source` | `TLSSOURCE` | `self-signed` (default), `store`, `file` |
|
||||
| `TLS_CERT_THUMBPRINT` | `--tls-thumbprint` | `TLSTHUMBPRINT` | LocalMachine\My, with its private key (Windows) |
|
||||
| `TLS_CERT_FILE` | `--tls-cert-file` | `TLSCERTFILE` | a PFX/P12, or a PEM (a fullchain PEM brings its intermediates) |
|
||||
| `TLS_CERT_KEY_FILE` | `--tls-key-file` | `TLSKEYFILE` | the PEM key, when it is not in `TLS_CERT_FILE` |
|
||||
| `TLS_CERT_PASSWORD` | `--tls-password` | `TLSCERTPASSWORD` | the PFX password, or an encrypted PEM key's |
|
||||
| `TLS_DISTRIBUTE_CA` | | | `1`/`0` overrides whether agents are given the issuing chain |
|
||||
|
||||
A provided certificate turns HTTPS on by itself and is **reloaded without a
|
||||
restart**: a replaced file within a minute, and a store certificate renewed
|
||||
by auto-enrollment (the configured one archived or within 14 days of expiry,
|
||||
its successor with the same subject and issuer) is followed, with the new
|
||||
thumbprint logged. The handshake sends the intermediates. A certificate that
|
||||
cannot be loaded stops the first start with the reason; a later failed reload
|
||||
keeps the current one in service.
|
||||
|
||||
When the provided certificate's issuing chain is **not publicly trusted** —
|
||||
an enterprise CA — it is treated like the managed chain: the server's own
|
||||
machine stores get the intermediate (Windows), `/api/enrollment/ca` serves
|
||||
the intermediates and root (never the leaf), bootstrap tokens carry that
|
||||
root's fingerprint, and `<data>/ca-certificates` holds the same files for
|
||||
Group Policy. A **publicly trusted** chain (Windows: the root is in the
|
||||
Third-Party Root Certification Authorities store; elsewhere, in the system
|
||||
bundle rather than a locally added anchor) distributes nothing:
|
||||
`/api/enrollment/ca` stays 404 and agents just validate it.
|
||||
|
||||
### Settings › Server Certificate
|
||||
|
||||
The console shows the certificate in use — source, subject, names, issuer,
|
||||
expiry, thumbprint, the chain and whether it is public or private, the
|
||||
distribution folder, and whether agents get the chain pinned — and, on a
|
||||
Windows server, the certificates in **Local Computer › Personal** that could
|
||||
serve TLS (current, a private key the service can open, Server
|
||||
Authentication or no EKU; unusable ones are listed disabled with the reason
|
||||
on hover). Administrators (`settings.manage`) can **Bind** one, switch to
|
||||
**Self-Signed**, or **Use Configured** again; each change is audited
|
||||
(`tls.certificate.bind`, `tls.certificate.self-signed`,
|
||||
`tls.certificate.unbind`) and applied without a restart.
|
||||
|
||||
A binding is **not a thumbprint**. It stores the certificate's identity —
|
||||
subject, issuer, DNS names and the certificate template an enterprise CA
|
||||
stamps in — and every minute each server picks the certificate to serve:
|
||||
|
||||
1. Windows' own renewal link first: when the certificate it served was
|
||||
renewed (auto-enrollment archives it and records its successor), the
|
||||
successor, followed through several renewals, if usable.
|
||||
2. Otherwise the **newest usable certificate matching the identity** (latest
|
||||
issued, then latest expiry): the same template when the bound one had one
|
||||
(then from any issuing CA of that template), else the same issuer; and the
|
||||
same subject or the same set of DNS names.
|
||||
|
||||
So renewals and reissues need nobody; the page shows **Following Renewals**
|
||||
and when this server last switched. The binding is a database setting (key
|
||||
`tls.serverCertificate`), so every replica follows the same identity in its
|
||||
own store; a Linux replica says it cannot use the Windows store and keeps its
|
||||
configured certificate.
|
||||
|
||||
**Precedence:** a certificate setting in the process environment
|
||||
(`TLS_CERT_SOURCE`, `TLS_CERT_THUMBPRINT` or `TLS_CERT_FILE` — a container or
|
||||
service definition) decides, and the page says so; otherwise the console
|
||||
binding wins over `appsettings.json`, which is what `setup` and the MSI write
|
||||
and stays the default when no binding exists. A listener started on plain
|
||||
HTTP needs TLS turned on and a restart before a certificate can be bound.
|
||||
|
||||
When a switch brings a **new private root**, the page calls it out for 30
|
||||
days (**New Root Since**): agents enrolled before cannot validate the new
|
||||
chain until that root is pushed to them (from the distribution folder) or
|
||||
they enroll again; new bootstrap tokens already carry its fingerprint.
|
||||
Renewals under the same CA need nothing — the handshake sends the new
|
||||
intermediates and the agents' CA refresh installs them.
|
||||
|
||||
API (`settings.manage`): `GET /api/settings/server-certificate`,
|
||||
`POST /api/settings/server-certificate/bind` `{ "thumbprint": "…" }`,
|
||||
`POST /api/settings/server-certificate/self-signed`,
|
||||
`DELETE /api/settings/server-certificate/binding`.
|
||||
|
||||
### How agents trust the server
|
||||
|
||||
**It just works when the agent talks to the server directly.** Every
|
||||
channel — enrollment, the HTTPS API, downloads and upgrades, and the NATS
|
||||
WebSocket — first validates the certificate normally; if that succeeds the
|
||||
agent does nothing more (a public certificate, a proxy's, or a CA already
|
||||
trusted, for instance by Group Policy). Only when validation fails on an
|
||||
untrusted chain does the agent use the **fingerprint in the bootstrap token**
|
||||
(`<secret>.<sha256 of the root's public key>`): it fetches the chain from
|
||||
`/api/enrollment/ca`, keeps only the root matching the fingerprint and the
|
||||
CAs that chain to it (anything else in the response is dropped), installs
|
||||
them into the OS trust store (LocalMachine Root / Intermediate CA on Windows,
|
||||
the system anchors on Linux, the System keychain on macOS), keeps them as its
|
||||
own anchors (`%ProgramData%\ExecuteR\server-ca.pem`) and connects again with
|
||||
normal validation. Those anchors back every later connection should the OS
|
||||
store lose the CA, and a background refresh over the validated connection
|
||||
keeps them and the store current as the server renews. Name mismatches are
|
||||
never accepted. The install scripts' package download follows the same
|
||||
rule: validate first, and only on a trust failure fetch the CA and accept the
|
||||
server through a chain that ends at the pinned root (PowerShell 5.1, or
|
||||
curl `--cacert` after an `openssl` check). For an accept-any escape hatch,
|
||||
`insecure` / `TlsSkipVerify=1` remains.
|
||||
|
||||
Agents enrolled before a switch to a certificate from a different CA cannot
|
||||
validate the new one through their old anchors: give them a new bootstrap
|
||||
token (or push the new CA by Group Policy first).
|
||||
|
||||
---
|
||||
|
||||
@@ -981,14 +1119,18 @@ and carry a CSRF token checked on every write.
|
||||
**Break-glass account.** One built-in account always has full access through
|
||||
no binding, and cannot be turned off or removed. On an empty database it is
|
||||
created from `INITIAL_ADMIN_USERNAME` / `INITIAL_ADMIN_PASSWORD`. Without
|
||||
those, it is `admin` with a one-time password written once to the server log.
|
||||
a password, it gets a generated one-time password recorded in
|
||||
`<data>/initial-admin-password.txt` for administrators only (the log says
|
||||
where, never what), changed at the first sign-in.
|
||||
|
||||
**Lockout recovery** (an identity-provider outage is never terminal):
|
||||
|
||||
- `AUTH_FORCE_LOCAL=1` (environment only) always offers the built-in form.
|
||||
- `dotnet Backend.dll auth-reset` turns Built-In sign-in back on, turns
|
||||
redirect off, and prints a new one-time password for the break-glass
|
||||
account. Add `--user <name>` for another built-in account.
|
||||
- `ExecuteR-Server reset-admin` (`dotnet Backend.dll reset-admin` in a
|
||||
container; `auth-reset` is the same verb) turns Built-In sign-in back on,
|
||||
turns redirect off, turns the account back on, and prints a new one-time
|
||||
password for the break-glass account. Add `--user <name>` for another
|
||||
built-in account, `--password <pw>` to choose it.
|
||||
|
||||
**Upgrading from an earlier ExecuteR** happens once, at the first start:
|
||||
|
||||
@@ -1210,6 +1352,19 @@ the standard module path and resolve in subsequent jobs.
|
||||
|
||||
## Secrets providers and $Secrets
|
||||
|
||||
Every server has a **built-in vault**, with nothing to set up: it is always the
|
||||
first provider, so scripts can bind secrets out of the box. Manage it under
|
||||
**Vault** (nav): folders and secrets, create, edit, rename, move and delete.
|
||||
Secrets live in the application database, folder and name in clear for
|
||||
listing, the **value encrypted with the server's Data Protection key ring**
|
||||
(shared by replicas through `DATAPROTECTION_PATH`, so every node reads what
|
||||
another wrote). Values are masked; the eye button fetches one with a separate
|
||||
call that needs the **Reveal secrets** (`secrets.reveal`) permission, kept
|
||||
apart from **Manage secrets** (`secrets.manage`, which edits the vault). Every
|
||||
create, change, move, delete and reveal is audited under `secrets`, never with
|
||||
the value. Each save bumps the secret's version, and a save over a version
|
||||
someone else already replaced is refused.
|
||||
|
||||
Configure external vaults under **Settings → Secrets providers** (Infisical
|
||||
first; the driver interface is pluggable). Connection details are stored as a
|
||||
**Data Protection-encrypted blob**, secret config fields never return to the
|
||||
@@ -2210,7 +2365,7 @@ SignalR or SSE.
|
||||
|
||||
## Licence
|
||||
|
||||
ExecuteR is proprietary software of Grace Solutions, provided under licence
|
||||
ExecuteR is proprietary software of Endexa Solutions, provided under licence
|
||||
only; see [LICENSE](LICENSE). It includes third-party components under their
|
||||
own licences, and its web console is built on the commercially licensed Mantis
|
||||
Pro template — see [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md).
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Generates strong local development secrets:
|
||||
- .env (from .env.example) with a random initial admin password
|
||||
- .env (from .env.example); INITIAL_ADMIN_PASSWORD stays empty, so the
|
||||
backend generates the one-time admin password at its first start and
|
||||
records it in its data volume (/data/initial-admin-password.txt)
|
||||
- Real Ed25519 NATS operator/account/signing NKeys and JWTs via the backend's
|
||||
nats-auth CLI (NATS.NKeys / NATS.Jwt — no fake seeds)
|
||||
- secrets/nats/resolver.conf for the NATS container
|
||||
@@ -36,18 +38,17 @@ $accountPublic = (Get-Content (Join-Path $natsSecretsDir 'account.pub') -Raw).Tr
|
||||
$operatorPublic = (Get-Content (Join-Path $natsSecretsDir 'operator.pub') -Raw).Trim()
|
||||
|
||||
# ── .env ──────────────────────────────────────────────────────────────────
|
||||
function New-RandomPassword {
|
||||
param([int]$Length = 24)
|
||||
$alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#%^*-_=+'
|
||||
$bytes = [byte[]]::new($Length)
|
||||
[System.Security.Cryptography.RandomNumberGenerator]::Fill($bytes)
|
||||
-join ($bytes | ForEach-Object { $alphabet[$_ % $alphabet.Length] })
|
||||
# INITIAL_ADMIN_PASSWORD is left as .env.example has it (empty): generate and
|
||||
# record at the first start. An existing .env's value is kept on -Force, so a
|
||||
# deployment that chose its own keeps it.
|
||||
$existingAdminPassword = if (Test-Path $envFile) {
|
||||
(Get-Content $envFile | Where-Object { $_ -match '^INITIAL_ADMIN_PASSWORD=' } | Select-Object -First 1) -replace '^INITIAL_ADMIN_PASSWORD=', ''
|
||||
}
|
||||
|
||||
$adminPassword = New-RandomPassword
|
||||
|
||||
$content = Get-Content $envExample
|
||||
$content = $content -replace '^INITIAL_ADMIN_PASSWORD=.*$', "INITIAL_ADMIN_PASSWORD=$adminPassword"
|
||||
if ($existingAdminPassword) {
|
||||
$content = $content -replace '^INITIAL_ADMIN_PASSWORD=.*$', "INITIAL_ADMIN_PASSWORD=$existingAdminPassword"
|
||||
}
|
||||
$content = $content -replace '^NATS_ACCOUNT_SIGNING_SEED=.*$', "NATS_ACCOUNT_SIGNING_SEED=$accountSigningSeed"
|
||||
$content = $content -replace '^NATS_ACCOUNT_PUBLIC_KEY=.*$', "NATS_ACCOUNT_PUBLIC_KEY=$accountPublic"
|
||||
$content = $content -replace '^NATS_OPERATOR_PUBLIC_KEY=.*$', "NATS_OPERATOR_PUBLIC_KEY=$operatorPublic"
|
||||
@@ -57,5 +58,11 @@ Set-Content -Path $envFile -Value $content -Encoding utf8NoBOM
|
||||
|
||||
Write-Host ''
|
||||
Write-Host "Wrote $envFile"
|
||||
Write-Host "Initial admin: admin / $adminPassword"
|
||||
if ($existingAdminPassword) {
|
||||
Write-Host 'Initial admin: admin with the INITIAL_ADMIN_PASSWORD kept from the existing .env'
|
||||
}
|
||||
else {
|
||||
Write-Host 'Initial admin: admin, one-time password recorded at the first start:'
|
||||
Write-Host ' docker exec EXECUTER-API-00001 cat /data/initial-admin-password.txt'
|
||||
}
|
||||
Write-Host 'NATS material written below secrets/nats (seeds are SECRET).'
|
||||
|
||||
@@ -5,8 +5,9 @@ WebUI (static SPA), the API, the /messaging WebSocket relay, and supervising a
|
||||
bundled nats-server sidecar. Produces a zip per platform.
|
||||
|
||||
Quick start on the target machine:
|
||||
unzip, run `ExecuteRServer setup`, set INITIAL_ADMIN_PASSWORD in
|
||||
appsettings.json, then run the binary (or `ExecuteRServer service install`).
|
||||
unzip, run `ExecuteR-Server setup`, then run the binary (or
|
||||
`ExecuteR-Server service install`); the first start records a one-time
|
||||
admin password in data/initial-admin-password.txt (administrators only).
|
||||
|
||||
.EXAMPLE
|
||||
./scripts/Package-Server.ps1 # win-x64 + linux-x64
|
||||
|
||||
+14
-8
@@ -109,11 +109,10 @@ cd "$STACK_DIR"
|
||||
if [[ ! -f .env ]]; then
|
||||
log "Creating .env from .env.example"
|
||||
cp .env.example .env
|
||||
|
||||
# Generate the initial admin password so the stack is usable immediately.
|
||||
ADMIN_PASSWORD="$(openssl rand -base64 24 2>/dev/null | tr -d '\n/+=' | cut -c1-24)"
|
||||
[[ -n "$ADMIN_PASSWORD" ]] && sed -i "s|^INITIAL_ADMIN_PASSWORD=.*|INITIAL_ADMIN_PASSWORD=$ADMIN_PASSWORD|" .env
|
||||
GENERATED_ADMIN_PASSWORD="$ADMIN_PASSWORD"
|
||||
# INITIAL_ADMIN_PASSWORD stays empty: the backend generates the one-time
|
||||
# admin password at its first start and records it in its data volume
|
||||
# (/data/initial-admin-password.txt, mode 600), never in .env or the log.
|
||||
NEW_ENV=1
|
||||
fi
|
||||
|
||||
# shellcheck disable=SC1091
|
||||
@@ -257,8 +256,15 @@ echo " WebUI: http://<host>:${WEBUI_PORT:-13080}"
|
||||
echo " API: http://<host>:${BACKEND_PORT:-19080}/api/health"
|
||||
echo " NATS WS: ws://<host>:${NATS_WS_PORT:-19222}"
|
||||
[[ $WITH_PROXY -eq 1 ]] && echo " Proxy: https://${PUBLIC_HOSTNAME}:${PROXY_HTTPS_PORT:-18443}"
|
||||
if [[ -n "${GENERATED_ADMIN_PASSWORD:-}" ]]; then
|
||||
if [[ -z "${INITIAL_ADMIN_PASSWORD:-}" ]]; then
|
||||
# Only the command is printed: the password stays in the data volume
|
||||
# (mode 600), out of this terminal's scrollback and any CI log.
|
||||
echo
|
||||
echo " Initial admin: ${INITIAL_ADMIN_USERNAME:-admin} / ${GENERATED_ADMIN_PASSWORD}"
|
||||
echo " (also stored in .env — change it after first sign-in)"
|
||||
echo " Initial admin: ${INITIAL_ADMIN_USERNAME:-admin}, with the one-time password the first start recorded:"
|
||||
echo " docker exec EXECUTER-API-00001 cat /data/initial-admin-password.txt"
|
||||
echo " A new password is required at the first sign-in. Locked out later:"
|
||||
echo " docker exec EXECUTER-API-00001 dotnet Backend.dll reset-admin"
|
||||
elif [[ -n "${NEW_ENV:-}" ]]; then
|
||||
echo
|
||||
echo " Initial admin: ${INITIAL_ADMIN_USERNAME:-admin} with INITIAL_ADMIN_PASSWORD from .env"
|
||||
fi
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ uses at runtime to issue agent and browser user JWTs. If you prefer
|
||||
|
||||
## Required secrets (production)
|
||||
|
||||
- `INITIAL_ADMIN_PASSWORD` — first-boot local admin password
|
||||
- `INITIAL_ADMIN_PASSWORD` — optional first-boot admin password; left empty, the backend generates one and records it in its data folder (`initial-admin-password.txt`, administrators only)
|
||||
- `NATS_OPERATOR_SEED` — operator identity (kept offline after setup)
|
||||
- `NATS_ACCOUNT_SEED` — application account identity
|
||||
- `NATS_ACCOUNT_SIGNING_SEED` — given to the backend for user JWT issuance
|
||||
|
||||
@@ -352,11 +352,8 @@ public sealed class CredentialRenewal(CredentialRenewalContext context, ILogger
|
||||
return create(skipVerify);
|
||||
}
|
||||
|
||||
var handler = new HttpClientHandler();
|
||||
if (skipVerify)
|
||||
{
|
||||
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
|
||||
}
|
||||
// The OS trust store, then the CA pinned at enrollment (ServerTrustAnchors).
|
||||
var handler = ServerTrustAnchors.Default.CreateHandler(skipVerify);
|
||||
|
||||
return handler;
|
||||
}
|
||||
|
||||
@@ -24,8 +24,11 @@ public sealed class EnrollmentService(
|
||||
RuntimeStateStore runtimeState,
|
||||
IHardwareIdentitySource hardwareIdentity,
|
||||
IInventoryCollector inventory,
|
||||
ILogger<EnrollmentService> logger)
|
||||
ILogger<EnrollmentService> logger,
|
||||
ServerTrustAnchors? anchors = null)
|
||||
{
|
||||
private readonly ServerTrustAnchors trustAnchors = anchors ?? ServerTrustAnchors.Default;
|
||||
|
||||
/// <summary>
|
||||
/// Returns valid credentials, either loaded from the protected store or
|
||||
/// obtained by bootstrapping. Null when enrollment is currently impossible
|
||||
@@ -154,7 +157,9 @@ public sealed class EnrollmentService(
|
||||
{
|
||||
try
|
||||
{
|
||||
using var validating = new HttpClientHandler();
|
||||
// Validation as every channel does it: the OS trust store, then the
|
||||
// CA pinned at an earlier enrollment.
|
||||
using var validating = trustAnchors.CreateHandler(skipVerify: false);
|
||||
response = await PostBootstrapAsync(validating, endpoint, request, cancellationToken);
|
||||
}
|
||||
catch (HttpRequestException ex) when (ex.HttpRequestError == HttpRequestError.SecureConnectionError)
|
||||
@@ -168,7 +173,7 @@ public sealed class EnrollmentService(
|
||||
}
|
||||
|
||||
var (status, pinnedChain) = await ServerTrust.FetchAndInstallCaAsync(
|
||||
serverUrl, HttpClient.DefaultProxy, logger, expectedFingerprint, cancellationToken);
|
||||
serverUrl, HttpClient.DefaultProxy, logger, expectedFingerprint, cancellationToken, trustAnchors);
|
||||
if (status != ServerCaStatus.Installed)
|
||||
{
|
||||
logger.LogError("Could not anchor server trust ({Status}); refusing to enroll", status);
|
||||
|
||||
@@ -27,13 +27,16 @@ public enum ServerCaStatus
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes the server's managed self-signed CA available to the OS trust store
|
||||
/// so ordinary system validation succeeds when the agent connects to the
|
||||
/// self-signed server directly (e.g. a local URL). It is intentionally NOT
|
||||
/// Makes the server's CA (its managed self-signed chain, or the private CA
|
||||
/// behind a certificate the administrator provided) available to the OS trust
|
||||
/// store so ordinary system validation succeeds when the agent connects to the
|
||||
/// server directly (e.g. a local URL), and keeps it as the agent's own anchors
|
||||
/// (<see cref="ServerTrustAnchors"/>) for every channel. It is intentionally NOT
|
||||
/// pinned or forced: if a reverse proxy with a real certificate is added
|
||||
/// later, system validation trusts that instead, and the installed
|
||||
/// self-signed CA simply goes unused — nothing to break. Certs come from
|
||||
/// GET /api/enrollment/ca; a 404 means the server is not self-signed.
|
||||
/// GET /api/enrollment/ca; a 404 means there is nothing to distribute (a
|
||||
/// publicly trusted certificate, or plain HTTP).
|
||||
/// </summary>
|
||||
public static class ServerTrust
|
||||
{
|
||||
@@ -47,7 +50,8 @@ public static class ServerTrust
|
||||
/// it directly, independent of OS trust-store timing).
|
||||
/// </summary>
|
||||
public static async Task<(ServerCaStatus Status, X509Certificate2Collection Chain)> FetchAndInstallCaAsync(
|
||||
ServerUrl serverUrl, IWebProxy? proxy, ILogger logger, string expectedFingerprint, CancellationToken cancellationToken)
|
||||
ServerUrl serverUrl, IWebProxy? proxy, ILogger logger, string expectedFingerprint, CancellationToken cancellationToken,
|
||||
ServerTrustAnchors? anchors = null)
|
||||
{
|
||||
using var handler = new HttpClientHandler
|
||||
{
|
||||
@@ -88,17 +92,31 @@ public static class ServerTrust
|
||||
|
||||
// Pin on the public key (SubjectPublicKeyInfo), not the certificate, so it
|
||||
// matches a root renewed in place (same key, re-issued cert). Only the root
|
||||
// carries this key — the intermediate and leaf have their own.
|
||||
var expected = expectedFingerprint.Trim().ToLowerInvariant();
|
||||
var matched = chain.Cast<X509Certificate2>()
|
||||
.Any(c => Convert.ToHexStringLower(SHA256.HashData(c.PublicKey.ExportSubjectPublicKeyInfo())) == expected);
|
||||
if (!matched)
|
||||
// carries this key — the intermediate and leaf have their own. Only that
|
||||
// root and the CAs that chain to it are kept: the response came over an
|
||||
// unverified connection, so anything else in it (an extra root added on
|
||||
// the path) must never reach the trust store.
|
||||
var pinned = ServerTrustAnchors.PinnedSubset(chain, expectedFingerprint);
|
||||
if (pinned.Count == 0)
|
||||
{
|
||||
logger.LogError(
|
||||
"Fetched server CA does not match the fingerprint pinned in the bootstrap token; refusing to trust (possible MITM)");
|
||||
return (ServerCaStatus.FingerprintMismatch, []);
|
||||
}
|
||||
|
||||
if (pinned.Count < chain.Count)
|
||||
{
|
||||
logger.LogWarning("Ignored {Count} certificate(s) in the server CA response that do not chain to the pinned root", chain.Count - pinned.Count);
|
||||
}
|
||||
|
||||
Install(pinned, logger);
|
||||
(anchors ?? ServerTrustAnchors.Default).Save(pinned, logger);
|
||||
return (ServerCaStatus.Installed, pinned);
|
||||
}
|
||||
|
||||
private static void Install(X509Certificate2Collection chain, ILogger logger)
|
||||
{
|
||||
var pem = string.Concat(chain.Cast<X509Certificate2>().Select(c => c.ExportCertificatePem() + '\n'));
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
InstallWindows(chain, logger);
|
||||
@@ -111,8 +129,6 @@ public static class ServerTrust
|
||||
{
|
||||
InstallLinux(pem, logger);
|
||||
}
|
||||
|
||||
return (ServerCaStatus.Installed, chain);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -121,13 +137,18 @@ public static class ServerTrust
|
||||
/// connection — a root renewed in place (same key, longer validity) or a new
|
||||
/// intermediate — is authentic and installed. No pin here: the validated
|
||||
/// transport, not a fingerprint, authenticates it (first contact was pinned at
|
||||
/// enrollment). A 404 (real certificate) or a validation failure is a harmless
|
||||
/// no-op. Returns true when a chain was installed.
|
||||
/// enrollment). The connection validates like every other channel: the OS
|
||||
/// trust store first, then the anchors kept at enrollment, so a CA that was
|
||||
/// taken out of the trust store is put back here. A 404 (real certificate)
|
||||
/// or a validation failure is a harmless no-op. Returns true when a chain
|
||||
/// was installed.
|
||||
/// </summary>
|
||||
public static async Task<bool> RefreshCaAsync(
|
||||
ServerUrl serverUrl, IWebProxy? proxy, ILogger logger, CancellationToken cancellationToken)
|
||||
ServerUrl serverUrl, IWebProxy? proxy, ILogger logger, CancellationToken cancellationToken,
|
||||
ServerTrustAnchors? anchors = null)
|
||||
{
|
||||
using var handler = new HttpClientHandler();
|
||||
anchors ??= ServerTrustAnchors.Default;
|
||||
using var handler = anchors.CreateHandler(skipVerify: false);
|
||||
if (proxy is not null)
|
||||
{
|
||||
handler.Proxy = proxy;
|
||||
@@ -162,19 +183,15 @@ public static class ServerTrust
|
||||
return false;
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsWindows())
|
||||
X509Certificate2Collection authorities = [.. chain.Cast<X509Certificate2>().Where(c => c.Extensions.OfType<X509BasicConstraintsExtension>().FirstOrDefault() is { CertificateAuthority: true }
|
||||
|| ServerTrustAnchors.IsSelfIssued(c))];
|
||||
if (authorities.Count == 0)
|
||||
{
|
||||
InstallWindows(chain, logger);
|
||||
}
|
||||
else if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
InstallMac(pem, chain, logger);
|
||||
}
|
||||
else
|
||||
{
|
||||
InstallLinux(pem, logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
Install(authorities, logger);
|
||||
anchors.Save(authorities, logger);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Security;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shared.Infrastructure.Constants;
|
||||
|
||||
namespace Agent.Enrollment;
|
||||
|
||||
/// <summary>
|
||||
/// The server CA this agent verified when it enrolled (pinned to the token's
|
||||
/// fingerprint), kept in the agent's protected data folder so every channel
|
||||
/// to the server — the HTTPS API, downloads, upgrades, the NATS WebSocket —
|
||||
/// validates the same way: normal OS validation first, and only when that
|
||||
/// fails on an untrusted chain, a chain that ends at one of these anchors.
|
||||
/// The OS trust store holds the same CA (installed at enrollment), so this
|
||||
/// only matters when that install did not take or was undone (a trust-store
|
||||
/// policy, an unknown Linux layout), and it keeps the agent connected instead
|
||||
/// of stranded. Name mismatches and missing certificates are never accepted.
|
||||
/// </summary>
|
||||
public sealed class ServerTrustAnchors(string path)
|
||||
{
|
||||
public const string FileName = "server-ca.pem";
|
||||
|
||||
private readonly Lock gate = new();
|
||||
private X509Certificate2Collection anchors = [];
|
||||
private DateTime loadedStamp = DateTime.MinValue;
|
||||
|
||||
/// <summary>The agent's own anchors, %ProgramData%\ExecuteR\server-ca.pem (/var/lib/executer elsewhere).</summary>
|
||||
public static ServerTrustAnchors Default { get; } = new(Path.Combine(Branding.AgentProgramDataDirectory, FileName));
|
||||
|
||||
public string FilePath => path;
|
||||
|
||||
/// <summary>The persisted anchors (reloaded when the file changes); empty when none.</summary>
|
||||
public X509Certificate2Collection Load()
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
try
|
||||
{
|
||||
var stamp = File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue;
|
||||
if (stamp != loadedStamp)
|
||||
{
|
||||
X509Certificate2Collection fresh = [];
|
||||
if (stamp != DateTime.MinValue)
|
||||
{
|
||||
fresh.ImportFromPemFile(path);
|
||||
}
|
||||
|
||||
anchors = fresh;
|
||||
loadedStamp = stamp;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or CryptographicException)
|
||||
{
|
||||
anchors = [];
|
||||
}
|
||||
|
||||
return anchors;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Replaces the anchors with <paramref name="chain"/>'s CA certificates (public certificates only).</summary>
|
||||
public void Save(IEnumerable<X509Certificate2> chain, ILogger logger)
|
||||
{
|
||||
var pem = string.Concat(chain.Where(IsCertificateAuthority).Select(c => c.ExportCertificatePem() + '\n'));
|
||||
if (pem.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
if (File.Exists(path) && File.ReadAllText(path) == pem)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
File.WriteAllText(path, pem);
|
||||
lock (gate)
|
||||
{
|
||||
loadedStamp = DateTime.MinValue;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
logger.LogWarning(ex, "Could not keep the server CA in {Path}; the OS trust store alone validates the server", path);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normal validation's verdict when it passed; otherwise, for an untrusted
|
||||
/// chain only, whether the certificate chains to a pinned anchor.
|
||||
/// </summary>
|
||||
public bool Validate(X509Certificate2? certificate, X509Chain? presented, SslPolicyErrors errors)
|
||||
{
|
||||
if (errors == SslPolicyErrors.None)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if ((errors & ~SslPolicyErrors.RemoteCertificateChainErrors) != 0 || certificate is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var known = Load();
|
||||
return known.Count > 0 && ChainsTo(certificate, known, presented);
|
||||
}
|
||||
|
||||
/// <summary>For HttpClientHandler.ServerCertificateCustomValidationCallback.</summary>
|
||||
public bool ValidateHttp(HttpRequestMessage request, X509Certificate2? certificate, X509Chain? chain, SslPolicyErrors errors)
|
||||
=> Validate(certificate, chain, errors);
|
||||
|
||||
/// <summary>For ClientWebSocketOptions / SslStream RemoteCertificateValidationCallback.</summary>
|
||||
public bool ValidateSocket(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors errors)
|
||||
=> Validate(certificate as X509Certificate2 ?? (certificate is null ? null : X509CertificateLoader.LoadCertificate(certificate.GetRawCertData())), chain, errors);
|
||||
|
||||
/// <summary>A handler for the server: accept-any with TlsSkipVerify, else validation with this fallback.</summary>
|
||||
public HttpClientHandler CreateHandler(bool skipVerify)
|
||||
=> new()
|
||||
{
|
||||
ServerCertificateCustomValidationCallback = skipVerify
|
||||
? HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
|
||||
: ValidateHttp,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Custom-root validation against <paramref name="trusted"/>: self-issued
|
||||
/// certificates are the anchors, the rest (and what the server presented)
|
||||
/// only help build the path.
|
||||
/// </summary>
|
||||
public static bool ChainsTo(X509Certificate2 certificate, X509Certificate2Collection trusted, X509Chain? presented = null)
|
||||
{
|
||||
using var chain = new X509Chain();
|
||||
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
|
||||
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
||||
foreach (var ca in trusted)
|
||||
{
|
||||
if (IsSelfIssued(ca))
|
||||
{
|
||||
chain.ChainPolicy.CustomTrustStore.Add(ca);
|
||||
}
|
||||
else
|
||||
{
|
||||
chain.ChainPolicy.ExtraStore.Add(ca);
|
||||
}
|
||||
}
|
||||
|
||||
if (presented is not null)
|
||||
{
|
||||
foreach (var element in presented.ChainElements)
|
||||
{
|
||||
chain.ChainPolicy.ExtraStore.Add(element.Certificate);
|
||||
}
|
||||
}
|
||||
|
||||
return chain.ChainPolicy.CustomTrustStore.Count > 0 && chain.Build(certificate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What may be trusted from a fetched chain once the root matching
|
||||
/// <paramref name="fingerprint"/> is found: that root, and the CA
|
||||
/// certificates that chain to it. Anything else in the response — an extra
|
||||
/// root slipped in by someone on the path, a leaf — is dropped, so it can
|
||||
/// never become a trust anchor. Empty when no self-issued certificate
|
||||
/// matches.
|
||||
/// </summary>
|
||||
public static X509Certificate2Collection PinnedSubset(X509Certificate2Collection fetched, string fingerprint)
|
||||
{
|
||||
var expected = fingerprint.Trim().ToLowerInvariant();
|
||||
var root = fetched.Cast<X509Certificate2>()
|
||||
.FirstOrDefault(c => IsSelfIssued(c) && Convert.ToHexStringLower(SHA256.HashData(c.PublicKey.ExportSubjectPublicKeyInfo())) == expected);
|
||||
if (root is null)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
X509Certificate2Collection anchor = [root];
|
||||
X509Certificate2Collection result = [root];
|
||||
foreach (var candidate in fetched.Cast<X509Certificate2>().Where(c => c.Thumbprint != root.Thumbprint && IsCertificateAuthority(c) && !IsSelfIssued(c)))
|
||||
{
|
||||
using var chain = new X509Chain();
|
||||
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
|
||||
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
||||
chain.ChainPolicy.CustomTrustStore.AddRange(anchor);
|
||||
chain.ChainPolicy.ExtraStore.AddRange(fetched);
|
||||
if (chain.Build(candidate))
|
||||
{
|
||||
result.Add(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static bool IsSelfIssued(X509Certificate2 certificate)
|
||||
=> certificate.SubjectName.RawData.AsSpan().SequenceEqual(certificate.IssuerName.RawData);
|
||||
|
||||
private static bool IsCertificateAuthority(X509Certificate2 certificate)
|
||||
=> certificate.Extensions.OfType<X509BasicConstraintsExtension>().FirstOrDefault() is { CertificateAuthority: true }
|
||||
|| (IsSelfIssued(certificate) && !certificate.Extensions.OfType<X509BasicConstraintsExtension>().Any());
|
||||
}
|
||||
@@ -5,8 +5,9 @@ namespace Agent.Files;
|
||||
/// <summary>
|
||||
/// Where a download a command names comes from, and how it is fetched. A server path goes to the server this agent
|
||||
/// already talks to, so a link from the built-in S3 store needs no address of its own. An absolute URL is used as is.
|
||||
/// Trust is the same as enrollment's: OS validation (a self-signed server's CA was installed into the OS store when
|
||||
/// the agent enrolled), or accept-any when TlsSkipVerify is configured.
|
||||
/// Trust is the same as enrollment's: OS validation (the server's CA was installed into the OS store when the agent
|
||||
/// enrolled), then the CA pinned at enrollment (<see cref="Agent.Enrollment.ServerTrustAnchors"/>), or accept-any when
|
||||
/// TlsSkipVerify is configured.
|
||||
/// </summary>
|
||||
public sealed class ServerDownloads(ServerUrl? serverUrl, bool tlsSkipVerify)
|
||||
{
|
||||
@@ -39,15 +40,7 @@ public sealed class ServerDownloads(ServerUrl? serverUrl, bool tlsSkipVerify)
|
||||
}
|
||||
|
||||
public static HttpMessageHandler CreateHandler(bool tlsSkipVerify)
|
||||
{
|
||||
var handler = new HttpClientHandler();
|
||||
if (tlsSkipVerify)
|
||||
{
|
||||
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
|
||||
}
|
||||
|
||||
return handler;
|
||||
}
|
||||
=> Agent.Enrollment.ServerTrustAnchors.Default.CreateHandler(tlsSkipVerify);
|
||||
|
||||
/// <summary>A link's query is its authorization, which has no place in a job's output.</summary>
|
||||
private static string RedactQuery(string url) => url.Split('?')[0];
|
||||
|
||||
@@ -18,7 +18,8 @@ public static class AgentNatsOptionsFactory
|
||||
AgentCredentials credentials,
|
||||
AgentConfiguration configuration,
|
||||
ILoggerFactory loggerFactory,
|
||||
Func<AgentCredentials?>? current = null)
|
||||
Func<AgentCredentials?>? current = null,
|
||||
ServerTrustAnchors? trustAnchors = null)
|
||||
{
|
||||
var options = NatsOpts.Default with
|
||||
{
|
||||
@@ -44,9 +45,11 @@ public static class AgentNatsOptionsFactory
|
||||
};
|
||||
|
||||
// TlsSkipVerify accepts any cert (still encrypted); otherwise the OS
|
||||
// trust store validates the wss server cert — which trusts the
|
||||
// self-signed CA the agent auto-installs at enrollment.
|
||||
// trust store validates the wss server cert — which trusts the CA the
|
||||
// agent auto-installs at enrollment — and, should that fail, the CA
|
||||
// pinned at enrollment does (ServerTrustAnchors), as for HTTPS.
|
||||
var skipVerify = configuration.TlsSkipVerify.Value;
|
||||
var anchors = trustAnchors ?? ServerTrustAnchors.Default;
|
||||
if (skipVerify)
|
||||
{
|
||||
options = options with { TlsOpts = NatsTlsOpts.Default with { InsecureSkipVerify = true } };
|
||||
@@ -63,10 +66,9 @@ public static class AgentNatsOptionsFactory
|
||||
// HttpClient.DefaultProxy on its own.
|
||||
clientOptions.Proxy = System.Net.Http.HttpClient.DefaultProxy;
|
||||
|
||||
if (skipVerify)
|
||||
{
|
||||
clientOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true;
|
||||
}
|
||||
clientOptions.RemoteCertificateValidationCallback = skipVerify
|
||||
? (_, _, _, _) => true
|
||||
: anchors.ValidateSocket;
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
},
|
||||
|
||||
@@ -23,22 +23,21 @@ public static class ScriptArgumentBinder
|
||||
|
||||
foreach (var parameter in parameters)
|
||||
{
|
||||
JsonElement value;
|
||||
var hasValue = arguments is not null && arguments.TryGetValue(parameter.Name, out value);
|
||||
// An empty value is no value: the script's default applies (it is
|
||||
// filled in here, at run time, so a schedule that never set one
|
||||
// follows the current default), and without one PowerShell's own.
|
||||
JsonElement value = default;
|
||||
var hasValue = arguments is not null
|
||||
&& arguments.TryGetValue(parameter.Name, out value)
|
||||
&& !ScriptArgumentValue.IsEmpty(value);
|
||||
if (!hasValue)
|
||||
{
|
||||
if (parameter.DefaultValue is { } def && def.ValueKind is not JsonValueKind.Undefined)
|
||||
{
|
||||
value = def;
|
||||
}
|
||||
else
|
||||
if (ScriptArgumentValue.IsEmpty(parameter.DefaultValue))
|
||||
{
|
||||
continue; // Let PowerShell apply its own default / prompt suppression.
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
value = arguments![parameter.Name];
|
||||
|
||||
value = parameter.DefaultValue!.Value;
|
||||
}
|
||||
|
||||
result[parameter.Name] = Convert(parameter, value);
|
||||
|
||||
@@ -48,13 +48,15 @@ public static class BootstrapTokenEndpoints
|
||||
var maxUses = request?.MaxUses ?? ProtocolDefaults.BootstrapTokenDefaultMaxUses;
|
||||
|
||||
// Plaintext exists exactly once: in this response. Only the hash is stored.
|
||||
// When the server runs the managed self-signed chain, append its CA
|
||||
// fingerprint (token = "secret.fp"): the agent pins the CA it fetches on
|
||||
// When the server hands agents its issuing chain (the managed self-signed
|
||||
// chain, or a provided certificate from a CA that is not publicly
|
||||
// trusted), append that root's fingerprint (token = "secret.fp"): the
|
||||
// agent pins the CA it fetches on
|
||||
// first contact to this value, so an on-path attacker cannot substitute a
|
||||
// CA. The fp travels wherever the token does — no extra plumbing — and the
|
||||
// hash covers the whole string, so enrollment validation is unchanged.
|
||||
var token = TokenGenerator.CreateUrlSafeToken(ProtocolDefaults.BootstrapTokenEntropyBytes);
|
||||
var caFingerprint = context.RequestServices.GetService<SelfSignedTlsManager>()?.CaFingerprint();
|
||||
var caFingerprint = context.RequestServices.GetService<IServerTlsSource>()?.CaFingerprint();
|
||||
if (caFingerprint is not null)
|
||||
{
|
||||
token += "." + caFingerprint;
|
||||
|
||||
@@ -5,27 +5,54 @@ using Microsoft.AspNetCore.DataProtection;
|
||||
namespace Backend.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Lockout recovery, run on the server (or inside the container):
|
||||
/// Lockout recovery, run on the server (or inside the container), with the service running or stopped:
|
||||
///
|
||||
/// dotnet Backend.dll auth-reset Built-In sign-in on, OIDC redirect off, and a new one-time
|
||||
/// password for the break-glass account (created if missing)
|
||||
/// dotnet Backend.dll auth-reset --user jdoe a new one-time password for that built-in account instead
|
||||
/// dotnet Backend.dll auth-reset --password 'secret' that password rather than a generated one (still changed at sign-in)
|
||||
/// ExecuteR-Server reset-admin Built-In sign-in on, OIDC redirect off, and a new one-time
|
||||
/// password for the break-glass account (created if missing)
|
||||
/// ExecuteR-Server reset-admin --user jdoe a new one-time password for that built-in account instead
|
||||
/// ExecuteR-Server reset-admin --password 'secret' that password rather than a generated one (still changed at sign-in)
|
||||
///
|
||||
/// So an identity provider that is down, misconfigured or has revoked the
|
||||
/// client never locks anyone out for good. AUTH_FORCE_LOCAL=1 offers the
|
||||
/// built-in form at startup without a database write. Exit codes: 0 done,
|
||||
/// 1 failed, 2 no such account.
|
||||
/// (<c>auth-reset</c> is the same verb; containers run <c>dotnet Backend.dll reset-admin</c>.) The account is turned
|
||||
/// back on, its sign-in back-off cleared and its sessions ended; the reset is audited. The new password is printed
|
||||
/// here only. So an identity provider that is down, misconfigured or has revoked the client, or a lost first-start
|
||||
/// password, never locks anyone out for good. AUTH_FORCE_LOCAL=1 offers the built-in form at startup without a
|
||||
/// database write. Exit codes: 0 done, 1 failed, 2 no such account.
|
||||
/// </summary>
|
||||
public static class AuthResetCli
|
||||
{
|
||||
public static readonly string[] Verbs = ["reset-admin", "auth-reset"];
|
||||
|
||||
/// <summary>
|
||||
/// The server's own settings: the standalone server's appsettings.json beside the binary (where setup wrote the
|
||||
/// database and data paths), then the environment, as the server itself reads them.
|
||||
/// </summary>
|
||||
public static IConfiguration LoadConfiguration(string? baseDirectory = null)
|
||||
=> new ConfigurationBuilder()
|
||||
.AddJsonFile(Path.Combine(baseDirectory ?? AppContext.BaseDirectory, "appsettings.json"), optional: true, reloadOnChange: false)
|
||||
.AddEnvironmentVariables()
|
||||
.Build();
|
||||
|
||||
public static async Task<int> RunAsync(string[] args, IConfiguration configuration)
|
||||
{
|
||||
if (args.Contains("--help") || args.Contains("-h") || args.Contains("/?"))
|
||||
{
|
||||
Console.WriteLine("Usage: reset-admin [--user <name>] [--password <password>]");
|
||||
Console.WriteLine(" Gives the break-glass account (or --user) a new password that must be changed at the next sign-in,");
|
||||
Console.WriteLine(" turns it back on and restores Built-In sign-in. Without --password one is generated and printed.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
var userName = ArgValue(args, "--user") ?? ArgValue(args, "--admin");
|
||||
var password = ArgValue(args, "--password");
|
||||
if (password is { Length: > PasswordHashing.MaxLength })
|
||||
{
|
||||
Console.Error.WriteLine($"--password may be at most {PasswordHashing.MaxLength} characters.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging(b => b.AddSimpleConsole());
|
||||
// Warnings only: the output is read by a person, and the password line must not drown in query logging.
|
||||
services.AddLogging(b => b.AddSimpleConsole().SetMinimumLevel(LogLevel.Warning));
|
||||
services.AddSingleton(configuration);
|
||||
services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(DataProtectionPath(configuration)));
|
||||
services.AddApplicationDatabase(DatabaseOptions.FromConfiguration(configuration));
|
||||
@@ -41,24 +68,20 @@ public static class AuthResetCli
|
||||
var row = await SettingsDocuments.LoadAsync(db, AuthenticationMethods.Key, CancellationToken.None);
|
||||
var before = SettingsDocuments.Parse(row?.Value, AuthenticationMethods.Defaults);
|
||||
SettingsDocuments.Stage(db, row, AuthenticationMethods.Key, row is null ? null : before, before with { BuiltIn = true, OidcRedirect = false },
|
||||
"auth-reset", always: true);
|
||||
"reset-admin", always: true);
|
||||
await db.SaveChangesAsync();
|
||||
Console.WriteLine("Built-In sign-in is on and OIDC redirect is off.");
|
||||
}
|
||||
|
||||
var (user, generated) = await provider.GetRequiredService<BreakGlass>().ResetAsync(userName, "auth-reset", CancellationToken.None);
|
||||
if (!string.IsNullOrEmpty(password))
|
||||
var (user, generated) = await provider.GetRequiredService<BreakGlass>().ResetAsync(userName, "reset-admin", CancellationToken.None, password);
|
||||
Console.WriteLine(string.IsNullOrEmpty(password)
|
||||
? $"{user.UserName}: one-time password {generated} (a new one is required at the next sign-in)."
|
||||
: $"{user.UserName}: password set; a new one is required at the next sign-in.");
|
||||
|
||||
// A first-start record no longer holds a working password.
|
||||
if (user.IsBreakGlass && InitialAdminPasswordFile.Delete(InitialAdminPasswordFile.PathFor(configuration)))
|
||||
{
|
||||
using var scope = provider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
var tracked = await db.Users.FindAsync(user.Id);
|
||||
tracked!.PasswordHash = PasswordHashing.Hash(password);
|
||||
await db.SaveChangesAsync();
|
||||
Console.WriteLine($"{user.UserName}: password set; it must be changed at the next sign-in.");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"{user.UserName}: one-time password {generated} (change it at the next sign-in).");
|
||||
Console.WriteLine($"Removed the first-start record {InitialAdminPasswordFile.PathFor(configuration)}.");
|
||||
}
|
||||
|
||||
Console.WriteLine("No restart needed; sign in at /sign-in.");
|
||||
@@ -71,7 +94,8 @@ public static class AuthResetCli
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Console.Error.WriteLine($"auth-reset failed: {exception.Message}");
|
||||
Console.Error.WriteLine($"reset-admin failed: {exception.Message}");
|
||||
Console.Error.WriteLine("Run it as administrator (root) on the server, where the server's data folder can be written.");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ public static class Permissions
|
||||
public const string AutomationManage = "automation.manage";
|
||||
public const string SecretsUse = "secrets.use";
|
||||
public const string SecretsManage = "secrets.manage";
|
||||
public const string SecretsReveal = "secrets.reveal";
|
||||
public const string ShellUse = "shell.use";
|
||||
public const string FilesSend = "files.send";
|
||||
public const string FilesBrowse = "files.browse";
|
||||
@@ -70,8 +71,9 @@ public static class Permissions
|
||||
]),
|
||||
new("Secrets",
|
||||
[
|
||||
new(SecretsUse, "Use secrets", "Browse provider paths and bind secrets into scripts."),
|
||||
new(SecretsManage, "Manage secret providers", "Configure and test secrets provider connections."),
|
||||
new(SecretsUse, "Use secrets", "Browse provider paths and the built-in vault, and bind secrets into scripts."),
|
||||
new(SecretsManage, "Manage secrets", "Configure and test secrets provider connections, and edit the built-in vault."),
|
||||
new(SecretsReveal, "Reveal secrets", "Show built-in vault values in the console. Every reveal is audited."),
|
||||
]),
|
||||
new("Remote access",
|
||||
[
|
||||
|
||||
@@ -9,9 +9,10 @@ namespace Backend.Auth;
|
||||
/// The one break-glass built-in account: full access through no binding, kept
|
||||
/// for recovery, audited on every use. Created on the first start of an empty
|
||||
/// database: with INITIAL_ADMIN_USERNAME/INITIAL_ADMIN_PASSWORD when the
|
||||
/// deployment set them, otherwise as <c>admin</c> with a generated password
|
||||
/// written once to the log. The <c>auth-reset</c> verb gives it a new one-time
|
||||
/// password.
|
||||
/// deployment set them, otherwise with a generated password that must be changed
|
||||
/// at the first sign-in, recorded in the data folder for administrators only
|
||||
/// (<see cref="InitialAdminPasswordFile"/>). The <c>reset-admin</c> verb (also
|
||||
/// <c>auth-reset</c>) gives it a new one-time password.
|
||||
/// </summary>
|
||||
public sealed class BreakGlass(IServiceScopeFactory scopes)
|
||||
{
|
||||
@@ -84,10 +85,11 @@ public sealed class BreakGlass(IServiceScopeFactory scopes)
|
||||
|
||||
/// <summary>
|
||||
/// Gives a built-in account (the break-glass account when <paramref name="userName"/>
|
||||
/// is null, creating it if missing) a new generated password that must be
|
||||
/// changed at the next sign-in, clears its back-off and ends its sessions.
|
||||
/// is null, creating it if missing) a new password that must be changed at the
|
||||
/// next sign-in (<paramref name="password"/>, or a generated one), turns it back
|
||||
/// on, clears its back-off and ends its sessions.
|
||||
/// </summary>
|
||||
public async Task<(UserEntity User, string Password)> ResetAsync(string? userName, string actor, CancellationToken cancellationToken)
|
||||
public async Task<(UserEntity User, string Password)> ResetAsync(string? userName, string actor, CancellationToken cancellationToken, string? password = null)
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
@@ -100,7 +102,7 @@ public sealed class BreakGlass(IServiceScopeFactory scopes)
|
||||
}
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var password = PasswordHashing.Generate();
|
||||
password = string.IsNullOrEmpty(password) ? PasswordHashing.Generate() : password;
|
||||
if (user is null)
|
||||
{
|
||||
var taken = await db.Users.AnyAsync(u => u.Kind == SignInProviders.Local && u.UserName == DefaultUserName, cancellationToken);
|
||||
@@ -157,11 +159,29 @@ public sealed class IdentityStartup(IServiceScopeFactory scopes, BreakGlass brea
|
||||
var userName = configuration["INITIAL_ADMIN_USERNAME"];
|
||||
var generated = await breakGlass.EnsureAsync(userName, configuration["INITIAL_ADMIN_PASSWORD"],
|
||||
configuration["INITIAL_ADMIN_MUST_CHANGE"] is "1" or "true", cancellationToken);
|
||||
var record = InitialAdminPasswordFile.PathFor(configuration);
|
||||
if (generated is not null)
|
||||
{
|
||||
logger.LogWarning(
|
||||
"First start: sign in as {User} with the one-time password {Password} and choose a new one. This is the only place it is shown; if it is lost, run the auth-reset verb on this server.",
|
||||
string.IsNullOrWhiteSpace(userName) ? BreakGlass.DefaultUserName : userName.Trim(), generated);
|
||||
// An empty INITIAL_ADMIN_PASSWORD means generate and record: the password goes to a file only administrators can
|
||||
// open, never to the log, which is shipped, bundled and read far more widely than the data folder.
|
||||
var name = string.IsNullOrWhiteSpace(userName) ? BreakGlass.DefaultUserName : userName.Trim();
|
||||
try
|
||||
{
|
||||
InitialAdminPasswordFile.Write(record, name, generated, DateTimeOffset.UtcNow);
|
||||
logger.LogWarning(
|
||||
"First start: the one-time password for {User} is in {Path} (administrators only); a new one is required at the first sign-in. Lost? Run reset-admin on this server.",
|
||||
name, record);
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or PlatformNotSupportedException)
|
||||
{
|
||||
logger.LogError(exception,
|
||||
"First start: the one-time password for {User} could not be written to {Path}. Run reset-admin on this server to set a new one.",
|
||||
name, record);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
await ForgetChangedPasswordAsync(record, cancellationToken);
|
||||
}
|
||||
|
||||
await UpgradeUsersAsync(userName, cancellationToken);
|
||||
@@ -170,6 +190,22 @@ public sealed class IdentityStartup(IServiceScopeFactory scopes, BreakGlass brea
|
||||
access.Invalidate();
|
||||
}
|
||||
|
||||
/// <summary>The recorded one-time password goes once the break-glass account has chosen its own.</summary>
|
||||
private async Task ForgetChangedPasswordAsync(string record, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!File.Exists(record))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
if (!await db.Users.AnyAsync(u => u.IsBreakGlass && u.MustChangePassword, cancellationToken) && InitialAdminPasswordFile.Delete(record))
|
||||
{
|
||||
logger.LogInformation("Removed {Path}: the one-time password in it has been changed.", record);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task UpgradeUsersAsync(string? initialAdmin, CancellationToken cancellationToken)
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using Backend.Upgrades;
|
||||
|
||||
namespace Backend.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Where a generated first-start password is recorded: <c>initial-admin-password.txt</c> in the data folder.
|
||||
/// On Windows only BUILTIN\Administrators, SYSTEM and the account the server runs as can open it (inheritance off);
|
||||
/// elsewhere it is mode 600, owned by the server's account. The general log only says where it is, so log
|
||||
/// shipping, support bundles and <c>docker logs</c> never carry the password. The file is removed once the
|
||||
/// password has been changed, or replaced by a <c>reset-admin</c>.
|
||||
/// </summary>
|
||||
public static class InitialAdminPasswordFile
|
||||
{
|
||||
public const string FileName = "initial-admin-password.txt";
|
||||
|
||||
public static string PathFor(IConfiguration configuration) => Path.Combine(AgentCatalogStorage.DataRoot(configuration), FileName);
|
||||
|
||||
public static void Write(string path, string userName, string password, DateTimeOffset createdUtc)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
|
||||
var content = $"""
|
||||
ExecuteR one-time administrator sign-in, created {createdUtc:u}
|
||||
User: {userName}
|
||||
Password: {password}
|
||||
|
||||
A new password is required at the first sign-in; this file is deleted once it has been changed.
|
||||
Lost or locked out? Run as administrator on the server: ExecuteR-Server reset-admin
|
||||
|
||||
""";
|
||||
|
||||
using var stream = OperatingSystem.IsWindows() ? CreateWindows(path) : CreateUnix(path);
|
||||
using var writer = new StreamWriter(stream);
|
||||
writer.Write(content.ReplaceLineEndings());
|
||||
}
|
||||
|
||||
/// <summary>Removes the record; true when there was one.</summary>
|
||||
public static bool Delete(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
File.Delete(path);
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static FileStream CreateWindows(string path)
|
||||
{
|
||||
var security = new FileSecurity();
|
||||
security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
|
||||
var sids = new List<SecurityIdentifier>
|
||||
{
|
||||
new(WellKnownSidType.BuiltinAdministratorsSid, null),
|
||||
new(WellKnownSidType.LocalSystemSid, null),
|
||||
};
|
||||
|
||||
// The account the server runs as already owns the database; without it a non-elevated development run could not read its own record.
|
||||
if (WindowsIdentity.GetCurrent().User is { } self && !sids.Contains(self))
|
||||
{
|
||||
sids.Add(self);
|
||||
}
|
||||
|
||||
foreach (var sid in sids)
|
||||
{
|
||||
security.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.FullControl, AccessControlType.Allow));
|
||||
}
|
||||
|
||||
// Created with the protected ACL in one step, so the password is never readable through an inherited ACE.
|
||||
return new FileInfo(path).Create(FileMode.CreateNew, FileSystemRights.Write | FileSystemRights.ReadData, FileShare.None, 4096, FileOptions.None, security);
|
||||
}
|
||||
|
||||
[UnsupportedOSPlatform("windows")]
|
||||
private static FileStream CreateUnix(string path)
|
||||
=> new(path, new FileStreamOptions
|
||||
{
|
||||
Mode = FileMode.CreateNew,
|
||||
Access = FileAccess.Write,
|
||||
Share = FileShare.None,
|
||||
UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite,
|
||||
});
|
||||
}
|
||||
@@ -235,6 +235,11 @@ public sealed class SignInService(
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
await sessions.RevokeAllAsync(user.Id, caller.SessionId, cancellationToken);
|
||||
await AuditAsync(context, "auth.password.change", SignInProviders.Local, user.UserName, "succeeded", null, cancellationToken);
|
||||
if (user.IsBreakGlass)
|
||||
{
|
||||
// The recorded one-time password is spent now.
|
||||
InitialAdminPasswordFile.Delete(InitialAdminPasswordFile.PathFor(scope.ServiceProvider.GetRequiredService<IConfiguration>()));
|
||||
}
|
||||
|
||||
var updated = caller with { PasswordChangeRequired = false };
|
||||
context.SetCaller(updated);
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
<PackageReference Include="Cronos" />
|
||||
<PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" />
|
||||
<PackageReference Include="System.DirectoryServices.Protocols" />
|
||||
<PackageReference Include="System.Management.Automation" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" />
|
||||
|
||||
@@ -31,6 +31,8 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
|
||||
public DbSet<ScriptTriggerRunEntity> ScriptTriggerRuns => Set<ScriptTriggerRunEntity>();
|
||||
public DbSet<AppSettingEntity> AppSettings => Set<AppSettingEntity>();
|
||||
public DbSet<SecretsProviderEntity> SecretsProviders => Set<SecretsProviderEntity>();
|
||||
public DbSet<VaultSecretEntity> VaultSecrets => Set<VaultSecretEntity>();
|
||||
public DbSet<VaultFolderEntity> VaultFolders => Set<VaultFolderEntity>();
|
||||
public DbSet<AgentPackageEntity> AgentPackages => Set<AgentPackageEntity>();
|
||||
public DbSet<AgentUpgradeEntity> AgentUpgrades => Set<AgentUpgradeEntity>();
|
||||
public DbSet<DeviceRemovalEntity> DeviceRemovals => Set<DeviceRemovalEntity>();
|
||||
@@ -325,6 +327,28 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
|
||||
entity.HasIndex(e => e.Name).IsUnique();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<VaultSecretEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("VaultSecrets");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Path).HasMaxLength(512);
|
||||
entity.Property(e => e.PathKey).HasMaxLength(512);
|
||||
entity.Property(e => e.Name).HasMaxLength(200);
|
||||
entity.Property(e => e.NameKey).HasMaxLength(200);
|
||||
// Replicas creating the same secret at once race on this.
|
||||
entity.HasIndex(e => new { e.PathKey, e.NameKey }).IsUnique();
|
||||
entity.Property(e => e.Version).IsConcurrencyToken();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<VaultFolderEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("VaultFolders");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Path).HasMaxLength(512);
|
||||
entity.Property(e => e.PathKey).HasMaxLength(512);
|
||||
entity.HasIndex(e => e.PathKey).IsUnique();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<AgentPackageEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("AgentPackages");
|
||||
|
||||
@@ -364,6 +364,39 @@ public sealed class SecretsProviderEntity
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A secret in the built-in vault. Folder and name are clear text so the
|
||||
/// vault can be listed; the value is Data Protection-encrypted. The key
|
||||
/// columns are the upper-cased folder and name, so uniqueness and lookups are
|
||||
/// case-insensitive on every database provider.
|
||||
/// </summary>
|
||||
public sealed class VaultSecretEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
/// <summary>Normalized folder, "/" or "/a/b".</summary>
|
||||
public required string Path { get; set; }
|
||||
public required string PathKey { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public required string NameKey { get; set; }
|
||||
public required string ValueProtected { get; set; }
|
||||
/// <summary>Starts at 1 and counts value changes; also the concurrency token.</summary>
|
||||
public int Version { get; set; }
|
||||
public DateTimeOffset CreatedUtc { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTimeOffset UpdatedUtc { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A folder created in the built-in vault before (or without) holding secrets.</summary>
|
||||
public sealed class VaultFolderEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public required string Path { get; set; }
|
||||
public required string PathKey { get; set; }
|
||||
public DateTimeOffset CreatedUtc { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Operator-editable application settings that override environment defaults.
|
||||
/// Values marked secret are encrypted at rest with ASP.NET Data Protection and
|
||||
|
||||
+1416
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,73 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Backend.Data.Migrations.Postgres
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class BuiltInVault : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "VaultFolders",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Path = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: false),
|
||||
PathKey = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: false),
|
||||
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
CreatedBy = table.Column<string>(type: "text", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_VaultFolders", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "VaultSecrets",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Path = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: false),
|
||||
PathKey = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: false),
|
||||
Name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
|
||||
NameKey = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
|
||||
ValueProtected = table.Column<string>(type: "text", nullable: false),
|
||||
Version = table.Column<int>(type: "integer", nullable: false),
|
||||
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
CreatedBy = table.Column<string>(type: "text", nullable: true),
|
||||
UpdatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
UpdatedBy = table.Column<string>(type: "text", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_VaultSecrets", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_VaultFolders_PathKey",
|
||||
table: "VaultFolders",
|
||||
column: "PathKey",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_VaultSecrets_PathKey_NameKey",
|
||||
table: "VaultSecrets",
|
||||
columns: new[] { "PathKey", "NameKey" },
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "VaultFolders");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "VaultSecrets");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1275,6 +1275,90 @@ namespace Backend.Data.Migrations.Postgres
|
||||
b.ToTable("Users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.VaultFolderEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("CreatedBy")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Path")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("PathKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PathKey")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("VaultFolders", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.VaultSecretEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("CreatedBy")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("NameKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("Path")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("PathKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("UpdatedBy")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("ValueProtected")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Version")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PathKey", "NameKey")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("VaultSecrets", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
|
||||
{
|
||||
b.HasOne("Backend.Data.DeviceEntity", null)
|
||||
|
||||
+1416
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,73 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Backend.Data.Migrations.SqlServer
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class BuiltInVault : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "VaultFolders",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||
Path = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: false),
|
||||
PathKey = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: false),
|
||||
CreatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
|
||||
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_VaultFolders", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "VaultSecrets",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||
Path = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: false),
|
||||
PathKey = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: false),
|
||||
Name = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false),
|
||||
NameKey = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false),
|
||||
ValueProtected = table.Column<string>(type: "nvarchar(max)", nullable: false),
|
||||
Version = table.Column<int>(type: "int", nullable: false),
|
||||
CreatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
|
||||
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
UpdatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
|
||||
UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_VaultSecrets", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_VaultFolders_PathKey",
|
||||
table: "VaultFolders",
|
||||
column: "PathKey",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_VaultSecrets_PathKey_NameKey",
|
||||
table: "VaultSecrets",
|
||||
columns: new[] { "PathKey", "NameKey" },
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "VaultFolders");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "VaultSecrets");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1275,6 +1275,90 @@ namespace Backend.Data.Migrations.SqlServer
|
||||
b.ToTable("Users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.VaultFolderEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<string>("CreatedBy")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedUtc")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<string>("Path")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("nvarchar(512)");
|
||||
|
||||
b.Property<string>("PathKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("nvarchar(512)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PathKey")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("VaultFolders", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.VaultSecretEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<string>("CreatedBy")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedUtc")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("NameKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("Path")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("nvarchar(512)");
|
||||
|
||||
b.Property<string>("PathKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("nvarchar(512)");
|
||||
|
||||
b.Property<string>("UpdatedBy")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedUtc")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<string>("ValueProtected")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<int>("Version")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PathKey", "NameKey")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("VaultSecrets", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
|
||||
{
|
||||
b.HasOne("Backend.Data.DeviceEntity", null)
|
||||
|
||||
+1403
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,73 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Backend.Data.Migrations.Sqlite
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class BuiltInVault : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "VaultFolders",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
Path = table.Column<string>(type: "TEXT", maxLength: 512, nullable: false),
|
||||
PathKey = table.Column<string>(type: "TEXT", maxLength: 512, nullable: false),
|
||||
CreatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
CreatedBy = table.Column<string>(type: "TEXT", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_VaultFolders", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "VaultSecrets",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
Path = table.Column<string>(type: "TEXT", maxLength: 512, nullable: false),
|
||||
PathKey = table.Column<string>(type: "TEXT", maxLength: 512, nullable: false),
|
||||
Name = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
|
||||
NameKey = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
|
||||
ValueProtected = table.Column<string>(type: "TEXT", nullable: false),
|
||||
Version = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
CreatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
CreatedBy = table.Column<string>(type: "TEXT", nullable: true),
|
||||
UpdatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
UpdatedBy = table.Column<string>(type: "TEXT", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_VaultSecrets", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_VaultFolders_PathKey",
|
||||
table: "VaultFolders",
|
||||
column: "PathKey",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_VaultSecrets_PathKey_NameKey",
|
||||
table: "VaultSecrets",
|
||||
columns: new[] { "PathKey", "NameKey" },
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "VaultFolders");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "VaultSecrets");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1262,6 +1262,90 @@ namespace Backend.Data.Migrations.Sqlite
|
||||
b.ToTable("Users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.VaultFolderEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("CreatedBy")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedUtc")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Path")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("PathKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PathKey")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("VaultFolders", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.VaultSecretEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("CreatedBy")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedUtc")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("NameKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Path")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("PathKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("UpdatedBy")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("UpdatedUtc")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("ValueProtected")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Version")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PathKey", "NameKey")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("VaultSecrets", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
|
||||
{
|
||||
b.HasOne("Backend.Data.DeviceEntity", null)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Backend.Proxy;
|
||||
using Backend.Security;
|
||||
using Shared.Contracts.Api;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Backend.Enrollment;
|
||||
|
||||
@@ -31,16 +32,18 @@ public static class InstallEndpoints
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serves the managed self-signed CA chain (root + intermediate, public
|
||||
/// certs only) so agents can trust the server across renewals. This is the
|
||||
/// self-signed signal too: a 200 (a chain) means the server runs self-signed
|
||||
/// TLS and agents should auto-trust it; a 404 means it is not self-signed
|
||||
/// (a real edge certificate validates on its own — nothing to distribute).
|
||||
/// The chain is not pinned; it is installed into the OS trust store.
|
||||
/// Serves the issuing chain of the certificate this server presents
|
||||
/// (intermediates + root, public certs only, never the leaf): the managed
|
||||
/// self-signed chain, or a provided certificate's chain when that is not
|
||||
/// publicly trusted (an enterprise CA). A 200 means agents that fail to
|
||||
/// validate the server may anchor trust in it (pinned to the token's
|
||||
/// fingerprint, then installed into the OS trust store); a 404 means there
|
||||
/// is nothing to distribute (plain HTTP, or a publicly trusted chain that
|
||||
/// validates on its own).
|
||||
/// </summary>
|
||||
private static IResult GetCaChain(HttpContext context)
|
||||
{
|
||||
var manager = context.RequestServices.GetService<Backend.Tls.SelfSignedTlsManager>();
|
||||
var manager = context.RequestServices.GetService<Backend.Tls.IServerTlsSource>();
|
||||
var pem = manager?.CaChainPem();
|
||||
return pem is null
|
||||
? Results.NotFound()
|
||||
@@ -57,15 +60,15 @@ public static class InstallEndpoints
|
||||
|
||||
var baseUrl = ResolveBaseUrl(context, configuration);
|
||||
|
||||
// The only thing the script needs from the server is whether its own
|
||||
// download must skip verification: true when this request arrived over
|
||||
// the self-signed listener directly (no proxy in front), so the agent's
|
||||
// download from the same URL succeeds. A proxied request (real cert)
|
||||
// needs no skip. Trust itself is handled by the agent at enrollment: it
|
||||
// always probes GET /api/enrollment/ca (accept-any) and installs the CA
|
||||
// when self-signed (404 = not self-signed = nothing to do). Where TLS
|
||||
// terminates follows the URL, which keeps this flexible.
|
||||
var skipDownloadVerify = tls.IsSelfSignedDirect(context);
|
||||
// The package download trusts the server the way the agent does: normal
|
||||
// validation first, and only when that fails, the CA the server
|
||||
// publishes (GET /api/enrollment/ca), checked against the fingerprint
|
||||
// the token carries. A token without one (made while the server served
|
||||
// no chain of its own) keeps the old rule: skip verification only when
|
||||
// this request arrived over this server's own private-chain listener
|
||||
// directly, so the download from the same URL succeeds.
|
||||
var fingerprint = TokenFingerprint(token);
|
||||
var skipDownloadVerify = fingerprint is null && tls.IsSelfSignedDirect(context);
|
||||
|
||||
// Token is embedded so the operator can paste one command; knowledge of a
|
||||
// valid token is itself the enrollment gate. The Windows scripts run in
|
||||
@@ -77,31 +80,53 @@ public static class InstallEndpoints
|
||||
var zipUrl = $"{baseUrl}{ApiRoutes.AgentPackage}?type=zip";
|
||||
var script = type?.ToLowerInvariant() switch
|
||||
{
|
||||
"linux" => BuildUnixScript(baseUrl, token!, "linux", skipDownloadVerify),
|
||||
"osx" or "mac" or "macos" or "darwin" => BuildUnixScript(baseUrl, token!, "osx", skipDownloadVerify),
|
||||
"zip" => BuildZipScript(baseUrl, token!, zipUrl, skipDownloadVerify),
|
||||
_ => BuildMsiScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=msi", zipUrl, skipDownloadVerify),
|
||||
"linux" => BuildUnixScript(baseUrl, token!, "linux", skipDownloadVerify, fingerprint),
|
||||
"osx" or "mac" or "macos" or "darwin" => BuildUnixScript(baseUrl, token!, "osx", skipDownloadVerify, fingerprint),
|
||||
"zip" => BuildZipScript(baseUrl, token!, zipUrl, skipDownloadVerify, fingerprint),
|
||||
_ => BuildMsiScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=msi", zipUrl, skipDownloadVerify, fingerprint),
|
||||
};
|
||||
|
||||
return Results.Text(script, "text/plain; charset=utf-8");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The newest agent there is: the catalog's newest build for the platform
|
||||
/// unless this node holds a newer one than the catalog has caught up with.
|
||||
/// A new device then starts on the version upgrades would take it to,
|
||||
/// instead of an old package left in a volume and upgraded straight after.
|
||||
/// </summary>
|
||||
private static async Task<IResult> GetAgentPackage(
|
||||
Files.AgentPackageService packages, string? type, CancellationToken cancellationToken)
|
||||
Files.AgentPackageService packages, Upgrades.AgentCatalogService catalog, Upgrades.AgentCatalogStorage storage,
|
||||
string? type, CancellationToken cancellationToken)
|
||||
{
|
||||
var packageType = Files.AgentPackageService.NormalizeType(type);
|
||||
var fileName = Files.AgentPackageService.FileNameFor(packageType);
|
||||
var path = packages.ResolveLocalPath(packageType);
|
||||
var localVersion = path is null ? null : Files.AgentPackageService.ReadVersionMarker(Path.GetDirectoryName(path));
|
||||
|
||||
// When S3 offload is on, hand the endpoint a presigned URL so the
|
||||
// transfer never touches the control plane. Falls through to local
|
||||
// delivery if presigning fails for any reason.
|
||||
if ((await catalog.NewestByTypeAsync(cancellationToken)).GetValueOrDefault(packageType) is { } newest
|
||||
&& (path is null || !AgentVersions.IsNewer(localVersion, newest.Version)))
|
||||
{
|
||||
// Offloaded: a presigned URL, so the transfer never touches the control plane.
|
||||
if (newest.S3Key is { } key && await packages.TryPresignOffloadedAsync(key, cancellationToken) is { } url)
|
||||
{
|
||||
return Results.Redirect(url, permanent: false);
|
||||
}
|
||||
|
||||
var catalogued = storage.FullPath(newest.StoragePath);
|
||||
if (File.Exists(catalogued))
|
||||
{
|
||||
return Results.File(catalogued, ContentTypeFor(packageType), fileName, enableRangeProcessing: true);
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing catalogued yet (an unversioned build, or the first sync still running).
|
||||
var offloadUrl = await packages.TryGetOffloadUrlAsync(packageType, cancellationToken);
|
||||
if (offloadUrl is not null)
|
||||
{
|
||||
return Results.Redirect(offloadUrl, permanent: false);
|
||||
}
|
||||
|
||||
var path = packages.ResolveLocalPath(packageType);
|
||||
if (path is null)
|
||||
{
|
||||
return Results.NotFound(new
|
||||
@@ -112,11 +137,12 @@ public static class InstallEndpoints
|
||||
});
|
||||
}
|
||||
|
||||
var contentType = packageType == "msi" ? "application/x-msi" : "application/zip";
|
||||
var stream = File.OpenRead(path);
|
||||
return Results.Stream(stream, contentType, fileDownloadName: fileName, enableRangeProcessing: true);
|
||||
return Results.Stream(stream, ContentTypeFor(packageType), fileDownloadName: fileName, enableRangeProcessing: true);
|
||||
}
|
||||
|
||||
private static string ContentTypeFor(string packageType) => packageType == "msi" ? "application/x-msi" : "application/zip";
|
||||
|
||||
private static string ResolveBaseUrl(HttpContext context, IConfiguration configuration)
|
||||
=> Backend.Proxy.PublicUrl.Resolve(context, configuration);
|
||||
|
||||
@@ -132,23 +158,24 @@ public static class InstallEndpoints
|
||||
"[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }";
|
||||
|
||||
// NOTE: $$""" — interpolations are {{ }}, single braces are literal PowerShell.
|
||||
// selfSigned: the server serves its managed self-signed chain directly, so
|
||||
// the initial download skips verification (the cert isn't trusted yet) and
|
||||
// the agent is told to install the server CA into the OS trust store (and
|
||||
// keep it current) — system validation then trusts the server, without
|
||||
// pinning, so a proxy with a real cert added later still works.
|
||||
// The download validates normally and, only when the certificate is not
|
||||
// trusted, pins the server's CA to the token's fingerprint (PsDownload);
|
||||
// the agent then installs that CA into the OS trust store at enrollment, so
|
||||
// system validation trusts the server and a proxy with a real cert added
|
||||
// later still works.
|
||||
// The install runs in place: no auto-elevation (the self-relaunch tripped
|
||||
// AV/EDR ClickFix heuristics), no -EncodedCommand. The operator runs it from
|
||||
// an elevated PowerShell — the Add device modal states this prerequisite.
|
||||
// Windows PE (the MiniNT key) has no Windows Installer, so there the MSI
|
||||
// script takes the portable path instead — same service, same enrollment.
|
||||
private static string BuildMsiScript(
|
||||
string baseUrl, string token, string packageUrl, string zipUrl, bool skipDownloadVerify) => $$"""
|
||||
string baseUrl, string token, string packageUrl, string zipUrl, bool skipDownloadVerify, string? fingerprint) => $$"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
{{PsDownloadTls}}
|
||||
{{(skipDownloadVerify ? PsAcceptCert : "")}}
|
||||
$server = '{{baseUrl}}'
|
||||
$token = '{{token}}'
|
||||
{{PsDownload(fingerprint)}}
|
||||
if (Test-Path '{{PsWinPeKey}}') {
|
||||
Write-Host 'Windows PE detected: installing ExecuteR Agent (portable)...'
|
||||
{{PortableInstall(zipUrl)}}
|
||||
@@ -157,9 +184,7 @@ public static class InstallEndpoints
|
||||
Write-Host 'Installing ExecuteR Agent...'
|
||||
$msi = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.msi')
|
||||
try {
|
||||
$wc = New-Object System.Net.WebClient
|
||||
$wc.DownloadFile('{{packageUrl}}', $msi)
|
||||
$wc.Dispose()
|
||||
Save-ExecuteRFile '{{packageUrl}}' $msi
|
||||
$arguments = @('/i', ('"' + $msi + '"'), '/qn', "SERVERURL=$server", "BOOTSTRAPTOKEN=$token")
|
||||
$p = Start-Process msiexec.exe -ArgumentList $arguments -Wait -PassThru
|
||||
if ($p.ExitCode -ne 0) { throw "msiexec exited with $($p.ExitCode)" }
|
||||
@@ -189,9 +214,7 @@ public static class InstallEndpoints
|
||||
$zip = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.zip')
|
||||
$unpacked = $zip + '.d'
|
||||
try {
|
||||
$wc = New-Object System.Net.WebClient
|
||||
$wc.DownloadFile('{{packageUrl}}', $zip)
|
||||
$wc.Dispose()
|
||||
Save-ExecuteRFile '{{packageUrl}}' $zip
|
||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
if (Test-Path $dest) {
|
||||
[System.IO.Compression.ZipFile]::ExtractToDirectory($zip, $unpacked)
|
||||
@@ -224,7 +247,7 @@ public static class InstallEndpoints
|
||||
// ReplaceLineEndings("\n"): the .cs source is checked out with CRLF on
|
||||
// Windows, but a bash script with CRLF fails hard when piped to bash
|
||||
// (`set -euo pipefail\r` -> ": invalid option namepefail"). Force LF.
|
||||
private static string BuildUnixScript(string baseUrl, string token, string os, bool skipDownloadVerify) => ($$"""
|
||||
private static string BuildUnixScript(string baseUrl, string token, string os, bool skipDownloadVerify, string? fingerprint) => ($$"""
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
if [ "$(id -u)" -ne 0 ]; then echo 'Run with sudo/root.' >&2; exit 1; fi
|
||||
@@ -239,8 +262,9 @@ public static class InstallEndpoints
|
||||
dest=/opt/executer/agent
|
||||
tmp=$(mktemp -d)
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
{{ShDownload(fingerprint, skipDownloadVerify)}}
|
||||
echo "Installing ExecuteR Agent ({{os}}-${arch})..."
|
||||
curl -fsSL{{(skipDownloadVerify ? "k" : "")}} "$pkg" -o "$tmp/agent.zip"
|
||||
download "$pkg" "$tmp/agent.zip"
|
||||
mkdir -p "$dest"
|
||||
if command -v unzip >/dev/null 2>&1; then
|
||||
unzip -oq "$tmp/agent.zip" -d "$dest"
|
||||
@@ -253,13 +277,142 @@ public static class InstallEndpoints
|
||||
echo 'ExecuteR Agent installed. It will enroll and start automatically.'
|
||||
""").ReplaceLineEndings("\n");
|
||||
|
||||
private static string BuildZipScript(string baseUrl, string token, string packageUrl, bool skipDownloadVerify) => $$"""
|
||||
private static string BuildZipScript(string baseUrl, string token, string packageUrl, bool skipDownloadVerify, string? fingerprint) => $$"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Write-Host 'Installing ExecuteR Agent (portable)...'
|
||||
{{PsDownloadTls}}
|
||||
{{(skipDownloadVerify ? PsAcceptCert : "")}}
|
||||
$server = '{{baseUrl}}'
|
||||
$token = '{{token}}'
|
||||
{{PsDownload(fingerprint)}}
|
||||
{{PortableInstall(packageUrl)}}
|
||||
""";
|
||||
|
||||
/// <summary>
|
||||
/// The CA fingerprint a bootstrap token carries ("secret.fp", 64 hex
|
||||
/// characters, as the agent reads it), or null.
|
||||
/// </summary>
|
||||
internal static string? TokenFingerprint(string? token)
|
||||
{
|
||||
var dot = token?.LastIndexOf('.') ?? -1;
|
||||
if (token is null || dot < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var fingerprint = token[(dot + 1)..];
|
||||
return fingerprint.Length == 64 && fingerprint.All(Uri.IsHexDigit) ? fingerprint.ToLowerInvariant() : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Save-ExecuteRFile: a WebClient download. With a fingerprint in the token
|
||||
/// it validates normally first (the outer one-liner's accept-any is undone)
|
||||
/// and only when the certificate is not trusted fetches the server's CA,
|
||||
/// finds the root whose SubjectPublicKeyInfo hashes to the fingerprint
|
||||
/// (parsed from the DER, as Windows PowerShell 5.1's .NET has no SPKI
|
||||
/// export), and accepts the server only through a chain that ends at that
|
||||
/// root — extra certificates in the response cannot become anchors. The
|
||||
/// agent installs the CA into the trust store itself when it enrolls.
|
||||
/// </summary>
|
||||
internal static string PsDownload(string? fingerprint) => fingerprint is null
|
||||
? """
|
||||
function Save-ExecuteRFile([string]$Url, [string]$Path) {
|
||||
$wc = New-Object System.Net.WebClient
|
||||
try { $wc.DownloadFile($Url, $Path) } finally { $wc.Dispose() }
|
||||
}
|
||||
"""
|
||||
: $$"""
|
||||
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null
|
||||
$global:ExecuteRCaPin = '{{fingerprint}}'
|
||||
$global:ExecuteRCa = $null
|
||||
function Get-ExecuteRDerHeader([byte[]]$d, [int]$p) {
|
||||
$l = [int]$d[$p + 1]
|
||||
if ($l -lt 128) { return @(2, $l) }
|
||||
$n = $l - 128; $l = 0
|
||||
for ($i = 0; $i -lt $n; $i++) { $l = $l * 256 + $d[$p + 2 + $i] }
|
||||
return @((2 + $n), $l)
|
||||
}
|
||||
function Get-ExecuteRSpkiHash([byte[]]$d) {
|
||||
$h = Get-ExecuteRDerHeader $d 0; $p = $h[0]
|
||||
$h = Get-ExecuteRDerHeader $d $p; $p += $h[0]
|
||||
if ($d[$p] -eq 0xA0) { $h = Get-ExecuteRDerHeader $d $p; $p += $h[0] + $h[1] }
|
||||
for ($k = 0; $k -lt 5; $k++) { $h = Get-ExecuteRDerHeader $d $p; $p += $h[0] + $h[1] }
|
||||
$h = Get-ExecuteRDerHeader $d $p
|
||||
$sha = [System.Security.Cryptography.SHA256]::Create()
|
||||
try { -join ($sha.ComputeHash($d, $p, $h[0] + $h[1]) | ForEach-Object { $_.ToString('x2') }) } finally { $sha.Dispose() }
|
||||
}
|
||||
function Use-ExecuteRCa {
|
||||
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
|
||||
$wc = New-Object System.Net.WebClient
|
||||
try { $pem = $wc.DownloadString($server + '{{ApiRoutes.EnrollmentCaChain}}') }
|
||||
finally { $wc.Dispose(); [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null }
|
||||
$cas = @()
|
||||
foreach ($m in [regex]::Matches($pem, '-----BEGIN CERTIFICATE-----([A-Za-z0-9+/=\s]+)-----END CERTIFICATE-----')) {
|
||||
$cas += New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 (,[Convert]::FromBase64String(($m.Groups[1].Value -replace '\s', '')))
|
||||
}
|
||||
$anchor = @($cas | Where-Object { (Get-ExecuteRSpkiHash $_.RawData) -eq $global:ExecuteRCaPin })
|
||||
if ($anchor.Count -eq 0) { throw 'The server CA does not match the bootstrap token; refusing to continue (possible interception).' }
|
||||
$global:ExecuteRCa = @{ Anchor = $anchor[0].Thumbprint; Certificates = $cas }
|
||||
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {
|
||||
param($sender, $certificate, $chain, $errors)
|
||||
if ($errors -eq [System.Net.Security.SslPolicyErrors]::None) { return $true }
|
||||
if ($errors -ne [System.Net.Security.SslPolicyErrors]::RemoteCertificateChainErrors) { return $false }
|
||||
$c = New-Object System.Security.Cryptography.X509Certificates.X509Chain
|
||||
$c.ChainPolicy.RevocationMode = [System.Security.Cryptography.X509Certificates.X509RevocationMode]::NoCheck
|
||||
$c.ChainPolicy.VerificationFlags = [System.Security.Cryptography.X509Certificates.X509VerificationFlags]::AllowUnknownCertificateAuthority
|
||||
foreach ($ca in $global:ExecuteRCa.Certificates) { [void]$c.ChainPolicy.ExtraStore.Add($ca) }
|
||||
if (-not $c.Build((New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 (,$certificate.GetRawCertData())))) { return $false }
|
||||
return $c.ChainElements[$c.ChainElements.Count - 1].Certificate.Thumbprint -eq $global:ExecuteRCa.Anchor
|
||||
}
|
||||
}
|
||||
function Save-ExecuteRFile([string]$Url, [string]$Path) {
|
||||
$wc = New-Object System.Net.WebClient
|
||||
try { $wc.DownloadFile($Url, $Path) }
|
||||
catch {
|
||||
$e = $_.Exception
|
||||
while ($e -and -not ($e -is [System.Net.WebException])) { $e = $e.InnerException }
|
||||
if ($global:ExecuteRCa -or -not $e -or ($e.Status -ne [System.Net.WebExceptionStatus]::TrustFailure -and $e.Status -ne [System.Net.WebExceptionStatus]::SecureChannelFailure)) { throw }
|
||||
Write-Host 'The server certificate is not trusted here yet: checking its CA against the bootstrap token...'
|
||||
Use-ExecuteRCa
|
||||
$wc.DownloadFile($Url, $Path)
|
||||
}
|
||||
finally { $wc.Dispose() }
|
||||
}
|
||||
""";
|
||||
|
||||
/// <summary>
|
||||
/// download URL FILE for the Unix script: the same rule with curl and
|
||||
/// openssl. The CA file handed to curl holds only the pinned root and the
|
||||
/// certificates that verify against it.
|
||||
/// </summary>
|
||||
internal static string ShDownload(string? fingerprint, bool skipDownloadVerify) => fingerprint is null
|
||||
? $$"""
|
||||
download() { curl -fsSL{{(skipDownloadVerify ? "k" : "")}} "$1" -o "$2"; }
|
||||
"""
|
||||
: $$"""
|
||||
pin='{{fingerprint}}'
|
||||
cafile="$tmp/server-ca.pem"
|
||||
download() {
|
||||
local rc=0 anchor='' f
|
||||
if [ -s "$cafile" ]; then curl -fsSL --cacert "$cafile" "$1" -o "$2"; return; fi
|
||||
curl -fsSL "$1" -o "$2" || rc=$?
|
||||
[ "$rc" -eq 0 ] && return 0
|
||||
[ "$rc" -eq 60 ] || [ "$rc" -eq 51 ] || [ "$rc" -eq 35 ] || return "$rc"
|
||||
command -v openssl >/dev/null 2>&1 || { echo 'The server certificate is not trusted here, and openssl is needed to check its CA against the bootstrap token.' >&2; return 1; }
|
||||
echo 'The server certificate is not trusted here yet: checking its CA against the bootstrap token...'
|
||||
curl -fsSLk "$server{{ApiRoutes.EnrollmentCaChain}}" -o "$tmp/fetched-ca.pem"
|
||||
awk -v dir="$tmp" '/-----BEGIN CERTIFICATE-----/{n++} n{print > (dir "/fetched-ca-" n ".pem")}' "$tmp/fetched-ca.pem"
|
||||
for f in "$tmp"/fetched-ca-*.pem; do
|
||||
[ -e "$f" ] || continue
|
||||
if [ "$(openssl x509 -in "$f" -noout -pubkey | openssl pkey -pubin -outform DER | openssl dgst -sha256 -r | cut -d' ' -f1)" = "$pin" ]; then anchor="$f"; fi
|
||||
done
|
||||
[ -n "$anchor" ] || { echo 'The server CA does not match the bootstrap token; refusing to continue (possible interception).' >&2; return 1; }
|
||||
cat "$anchor" > "$cafile"
|
||||
for f in "$tmp"/fetched-ca-*.pem; do
|
||||
[ "$f" = "$anchor" ] && continue
|
||||
if openssl verify -CAfile "$anchor" -untrusted "$tmp/fetched-ca.pem" "$f" >/dev/null 2>&1; then cat "$f" >> "$cafile"; fi
|
||||
done
|
||||
curl -fsSL --cacert "$cafile" "$1" -o "$2"
|
||||
}
|
||||
""";
|
||||
}
|
||||
|
||||
@@ -2,18 +2,22 @@ using System.Security.Cryptography;
|
||||
using Amazon.S3;
|
||||
using Amazon.S3.Model;
|
||||
using Shared.Contracts.Api;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Backend.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Locates the agent installer that the URL-install flow hands out.
|
||||
///
|
||||
/// Search order:
|
||||
/// Places searched:
|
||||
/// 1. AGENT_PACKAGE_PATH (compose defaults it to /data/agent, which is a
|
||||
/// host bind mount) — dropping a package there delivers an out-of-band
|
||||
/// agent update with no new backend image or restart
|
||||
/// 2. /opt/executer/agent — baked into the backend image by CI
|
||||
/// 3. /data/agent — fallback when AGENT_PACKAGE_PATH points elsewhere
|
||||
/// The newest by VERSION marker wins, so a package left behind in a volume
|
||||
/// never shadows the newer one a later image brings; between equal versions
|
||||
/// the earlier place wins.
|
||||
///
|
||||
/// CI copies the Windows-built package into the image, so a stock deployment
|
||||
/// serves the agent with no manual step. When S3 offload is enabled the same
|
||||
@@ -55,22 +59,32 @@ public sealed class AgentPackageService(
|
||||
yield return SeededPath;
|
||||
}
|
||||
|
||||
/// <summary>Full path to the package on local disk, or null when absent.</summary>
|
||||
public string? ResolveLocalPath(string packageType)
|
||||
/// <summary>Full path to the newest package on local disk, or null when absent.</summary>
|
||||
public string? ResolveLocalPath(string packageType) => LocalPackages(packageType).FirstOrDefault().Path;
|
||||
|
||||
/// <summary>Every copy of the package on local disk, newest first; one without a VERSION marker counts as oldest.</summary>
|
||||
private List<(string Path, string? Version)> LocalPackages(string packageType)
|
||||
{
|
||||
var fileName = FileNameFor(packageType);
|
||||
foreach (var directory in CandidateDirectories())
|
||||
{
|
||||
var path = Path.Combine(directory, fileName);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
return CandidateDirectories()
|
||||
.Select(directory => Path.GetFullPath(Path.Combine(directory, fileName)))
|
||||
.Distinct(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal)
|
||||
.Where(File.Exists)
|
||||
.Select(path => (Path: path, Version: ReadVersionMarker(Path.GetDirectoryName(path))))
|
||||
// Stable: equal versions keep the search order.
|
||||
.OrderByDescending(package => package.Version, MarkedVersions)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static readonly IComparer<string?> MarkedVersions = Comparer<string?>.Create(
|
||||
(left, right) => (AgentVersions.IsValid(left), AgentVersions.IsValid(right)) switch
|
||||
{
|
||||
(true, true) => AgentVersions.Compare(left, right),
|
||||
(true, false) => 1,
|
||||
(false, true) => -1,
|
||||
_ => 0,
|
||||
});
|
||||
|
||||
public async Task<AgentPackageStatusDto> GetStatusAsync(string packageType, CancellationToken cancellationToken)
|
||||
{
|
||||
var offloadEnabled = await s3Settings.GetAgentOffloadEnabledAsync(cancellationToken);
|
||||
@@ -108,16 +122,16 @@ public sealed class AgentPackageService(
|
||||
|
||||
/// <summary>
|
||||
/// The upgradable packages visible right now (the MSI, the portable zip and
|
||||
/// the Unix builds), each with the version from its VERSION marker:
|
||||
/// what the agent catalog imports.
|
||||
/// the Unix builds) in every place searched, each with the version from
|
||||
/// its VERSION marker: what the agent catalog imports.
|
||||
/// </summary>
|
||||
public IEnumerable<(string PackageType, string Path, string? Version)> LocateUpgradePackages()
|
||||
{
|
||||
foreach (var packageType in Shared.Contracts.Models.AgentPackageTypes.Upgradable)
|
||||
foreach (var packageType in AgentPackageTypes.Upgradable)
|
||||
{
|
||||
if (ResolveLocalPath(packageType) is { } path)
|
||||
foreach (var (path, version) in LocalPackages(packageType))
|
||||
{
|
||||
yield return (packageType, path, ReadVersionMarker(System.IO.Path.GetDirectoryName(path)));
|
||||
yield return (packageType, path, version);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,6 +223,59 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The distinct values a rule field holds across the given devices (every
|
||||
/// device when <paramref name="allowed"/> is null), read from the same field
|
||||
/// bag rules evaluate, so a suggestion always matches as shown. Values that
|
||||
/// differ only in case are one value, as rules compare them. Most-held
|
||||
/// first, at most <paramref name="limit"/>, optionally only those starting with
|
||||
/// <paramref name="prefix"/> (ignoring case).
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<GroupFieldValueDto>> KnownValuesAsync(
|
||||
string field, IReadOnlySet<string>? allowed, string? prefix, int limit, CancellationToken cancellationToken)
|
||||
{
|
||||
var devices = await db.Devices.AsNoTracking().ToListAsync(cancellationToken);
|
||||
if (allowed is not null)
|
||||
{
|
||||
devices = devices.Where(d => allowed.Contains(d.ClientId)).ToList();
|
||||
}
|
||||
|
||||
if (devices.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var inventory = await GetAllInventoryAsync(cancellationToken);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var counts = new Dictionary<string, (string Value, int Devices)>(StringComparer.OrdinalIgnoreCase);
|
||||
var start = prefix?.Trim();
|
||||
foreach (var device in devices)
|
||||
{
|
||||
if (!BuildFields(device, inventory.GetValueOrDefault(device.ClientId), now).TryGet(field, out var values))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// A device holding a value twice (two adapters, one DNS server) counts once for it.
|
||||
foreach (var value in values.Select(v => v.Trim()).Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
if (value.Length == 0 || (!string.IsNullOrEmpty(start) && !value.StartsWith(start, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
counts[value] = counts.TryGetValue(value, out var seen) ? (seen.Value, seen.Devices + 1) : (value, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return counts.Values
|
||||
.OrderByDescending(v => v.Devices)
|
||||
.ThenBy(v => v.Value, StringComparer.OrdinalIgnoreCase)
|
||||
.Take(limit)
|
||||
.Select(v => new GroupFieldValueDto(v.Value, v.Devices))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Groups a single device belongs to: the ones it is directly in, plus
|
||||
/// their ancestors (marked inherited, since nesting includes children).
|
||||
|
||||
@@ -6,12 +6,18 @@ using Shared.Contracts.Api;
|
||||
using Shared.Contracts.Models;
|
||||
using Shared.Contracts.Serialization;
|
||||
using Shared.Infrastructure.Constants;
|
||||
using Shared.Infrastructure.Grouping;
|
||||
using Shared.Infrastructure.Nats;
|
||||
|
||||
namespace Backend.Groups;
|
||||
|
||||
public static class GroupEndpoints
|
||||
{
|
||||
/// <summary>Value suggestions: how many by default, at most, and the longest prefix accepted.</summary>
|
||||
private const int DefaultValueLimit = 25;
|
||||
private const int MaxValueLimit = 100;
|
||||
private const int MaxValuePrefixLength = 200;
|
||||
|
||||
public static void Map(WebApplication app)
|
||||
{
|
||||
app.MapGet(ApiRoutes.Groups, ListAsync).RequirePermission(Permissions.GroupsView);
|
||||
@@ -27,6 +33,8 @@ public static class GroupEndpoints
|
||||
app.MapPost(ApiRoutes.GroupPreview, PreviewAsync).RequirePermission(Permissions.GroupsView);
|
||||
app.MapGet(ApiRoutes.GroupFields, () => Results.Ok(GroupFields.All))
|
||||
.RequirePermission(Permissions.GroupsView);
|
||||
// Suggestions serve the rule editor, so only those who may edit rules read device values through it.
|
||||
app.MapGet(ApiRoutes.GroupFieldValues, FieldValuesAsync).RequirePermission(Permissions.GroupsManage);
|
||||
|
||||
app.MapPut(ApiRoutes.DeviceTags, UpdateTagsAsync).RequirePermission(Permissions.DevicesManage);
|
||||
}
|
||||
@@ -67,6 +75,11 @@ public static class GroupEndpoints
|
||||
return Results.BadRequest(new { error = parentError });
|
||||
}
|
||||
|
||||
if (RulesProblem(request) is { } rulesProblem)
|
||||
{
|
||||
return rulesProblem;
|
||||
}
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var entity = new DeviceGroupEntity
|
||||
{
|
||||
@@ -104,6 +117,11 @@ public static class GroupEndpoints
|
||||
return Results.BadRequest(new { error = parentError });
|
||||
}
|
||||
|
||||
if (RulesProblem(request) is { } rulesProblem)
|
||||
{
|
||||
return rulesProblem;
|
||||
}
|
||||
|
||||
// Only static groups keep an explicit list; switching kind drops it so
|
||||
// a later switch back does not resurrect stale members.
|
||||
if (request.Kind != GroupKind.Static && entity.Kind == GroupKind.Static)
|
||||
@@ -203,9 +221,13 @@ public static class GroupEndpoints
|
||||
return Results.NoContent();
|
||||
}
|
||||
|
||||
/// <summary>Devices in the group, including those of its nested groups.</summary>
|
||||
/// <summary>
|
||||
/// Devices in the group, including those of its nested groups. A scoped
|
||||
/// role sees only the members inside its device scope.
|
||||
/// </summary>
|
||||
private static async Task<IResult> MembersAsync(
|
||||
Guid id, AppDbContext db, DeviceGroupService groups, CancellationToken cancellationToken)
|
||||
Guid id, AppDbContext db, DeviceGroupService groups, DeviceScopeService scope, HttpContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await db.DeviceGroups.AsNoTracking().SingleOrDefaultAsync(g => g.Id == id, cancellationToken);
|
||||
if (entity is null)
|
||||
@@ -213,7 +235,13 @@ public static class GroupEndpoints
|
||||
return Results.NotFound();
|
||||
}
|
||||
|
||||
var clientIds = await groups.GetMembersAsync(entity, cancellationToken);
|
||||
IEnumerable<string> members = await groups.GetMembersAsync(entity, cancellationToken);
|
||||
if (await scope.GetAllowedClientIdsAsync(context.User, cancellationToken) is { } allowed)
|
||||
{
|
||||
members = members.Where(allowed.Contains);
|
||||
}
|
||||
|
||||
var clientIds = members.ToList();
|
||||
var devices = await db.Devices.AsNoTracking()
|
||||
.Where(d => clientIds.Contains(d.ClientId))
|
||||
.OrderBy(d => d.Hostname)
|
||||
@@ -281,13 +309,28 @@ public static class GroupEndpoints
|
||||
return Results.NoContent();
|
||||
}
|
||||
|
||||
/// <summary>Evaluates a candidate rule set without saving it (live preview).</summary>
|
||||
/// <summary>
|
||||
/// Evaluates a candidate rule set without saving it (live preview). A
|
||||
/// scoped role sees only the matches inside its device scope.
|
||||
/// </summary>
|
||||
private static async Task<IResult> PreviewAsync(
|
||||
PreviewGroupRequest request, AppDbContext db, DeviceGroupService groups, CancellationToken cancellationToken)
|
||||
PreviewGroupRequest request, AppDbContext db, DeviceGroupService groups, DeviceScopeService scope,
|
||||
HttpContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
var clientIds = await groups.EvaluateAsync(request.Rules, cancellationToken);
|
||||
if (ValidationProblem(request.Rules) is { } rulesProblem)
|
||||
{
|
||||
return rulesProblem;
|
||||
}
|
||||
|
||||
IEnumerable<string> clientIds = await groups.EvaluateAsync(request.Rules, cancellationToken);
|
||||
if (await scope.GetAllowedClientIdsAsync(context.User, cancellationToken) is { } allowed)
|
||||
{
|
||||
clientIds = clientIds.Where(allowed.Contains);
|
||||
}
|
||||
|
||||
var matched = clientIds.ToList();
|
||||
var devices = await db.Devices.AsNoTracking()
|
||||
.Where(d => clientIds.Contains(d.ClientId))
|
||||
.Where(d => matched.Contains(d.ClientId))
|
||||
.OrderBy(d => d.Hostname)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
@@ -295,6 +338,41 @@ public static class GroupEndpoints
|
||||
return Results.Ok(devices.Select(d => Api.DeviceEndpoints.ToDto(d, now)).ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Suggestions for a rule's value: the field's distinct values on the
|
||||
/// devices the caller may see, those starting with <paramref name="prefix"/>.
|
||||
/// </summary>
|
||||
private static async Task<IResult> FieldValuesAsync(
|
||||
string? field, string? prefix, int? limit, DeviceGroupService groups, DeviceScopeService scope,
|
||||
HttpContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
if (GroupFields.Find(field) is not { } descriptor)
|
||||
{
|
||||
return Results.BadRequest(new { error = "Unknown field." });
|
||||
}
|
||||
|
||||
if (prefix is { Length: > MaxValuePrefixLength })
|
||||
{
|
||||
return Results.BadRequest(new { error = $"Type at most {MaxValuePrefixLength} characters." });
|
||||
}
|
||||
|
||||
var allowed = await scope.GetAllowedClientIdsAsync(context.User, cancellationToken);
|
||||
return Results.Ok(await groups.KnownValuesAsync(
|
||||
descriptor.Field, allowed, prefix, Math.Clamp(limit ?? DefaultValueLimit, 1, MaxValueLimit), cancellationToken));
|
||||
}
|
||||
|
||||
/// <summary>The rules' problems by row path, when a dynamic group is saved with rules that break the limits.</summary>
|
||||
private static IResult? RulesProblem(SaveDeviceGroupRequest request)
|
||||
=> request.Kind == GroupKind.Dynamic ? ValidationProblem(request.Rules) : null;
|
||||
|
||||
private static IResult? ValidationProblem(GroupRuleSet? rules)
|
||||
{
|
||||
var errors = RuleValidator.Validate(rules);
|
||||
return errors.Count == 0
|
||||
? null
|
||||
: Results.ValidationProblem(errors, detail: errors.Values.First()[0], title: "The rule needs a change.");
|
||||
}
|
||||
|
||||
private static async Task<IResult> UpdateTagsAsync(
|
||||
string clientId, UpdateDeviceTagsRequest request, AppDbContext db, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -103,7 +103,17 @@ public sealed class ScriptTriggerService(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Same check as every other start, against the script as it is
|
||||
// now; like a vault outage, a failure shows as a failed job.
|
||||
var arguments = TriggerExecutor.ParseArguments(trigger.ArgumentsJson);
|
||||
if (ScriptArguments.Validate(prepared.Parameters ?? [], arguments, rejectUnknown: false) is { } argumentsProblem)
|
||||
{
|
||||
await runner.MarkFailedAsync(job, $"Not run: {argumentsProblem}", cancellationToken);
|
||||
logger.LogWarning(
|
||||
"Trigger {TriggerId} job {JobId} not run: {Problem}", trigger.Id, job.JobId, argumentsProblem);
|
||||
continue;
|
||||
}
|
||||
|
||||
var sent = await runner.DispatchAsync(
|
||||
prepared, job, arguments,
|
||||
$"Trigger ({triggerType}) queued “{script.Name}” for {device.Hostname}",
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Security.Claims;
|
||||
using Backend.Auth;
|
||||
using Backend.Data;
|
||||
using Backend.Jobs;
|
||||
using Backend.Scripts;
|
||||
using Backend.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shared.Contracts.Api;
|
||||
@@ -32,12 +33,14 @@ public static class TriggerEndpoints
|
||||
.OrderBy(t => t.ScriptId).ThenBy(t => t.TriggerType)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var scriptNames = await db.Scripts.AsNoTracking().ToDictionaryAsync(s => s.Id, s => s.Name, cancellationToken);
|
||||
var scripts = await db.Scripts.AsNoTracking()
|
||||
.Select(s => new { s.Id, s.Name, s.ParametersJson })
|
||||
.ToDictionaryAsync(s => s.Id, cancellationToken);
|
||||
var groupNames = await db.DeviceGroups.AsNoTracking().ToDictionaryAsync(g => g.Id, g => g.Name, cancellationToken);
|
||||
var hostnames = await db.Devices.AsNoTracking().ToDictionaryAsync(d => d.ClientId, d => d.Hostname, cancellationToken);
|
||||
|
||||
return Results.Ok(triggers.Select(t => new ScriptTriggerDto(
|
||||
t.Id, t.ScriptId, scriptNames.GetValueOrDefault(t.ScriptId, "(deleted script)"),
|
||||
t.Id, t.ScriptId, scripts.GetValueOrDefault(t.ScriptId)?.Name ?? "(deleted script)",
|
||||
t.GroupId,
|
||||
t.GroupId is null ? null : groupNames.GetValueOrDefault(t.GroupId.Value, "(deleted group)"),
|
||||
t.ClientId,
|
||||
@@ -50,7 +53,13 @@ public static class TriggerEndpoints
|
||||
Arguments: TriggerExecutor.ParseArguments(t.ArgumentsJson),
|
||||
CreatedBy: t.CreatedBy,
|
||||
StaggerSeconds: t.StaggerSeconds,
|
||||
StaggerBatchSize: t.StaggerBatchSize)).ToList());
|
||||
StaggerBatchSize: t.StaggerBatchSize,
|
||||
ArgumentsProblem: scripts.GetValueOrDefault(t.ScriptId) is { } script
|
||||
? ScriptArguments.Validate(
|
||||
ScriptEndpoints.DeserializeParameters(script.ParametersJson),
|
||||
TriggerExecutor.ParseArguments(t.ArgumentsJson),
|
||||
rejectUnknown: false)
|
||||
: null)).ToList());
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateAsync(
|
||||
@@ -62,6 +71,11 @@ public static class TriggerEndpoints
|
||||
return invalid;
|
||||
}
|
||||
|
||||
if (await ValidateArgumentsAsync(request, db, cancellationToken) is { } badArguments)
|
||||
{
|
||||
return badArguments;
|
||||
}
|
||||
|
||||
var entity = new ScriptTriggerEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
@@ -102,6 +116,11 @@ public static class TriggerEndpoints
|
||||
return invalid;
|
||||
}
|
||||
|
||||
if (await ValidateArgumentsAsync(request, db, cancellationToken) is { } badArguments)
|
||||
{
|
||||
return badArguments;
|
||||
}
|
||||
|
||||
if (Apply(entity, request) is { } error)
|
||||
{
|
||||
return Results.BadRequest(new { error });
|
||||
@@ -285,6 +304,24 @@ public static class TriggerEndpoints
|
||||
return await CheckScopeAsync(request.ClientId, request.GroupId, db, scope, groups, user, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The values set on the trigger must run its script as it is now (the
|
||||
/// same check as a manual run; see <see cref="ScriptArguments"/>). Only
|
||||
/// set values are stored, so untouched ones follow the script's defaults.
|
||||
/// </summary>
|
||||
private static async Task<IResult?> ValidateArgumentsAsync(
|
||||
SaveScriptTriggerRequest request, AppDbContext db, CancellationToken cancellationToken)
|
||||
{
|
||||
var parametersJson = await db.Scripts.AsNoTracking()
|
||||
.Where(s => s.Id == request.ScriptId)
|
||||
.Select(s => s.ParametersJson)
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
return ScriptArguments.Validate(
|
||||
ScriptEndpoints.DeserializeParameters(parametersJson), request.Arguments, rejectUnknown: true) is { } problem
|
||||
? Results.BadRequest(new { error = problem })
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A device-scoped role may only act on targets inside its scope: a device
|
||||
/// it can see, or a group whose members it can all see — never "all
|
||||
|
||||
@@ -564,6 +564,13 @@ public static class JobEndpoints
|
||||
return Results.NotFound(new { error = "Script not found." });
|
||||
}
|
||||
|
||||
if (Backend.Scripts.ScriptArguments.Validate(
|
||||
Backend.Scripts.ScriptEndpoints.DeserializeParameters(script.ParametersJson), request.Arguments, rejectUnknown: true)
|
||||
is { } argumentsProblem)
|
||||
{
|
||||
return Results.BadRequest(new { error = argumentsProblem });
|
||||
}
|
||||
|
||||
// The original single-device contract: 404/409 on the device itself
|
||||
// and the created JobDto back (CLI and older UIs depend on it).
|
||||
var singleDevice = groupIds.Count == 0 && clientIds.Count == 1 && request.ClientIds is not { Count: > 0 };
|
||||
|
||||
@@ -35,6 +35,18 @@ public sealed class TriggerExecutor(
|
||||
return Record(trigger, new TriggerFiring(null, 0, "Disabled: the script no longer exists."));
|
||||
}
|
||||
|
||||
// Checked against the script as it is now: it may have gained a
|
||||
// required parameter since the trigger was saved. The trigger stays
|
||||
// enabled; the next firing runs once it is fixed.
|
||||
var arguments = ParseArguments(trigger.ArgumentsJson);
|
||||
if (Backend.Scripts.ScriptArguments.Validate(
|
||||
Backend.Scripts.ScriptEndpoints.DeserializeParameters(script.ParametersJson), arguments, rejectUnknown: false)
|
||||
is { } argumentsProblem)
|
||||
{
|
||||
logger.LogWarning("Trigger {TriggerId} not run: {Problem}", trigger.Id, argumentsProblem);
|
||||
return Record(trigger, new TriggerFiring(null, 0, $"Not run: {argumentsProblem}"));
|
||||
}
|
||||
|
||||
var (targetsLabel, targeted) = await ResolveTargetsAsync(trigger, cancellationToken);
|
||||
var devices = targeted.Where(d => !d.IsOrphaned).ToList();
|
||||
if (devices.Count == 0)
|
||||
@@ -53,8 +65,7 @@ public sealed class TriggerExecutor(
|
||||
return Record(trigger, new TriggerFiring(null, 0, ex.Message));
|
||||
}
|
||||
|
||||
var arguments = ParseArguments(trigger.ArgumentsJson);
|
||||
var label = string.IsNullOrWhiteSpace(trigger.Name) ? "Scheduled trigger" : $"Schedule “{trigger.Name}”";
|
||||
var label =string.IsNullOrWhiteSpace(trigger.Name) ? "Scheduled trigger" : $"Schedule “{trigger.Name}”";
|
||||
var runId = Guid.NewGuid();
|
||||
var skipped = targeted
|
||||
.Where(d => d.IsOrphaned)
|
||||
|
||||
+48
-31
@@ -35,11 +35,12 @@ if (args.Length > 0 && args[0] == "nats-auth")
|
||||
return NatsAuthCli.Run(args[1..]);
|
||||
}
|
||||
|
||||
// CLI mode: lockout recovery — disable OIDC and restore local sign-in.
|
||||
if (args.Length > 0 && args[0] == "auth-reset")
|
||||
// CLI mode: lockout recovery — a new one-time admin password, local sign-in
|
||||
// restored. Reads the standalone appsettings.json like the server does, so it
|
||||
// reaches the same database whether the service is running or stopped.
|
||||
if (args.Length > 0 && AuthResetCli.Verbs.Contains(args[0]))
|
||||
{
|
||||
var cliConfig = new ConfigurationBuilder().AddEnvironmentVariables().Build();
|
||||
return await AuthResetCli.RunAsync(args[1..], cliConfig);
|
||||
return await AuthResetCli.RunAsync(args[1..], AuthResetCli.LoadConfiguration());
|
||||
}
|
||||
|
||||
// CLI mode: standalone single-binary server management.
|
||||
@@ -95,22 +96,29 @@ builder.Services.ConfigureHttpJsonOptions(options =>
|
||||
var proxySettings = ProxySettings.FromConfiguration(builder.Configuration);
|
||||
builder.Services.AddSingleton(proxySettings);
|
||||
|
||||
// ── Built-in encryption (self-signed, on by default) ─────────────────────
|
||||
// ── Built-in encryption (self-signed by default, or a provided certificate) ─
|
||||
// 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.
|
||||
// hop cannot be sniffed; TLS_SELF_SIGNED=0 opts out. TLS_CERT_SOURCE=store
|
||||
// (TLS_CERT_THUMBPRINT) or file (TLS_CERT_FILE) serves the administrator's
|
||||
// own certificate instead, hot-reloaded the same way. Agents are handed the
|
||||
// issuing chain unless it is publicly trusted. Public TLS stays at the edge.
|
||||
var tlsSettings = TlsSettings.FromConfiguration(builder.Configuration);
|
||||
builder.Services.AddSingleton(tlsSettings);
|
||||
SelfSignedTlsManager? tlsManager = null;
|
||||
ServerTlsSwitch? tlsSource = null;
|
||||
if (tlsSettings.Enabled)
|
||||
{
|
||||
tlsManager = new SelfSignedTlsManager(tlsSettings);
|
||||
builder.Services.AddSingleton(tlsManager);
|
||||
// The configured source is the default; the console's binding (Settings ›
|
||||
// Server Certificate, a database document every replica follows) switches
|
||||
// it at runtime unless the environment sets the certificate.
|
||||
IServerTlsSource configuredTls = tlsSettings.Source == TlsCertificateSource.SelfSigned
|
||||
? new SelfSignedTlsManager(tlsSettings)
|
||||
: new ProvidedTlsCertificate(tlsSettings);
|
||||
tlsSource = new ServerTlsSwitch(tlsSettings, configuredTls, TlsSettings.ForcedByEnvironment());
|
||||
builder.Services.AddSingleton(tlsSource);
|
||||
builder.Services.AddSingleton<IServerTlsSource>(tlsSource);
|
||||
builder.Services.AddHostedService<TlsRenewalService>();
|
||||
builder.WebHost.ConfigureKestrel(kestrel => kestrel.ConfigureHttpsDefaults(https =>
|
||||
https.ServerCertificateSelector = (_, _) => tlsManager.ServerCertificate));
|
||||
builder.WebHost.ConfigureKestrel(kestrel => kestrel.ConfigureHttpsDefaults(https => ServerTls.UseSource(https, tlsSource)));
|
||||
var listenUrls = builder.Configuration["urls"] is { Length: > 0 } configured
|
||||
? configured
|
||||
: "http://0.0.0.0:8080";
|
||||
@@ -183,10 +191,13 @@ if (Backend.Standalone.NatsSidecar.IsEnabled(builder.Configuration))
|
||||
builder.Services.AddHostedService(sp => sp.GetRequiredService<Backend.Standalone.NatsSidecar>());
|
||||
}
|
||||
|
||||
// Secrets providers: pluggable drivers; add implementations here.
|
||||
// Secrets providers: pluggable drivers; add implementations here. The
|
||||
// built-in vault is one of them, kept in the application database.
|
||||
builder.Services.AddHttpClient();
|
||||
builder.Services.AddSingleton<Backend.Secrets.ISecretsProviderDriver, Backend.Secrets.InfisicalDriver>();
|
||||
builder.Services.AddSingleton<Backend.Secrets.ISecretsProviderDriver, Backend.Secrets.BuiltInVaultDriver>();
|
||||
builder.Services.AddScoped<Backend.Secrets.SecretsProviderService>();
|
||||
builder.Services.AddScoped<Backend.Secrets.VaultService>();
|
||||
builder.Services.AddSingleton<ShellBridge>();
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddSingleton<Backend.DeviceFiles.IDeviceFileClient>(sp => new Backend.DeviceFiles.NatsDeviceFileClient(() => sp.GetRequiredService<NatsHub>().Connection));
|
||||
@@ -234,23 +245,6 @@ 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())
|
||||
{
|
||||
@@ -258,6 +252,27 @@ using (var scope = app.Services.CreateScope())
|
||||
db.Database.Migrate();
|
||||
app.Logger.LogInformation("Database ready ({Provider})", databaseOptions.Provider);
|
||||
|
||||
// The certificate must be loaded before Kestrel accepts the first TLS
|
||||
// handshake (after the migration, so the console's binding is read); a
|
||||
// configured one that cannot be loaded stops the server here with the reason.
|
||||
if (tlsSource is not null)
|
||||
{
|
||||
tlsSource.UseDatabase(app.Services.GetRequiredService<IServiceScopeFactory>());
|
||||
tlsSource.Refresh(app.Logger);
|
||||
if (tlsSource.Active is SelfSignedTlsManager { UsesWindowsStore: true })
|
||||
{
|
||||
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 from {Distribution})",
|
||||
tlsSettings.DistributionDirectory);
|
||||
}
|
||||
else if (tlsSource.Active is SelfSignedTlsManager)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// First-boot defaults: platform dynamic groups + starter schedules.
|
||||
await DefaultSeeder.SeedAsync(db, CancellationToken.None);
|
||||
|
||||
@@ -418,9 +433,11 @@ Backend.DeviceFiles.DeviceFileEndpoints.Map(app);
|
||||
GroupEndpoints.Map(app);
|
||||
TriggerEndpoints.Map(app);
|
||||
SettingsEndpoints.Map(app);
|
||||
ServerCertificateEndpoints.Map(app);
|
||||
Backend.Upgrades.AgentUpgradeEndpoints.Map(app);
|
||||
Backend.Removals.DeviceRemovalEndpoints.Map(app);
|
||||
Backend.Secrets.SecretsEndpoints.Map(app);
|
||||
Backend.Secrets.VaultEndpoints.Map(app);
|
||||
|
||||
if (staticUiPath is not null)
|
||||
{
|
||||
|
||||
@@ -52,8 +52,7 @@ public static class DeviceRemovalEndpoints
|
||||
.Take(take)
|
||||
.ToList();
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
return Results.Ok(rows.Select(r => DeviceRemovalService.ToDto(r, now)).ToList());
|
||||
return Results.Ok(rows.Select(DeviceRemovalService.ToDto).ToList());
|
||||
}
|
||||
|
||||
private static async Task<IResult> RemoveAsync(
|
||||
@@ -131,9 +130,8 @@ public static class DeviceRemovalEndpoints
|
||||
removed.Count == 1 ? removed[0].ClientId : null, null, DateTimeOffset.UtcNow), cancellationToken);
|
||||
}
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
return Results.Ok(new DeviceRemovalBatchDto(
|
||||
removed.OrderBy(r => r.Hostname, StringComparer.OrdinalIgnoreCase).Select(r => DeviceRemovalService.ToDto(r, now)).ToList(),
|
||||
removed.OrderBy(r => r.Hostname, StringComparer.OrdinalIgnoreCase).Select(DeviceRemovalService.ToDto).ToList(),
|
||||
skipped));
|
||||
}
|
||||
|
||||
@@ -184,6 +182,6 @@ public static class DeviceRemovalEndpoints
|
||||
await audit.LogAsync(AuditCategories.Admin, "device-removal-stopped", actor, clientId: row.ClientId,
|
||||
detail: $"removal={row.Id}", cancellationToken: cancellationToken);
|
||||
await removals.AnnounceAsync(row, cancellationToken);
|
||||
return Results.Ok(DeviceRemovalService.ToDto(row, now));
|
||||
return Results.Ok(DeviceRemovalService.ToDto(row));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,8 +53,9 @@ public sealed record RemovalPass(int Sent, int Finished);
|
||||
/// Drives open removals every 15 seconds:
|
||||
/// <list type="bullet">
|
||||
/// <item>Sends the remove command to a device seen online, not more often than
|
||||
/// <see cref="ResendAfter"/>. An agent too old to take it is marked and stays
|
||||
/// open: the server keeps blocking it.</item>
|
||||
/// <see cref="ResendAfter"/>. An agent too old to take it, or one that can't
|
||||
/// uninstall itself there, is removed from the system at once and left on the
|
||||
/// device.</item>
|
||||
/// <item>A command nobody answered goes back to waiting after
|
||||
/// <see cref="ReportDeadline"/>, for when the device next returns.</item>
|
||||
/// <item>An agent that said it was uninstalling and then went silent counts as
|
||||
@@ -165,22 +166,20 @@ public sealed class DeviceRemovalScheduler(
|
||||
private async Task<SendResult> TrySendAsync(
|
||||
AppDbContext db, DeviceRemovalService removals, DeviceRemovalEntity row, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
// Presence brings the running version, so an agent upgraded by hand gets past this.
|
||||
// Nothing to ask: the device is gone from the system all the same, and only its agent stays.
|
||||
var tooOld = !string.IsNullOrWhiteSpace(row.AgentVersion)
|
||||
&& AgentVersions.Compare(row.AgentVersion, DeviceRemovalDefaults.MinimumAgentVersion) < 0;
|
||||
if (tooOld)
|
||||
{
|
||||
if (row.Reason != DeviceRemovalReasons.AgentTooOld)
|
||||
{
|
||||
row.Reason = DeviceRemovalReasons.AgentTooOld;
|
||||
row.Detail = $"The agent runs {row.AgentVersion}; removing it needs {DeviceRemovalDefaults.MinimumAgentVersion} or later.";
|
||||
row.UpdatedUtc = now;
|
||||
if (await TrySaveAsync(db, row, cancellationToken))
|
||||
{
|
||||
await removals.AnnounceAsync(row, cancellationToken);
|
||||
}
|
||||
}
|
||||
await CloseUnremovableAsync(db, removals, row, now, DeviceRemovalReasons.AgentTooOld,
|
||||
$"The agent runs {row.AgentVersion}, too old to uninstall itself; it stays on the device.", cancellationToken);
|
||||
return SendResult.NotDue;
|
||||
}
|
||||
|
||||
if (row is { State: DeviceRemovalStates.Failed, Reason: DeviceRemovalReasons.Unsupported })
|
||||
{
|
||||
await CloseUnremovableAsync(db, removals, row, now, DeviceRemovalReasons.Unsupported,
|
||||
row.Detail ?? "The agent can't uninstall itself here; it stays on the device.", cancellationToken);
|
||||
return SendResult.NotDue;
|
||||
}
|
||||
|
||||
@@ -218,6 +217,38 @@ public sealed class DeviceRemovalScheduler(
|
||||
return SendResult.Sent;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the removal of an agent that can't take it away itself: removed
|
||||
/// from the system, its commands cleared, the agent left where it is. Its
|
||||
/// later sightings don't reopen it, and enrolling again still needs a new token.
|
||||
/// </summary>
|
||||
private async Task CloseUnremovableAsync(
|
||||
AppDbContext db, DeviceRemovalService removals, DeviceRemovalEntity row, DateTimeOffset now,
|
||||
string reason, string detail, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await sender.ClearCommandsAsync(row.ClientId, cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// Close it only once nothing can replay; the next pass tries again.
|
||||
logger.LogWarning(ex, "Could not clear the commands of removed device {ClientId}", row.ClientId);
|
||||
return;
|
||||
}
|
||||
|
||||
row.State = DeviceRemovalStates.Removed;
|
||||
row.Reason = reason;
|
||||
row.Detail = detail;
|
||||
row.FinishedUtc = now;
|
||||
row.UpdatedUtc = now;
|
||||
DeviceHistory.RecordRemoved(db, row.ClientId, detail);
|
||||
if (await TrySaveAsync(db, row, cancellationToken))
|
||||
{
|
||||
await removals.AnnounceAsync(row, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when the removal closed.</summary>
|
||||
private async Task<bool> AdvanceUninstallingAsync(
|
||||
AppDbContext db, DeviceRemovalService removals, DeviceRemovalEntity row, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
|
||||
@@ -40,13 +40,15 @@ public sealed class DeviceRemovalService(
|
||||
DeviceRemovalStates.Uninstalling, DeviceRemovalStates.Failed,
|
||||
};
|
||||
|
||||
public static DeviceRemovalDto ToDto(DeviceRemovalEntity row, DateTimeOffset now) => new(
|
||||
public static DeviceRemovalDto ToDto(DeviceRemovalEntity row) => new(
|
||||
row.Id, row.ClientId, row.Hostname, row.OsCaption, row.AgentVersion, row.State, row.Reason, row.Detail,
|
||||
row.Attempts, row.RequestedBy, row.Note, row.RequestedUtc, row.UpdatedUtc, row.SentUtc, row.LastSeenUtc,
|
||||
row.FinishedUtc, ShowInDeviceList(row, now));
|
||||
row.FinishedUtc);
|
||||
|
||||
public static bool ShowInDeviceList(DeviceRemovalEntity row, DateTimeOffset now)
|
||||
=> now - row.UpdatedUtc < DeviceRemovalDefaults.VisibleInDeviceList;
|
||||
/// <summary>Removed from the system with its agent left installed: too old, or unable to uninstall itself there.</summary>
|
||||
public static bool LeftOnDevice(DeviceRemovalEntity row)
|
||||
=> row.State == DeviceRemovalStates.Removed
|
||||
&& row.Reason is DeviceRemovalReasons.AgentTooOld or DeviceRemovalReasons.Unsupported;
|
||||
|
||||
/// <summary>
|
||||
/// For each device: its tombstone in, its row and everything that would
|
||||
@@ -203,7 +205,8 @@ public sealed class DeviceRemovalService(
|
||||
/// the device row is never resurrected. An agent still talking after its
|
||||
/// removal closed as removed was not gone after all: back to waiting, with
|
||||
/// its command consumer restored when the next command is sent. A stopped
|
||||
/// removal stays stopped. True when a removal took the sighting.
|
||||
/// removal stays stopped, and so does one whose agent was left on the
|
||||
/// device. True when a removal took the sighting.
|
||||
/// </summary>
|
||||
public async Task<bool> NoteSightingAsync(
|
||||
string? subjectClientId, string clientId, string? agentVersion, CancellationToken cancellationToken)
|
||||
@@ -220,7 +223,8 @@ public sealed class DeviceRemovalService(
|
||||
}
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var reopened = row.State == DeviceRemovalStates.Removed;
|
||||
// One removed while its agent stayed on the device is expected to keep talking.
|
||||
var reopened = row.State == DeviceRemovalStates.Removed && !LeftOnDevice(row);
|
||||
row.LastSeenUtc = now;
|
||||
row.AgentVersion = string.IsNullOrWhiteSpace(agentVersion) ? row.AgentVersion : agentVersion;
|
||||
if (reopened)
|
||||
|
||||
@@ -0,0 +1,485 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using System.Management.Automation;
|
||||
using System.Management.Automation.Language;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Shared.Contracts.Api;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Backend.Scripts;
|
||||
|
||||
/// <summary>One parameter as a script's param() block declares it.</summary>
|
||||
/// <param name="Parameter">Name, type, required, default, ValidateSet and help as the code says; Expansion is left at Auto.</param>
|
||||
/// <param name="DescriptionFromCode">The description is a HelpMessage or comment-based .PARAMETER help.</param>
|
||||
public sealed record DeclaredParameter(ScriptParameter Parameter, bool DescriptionFromCode);
|
||||
|
||||
/// <summary>What the parser found. With <c>HasErrors</c> the declarations are not to be trusted.</summary>
|
||||
public sealed record ParameterReadResult(
|
||||
bool HasParamBlock,
|
||||
IReadOnlyList<DeclaredParameter> Parameters,
|
||||
IReadOnlyList<ScriptDiagnosticDto> Diagnostics)
|
||||
{
|
||||
public bool HasErrors => Diagnostics.Any(d => d.Severity == "error");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a PowerShell script's <c>param()</c> block with PowerShell's own
|
||||
/// parser. Nothing is run: the text is parsed into an AST and only constant
|
||||
/// literals are read back out of it.
|
||||
///
|
||||
/// Types become what the console can send — text, a number, true/false, a
|
||||
/// list or a hashtable — and PowerShell converts on binding: [int]/[double]/…
|
||||
/// → Number; [bool]/[switch] → Boolean; [string] and anything convertible
|
||||
/// from text ([datetime], [guid], [version], enums, …) → String; arrays and
|
||||
/// generic lists of those → Array of that element type; dictionaries →
|
||||
/// Hashtable. Untyped parameters take the kind of a constant default, else
|
||||
/// String.
|
||||
///
|
||||
/// Defaults are imported only when they are constant primitives or lists of
|
||||
/// them ('a', 5, -1.5, $true, @('a','b'), (1,2,3); a bare 1,2,3 only
|
||||
/// counts where a comma does not end the parameter). Anything else (variables,
|
||||
/// expressions, subexpressions, script blocks) is kept as text in
|
||||
/// DefaultExpression and no value is imported: PowerShell evaluates it.
|
||||
/// </summary>
|
||||
public static partial class PowerShellParameterReader
|
||||
{
|
||||
/// <summary>Longest script read (characters); the editor never sends more.</summary>
|
||||
public const int MaxLength = 1_000_000;
|
||||
|
||||
private const int MaxExpressionLength = 200;
|
||||
|
||||
public static ParameterReadResult Read(string? content)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReadCore(content ?? string.Empty);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Pathological input (e.g. nesting deep enough to exhaust the
|
||||
// stack guard) reports instead of failing the request.
|
||||
return new ParameterReadResult(false, [], [new ScriptDiagnosticDto("error", $"The script could not be read: {ex.Message}", 1, 1)]);
|
||||
}
|
||||
}
|
||||
|
||||
private static ParameterReadResult ReadCore(string content)
|
||||
{
|
||||
var ast = ParseSafely(content, out var errors);
|
||||
var diagnostics = errors
|
||||
.Select(e => new ScriptDiagnosticDto("error", e.Message, e.Extent.StartLineNumber, e.Extent.StartColumnNumber))
|
||||
.ToList();
|
||||
|
||||
if (ast.ParamBlock is not { } block)
|
||||
{
|
||||
return new ParameterReadResult(false, [], diagnostics);
|
||||
}
|
||||
|
||||
CommentHelpInfo? help = null;
|
||||
try
|
||||
{
|
||||
help = ast.GetHelpContent();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Help is optional; a malformed help block only loses descriptions.
|
||||
}
|
||||
|
||||
var declared = new List<DeclaredParameter>(block.Parameters.Count);
|
||||
foreach (var parameter in block.Parameters)
|
||||
{
|
||||
declared.Add(Declare(parameter, help, diagnostics));
|
||||
}
|
||||
|
||||
return new ParameterReadResult(true, declared, diagnostics);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ParseInput resolves <c>using assembly</c> as it parses, loading the
|
||||
/// named assembly (and a DLL's module initializer would run). Every such
|
||||
/// statement is turned into a comment of the same length before parsing,
|
||||
/// so positions hold; occurrences that were really inside a string or a
|
||||
/// comment are put back and the text parsed again.
|
||||
/// </summary>
|
||||
private static ScriptBlockAst ParseSafely(string content, out ParseError[] errors)
|
||||
{
|
||||
var matches = UsingAssembly().Matches(content);
|
||||
if (matches.Count == 0)
|
||||
{
|
||||
return Parser.ParseInput(content, out _, out errors);
|
||||
}
|
||||
|
||||
var masked = Mask(content, matches.Select(m => m.Index));
|
||||
var ast = Parser.ParseInput(masked, out var tokens, out errors);
|
||||
|
||||
// Ours: a comment token that starts exactly where "using" was. Anything
|
||||
// else (inside a string, a here-string or someone's comment) was text.
|
||||
var textual = matches
|
||||
.Select(m => m.Index)
|
||||
.Where(index => !tokens.Any(t => t.Kind == TokenKind.Comment && t.Extent.StartOffset == index))
|
||||
.ToHashSet();
|
||||
if (textual.Count == 0)
|
||||
{
|
||||
return ast;
|
||||
}
|
||||
|
||||
return Parser.ParseInput(
|
||||
Mask(content, matches.Select(m => m.Index).Where(index => !textual.Contains(index))), out _, out errors);
|
||||
}
|
||||
|
||||
private static string Mask(string content, IEnumerable<int> indexes)
|
||||
{
|
||||
var chars = content.ToCharArray();
|
||||
foreach (var index in indexes)
|
||||
{
|
||||
"# ".CopyTo(0, chars, index, 5);
|
||||
}
|
||||
|
||||
return new string(chars);
|
||||
}
|
||||
|
||||
private static DeclaredParameter Declare(ParameterAst ast, CommentHelpInfo? help, List<ScriptDiagnosticDto> diagnostics)
|
||||
{
|
||||
var name = ast.Name.VariablePath.UserPath;
|
||||
var typeConstraint = ast.Attributes.OfType<TypeConstraintAst>().FirstOrDefault();
|
||||
var declaredType = typeConstraint?.TypeName.FullName;
|
||||
var parameterAttributes = ast.Attributes.OfType<AttributeAst>().Where(a => IsAttribute(a, "Parameter")).ToList();
|
||||
|
||||
// Mandatory in every parameter set it belongs to.
|
||||
var required = parameterAttributes.Count > 0
|
||||
&& parameterAttributes.All(a => NamedFlag(a, "Mandatory"));
|
||||
|
||||
string? description = parameterAttributes
|
||||
.Select(a => NamedString(a, "HelpMessage"))
|
||||
.FirstOrDefault(m => !string.IsNullOrWhiteSpace(m))?.Trim();
|
||||
if (description is null && help?.Parameters is { } helpParameters)
|
||||
{
|
||||
// Keys are upper-cased by PowerShell.
|
||||
description = helpParameters
|
||||
.FirstOrDefault(p => string.Equals(p.Key, name, StringComparison.OrdinalIgnoreCase)).Value?.Trim();
|
||||
description = string.IsNullOrWhiteSpace(description) ? null : CollapseWhitespace(description);
|
||||
}
|
||||
|
||||
var allowed = ast.Attributes.OfType<AttributeAst>()
|
||||
.Where(a => IsAttribute(a, "ValidateSet"))
|
||||
.SelectMany(a => a.PositionalArguments)
|
||||
.Select(e => TryConstant(e, out var v) && v is string or int or long or double or decimal ? Convert.ToString(v, CultureInfo.InvariantCulture) : null)
|
||||
.OfType<string>()
|
||||
.ToList();
|
||||
|
||||
object? constant = null;
|
||||
var isConstant = ast.DefaultValue is { } defaultAst && TryConstant(defaultAst, out constant);
|
||||
|
||||
var (type, elementType) = typeConstraint is null
|
||||
? Infer(constant)
|
||||
: Map(Resolve(typeConstraint.TypeName));
|
||||
|
||||
JsonElement? defaultValue = constant is null ? null : ToDefault(constant, type, elementType);
|
||||
|
||||
// A computed default (or a literal that does not fit the type) stays
|
||||
// in the code: shown as text, never sent. $null is simply no default.
|
||||
string? defaultExpression = null;
|
||||
if (ast.DefaultValue is { } expression && defaultValue is null && !(isConstant && constant is null))
|
||||
{
|
||||
var text = expression.Extent.Text.Trim();
|
||||
defaultExpression = text.Length > MaxExpressionLength ? text[..(MaxExpressionLength - 1)] + "…" : text;
|
||||
}
|
||||
|
||||
if (typeConstraint is not null && NotFromText(Resolve(typeConstraint.TypeName)))
|
||||
{
|
||||
diagnostics.Add(new ScriptDiagnosticDto(
|
||||
"warning",
|
||||
$"${name} is [{declaredType}], which cannot be given as text; runs fail unless the code supplies it.",
|
||||
ast.Extent.StartLineNumber,
|
||||
ast.Extent.StartColumnNumber));
|
||||
}
|
||||
|
||||
return new DeclaredParameter(
|
||||
new ScriptParameter(
|
||||
name,
|
||||
type,
|
||||
Required: required,
|
||||
Description: description,
|
||||
ElementType: type == ScriptParameterType.Array ? elementType : null,
|
||||
DefaultValue: defaultValue,
|
||||
AllowedValues: allowed.Count > 0 && type is ScriptParameterType.String or ScriptParameterType.Array ? allowed : null,
|
||||
DeclaredType: declaredType,
|
||||
DefaultExpression: defaultExpression),
|
||||
description is not null);
|
||||
}
|
||||
|
||||
// ── Types ───────────────────────────────────────────────────────────
|
||||
|
||||
private static Type? Resolve(ITypeName typeName)
|
||||
{
|
||||
try
|
||||
{
|
||||
return typeName.GetReflectionType();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static (ScriptParameterType Type, PrimitiveType? Element) Map(Type? type)
|
||||
{
|
||||
if (type is null || type == typeof(object))
|
||||
{
|
||||
// Unknown (a class from a module, a typo) or [object]: text, converted by PowerShell.
|
||||
return (ScriptParameterType.String, null);
|
||||
}
|
||||
|
||||
type = Nullable.GetUnderlyingType(type) ?? type;
|
||||
if (type == typeof(bool) || type == typeof(SwitchParameter))
|
||||
{
|
||||
return (ScriptParameterType.Boolean, null);
|
||||
}
|
||||
|
||||
if (IsNumeric(type))
|
||||
{
|
||||
return (ScriptParameterType.Number, null);
|
||||
}
|
||||
|
||||
if (typeof(IDictionary).IsAssignableFrom(type))
|
||||
{
|
||||
return (ScriptParameterType.Hashtable, null);
|
||||
}
|
||||
|
||||
if (type.IsArray)
|
||||
{
|
||||
return (ScriptParameterType.Array, Primitive(type.GetElementType()));
|
||||
}
|
||||
|
||||
if (type != typeof(string)
|
||||
&& type.IsGenericType
|
||||
&& type.GetGenericArguments() is [var item]
|
||||
&& typeof(IEnumerable<>).MakeGenericType(item).IsAssignableFrom(type))
|
||||
{
|
||||
return (ScriptParameterType.Array, Primitive(item));
|
||||
}
|
||||
|
||||
return (ScriptParameterType.String, null);
|
||||
}
|
||||
|
||||
private static PrimitiveType Primitive(Type? type)
|
||||
{
|
||||
type = type is null ? null : Nullable.GetUnderlyingType(type) ?? type;
|
||||
return type == typeof(bool) || type == typeof(SwitchParameter) ? PrimitiveType.Boolean
|
||||
: type is not null && IsNumeric(type) ? PrimitiveType.Number
|
||||
: PrimitiveType.String;
|
||||
}
|
||||
|
||||
private static bool IsNumeric(Type type)
|
||||
=> type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(byte)
|
||||
|| type == typeof(sbyte) || type == typeof(uint) || type == typeof(ulong) || type == typeof(ushort)
|
||||
|| type == typeof(double) || type == typeof(float) || type == typeof(decimal)
|
||||
|| type == typeof(System.Numerics.BigInteger);
|
||||
|
||||
/// <summary>Types PowerShell cannot build from a string.</summary>
|
||||
private static bool NotFromText(Type? type)
|
||||
=> type == typeof(ScriptBlock) || type == typeof(PSCredential) || type == typeof(System.Security.SecureString);
|
||||
|
||||
/// <summary>An untyped parameter takes the kind of its constant default.</summary>
|
||||
private static (ScriptParameterType, PrimitiveType?) Infer(object? constant) => constant switch
|
||||
{
|
||||
bool => (ScriptParameterType.Boolean, null),
|
||||
string or null => (ScriptParameterType.String, null),
|
||||
object?[] items => (ScriptParameterType.Array, items.Select(KindOf).Distinct().ToList() is [var only] ? only : PrimitiveType.String),
|
||||
_ => (ScriptParameterType.Number, null),
|
||||
};
|
||||
|
||||
private static PrimitiveType KindOf(object? value)
|
||||
=> value is bool ? PrimitiveType.Boolean : value is string or null ? PrimitiveType.String : PrimitiveType.Number;
|
||||
|
||||
// ── Attributes ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>[Parameter], [ParameterAttribute] or [System.Management.Automation.Parameter].</summary>
|
||||
private static bool IsAttribute(AttributeAst attribute, string name)
|
||||
{
|
||||
var written = attribute.TypeName.Name;
|
||||
var leaf = written[(written.LastIndexOf('.') + 1)..];
|
||||
return leaf.Equals(name, StringComparison.OrdinalIgnoreCase)
|
||||
|| leaf.Equals(name + "Attribute", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>[Parameter(Mandatory)], Mandatory=$true or Mandatory=1.</summary>
|
||||
private static bool NamedFlag(AttributeAst attribute, string name)
|
||||
{
|
||||
var argument = attribute.NamedArguments
|
||||
.FirstOrDefault(a => a.ArgumentName.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
if (argument is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (argument.ExpressionOmitted)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return TryConstant(argument.Argument, out var value) && value switch
|
||||
{
|
||||
bool b => b,
|
||||
int i => i != 0,
|
||||
long l => l != 0,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
private static string? NamedString(AttributeAst attribute, string name)
|
||||
=> attribute.NamedArguments
|
||||
.FirstOrDefault(a => a.ArgumentName.Equals(name, StringComparison.OrdinalIgnoreCase)) is { ExpressionOmitted: false } argument
|
||||
&& TryConstant(argument.Argument, out var value)
|
||||
? value as string
|
||||
: null;
|
||||
|
||||
// ── Constants ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// A literal, $true/$false/$null, a signed number, or a list of literals
|
||||
/// (1,2,3 / @('a','b') / ('a','b')). Never evaluates anything.
|
||||
/// </summary>
|
||||
internal static bool TryConstant(ExpressionAst expression, out object? value)
|
||||
{
|
||||
value = null;
|
||||
switch (expression)
|
||||
{
|
||||
case StringConstantExpressionAst text:
|
||||
value = text.Value;
|
||||
return true;
|
||||
case ConstantExpressionAst constant when IsNumericValue(constant.Value):
|
||||
value = constant.Value;
|
||||
return true;
|
||||
case VariableExpressionAst variable when variable.VariablePath.IsUnscopedVariable:
|
||||
switch (variable.VariablePath.UserPath.ToLowerInvariant())
|
||||
{
|
||||
case "true":
|
||||
value = true;
|
||||
return true;
|
||||
case "false":
|
||||
value = false;
|
||||
return true;
|
||||
case "null":
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
case UnaryExpressionAst { TokenKind: TokenKind.Minus or TokenKind.Plus } unary
|
||||
when unary.Child is ConstantExpressionAst { Value: var number } && IsNumericValue(number) && number is not string:
|
||||
value = unary.TokenKind == TokenKind.Minus ? Negate(number) : number;
|
||||
return value is not null;
|
||||
case ArrayLiteralAst list:
|
||||
return TryList(list.Elements, out value);
|
||||
case ParenExpressionAst { Pipeline: PipelineAst paren } when SingleExpression(paren) is { } inner:
|
||||
return TryConstant(inner, out value);
|
||||
case ArrayExpressionAst array:
|
||||
var items = new List<ExpressionAst>();
|
||||
foreach (var statement in array.SubExpression.Statements)
|
||||
{
|
||||
if (statement is not PipelineAst pipeline || SingleExpression(pipeline) is not { } item)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
items.AddRange(item is ArrayLiteralAst nested ? nested.Elements : [item]);
|
||||
}
|
||||
|
||||
return TryList(items, out value);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryList(IEnumerable<ExpressionAst> elements, out object? value)
|
||||
{
|
||||
var items = new List<object?>();
|
||||
foreach (var element in elements)
|
||||
{
|
||||
if (!TryConstant(element, out var item) || item is object?[])
|
||||
{
|
||||
value = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
items.Add(item);
|
||||
}
|
||||
|
||||
value = items.ToArray();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static ExpressionAst? SingleExpression(PipelineAst pipeline)
|
||||
=> pipeline.PipelineElements is [CommandExpressionAst { Redirections.Count: 0 } command] ? command.Expression : null;
|
||||
|
||||
private static bool IsNumericValue(object? value)
|
||||
=> value is int or long or double or float or decimal or short or byte or sbyte or uint or ulong or ushort;
|
||||
|
||||
private static object? Negate(object number) => number switch
|
||||
{
|
||||
int i => i == int.MinValue ? -(long)i : -i,
|
||||
long l => -l,
|
||||
double d => -d,
|
||||
float f => -f,
|
||||
decimal m => -m,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
// ── Defaults ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The constant as the parameter's kind would send it, or null when it does not fit.</summary>
|
||||
private static JsonElement? ToDefault(object constant, ScriptParameterType type, PrimitiveType? elementType)
|
||||
{
|
||||
object? value = type switch
|
||||
{
|
||||
ScriptParameterType.Array => constant is object?[] items
|
||||
? ConvertAll(items, elementType ?? PrimitiveType.String)
|
||||
: ConvertAll([constant], elementType ?? PrimitiveType.String),
|
||||
ScriptParameterType.Number => ToPrimitive(constant, PrimitiveType.Number),
|
||||
ScriptParameterType.Boolean => ToPrimitive(constant, PrimitiveType.Boolean),
|
||||
ScriptParameterType.String => ToPrimitive(constant, PrimitiveType.String),
|
||||
_ => null,
|
||||
};
|
||||
return value is null ? null : JsonSerializer.SerializeToElement(value);
|
||||
}
|
||||
|
||||
private static object?[]? ConvertAll(object?[] items, PrimitiveType elementType)
|
||||
{
|
||||
var converted = items.Select(i => ToPrimitive(i, elementType)).ToArray();
|
||||
return converted.Any(c => c is null) ? null : converted;
|
||||
}
|
||||
|
||||
private static object? ToPrimitive(object? value, PrimitiveType type) => type switch
|
||||
{
|
||||
PrimitiveType.Number => value switch
|
||||
{
|
||||
string s when double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var parsed) => parsed,
|
||||
bool or string or null or object?[] => null,
|
||||
_ => value,
|
||||
},
|
||||
PrimitiveType.Boolean => value switch
|
||||
{
|
||||
bool b => b,
|
||||
int i => i != 0,
|
||||
long l => l != 0,
|
||||
_ => null,
|
||||
},
|
||||
_ => value switch
|
||||
{
|
||||
string s => s,
|
||||
bool b => b ? "True" : "False",
|
||||
null or object?[] => null,
|
||||
_ => Convert.ToString(value, CultureInfo.InvariantCulture),
|
||||
},
|
||||
};
|
||||
|
||||
private static string CollapseWhitespace(string text) => Whitespace().Replace(text, " ");
|
||||
|
||||
/// <summary>"using" (any case) followed, past blanks, comments or line continuations, by "assembly".</summary>
|
||||
[GeneratedRegex(@"\busing(?=(?:\s|`\r?\n|<#[\s\S]*?#>)+assembly\b)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
|
||||
private static partial Regex UsingAssembly();
|
||||
|
||||
[GeneratedRegex(@"\s+")]
|
||||
private static partial Regex Whitespace();
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Backend.Scripts;
|
||||
|
||||
/// <summary>
|
||||
/// The one check every way of starting a script shares (manual runs, the
|
||||
/// trigger and schedule editors, and each firing), so the console and the
|
||||
/// API refuse the same things.
|
||||
///
|
||||
/// Values are only what the run, schedule or trigger set. One not given is
|
||||
/// filled from the parameter's default when the job is dispatched, and with
|
||||
/// no default PowerShell applies its own. So a required parameter needs a
|
||||
/// value here or a default on the script; anything given must fit the
|
||||
/// parameter's type (the agent then converts it, and PowerShell converts
|
||||
/// text to [datetime], [guid], enums and the like).
|
||||
///
|
||||
/// A schedule stores only what was set on it: an explicit value wins over
|
||||
/// later changes to the script's default, an untouched one follows the
|
||||
/// default. Firing re-checks against the script as it is then, ignoring
|
||||
/// values for parameters the script no longer has.
|
||||
/// </summary>
|
||||
public static partial class ScriptArguments
|
||||
{
|
||||
/// <summary>Why these values cannot run the script, or null when they can.</summary>
|
||||
/// <param name="rejectUnknown">Refuse names the script does not declare (requests); firings ignore them.</param>
|
||||
public static string? Validate(
|
||||
IReadOnlyList<ScriptParameter> parameters,
|
||||
IReadOnlyDictionary<string, JsonElement>? arguments,
|
||||
bool rejectUnknown)
|
||||
{
|
||||
if (rejectUnknown && arguments is not null)
|
||||
{
|
||||
// Exact names, as the agent binds them.
|
||||
var known = parameters.Select(p => p.Name).ToHashSet(StringComparer.Ordinal);
|
||||
if (arguments.Keys.FirstOrDefault(name => !known.Contains(name)) is { } unknown)
|
||||
{
|
||||
return $"“{unknown}” is not a parameter of this script.";
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var parameter in parameters)
|
||||
{
|
||||
JsonElement? value = arguments is not null && arguments.TryGetValue(parameter.Name, out var given) ? given : null;
|
||||
if (!IsEmpty(value))
|
||||
{
|
||||
if (CheckValue(parameter, value!.Value) is { } problem)
|
||||
{
|
||||
return problem;
|
||||
}
|
||||
}
|
||||
else if (parameter.Required && IsEmpty(parameter.DefaultValue))
|
||||
{
|
||||
return $"“{parameter.Name}” needs a value.";
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The script's parameter list as saved: names usable as $Name, once each, defaults that fit.</summary>
|
||||
public static string? ValidateDefinitions(IReadOnlyList<ScriptParameter>? parameters)
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var parameter in parameters ?? [])
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(parameter.Name) || !Identifier().IsMatch(parameter.Name))
|
||||
{
|
||||
return "Every parameter needs a name usable as $Name (letters, digits, underscore).";
|
||||
}
|
||||
|
||||
if (!seen.Add(parameter.Name))
|
||||
{
|
||||
return $"Two parameters are named “{parameter.Name}”.";
|
||||
}
|
||||
|
||||
if (!IsEmpty(parameter.DefaultValue) && CheckValue(parameter, parameter.DefaultValue!.Value) is { } problem)
|
||||
{
|
||||
return $"Default: {problem}";
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Nothing given (see <see cref="ScriptArgumentValue"/>); the same test decides whether a default counts.</summary>
|
||||
public static bool IsEmpty(JsonElement? value) => ScriptArgumentValue.IsEmpty(value);
|
||||
|
||||
/// <summary>Whether a value fits the parameter's type and allowed values; the problem otherwise.</summary>
|
||||
public static string? CheckValue(ScriptParameter parameter, JsonElement value)
|
||||
{
|
||||
var name = parameter.Name;
|
||||
switch (parameter.Type)
|
||||
{
|
||||
case ScriptParameterType.Number:
|
||||
return IsNumber(value) ? null : $"“{name}” must be a number.";
|
||||
case ScriptParameterType.Boolean:
|
||||
return IsBoolean(value) ? null : $"“{name}” must be true or false.";
|
||||
case ScriptParameterType.Array:
|
||||
if (value.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
return $"“{name}” must be a list.";
|
||||
}
|
||||
|
||||
foreach (var item in value.EnumerateArray())
|
||||
{
|
||||
if (CheckPrimitive(parameter.ElementType ?? PrimitiveType.String, item) is { } kind)
|
||||
{
|
||||
return $"Every item of “{name}” must be {kind}.";
|
||||
}
|
||||
|
||||
if (NotAllowed(parameter, item))
|
||||
{
|
||||
return $"Every item of “{name}” must be one of: {string.Join(", ", parameter.AllowedValues!)}.";
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
case ScriptParameterType.Hashtable:
|
||||
return value.ValueKind == JsonValueKind.Object
|
||||
|| (value.ValueKind == JsonValueKind.Array && value.EnumerateArray().All(IsHashEntry))
|
||||
? null
|
||||
: $"“{name}” must be a hashtable.";
|
||||
default:
|
||||
if (CheckPrimitive(PrimitiveType.String, value) is not null)
|
||||
{
|
||||
return $"“{name}” must be text.";
|
||||
}
|
||||
|
||||
return NotAllowed(parameter, value)
|
||||
? $"“{name}” must be one of: {string.Join(", ", parameter.AllowedValues!)}."
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the item should have been ("a number"), or null when it fits.</summary>
|
||||
private static string? CheckPrimitive(PrimitiveType type, JsonElement value) => type switch
|
||||
{
|
||||
PrimitiveType.Number => IsNumber(value) ? null : "a number",
|
||||
PrimitiveType.Boolean => IsBoolean(value) ? null : "true or false",
|
||||
_ => value.ValueKind is JsonValueKind.String or JsonValueKind.Number or JsonValueKind.True or JsonValueKind.False
|
||||
? null
|
||||
: "text",
|
||||
};
|
||||
|
||||
private static bool IsNumber(JsonElement value) => value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Number => true,
|
||||
JsonValueKind.String => double.TryParse(value.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out _),
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static bool IsBoolean(JsonElement value) => value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.True or JsonValueKind.False => true,
|
||||
JsonValueKind.String => bool.TryParse(value.GetString(), out _),
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static bool IsHashEntry(JsonElement entry)
|
||||
=> entry.ValueKind == JsonValueKind.Object && entry.TryGetProperty("key", out _) && entry.TryGetProperty("value", out _);
|
||||
|
||||
/// <summary>A [ValidateSet()] matches as PowerShell does: ignoring case.</summary>
|
||||
private static bool NotAllowed(ScriptParameter parameter, JsonElement value)
|
||||
=> parameter.AllowedValues is { Count: > 0 } allowed
|
||||
&& !allowed.Contains(value.ToString(), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
[GeneratedRegex("^[A-Za-z_][A-Za-z0-9_]*$")]
|
||||
private static partial Regex Identifier();
|
||||
}
|
||||
@@ -19,6 +19,63 @@ public static class ScriptEndpoints
|
||||
app.MapGet(ApiRoutes.Script, GetAsync).RequirePermission(Permissions.ScriptsView);
|
||||
app.MapPut(ApiRoutes.Script, UpdateAsync).RequirePermission(Permissions.ScriptsManage);
|
||||
app.MapDelete(ApiRoutes.Script, DeleteAsync).RequirePermission(Permissions.ScriptsManage);
|
||||
app.MapPost(ApiRoutes.ScriptParametersParse, ParseParameters).RequirePermission(Permissions.ScriptsView);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What is stored: for PowerShell engines the parameters the code declares,
|
||||
/// whatever the client sent, with the user-owned fields (Literal, and a
|
||||
/// description the code has no help for) kept from the request, else from
|
||||
/// the stored script (see <see cref="ScriptParameterSync"/>). Code that
|
||||
/// does not parse keeps the request's parameters, the editor's last good
|
||||
/// read. Bash scripts store what was sent.
|
||||
/// </summary>
|
||||
internal static IReadOnlyList<ScriptParameter> ParametersToStore(
|
||||
SaveScriptRequest request, IReadOnlyList<ScriptParameter>? stored)
|
||||
{
|
||||
var sent = request.Parameters ?? [];
|
||||
if (request.Engine == ScriptEngine.Bash)
|
||||
{
|
||||
return sent;
|
||||
}
|
||||
|
||||
var read = PowerShellParameterReader.Read(request.Content);
|
||||
if (read.HasErrors)
|
||||
{
|
||||
return sent;
|
||||
}
|
||||
|
||||
var names = sent.Select(p => p.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
return ScriptParameterSync.Merge([.. sent, .. (stored ?? []).Where(p => !names.Contains(p.Name))], read.Parameters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the param() block of unsaved code and merges it into the
|
||||
/// editor's parameters (see <see cref="ScriptParameterSync"/>). Parsing
|
||||
/// only: nothing is stored and no code runs. Code with syntax errors is
|
||||
/// not merged, so a half-typed block never drops parameters.
|
||||
/// </summary>
|
||||
private static IResult ParseParameters(ParseScriptParametersRequest request)
|
||||
{
|
||||
if (request.Engine == ScriptEngine.Bash)
|
||||
{
|
||||
return Results.BadRequest(new { error = "Parameters are read from code for PowerShell scripts only." });
|
||||
}
|
||||
|
||||
if (request.Content is { Length: > PowerShellParameterReader.MaxLength })
|
||||
{
|
||||
return Results.BadRequest(new { error = "The script is too long to read parameters from." });
|
||||
}
|
||||
|
||||
var current = request.Current ?? [];
|
||||
var read = PowerShellParameterReader.Read(request.Content);
|
||||
var merged = !read.HasErrors;
|
||||
return Results.Ok(new ScriptParametersParseDto(
|
||||
merged,
|
||||
read.HasParamBlock,
|
||||
merged ? ScriptParameterSync.Merge(current, read.Parameters) : current,
|
||||
read.Parameters.Select(p => new DeclaredParameterDto(p.Parameter.Name, p.DescriptionFromCode)).ToList(),
|
||||
read.Diagnostics));
|
||||
}
|
||||
|
||||
private static async Task<IResult> ListAsync(AppDbContext db, CancellationToken cancellationToken)
|
||||
@@ -53,6 +110,12 @@ public static class ScriptEndpoints
|
||||
return filesProblem;
|
||||
}
|
||||
|
||||
var parameters = ParametersToStore(request, stored: null);
|
||||
if (ScriptArguments.ValidateDefinitions(parameters) is { } parametersProblem)
|
||||
{
|
||||
return Results.BadRequest(new { error = parametersProblem });
|
||||
}
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var actor = context.User.Identity?.Name;
|
||||
var script = new ScriptEntity
|
||||
@@ -62,7 +125,7 @@ public static class ScriptEndpoints
|
||||
Description = request.Description,
|
||||
Language = request.Engine.ToString(),
|
||||
Content = request.Content ?? string.Empty,
|
||||
ParametersJson = SerializeParameters(request.Parameters),
|
||||
ParametersJson = SerializeParameters(parameters),
|
||||
FunctionModuleIdsJson = SerializeModuleIds(request.FunctionModuleIds),
|
||||
SecretBindingsJson = SerializeSecretBindings(request.SecretBindings),
|
||||
SecretsVariableName = NormalizeVariableName(request.SecretsVariableName),
|
||||
@@ -103,11 +166,17 @@ public static class ScriptEndpoints
|
||||
return filesProblem;
|
||||
}
|
||||
|
||||
var parameters = ParametersToStore(request, DeserializeParameters(script.ParametersJson));
|
||||
if (ScriptArguments.ValidateDefinitions(parameters) is { } parametersProblem)
|
||||
{
|
||||
return Results.BadRequest(new { error = parametersProblem });
|
||||
}
|
||||
|
||||
script.Name = request.Name.Trim();
|
||||
script.Description = request.Description;
|
||||
script.Language = request.Engine.ToString();
|
||||
script.Content = request.Content ?? string.Empty;
|
||||
script.ParametersJson = SerializeParameters(request.Parameters);
|
||||
script.ParametersJson = SerializeParameters(parameters);
|
||||
script.FunctionModuleIdsJson = SerializeModuleIds(request.FunctionModuleIds);
|
||||
script.SecretBindingsJson = SerializeSecretBindings(request.SecretBindings);
|
||||
script.SecretsVariableName = NormalizeVariableName(request.SecretsVariableName);
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Backend.Scripts;
|
||||
|
||||
/// <summary>
|
||||
/// Folds what a PowerShell script's param() block declares into the
|
||||
/// parameters the editor holds. The code is the source of truth for the
|
||||
/// parameters it declares: their order, name, type, element type, required,
|
||||
/// default, ValidateSet, declared type and computed default. What the code
|
||||
/// does not say is kept from the editor's copy (matched by name, ignoring
|
||||
/// case): Expansion always, and the description when the code has no help
|
||||
/// for that parameter. Parameters the code no longer declares are dropped;
|
||||
/// PowerShell engines bind by param() alone, so they could never be set.
|
||||
/// </summary>
|
||||
public static class ScriptParameterSync
|
||||
{
|
||||
public static IReadOnlyList<ScriptParameter> Merge(
|
||||
IReadOnlyList<ScriptParameter> current, IReadOnlyList<DeclaredParameter> declared)
|
||||
{
|
||||
var byName = new Dictionary<string, ScriptParameter>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var parameter in current)
|
||||
{
|
||||
byName.TryAdd(parameter.Name, parameter);
|
||||
}
|
||||
|
||||
return declared
|
||||
.Select(d =>
|
||||
{
|
||||
var kept = byName.GetValueOrDefault(d.Parameter.Name);
|
||||
return d.Parameter with
|
||||
{
|
||||
Description = d.DescriptionFromCode ? d.Parameter.Description : kept?.Description,
|
||||
Expansion = kept?.Expansion ?? ValueExpansion.Auto,
|
||||
};
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using Shared.Contracts.Api;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Backend.Secrets;
|
||||
|
||||
/// <summary>
|
||||
/// The built-in vault as a provider kind, so script bindings, the picker's
|
||||
/// listings and dispatch-time resolution treat it like any external store.
|
||||
/// It has no config: the secrets live in this server's database.
|
||||
/// </summary>
|
||||
public sealed class BuiltInVaultDriver(IServiceScopeFactory scopes) : ISecretsProviderDriver
|
||||
{
|
||||
public string Kind => BuiltInVault.Kind;
|
||||
|
||||
public string DisplayName => BuiltInVault.DisplayName;
|
||||
|
||||
public IReadOnlyList<string> SecretFields { get; } = [];
|
||||
|
||||
public IReadOnlyList<ConfigField> Fields { get; } = [];
|
||||
|
||||
public async Task<List<S3TestStepDto>> TestAsync(string configJson, CancellationToken cancellationToken)
|
||||
{
|
||||
var steps = new List<S3TestStepDto>();
|
||||
await using var scope = scopes.CreateAsyncScope();
|
||||
var vault = scope.ServiceProvider.GetRequiredService<VaultService>();
|
||||
|
||||
try
|
||||
{
|
||||
steps.Add(new S3TestStepDto("database", true, $"{await vault.CountAsync(cancellationToken)} secret(s)"));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
steps.Add(new S3TestStepDto("database", false, ex.Message));
|
||||
return steps;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
steps.Add(vault.KeyRingWorks()
|
||||
? new S3TestStepDto("encryption", true, "key ring round trip ok")
|
||||
: new S3TestStepDto("encryption", false, "key ring round trip returned a different value"));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
steps.Add(new S3TestStepDto("encryption", false, ex.Message));
|
||||
}
|
||||
|
||||
return steps;
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<string>> ListSecretNamesAsync(string configJson, string? path, CancellationToken cancellationToken)
|
||||
=> WithVaultAsync(vault => vault.NamesAsync(path, cancellationToken));
|
||||
|
||||
public Task<IReadOnlyList<string>> ListFolderPathsAsync(string configJson, string? path, CancellationToken cancellationToken)
|
||||
=> WithVaultAsync(vault => vault.FolderPathsAsync(path, cancellationToken));
|
||||
|
||||
public Task<string> GetSecretAsync(string configJson, string secretName, string? path, CancellationToken cancellationToken)
|
||||
=> WithVaultAsync(vault => vault.GetValueAsync(path, secretName, cancellationToken));
|
||||
|
||||
private async Task<T> WithVaultAsync<T>(Func<VaultService, Task<T>> action)
|
||||
{
|
||||
await using var scope = scopes.CreateAsyncScope();
|
||||
try
|
||||
{
|
||||
return await action(scope.ServiceProvider.GetRequiredService<VaultService>());
|
||||
}
|
||||
catch (VaultException ex)
|
||||
{
|
||||
throw new SecretResolutionException(ex.Message, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,10 @@ using Shared.Contracts.Api;
|
||||
namespace Backend.Secrets;
|
||||
|
||||
/// <summary>
|
||||
/// One kind of external secrets store. Drivers are stateless singletons; the
|
||||
/// per-provider connection settings arrive as the decrypted driver-specific
|
||||
/// config JSON. Register additional implementations to add providers.
|
||||
/// One kind of secrets store, external or the built-in vault. Drivers are
|
||||
/// stateless singletons; the per-provider connection settings arrive as the
|
||||
/// decrypted driver-specific config JSON. Register additional implementations
|
||||
/// to add providers.
|
||||
/// </summary>
|
||||
public interface ISecretsProviderDriver
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Backend.Auth;
|
||||
using Backend.Security;
|
||||
using Shared.Contracts.Api;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Backend.Secrets;
|
||||
|
||||
@@ -59,7 +60,7 @@ public static class SecretsEndpoints
|
||||
{
|
||||
var providers = await service.ListAsync(cancellationToken);
|
||||
var kinds = service.Drivers
|
||||
.Select(d => new { kind = d.Kind, displayName = d.DisplayName, fields = d.Fields })
|
||||
.Select(d => new { kind = d.Kind, displayName = d.DisplayName, fields = d.Fields, builtIn = d.Kind == BuiltInVault.Kind })
|
||||
.ToList();
|
||||
return Results.Ok(new { providers, kinds });
|
||||
}
|
||||
@@ -96,6 +97,11 @@ public static class SecretsEndpoints
|
||||
return problem;
|
||||
}
|
||||
|
||||
if (SecretsProviderService.IsBuiltIn(id))
|
||||
{
|
||||
return Results.BadRequest(new { error = "The built-in vault has no settings to change." });
|
||||
}
|
||||
|
||||
var entity = await service.FindAsync(id, cancellationToken);
|
||||
if (entity is null)
|
||||
{
|
||||
@@ -117,6 +123,11 @@ public static class SecretsEndpoints
|
||||
HttpContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (SecretsProviderService.IsBuiltIn(id))
|
||||
{
|
||||
return Results.BadRequest(new { error = "The built-in vault cannot be deleted." });
|
||||
}
|
||||
|
||||
var entity = await service.FindAsync(id, cancellationToken);
|
||||
if (entity is null)
|
||||
{
|
||||
@@ -188,6 +199,11 @@ public static class SecretsEndpoints
|
||||
return Results.BadRequest(new { error = $"Unknown provider kind “{request.Kind}”." });
|
||||
}
|
||||
|
||||
if (string.Equals(request.Kind, BuiltInVault.Kind, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return Results.BadRequest(new { error = "The built-in vault is always there; it cannot be added." });
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,8 @@ namespace Backend.Secrets;
|
||||
/// <summary>
|
||||
/// Stores secrets provider configurations (encrypted at rest with Data
|
||||
/// Protection) and resolves script secret bindings server-side, so agents
|
||||
/// and browsers never hold vault credentials or contact the vault.
|
||||
/// and browsers never hold vault credentials or contact the vault. The
|
||||
/// built-in vault is always listed, under a fixed id, without a stored row.
|
||||
/// </summary>
|
||||
public sealed class SecretsProviderService(
|
||||
AppDbContext db,
|
||||
@@ -26,16 +27,31 @@ public sealed class SecretsProviderService(
|
||||
public ISecretsProviderDriver? Driver(string kind)
|
||||
=> drivers.FirstOrDefault(d => string.Equals(d.Kind, kind, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>Every provider, the built-in vault first (so it is the picker's default).</summary>
|
||||
public async Task<List<SecretsProviderDto>> ListAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var rows = await db.SecretsProviders.AsNoTracking()
|
||||
.OrderBy(p => p.Name)
|
||||
.ToListAsync(cancellationToken);
|
||||
return rows.Select(ToDto).ToList();
|
||||
return rows.Prepend(BuiltIn()).Select(ToDto).ToList();
|
||||
}
|
||||
|
||||
public Task<SecretsProviderEntity?> FindAsync(Guid id, CancellationToken cancellationToken)
|
||||
=> db.SecretsProviders.SingleOrDefaultAsync(p => p.Id == id, cancellationToken);
|
||||
/// <summary>A stored provider, or the built-in vault's stand-in (never tracked, never saved).</summary>
|
||||
public async Task<SecretsProviderEntity?> FindAsync(Guid id, CancellationToken cancellationToken)
|
||||
=> IsBuiltIn(id) ? BuiltIn() : await db.SecretsProviders.SingleOrDefaultAsync(p => p.Id == id, cancellationToken);
|
||||
|
||||
public static bool IsBuiltIn(Guid id) => id == BuiltInVault.ProviderId;
|
||||
|
||||
/// <summary>The built-in vault has no provider row: every server has it, with nothing to configure.</summary>
|
||||
private static SecretsProviderEntity BuiltIn() => new()
|
||||
{
|
||||
Id = BuiltInVault.ProviderId,
|
||||
Name = BuiltInVault.DisplayName,
|
||||
Kind = BuiltInVault.Kind,
|
||||
ConfigProtected = string.Empty,
|
||||
CreatedUtc = DateTimeOffset.UnixEpoch,
|
||||
UpdatedUtc = DateTimeOffset.UnixEpoch,
|
||||
};
|
||||
|
||||
public async Task<SecretsProviderDto> CreateAsync(
|
||||
SaveSecretsProviderRequest request, string? actor, CancellationToken cancellationToken)
|
||||
@@ -99,6 +115,10 @@ public sealed class SecretsProviderService(
|
||||
var providers = await db.SecretsProviders.AsNoTracking()
|
||||
.Where(p => providerIds.Contains(p.Id))
|
||||
.ToDictionaryAsync(p => p.Id, cancellationToken);
|
||||
if (providerIds.Any(IsBuiltIn))
|
||||
{
|
||||
providers[BuiltInVault.ProviderId] = BuiltIn();
|
||||
}
|
||||
|
||||
var configCache = new Dictionary<Guid, string>();
|
||||
var result = new List<ScriptSecret>(bindings.Count);
|
||||
@@ -156,11 +176,16 @@ public sealed class SecretsProviderService(
|
||||
.ToList();
|
||||
|
||||
return new SecretsProviderDto(
|
||||
entity.Id, entity.Name, entity.Kind, sanitized, set, entity.UpdatedUtc, entity.UpdatedBy);
|
||||
entity.Id, entity.Name, entity.Kind, sanitized, set, entity.UpdatedUtc, entity.UpdatedBy, IsBuiltIn(entity.Id));
|
||||
}
|
||||
|
||||
private Dictionary<string, string?> DecryptConfig(SecretsProviderEntity entity)
|
||||
{
|
||||
if (IsBuiltIn(entity.Id))
|
||||
{
|
||||
return new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var json = protector.Unprotect(entity.ConfigProtected);
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
using Backend.Auth;
|
||||
using Backend.Security;
|
||||
using Shared.Contracts.Api;
|
||||
|
||||
namespace Backend.Secrets;
|
||||
|
||||
/// <summary>
|
||||
/// The built-in vault's console API. Listings carry names and folders only;
|
||||
/// a value leaves the server through the reveal call alone, which needs its
|
||||
/// own permission and is audited. Every change is audited too, never with
|
||||
/// the value.
|
||||
/// </summary>
|
||||
public static class VaultEndpoints
|
||||
{
|
||||
public static void Map(WebApplication app)
|
||||
{
|
||||
app.MapGet(ApiRoutes.Vault, ListAsync).RequirePermission(Permissions.SecretsUse);
|
||||
app.MapPost(ApiRoutes.VaultFolders, CreateFolderAsync).RequirePermission(Permissions.SecretsManage);
|
||||
app.MapDelete(ApiRoutes.VaultFolders, DeleteFolderAsync).RequirePermission(Permissions.SecretsManage);
|
||||
app.MapPost(ApiRoutes.VaultFolderMove, MoveFolderAsync).RequirePermission(Permissions.SecretsManage);
|
||||
app.MapPost(ApiRoutes.VaultSecrets, CreateAsync).RequirePermission(Permissions.SecretsManage);
|
||||
app.MapPut(ApiRoutes.VaultSecret, UpdateAsync).RequirePermission(Permissions.SecretsManage);
|
||||
app.MapDelete(ApiRoutes.VaultSecret, DeleteAsync).RequirePermission(Permissions.SecretsManage);
|
||||
app.MapPost(ApiRoutes.VaultSecretReveal, RevealAsync).RequirePermission(Permissions.SecretsReveal);
|
||||
}
|
||||
|
||||
private static Task<IResult> ListAsync(string? path, VaultService vault, CancellationToken cancellationToken)
|
||||
=> GuardAsync(async () => Results.Ok(await vault.ListAsync(path, cancellationToken)));
|
||||
|
||||
private static Task<IResult> CreateFolderAsync(
|
||||
VaultFolderRequest request, VaultService vault, AuditService audit, HttpContext context,
|
||||
CancellationToken cancellationToken)
|
||||
=> GuardAsync(async () =>
|
||||
{
|
||||
var path = await vault.CreateFolderAsync(request.Path, Actor(context), cancellationToken);
|
||||
await LogAsync(audit, context, "vault-folder-created", path, cancellationToken);
|
||||
return Results.Ok(new VaultFolderDto(path, path[(path.LastIndexOf('/') + 1)..]));
|
||||
});
|
||||
|
||||
private static Task<IResult> MoveFolderAsync(
|
||||
MoveVaultFolderRequest request, VaultService vault, AuditService audit, HttpContext context,
|
||||
CancellationToken cancellationToken)
|
||||
=> GuardAsync(async () =>
|
||||
{
|
||||
var (from, to, count) = await vault.MoveFolderAsync(request.From, request.To, Actor(context), cancellationToken);
|
||||
await LogAsync(audit, context, "vault-folder-moved", $"{from} → {to} ({count} secret(s))", cancellationToken);
|
||||
return Results.Ok(new VaultFolderDto(to, to[(to.LastIndexOf('/') + 1)..]));
|
||||
});
|
||||
|
||||
private static Task<IResult> DeleteFolderAsync(
|
||||
string? path, VaultService vault, AuditService audit, HttpContext context, CancellationToken cancellationToken)
|
||||
=> GuardAsync(async () =>
|
||||
{
|
||||
var (folder, count) = await vault.DeleteFolderAsync(path ?? string.Empty, cancellationToken);
|
||||
await LogAsync(audit, context, "vault-folder-deleted", $"{folder} ({count} secret(s))", cancellationToken);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
private static Task<IResult> CreateAsync(
|
||||
SaveVaultSecretRequest request, VaultService vault, AuditService audit, HttpContext context,
|
||||
CancellationToken cancellationToken)
|
||||
=> GuardAsync(async () =>
|
||||
{
|
||||
var dto = await vault.CreateAsync(request, Actor(context), cancellationToken);
|
||||
await LogAsync(audit, context, "vault-secret-created", Describe(dto), cancellationToken);
|
||||
return Results.Created(ApiRoutes.For.VaultSecret(dto.Id), dto);
|
||||
});
|
||||
|
||||
private static Task<IResult> UpdateAsync(
|
||||
Guid id, SaveVaultSecretRequest request, VaultService vault, AuditService audit, HttpContext context,
|
||||
CancellationToken cancellationToken)
|
||||
=> GuardAsync(async () =>
|
||||
{
|
||||
var entity = await vault.FindAsync(id, cancellationToken);
|
||||
if (entity is null)
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
|
||||
var change = await vault.UpdateAsync(entity, request, Actor(context), cancellationToken);
|
||||
var detail = Describe(change.Secret)
|
||||
+ (change.ValueChanged ? ", value changed" : string.Empty)
|
||||
+ (change.MovedFrom is { } before ? $", moved from {before}" : string.Empty);
|
||||
await LogAsync(audit, context, "vault-secret-updated", detail, cancellationToken);
|
||||
return Results.Ok(change.Secret);
|
||||
});
|
||||
|
||||
private static Task<IResult> DeleteAsync(
|
||||
Guid id, VaultService vault, AuditService audit, HttpContext context, CancellationToken cancellationToken)
|
||||
=> GuardAsync(async () =>
|
||||
{
|
||||
var entity = await vault.FindAsync(id, cancellationToken);
|
||||
if (entity is null)
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
|
||||
var detail = Describe(VaultService.ToDto(entity));
|
||||
await vault.DeleteAsync(entity, cancellationToken);
|
||||
await LogAsync(audit, context, "vault-secret-deleted", detail, cancellationToken);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
private static Task<IResult> RevealAsync(
|
||||
Guid id, VaultService vault, AuditService audit, HttpContext context, CancellationToken cancellationToken)
|
||||
=> GuardAsync(async () =>
|
||||
{
|
||||
var entity = await vault.FindAsync(id, cancellationToken);
|
||||
if (entity is null)
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
|
||||
var revealed = vault.Reveal(entity);
|
||||
// Audited before the value leaves: a reveal that cannot be recorded does not happen.
|
||||
await LogAsync(audit, context, "vault-secret-revealed", Describe(VaultService.ToDto(entity)), cancellationToken);
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
return Results.Ok(revealed);
|
||||
});
|
||||
|
||||
private static string? Actor(HttpContext context) => context.User.Identity?.Name;
|
||||
|
||||
private static string Describe(VaultSecretDto secret) => $"{VaultPaths.Join(secret.Path, secret.Name)} v{secret.Version}";
|
||||
|
||||
private static Task LogAsync(AuditService audit, HttpContext context, string action, string detail, CancellationToken cancellationToken)
|
||||
=> audit.LogAsync(AuditCategories.Secrets, action, Actor(context), detail: detail,
|
||||
remoteIp: Proxy.ClientIp.EffectiveText(context), cancellationToken: cancellationToken);
|
||||
|
||||
private static async Task<IResult> GuardAsync(Func<Task<IResult>> action)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await action();
|
||||
}
|
||||
catch (VaultException ex)
|
||||
{
|
||||
return Results.Json(new { error = ex.Message }, statusCode: ex.StatusCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
using System.Security.Cryptography;
|
||||
using Backend.Data;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shared.Contracts.Api;
|
||||
|
||||
namespace Backend.Secrets;
|
||||
|
||||
/// <summary>A vault request the caller can fix. Message is value-free.</summary>
|
||||
public sealed class VaultException(string message, int statusCode = StatusCodes.Status400BadRequest)
|
||||
: Exception(message)
|
||||
{
|
||||
public int StatusCode { get; } = statusCode;
|
||||
}
|
||||
|
||||
/// <summary>Folder and name rules for the built-in vault.</summary>
|
||||
public static class VaultPaths
|
||||
{
|
||||
public const int MaxPathLength = 512;
|
||||
public const int MaxSegmentLength = 100;
|
||||
public const int MaxNameLength = 200;
|
||||
public const int MaxValueLength = 64 * 1024;
|
||||
|
||||
/// <summary>"/" or "/a/b": slashes collapsed, segments trimmed, no "." or "..".</summary>
|
||||
public static string NormalizePath(string? path)
|
||||
{
|
||||
var segments = (path ?? string.Empty)
|
||||
.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
foreach (var segment in segments)
|
||||
{
|
||||
if (segment is "." or "..")
|
||||
{
|
||||
throw new VaultException("A folder cannot be named “.” or “..”.");
|
||||
}
|
||||
|
||||
if (segment.Length > MaxSegmentLength)
|
||||
{
|
||||
throw new VaultException($"Folder names are at most {MaxSegmentLength} characters.");
|
||||
}
|
||||
|
||||
if (segment.Any(char.IsControl))
|
||||
{
|
||||
throw new VaultException("Folder names cannot hold control characters.");
|
||||
}
|
||||
}
|
||||
|
||||
var normalized = "/" + string.Join('/', segments);
|
||||
return normalized.Length <= MaxPathLength
|
||||
? normalized
|
||||
: throw new VaultException($"Folder paths are at most {MaxPathLength} characters.");
|
||||
}
|
||||
|
||||
public static string NormalizeName(string? name)
|
||||
{
|
||||
var trimmed = (name ?? string.Empty).Trim();
|
||||
if (trimmed.Length == 0)
|
||||
{
|
||||
throw new VaultException("A secret name is required.");
|
||||
}
|
||||
|
||||
if (trimmed.Length > MaxNameLength)
|
||||
{
|
||||
throw new VaultException($"Secret names are at most {MaxNameLength} characters.");
|
||||
}
|
||||
|
||||
return trimmed.Contains('/') || trimmed.Any(char.IsControl)
|
||||
? throw new VaultException("Secret names cannot hold “/” or control characters.")
|
||||
: trimmed;
|
||||
}
|
||||
|
||||
/// <summary>Case-insensitive key; upper-casing keeps the length, so prefixes line up with the original.</summary>
|
||||
public static string Key(string value) => value.ToUpperInvariant();
|
||||
|
||||
public static string Join(string folder, string child) => folder == "/" ? "/" + child : $"{folder}/{child}";
|
||||
|
||||
/// <summary>Whether <paramref name="pathKey"/> is <paramref name="folderKey"/> or inside it.</summary>
|
||||
public static bool IsWithin(string pathKey, string folderKey)
|
||||
=> folderKey == "/" || pathKey == folderKey || pathKey.StartsWith(folderKey + "/", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>What an update changed, for the audit trail (never the value).</summary>
|
||||
public sealed record VaultSecretChange(VaultSecretDto Secret, bool ValueChanged, string? MovedFrom);
|
||||
|
||||
/// <summary>
|
||||
/// The built-in vault: secrets in the application database, values encrypted
|
||||
/// with the server's Data Protection key ring (shared by every replica), so
|
||||
/// any node reads what another wrote. Folders exist explicitly (created
|
||||
/// empty) or implicitly (a secret's path); both list the same way.
|
||||
/// </summary>
|
||||
public sealed class VaultService(AppDbContext db, IDataProtectionProvider protectionProvider)
|
||||
{
|
||||
private readonly IDataProtector protector = protectionProvider.CreateProtector("Backend.Vault.v1");
|
||||
|
||||
public async Task<VaultListingDto> ListAsync(string? path, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = await CanonicalAsync(VaultPaths.NormalizePath(path), cancellationToken);
|
||||
var key = VaultPaths.Key(folder);
|
||||
var secrets = await db.VaultSecrets.AsNoTracking()
|
||||
.Where(s => s.PathKey == key)
|
||||
.ToListAsync(cancellationToken);
|
||||
return new VaultListingDto(
|
||||
folder,
|
||||
await ChildFoldersAsync(folder, cancellationToken),
|
||||
secrets.OrderBy(s => s.Name, StringComparer.OrdinalIgnoreCase).Select(ToDto).ToList());
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<string>> NamesAsync(string? path, CancellationToken cancellationToken)
|
||||
{
|
||||
var key = VaultPaths.Key(VaultPaths.NormalizePath(path));
|
||||
var names = await db.VaultSecrets.AsNoTracking()
|
||||
.Where(s => s.PathKey == key)
|
||||
.Select(s => s.Name)
|
||||
.ToListAsync(cancellationToken);
|
||||
return names.Order(StringComparer.OrdinalIgnoreCase).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<string>> FolderPathsAsync(string? path, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = await CanonicalAsync(VaultPaths.NormalizePath(path), cancellationToken);
|
||||
return (await ChildFoldersAsync(folder, cancellationToken)).Select(f => f.Path).ToList();
|
||||
}
|
||||
|
||||
/// <summary>One value, for a script binding. Callers must never log the result.</summary>
|
||||
public async Task<string> GetValueAsync(string? path, string name, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = VaultPaths.NormalizePath(path);
|
||||
var secretName = VaultPaths.NormalizeName(name);
|
||||
var (pathKey, nameKey) = (VaultPaths.Key(folder), VaultPaths.Key(secretName));
|
||||
var entity = await db.VaultSecrets.AsNoTracking()
|
||||
.SingleOrDefaultAsync(s => s.PathKey == pathKey && s.NameKey == nameKey, cancellationToken)
|
||||
?? throw new VaultException($"No secret “{secretName}” in “{folder}”.", StatusCodes.Status404NotFound);
|
||||
return Unprotect(entity);
|
||||
}
|
||||
|
||||
public Task<VaultSecretEntity?> FindAsync(Guid id, CancellationToken cancellationToken)
|
||||
=> db.VaultSecrets.SingleOrDefaultAsync(s => s.Id == id, cancellationToken);
|
||||
|
||||
public Task<int> CountAsync(CancellationToken cancellationToken) => db.VaultSecrets.CountAsync(cancellationToken);
|
||||
|
||||
public async Task<VaultSecretDto> CreateAsync(SaveVaultSecretRequest request, string? actor, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = await CanonicalAsync(VaultPaths.NormalizePath(request.Path), cancellationToken);
|
||||
var name = VaultPaths.NormalizeName(request.Name);
|
||||
var value = RequireValue(request.Value);
|
||||
await EnsureFreeAsync(folder, name, null, cancellationToken);
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var entity = new VaultSecretEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Path = folder,
|
||||
PathKey = VaultPaths.Key(folder),
|
||||
Name = name,
|
||||
NameKey = VaultPaths.Key(name),
|
||||
ValueProtected = protector.Protect(value),
|
||||
Version = 1,
|
||||
CreatedUtc = now,
|
||||
CreatedBy = actor,
|
||||
UpdatedUtc = now,
|
||||
UpdatedBy = actor,
|
||||
};
|
||||
db.VaultSecrets.Add(entity);
|
||||
await SaveAsync(cancellationToken);
|
||||
return ToDto(entity);
|
||||
}
|
||||
|
||||
/// <summary>Renames, moves and/or replaces the value. Every save counts as a new version.</summary>
|
||||
public async Task<VaultSecretChange> UpdateAsync(
|
||||
VaultSecretEntity entity, SaveVaultSecretRequest request, string? actor, CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.Version is { } expected && expected != entity.Version)
|
||||
{
|
||||
throw Changed();
|
||||
}
|
||||
|
||||
var folder = await CanonicalAsync(VaultPaths.NormalizePath(request.Path), cancellationToken);
|
||||
var name = VaultPaths.NormalizeName(request.Name);
|
||||
var value = request.Value is null ? null : RequireValue(request.Value);
|
||||
await EnsureFreeAsync(folder, name, entity.Id, cancellationToken);
|
||||
|
||||
var before = VaultPaths.Join(entity.Path, entity.Name);
|
||||
entity.Path = folder;
|
||||
entity.PathKey = VaultPaths.Key(folder);
|
||||
entity.Name = name;
|
||||
entity.NameKey = VaultPaths.Key(name);
|
||||
if (value is not null)
|
||||
{
|
||||
entity.ValueProtected = protector.Protect(value);
|
||||
}
|
||||
|
||||
entity.Version++;
|
||||
entity.UpdatedUtc = DateTimeOffset.UtcNow;
|
||||
entity.UpdatedBy = actor;
|
||||
await SaveAsync(cancellationToken);
|
||||
|
||||
var after = VaultPaths.Join(folder, name);
|
||||
return new VaultSecretChange(ToDto(entity), value is not null, before == after ? null : before);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(VaultSecretEntity entity, CancellationToken cancellationToken)
|
||||
{
|
||||
db.VaultSecrets.Remove(entity);
|
||||
await SaveAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The value, for a person allowed to see it. The caller audits the reveal.</summary>
|
||||
public RevealedVaultSecretDto Reveal(VaultSecretEntity entity) => new(Unprotect(entity), entity.Version);
|
||||
|
||||
public async Task<string> CreateFolderAsync(string path, string? actor, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = await CanonicalAsync(VaultPaths.NormalizePath(path), cancellationToken);
|
||||
if (folder == "/")
|
||||
{
|
||||
throw new VaultException("A folder name is required.");
|
||||
}
|
||||
|
||||
if (await FolderExistsAsync(VaultPaths.Key(folder), cancellationToken))
|
||||
{
|
||||
throw new VaultException($"“{folder}” already exists.", StatusCodes.Status409Conflict);
|
||||
}
|
||||
|
||||
db.VaultFolders.Add(new VaultFolderEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Path = folder,
|
||||
PathKey = VaultPaths.Key(folder),
|
||||
CreatedUtc = DateTimeOffset.UtcNow,
|
||||
CreatedBy = actor,
|
||||
});
|
||||
await SaveAsync(cancellationToken);
|
||||
return folder;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renames or moves a folder with everything in it. Refused when a secret
|
||||
/// of the same name already lives at the destination. Returns the folder's
|
||||
/// new path and how many secrets moved.
|
||||
/// </summary>
|
||||
public async Task<(string From, string To, int Secrets)> MoveFolderAsync(
|
||||
string from, string to, string? actor, CancellationToken cancellationToken)
|
||||
{
|
||||
var source = await CanonicalAsync(VaultPaths.NormalizePath(from), cancellationToken);
|
||||
var target = VaultPaths.NormalizePath(to);
|
||||
if (source == "/" || target == "/")
|
||||
{
|
||||
throw new VaultException("The top of the vault cannot be moved or replaced.");
|
||||
}
|
||||
|
||||
// Adopt the casing of the destination's existing parents, but keep the
|
||||
// last segment as typed: a case-only rename is a rename.
|
||||
var cut = target.LastIndexOf('/');
|
||||
var parent = await CanonicalAsync(cut == 0 ? "/" : target[..cut], cancellationToken);
|
||||
target = VaultPaths.Join(parent, target[(cut + 1)..]);
|
||||
|
||||
var (sourceKey, targetKey) = (VaultPaths.Key(source), VaultPaths.Key(target));
|
||||
if (sourceKey != targetKey && VaultPaths.IsWithin(targetKey, sourceKey))
|
||||
{
|
||||
throw new VaultException("A folder cannot move inside itself.");
|
||||
}
|
||||
|
||||
if (!await FolderExistsAsync(sourceKey, cancellationToken))
|
||||
{
|
||||
throw new VaultException($"“{source}” does not exist.", StatusCodes.Status404NotFound);
|
||||
}
|
||||
|
||||
var secrets = await Within(db.VaultSecrets, sourceKey).ToListAsync(cancellationToken);
|
||||
var folders = await WithinFolders(sourceKey).ToListAsync(cancellationToken);
|
||||
string Rebase(string path) => target + path[source.Length..];
|
||||
|
||||
if (sourceKey != targetKey)
|
||||
{
|
||||
var taken = (await Within(db.VaultSecrets.AsNoTracking(), targetKey)
|
||||
.Select(s => new { s.PathKey, s.NameKey, s.Path, s.Name })
|
||||
.ToListAsync(cancellationToken))
|
||||
.ToDictionary(s => (s.PathKey, s.NameKey), s => VaultPaths.Join(s.Path, s.Name));
|
||||
var clash = secrets.FirstOrDefault(s => taken.ContainsKey((VaultPaths.Key(Rebase(s.Path)), s.NameKey)));
|
||||
if (clash is not null)
|
||||
{
|
||||
throw new VaultException(
|
||||
$"“{taken[(VaultPaths.Key(Rebase(clash.Path)), clash.NameKey)]}” already exists.",
|
||||
StatusCodes.Status409Conflict);
|
||||
}
|
||||
}
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
foreach (var secret in secrets)
|
||||
{
|
||||
secret.Path = Rebase(secret.Path);
|
||||
secret.PathKey = VaultPaths.Key(secret.Path);
|
||||
secret.Version++;
|
||||
secret.UpdatedUtc = now;
|
||||
secret.UpdatedBy = actor;
|
||||
}
|
||||
|
||||
// Folder rows merge into any already at the destination.
|
||||
var existing = sourceKey == targetKey
|
||||
? []
|
||||
: (await WithinFolders(targetKey).Select(f => f.PathKey).ToListAsync(cancellationToken)).ToHashSet();
|
||||
foreach (var folder in folders)
|
||||
{
|
||||
var path = Rebase(folder.Path);
|
||||
if (existing.Contains(VaultPaths.Key(path)))
|
||||
{
|
||||
db.VaultFolders.Remove(folder);
|
||||
continue;
|
||||
}
|
||||
|
||||
folder.Path = path;
|
||||
folder.PathKey = VaultPaths.Key(path);
|
||||
}
|
||||
|
||||
await SaveAsync(cancellationToken);
|
||||
return (source, target, secrets.Count);
|
||||
}
|
||||
|
||||
/// <summary>Deletes a folder and every secret in it. Returns the folder's path and how many secrets went.</summary>
|
||||
public async Task<(string Path, int Secrets)> DeleteFolderAsync(string path, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = await CanonicalAsync(VaultPaths.NormalizePath(path), cancellationToken);
|
||||
if (folder == "/")
|
||||
{
|
||||
throw new VaultException("The top of the vault cannot be deleted.");
|
||||
}
|
||||
|
||||
var key = VaultPaths.Key(folder);
|
||||
var secrets = await Within(db.VaultSecrets, key).ToListAsync(cancellationToken);
|
||||
var folders = await WithinFolders(key).ToListAsync(cancellationToken);
|
||||
if (secrets.Count == 0 && folders.Count == 0)
|
||||
{
|
||||
throw new VaultException($"“{folder}” does not exist.", StatusCodes.Status404NotFound);
|
||||
}
|
||||
|
||||
db.VaultSecrets.RemoveRange(secrets);
|
||||
db.VaultFolders.RemoveRange(folders);
|
||||
await SaveAsync(cancellationToken);
|
||||
return (folder, secrets.Count);
|
||||
}
|
||||
|
||||
/// <summary>Round-trips a value through the key ring, for the provider test.</summary>
|
||||
public bool KeyRingWorks()
|
||||
{
|
||||
var probe = Guid.NewGuid().ToString("N");
|
||||
return protector.Unprotect(protector.Protect(probe)) == probe;
|
||||
}
|
||||
|
||||
public static VaultSecretDto ToDto(VaultSecretEntity entity) => new(
|
||||
entity.Id, entity.Path, entity.Name, entity.Version,
|
||||
entity.CreatedUtc, entity.CreatedBy, entity.UpdatedUtc, entity.UpdatedBy);
|
||||
|
||||
private string Unprotect(VaultSecretEntity entity)
|
||||
{
|
||||
try
|
||||
{
|
||||
return protector.Unprotect(entity.ValueProtected);
|
||||
}
|
||||
catch (CryptographicException)
|
||||
{
|
||||
throw new VaultException(
|
||||
$"“{VaultPaths.Join(entity.Path, entity.Name)}” could not be decrypted: this server's key ring does not hold its key.",
|
||||
StatusCodes.Status500InternalServerError);
|
||||
}
|
||||
}
|
||||
|
||||
private static string RequireValue(string? value)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
throw new VaultException("A value is required.");
|
||||
}
|
||||
|
||||
return value.Length <= VaultPaths.MaxValueLength
|
||||
? value
|
||||
: throw new VaultException($"Values are at most {VaultPaths.MaxValueLength / 1024} KiB.");
|
||||
}
|
||||
|
||||
private async Task EnsureFreeAsync(string folder, string name, Guid? self, CancellationToken cancellationToken)
|
||||
{
|
||||
var (pathKey, nameKey) = (VaultPaths.Key(folder), VaultPaths.Key(name));
|
||||
if (await db.VaultSecrets.AnyAsync(
|
||||
s => s.PathKey == pathKey && s.NameKey == nameKey && s.Id != self, cancellationToken))
|
||||
{
|
||||
throw new VaultException($"“{VaultPaths.Join(folder, name)}” already exists.", StatusCodes.Status409Conflict);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Saves, turning a lost race with another replica into a value-free conflict.</summary>
|
||||
private async Task SaveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
throw Changed();
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
// The unique keys: another node saved the same folder or name first.
|
||||
throw new VaultException("Something with that name was saved at the same time. Reload and retry.",
|
||||
StatusCodes.Status409Conflict);
|
||||
}
|
||||
}
|
||||
|
||||
private static VaultException Changed()
|
||||
=> new("Changed by someone else since it was opened. Reload and retry.", StatusCodes.Status409Conflict);
|
||||
|
||||
/// <summary>A folder exists while a folder row or a secret is at or below it.</summary>
|
||||
private async Task<bool> FolderExistsAsync(string key, CancellationToken cancellationToken)
|
||||
=> key == "/"
|
||||
|| await WithinFolders(key).AnyAsync(cancellationToken)
|
||||
|| await Within(db.VaultSecrets, key).AnyAsync(cancellationToken);
|
||||
|
||||
private static IQueryable<VaultSecretEntity> Within(IQueryable<VaultSecretEntity> secrets, string key)
|
||||
{
|
||||
var below = key + "/";
|
||||
return secrets.Where(s => s.PathKey == key || s.PathKey.StartsWith(below));
|
||||
}
|
||||
|
||||
private IQueryable<VaultFolderEntity> WithinFolders(string key)
|
||||
{
|
||||
var below = key + "/";
|
||||
return db.VaultFolders.Where(f => f.PathKey == key || f.PathKey.StartsWith(below));
|
||||
}
|
||||
|
||||
/// <summary>The folders directly inside <paramref name="folder"/>, explicit and implied.</summary>
|
||||
private async Task<IReadOnlyList<VaultFolderDto>> ChildFoldersAsync(string folder, CancellationToken cancellationToken)
|
||||
{
|
||||
var key = VaultPaths.Key(folder);
|
||||
var below = key == "/" ? "/" : key + "/";
|
||||
var explicitPaths = await db.VaultFolders.AsNoTracking()
|
||||
.Where(f => f.PathKey.StartsWith(below))
|
||||
.Select(f => f.Path)
|
||||
.ToListAsync(cancellationToken);
|
||||
var secretPaths = await db.VaultSecrets.AsNoTracking()
|
||||
.Where(s => s.PathKey.StartsWith(below))
|
||||
.Select(s => s.Path)
|
||||
.Distinct()
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var children = new Dictionary<string, VaultFolderDto>(StringComparer.Ordinal);
|
||||
foreach (var path in explicitPaths.Concat(secretPaths))
|
||||
{
|
||||
if (path.Length <= below.Length || !VaultPaths.Key(path).StartsWith(below, StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var segment = path[below.Length..].Split('/')[0];
|
||||
children.TryAdd(VaultPaths.Key(segment), new VaultFolderDto(VaultPaths.Join(folder, segment), segment));
|
||||
}
|
||||
|
||||
return children.Values.OrderBy(f => f.Name, StringComparer.OrdinalIgnoreCase).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The path with the casing of the folders it already passes through, so
|
||||
/// "/prod/db" lands in an existing "/Prod" instead of beside it.
|
||||
/// </summary>
|
||||
private async Task<string> CanonicalAsync(string path, CancellationToken cancellationToken)
|
||||
{
|
||||
if (path == "/")
|
||||
{
|
||||
return path;
|
||||
}
|
||||
|
||||
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
var top = "/" + VaultPaths.Key(segments[0]);
|
||||
var known = (await WithinFolders(top).AsNoTracking().Select(f => f.Path).ToListAsync(cancellationToken))
|
||||
.Concat(await Within(db.VaultSecrets.AsNoTracking(), top).Select(s => s.Path).Distinct().ToListAsync(cancellationToken));
|
||||
|
||||
string[] best = [];
|
||||
foreach (var candidate in known)
|
||||
{
|
||||
var parts = candidate.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
var shared = 0;
|
||||
while (shared < parts.Length && shared < segments.Length
|
||||
&& VaultPaths.Key(parts[shared]) == VaultPaths.Key(segments[shared]))
|
||||
{
|
||||
shared++;
|
||||
}
|
||||
|
||||
if (shared > best.Length)
|
||||
{
|
||||
best = parts[..shared];
|
||||
}
|
||||
}
|
||||
|
||||
return "/" + string.Join('/', best.Concat(segments.Skip(best.Length)));
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,9 @@ public static class AuditCategories
|
||||
public const string Settings = "settings";
|
||||
public const string Automation = "automation";
|
||||
|
||||
/// <summary>The built-in vault: secrets created, changed, moved, deleted and revealed (never values).</summary>
|
||||
public const string Secrets = "secrets";
|
||||
|
||||
/// <summary>A device's own trail: enrolled, renamed, OS changed (see DeviceHistory).</summary>
|
||||
public const string Device = "device";
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ public static class SettingsEndpoints
|
||||
app.MapGet(ApiRoutes.S3Settings, GetS3Async).RequirePermission(Permissions.SettingsManage);
|
||||
app.MapPut(ApiRoutes.S3Settings, SaveS3Async).RequirePermission(Permissions.SettingsManage);
|
||||
app.MapPost(ApiRoutes.S3SettingsTest, TestS3Async).RequirePermission(Permissions.SettingsManage);
|
||||
app.MapGet(ApiRoutes.S3EmbeddedCredentials, RevealEmbeddedAsync).RequirePermission(Permissions.SettingsManage);
|
||||
|
||||
app.MapGet(ApiRoutes.AgentPackageStatus, AgentStatusAsync).RequirePermission(Permissions.SettingsManage);
|
||||
app.MapPost(ApiRoutes.AgentPackageOffload, OffloadAsync).RequirePermission(Permissions.SettingsManage);
|
||||
@@ -40,7 +41,7 @@ public static class SettingsEndpoints
|
||||
|
||||
private static async Task<IResult> GetS3Async(S3SettingsService settings, EmbeddedS3Store embedded, CancellationToken cancellationToken)
|
||||
{
|
||||
// The built-in store's credentials are never shown: the form's fields are always the external store's.
|
||||
// The form's fields are always the external store's; the built-in store's keys come only from the audited reveal.
|
||||
var effective = await settings.GetEffectiveAsync(cancellationToken);
|
||||
var external = await settings.GetExternalAsync(cancellationToken);
|
||||
return Results.Ok(new S3SettingsDto(
|
||||
@@ -61,6 +62,34 @@ public static class SettingsEndpoints
|
||||
Embedded: embedded.Allowed ? embedded.Status() : null));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The built-in store's keys, on demand. While it runs they are the keys it
|
||||
/// runs with (generated once, or the deployment's for a shared store);
|
||||
/// before that, the generated ones saved for it. Each reveal is audited.
|
||||
/// </summary>
|
||||
private static async Task<IResult> RevealEmbeddedAsync(
|
||||
S3SettingsService settings, EmbeddedS3Store embedded, AuditService audit, HttpContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!embedded.Allowed)
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
|
||||
var connection = embedded.Connection;
|
||||
var keys = connection is not null
|
||||
? (connection.AccessKey, connection.SecretKey)
|
||||
: await settings.GetEmbeddedCredentialsAsync(cancellationToken);
|
||||
if (keys is not { } found)
|
||||
{
|
||||
return Results.Conflict(new { error = "The built-in store has not started yet, so it has no keys." });
|
||||
}
|
||||
|
||||
await audit.LogAsync(AuditCategories.Admin, "s3-built-in-keys-revealed", context.User.Identity?.Name,
|
||||
cancellationToken: cancellationToken);
|
||||
return Results.Ok(new S3EmbeddedCredentialsDto(
|
||||
connection?.Endpoint ?? "", EmbeddedS3Store.Bucket, EmbeddedS3Store.Region, found.AccessKey, found.SecretKey));
|
||||
}
|
||||
|
||||
private static async Task<IResult> SaveS3Async(
|
||||
S3SettingsDto request,
|
||||
S3SettingsService settings,
|
||||
|
||||
@@ -9,15 +9,22 @@ namespace Backend.Standalone;
|
||||
/// <summary>
|
||||
/// Standalone-server commands for the combined single-binary deployment:
|
||||
///
|
||||
/// setup [--admin-user U] [--admin-password P] [--tls 0]
|
||||
/// setup [--tls 0] [--tls-source self-signed|store|file]
|
||||
/// [--tls-thumbprint T] [--tls-cert-file F] [--tls-key-file K] [--tls-password P]
|
||||
/// [--admin-user U] [--admin-password P]
|
||||
/// — generate NATS keys + sidecar config + appsettings,
|
||||
/// downloading nats-server for this platform if absent
|
||||
/// service install — register as a Windows service / systemd unit
|
||||
/// service uninstall — stop and remove the service
|
||||
/// purge [--yes] — remove the self-signed chain + generated state
|
||||
/// reset-admin [--user U] [--password P]
|
||||
/// — lockout recovery (AuthResetCli): a new one-time password
|
||||
///
|
||||
/// The same binary is the server: running it with no arguments starts the
|
||||
/// control plane (UI + API + WebSocket relay + optional NATS sidecar).
|
||||
/// control plane (UI + API + WebSocket relay + optional NATS sidecar). With no
|
||||
/// admin password given, the first start generates one, records it in
|
||||
/// data/initial-admin-password.txt for administrators only, and requires a new
|
||||
/// one at the first sign-in.
|
||||
/// </summary>
|
||||
public static class ServerCli
|
||||
{
|
||||
@@ -28,13 +35,22 @@ public static class ServerCli
|
||||
|
||||
public static async Task<int> RunSetupAsync(string[] args)
|
||||
{
|
||||
// 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. Port flags let several instances share a box
|
||||
// (one directory per instance; pair with `service install --name`).
|
||||
// Bare `setup` fully configures the server. The admin password is left
|
||||
// empty: the first start generates one, records it where only
|
||||
// administrators can read it and forces a new one at the first sign-in
|
||||
// (--admin-password still sets one, for scripted installs; the literal
|
||||
// old default "admin" forces the reset too). 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 adminPassword = "";
|
||||
var passwordDefaulted = false;
|
||||
// TLS source: the managed self-signed chain unless a certificate is given.
|
||||
string? tlsSourceText = null;
|
||||
string? tlsThumbprint = null;
|
||||
string? tlsCertFile = null;
|
||||
string? tlsKeyFile = null;
|
||||
string? tlsPassword = null;
|
||||
var httpPort = 9080;
|
||||
var bindAddress = "0.0.0.0";
|
||||
var natsPort = 4222;
|
||||
@@ -90,14 +106,34 @@ public static class ServerCli
|
||||
natsBind = natsCandidate;
|
||||
break;
|
||||
case "--admin-user":
|
||||
adminUser = args[++i];
|
||||
adminUser = args[++i] is { Length: > 0 } user ? user : "admin";
|
||||
break;
|
||||
case "--admin-password":
|
||||
adminPassword = args[++i];
|
||||
// The MSI passes the flag even when the wizard default was
|
||||
// kept: a literal "admin" password always forces the reset.
|
||||
// A silent install that still passes the old wizard default
|
||||
// (admin) gets the reset forced at the first sign-in.
|
||||
passwordDefaulted = adminPassword == "admin";
|
||||
break;
|
||||
case "--tls-source":
|
||||
case "--ts":
|
||||
tlsSourceText = args[++i];
|
||||
break;
|
||||
case "--tls-thumbprint":
|
||||
case "--tt":
|
||||
tlsThumbprint = args[++i];
|
||||
break;
|
||||
case "--tls-cert-file":
|
||||
case "--tf":
|
||||
tlsCertFile = args[++i];
|
||||
break;
|
||||
case "--tls-key-file":
|
||||
case "--tk":
|
||||
tlsKeyFile = args[++i];
|
||||
break;
|
||||
case "--tls-password":
|
||||
case "--tp":
|
||||
tlsPassword = args[++i];
|
||||
break;
|
||||
// Short aliases keep the MSI's custom-action command inside
|
||||
// the 255-character CustomAction table column (ICE03).
|
||||
case "--http-port":
|
||||
@@ -124,6 +160,35 @@ public static class ServerCli
|
||||
selfSignedTls = true;
|
||||
}
|
||||
|
||||
// A provided certificate (store or file) turns TLS on by itself and is
|
||||
// checked now, so a wrong thumbprint, path or password fails setup (and
|
||||
// the MSI) instead of the first start.
|
||||
Backend.Tls.TlsCertificateSource tlsSource;
|
||||
try
|
||||
{
|
||||
tlsThumbprint = Backend.Tls.TlsSettings.NormalizeThumbprint(tlsThumbprint);
|
||||
tlsCertFile = tlsCertFile is { Length: > 0 } ? Path.GetFullPath(tlsCertFile.Trim().Trim('"')) : null;
|
||||
tlsKeyFile = tlsKeyFile is { Length: > 0 } ? Path.GetFullPath(tlsKeyFile.Trim().Trim('"')) : null;
|
||||
tlsPassword = tlsPassword is { Length: > 0 } ? tlsPassword : null;
|
||||
tlsSource = Backend.Tls.TlsSettings.ParseSource(tlsSourceText, tlsThumbprint, tlsCertFile);
|
||||
}
|
||||
catch (InvalidOperationException exception)
|
||||
{
|
||||
return Fail(exception.Message.Replace("TLS_CERT_SOURCE", "--tls-source"));
|
||||
}
|
||||
|
||||
if (tlsSource != Backend.Tls.TlsCertificateSource.SelfSigned)
|
||||
{
|
||||
var problem = CheckProvidedCertificate(tlsSource, tlsThumbprint, tlsCertFile, tlsKeyFile, tlsPassword);
|
||||
if (problem is not null)
|
||||
{
|
||||
return Fail(problem);
|
||||
}
|
||||
}
|
||||
|
||||
var tlsOn = selfSignedTls || tlsSource != Backend.Tls.TlsCertificateSource.SelfSigned;
|
||||
selfSignedTls &= tlsSource == Backend.Tls.TlsCertificateSource.SelfSigned;
|
||||
|
||||
var baseDir = AppContext.BaseDirectory;
|
||||
var natsDir = Path.Combine(baseDir, "nats");
|
||||
var dataDir = Path.Combine(baseDir, "data");
|
||||
@@ -161,11 +226,12 @@ public static class ServerCli
|
||||
// The core protocol and monitor listeners are backend-only, so they
|
||||
// always stay on loopback. Only the WebSocket is proxy-facing; its bind
|
||||
// opens with --nats-bind for an edge proxy on another host, and when
|
||||
// that happens over self-signed TLS it reuses the server's own managed
|
||||
// leaf (data/tls) so nothing extra is generated. The loopback default
|
||||
// stays plaintext — the backend relays /messaging/* over loopback.
|
||||
// that happens over TLS it reuses the server's own leaf (data/tls: the
|
||||
// managed one, or a provided one mirrored there as PEM) so nothing extra
|
||||
// is generated. The loopback default stays plaintext — the backend
|
||||
// relays /messaging/* over loopback.
|
||||
var natsWsExposed = !System.Net.IPAddress.IsLoopback(System.Net.IPAddress.Parse(natsBind));
|
||||
var natsWsTls = selfSignedTls && natsWsExposed;
|
||||
var natsWsTls = tlsOn && natsWsExposed;
|
||||
var natsWsSecurity = natsWsTls
|
||||
? " tls {\n cert_file: \"../data/tls/server.crt\"\n key_file: \"../data/tls/server.key\"\n }"
|
||||
: " no_tls: true";
|
||||
@@ -211,9 +277,15 @@ public static class ServerCli
|
||||
{
|
||||
var signingSeed = File.ReadAllText(Path.Combine(secretsDir, "account-signing.nk")).Trim();
|
||||
var accountPublic = File.ReadAllText(Path.Combine(secretsDir, "account.pub")).Trim();
|
||||
var tlsSourceName = tlsSource switch
|
||||
{
|
||||
Backend.Tls.TlsCertificateSource.Store => "store",
|
||||
Backend.Tls.TlsCertificateSource.File => "file",
|
||||
_ => "self-signed",
|
||||
};
|
||||
File.WriteAllText(appsettings, $$"""
|
||||
{
|
||||
"Urls": "{{(selfSignedTls ? "https" : "http")}}://{{bindAddress}}:{{httpPort}}",
|
||||
"Urls": "{{(tlsOn ? "https" : "http")}}://{{bindAddress}}:{{httpPort}}",
|
||||
"DATA_PATH": "{{dataDir.Replace('\\', '/')}}",
|
||||
"DATABASE_PATH": "{{Path.Combine(dataDir, "db", "app.db").Replace('\\', '/')}}",
|
||||
"DATAPROTECTION_PATH": "{{Path.Combine(dataDir, "keys").Replace('\\', '/')}}",
|
||||
@@ -226,11 +298,17 @@ public static class ServerCli
|
||||
"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_USERNAME": {{Json(adminUser)}},
|
||||
"INITIAL_ADMIN_PASSWORD": {{Json(adminPassword)}},
|
||||
"INITIAL_ADMIN_MUST_CHANGE": "{{(passwordDefaulted ? "1" : "0")}}",
|
||||
|
||||
"TLS_SELF_SIGNED": "{{(selfSignedTls ? "1" : "0")}}",
|
||||
"TLS_CERT_SOURCE": "{{tlsSourceName}}",
|
||||
"TLS_CERT_THUMBPRINT": {{Json(tlsThumbprint)}},
|
||||
"TLS_CERT_FILE": {{Json(tlsCertFile?.Replace('\\', '/'))}},
|
||||
"TLS_CERT_KEY_FILE": {{Json(tlsKeyFile?.Replace('\\', '/'))}},
|
||||
"TLS_CERT_PASSWORD": {{Json(tlsPassword)}},
|
||||
"TLS_DISTRIBUTE_CA": "",
|
||||
"TLS_CERT_DIR": "",
|
||||
"PUBLIC_SERVER_URL": "",
|
||||
"TRUST_PROXY": "1",
|
||||
@@ -238,15 +316,29 @@ public static class ServerCli
|
||||
"TRUSTED_HOSTS": ""
|
||||
}
|
||||
""");
|
||||
ProtectSettingsFile(appsettings);
|
||||
Console.WriteLine($"Wrote {appsettings}");
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Setup complete.");
|
||||
Console.WriteLine(passwordDefaulted
|
||||
? $" - First sign-in: {adminUser} / admin — a new password is required immediately."
|
||||
: $" - First sign-in: {adminUser} / <your password>.");
|
||||
var scheme = selfSignedTls ? "https" : "http";
|
||||
Console.WriteLine(adminPassword.Length == 0
|
||||
? $" - First sign-in: {adminUser} with the one-time password the first start writes to {Path.Combine(dataDir, Backend.Auth.InitialAdminPasswordFile.FileName)} (administrators only); a new one is required immediately. Locked out? `reset-admin`."
|
||||
: passwordDefaulted
|
||||
? $" - First sign-in: {adminUser} / admin — a new password is required immediately."
|
||||
: $" - First sign-in: {adminUser} / <your password>.");
|
||||
if (tlsSource != Backend.Tls.TlsCertificateSource.SelfSigned)
|
||||
{
|
||||
Console.WriteLine(tlsSource == Backend.Tls.TlsCertificateSource.Store
|
||||
? $" - TLS: the certificate {tlsThumbprint} from LocalMachine\\My (renewals with the same subject and issuer are followed)."
|
||||
: $" - TLS: the certificate in {tlsCertFile} (replace the file to renew; it is reloaded within a minute).");
|
||||
if (natsWsTls && tlsSource == Backend.Tls.TlsCertificateSource.Store)
|
||||
{
|
||||
Console.WriteLine(" - The exposed NATS WebSocket serves the same certificate only when its private key is exportable.");
|
||||
}
|
||||
}
|
||||
|
||||
var scheme = tlsOn ? "https" : "http";
|
||||
Console.WriteLine($" - UI + API on {scheme}://{bindAddress}:{httpPort} (NATS on {natsBind}: {natsPort}/{natsWsPort}/{natsMonitorPort}).");
|
||||
if (selfSignedTls)
|
||||
{
|
||||
@@ -254,6 +346,7 @@ public static class ServerCli
|
||||
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($" Root and intermediate for Group Policy: {Path.Combine(dataDir, Backend.Tls.TlsSettings.DistributionFolderName)}.");
|
||||
}
|
||||
|
||||
Console.WriteLine(" - Run the binary directly, or `service install` to register the Windows service.");
|
||||
@@ -261,6 +354,78 @@ public static class ServerCli
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>A JSON string literal (quotes and escapes included); null is "".</summary>
|
||||
private static string Json(string? value) => System.Text.Json.JsonSerializer.Serialize(value ?? string.Empty);
|
||||
|
||||
/// <summary>Loads the certificate the way the server will; the reason it cannot be used, or null.</summary>
|
||||
private static string? CheckProvidedCertificate(
|
||||
Backend.Tls.TlsCertificateSource source, string? thumbprint, string? certificateFile, string? keyFile, string? password)
|
||||
{
|
||||
try
|
||||
{
|
||||
var settings = new Backend.Tls.TlsSettings
|
||||
{
|
||||
Enabled = true,
|
||||
Source = source,
|
||||
StoreThumbprint = thumbprint,
|
||||
CertificateFile = certificateFile,
|
||||
KeyFile = keyFile,
|
||||
CertificatePassword = password,
|
||||
CertificateDirectory = Path.GetTempPath(),
|
||||
UseWindowsStore = false,
|
||||
};
|
||||
new Backend.Tls.ProvidedTlsCertificate(settings).Refresh(Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance);
|
||||
return null;
|
||||
}
|
||||
catch (Exception exception) when (exception is InvalidOperationException or IOException or UnauthorizedAccessException
|
||||
or System.Security.Cryptography.CryptographicException or ArgumentException)
|
||||
{
|
||||
return $"The TLS certificate cannot be used: {exception.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// appsettings.json carries the NATS signing seed and any certificate
|
||||
/// password: on Windows only Administrators, SYSTEM (the service) and the
|
||||
/// account running setup may open it. Elsewhere it is mode 600.
|
||||
/// </summary>
|
||||
private static void ProtectSettingsFile(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
var security = new System.Security.AccessControl.FileSecurity();
|
||||
security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
|
||||
var sids = new List<System.Security.Principal.SecurityIdentifier>
|
||||
{
|
||||
new(System.Security.Principal.WellKnownSidType.BuiltinAdministratorsSid, null),
|
||||
new(System.Security.Principal.WellKnownSidType.LocalSystemSid, null),
|
||||
};
|
||||
if (System.Security.Principal.WindowsIdentity.GetCurrent().User is { } self && !sids.Contains(self))
|
||||
{
|
||||
sids.Add(self);
|
||||
}
|
||||
|
||||
foreach (var sid in sids)
|
||||
{
|
||||
security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(
|
||||
sid, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
|
||||
}
|
||||
|
||||
new FileInfo(path).SetAccessControl(security);
|
||||
}
|
||||
else
|
||||
{
|
||||
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidOperationException)
|
||||
{
|
||||
Console.Error.WriteLine($"Could not restrict access to {path}: {exception.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int ParsePort(string value, string flag)
|
||||
=> int.TryParse(value, out var port) && port is >= 1 and <= 65535
|
||||
? port
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
using System.Formats.Asn1;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
namespace Backend.Tls;
|
||||
|
||||
/// <summary>
|
||||
/// What a binding follows, rather than a thumbprint (which changes at every
|
||||
/// renewal or reissue): the subject, the issuer, the DNS names and the
|
||||
/// certificate template an enterprise CA stamps in.
|
||||
/// </summary>
|
||||
public sealed record CertificateIdentity(string Subject, string Issuer, IReadOnlyList<string> DnsNames, string? Template)
|
||||
{
|
||||
public static CertificateIdentity From(X509Certificate2 certificate)
|
||||
=> new(certificate.Subject, certificate.Issuer, CertificateBindingRules.DnsNames(certificate), CertificateBindingRules.Template(certificate));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The console's server-certificate choice, a settings document
|
||||
/// (<see cref="Key"/>) every replica reads: <c>store</c> follows
|
||||
/// <see cref="Identity"/> in each replica's own LocalMachine\My;
|
||||
/// <c>self-signed</c> serves the managed chain. No document means the
|
||||
/// configured source (appsettings.json / setup) applies.
|
||||
/// </summary>
|
||||
public sealed record ServerCertificateBinding
|
||||
{
|
||||
public const string Key = "tls.serverCertificate";
|
||||
public const string StoreMode = "store";
|
||||
public const string SelfSignedMode = "self-signed";
|
||||
|
||||
public string Mode { get; init; } = StoreMode;
|
||||
|
||||
public CertificateIdentity? Identity { get; init; }
|
||||
|
||||
/// <summary>The certificate chosen when it was bound.</summary>
|
||||
public string? Thumbprint { get; init; }
|
||||
|
||||
public DateTimeOffset BoundUtc { get; init; }
|
||||
|
||||
public string? BoundBy { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// What each replica (by machine name) serves for the binding: every
|
||||
/// replica follows the identity in its own store, so thumbprints differ.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, ReplicaCertificate>? Replicas { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>One replica's certificate for a binding, and when it last followed a renewal or reissue (from which certificate).</summary>
|
||||
public sealed record ReplicaCertificate(string Thumbprint, DateTimeOffset? LastSwitchedUtc, string? PreviousThumbprint);
|
||||
|
||||
/// <summary>
|
||||
/// A served chain whose root agents had not been given before (a new private
|
||||
/// CA after a switch), settings document <see cref="Key"/>: agents enrolled
|
||||
/// earlier cannot validate it until the root is pushed or they get a new token.
|
||||
/// </summary>
|
||||
public sealed record ServerRootChange(string Fingerprint, string? PreviousFingerprint, DateTimeOffset ChangedUtc)
|
||||
{
|
||||
public const string Key = "tls.rootChange";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which certificate in the store a binding serves, and whether a certificate
|
||||
/// can serve TLS at all.
|
||||
/// </summary>
|
||||
public static partial class CertificateBindingRules
|
||||
{
|
||||
private const string ServerAuthentication = "1.3.6.1.5.5.7.3.1";
|
||||
private const string TemplateV2 = "1.3.6.1.4.1.311.21.7";
|
||||
private const string TemplateV1 = "1.3.6.1.4.1.311.20.2";
|
||||
private const uint RenewalProperty = 64; // CERT_RENEWAL_PROP_ID
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="certificate"/> cannot be served by this process,
|
||||
/// or null when it can: current, with a private key the service can open,
|
||||
/// for server authentication (or no EKU), and a key usage that allows TLS.
|
||||
/// </summary>
|
||||
public static string? UnusableReason(X509Certificate2 certificate, DateTime now)
|
||||
{
|
||||
if (certificate.Archived)
|
||||
{
|
||||
return "Archived: replaced by its renewal.";
|
||||
}
|
||||
|
||||
if (!certificate.HasPrivateKey)
|
||||
{
|
||||
return "No private key.";
|
||||
}
|
||||
|
||||
if (certificate.NotAfter <= now)
|
||||
{
|
||||
return "Expired.";
|
||||
}
|
||||
|
||||
if (certificate.NotBefore > now)
|
||||
{
|
||||
return "Not valid yet.";
|
||||
}
|
||||
|
||||
if (certificate.Extensions.OfType<X509EnhancedKeyUsageExtension>().FirstOrDefault() is { } eku
|
||||
&& !eku.EnhancedKeyUsages.Cast<Oid>().Any(o => o.Value == ServerAuthentication))
|
||||
{
|
||||
return "Not for server authentication.";
|
||||
}
|
||||
|
||||
if (certificate.Extensions.OfType<X509KeyUsageExtension>().FirstOrDefault() is { } usage
|
||||
&& (usage.KeyUsages & (X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.KeyAgreement)) == 0)
|
||||
{
|
||||
return "Its key usage does not allow TLS.";
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using AsymmetricAlgorithm? key = (AsymmetricAlgorithm?)certificate.GetRSAPrivateKey() ?? certificate.GetECDsaPrivateKey();
|
||||
return key is null ? "Only RSA and ECDSA keys are supported." : null;
|
||||
}
|
||||
catch (Exception exception) when (exception is CryptographicException or ArgumentException or InvalidOperationException or NotSupportedException or UnauthorizedAccessException)
|
||||
{
|
||||
return "The server's account cannot open its private key.";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="certificate"/> is the same certificate renewed
|
||||
/// or reissued: the same template when the bound one had one (then any
|
||||
/// issuer of that template), otherwise the same issuer; and the same
|
||||
/// subject or the same set of DNS names.
|
||||
/// </summary>
|
||||
public static bool Matches(CertificateIdentity identity, X509Certificate2 certificate)
|
||||
{
|
||||
var template = Template(certificate);
|
||||
if (identity.Template is not null
|
||||
? !string.Equals(identity.Template, template, StringComparison.OrdinalIgnoreCase)
|
||||
: !string.Equals(identity.Issuer, certificate.Issuer, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (string.Equals(identity.Subject, certificate.Subject, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var names = DnsNames(certificate);
|
||||
return identity.DnsNames.Count > 0
|
||||
&& names.Count == identity.DnsNames.Count
|
||||
&& names.All(n => identity.DnsNames.Contains(n, StringComparer.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The certificate a binding serves now. Windows' own renewal link wins:
|
||||
/// when the last certificate was renewed (its renewal property names the
|
||||
/// successor, followed through several renewals) and the successor is
|
||||
/// usable, that is the one. Otherwise the newest usable certificate that
|
||||
/// matches the identity — latest issued, then latest expiry — which is
|
||||
/// the last one itself while nothing newer exists. Null when none is usable.
|
||||
/// </summary>
|
||||
public static X509Certificate2? Choose(CertificateIdentity identity, string? lastThumbprint, IEnumerable<X509Certificate2> certificates,
|
||||
DateTime now, Func<X509Certificate2, string?>? renewedBy = null)
|
||||
{
|
||||
var all = certificates.ToList();
|
||||
renewedBy ??= OperatingSystem.IsWindows() ? RenewedBy : _ => null;
|
||||
var current = lastThumbprint is null ? null : all.FirstOrDefault(c => string.Equals(c.Thumbprint, lastThumbprint, StringComparison.OrdinalIgnoreCase));
|
||||
for (var hop = 0; current is not null && hop < 8; hop++)
|
||||
{
|
||||
var next = renewedBy(current) is { } successor
|
||||
? all.FirstOrDefault(c => string.Equals(c.Thumbprint, successor, StringComparison.OrdinalIgnoreCase))
|
||||
: null;
|
||||
if (next is null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (UnusableReason(next, now) is null)
|
||||
{
|
||||
return next;
|
||||
}
|
||||
|
||||
current = next;
|
||||
}
|
||||
|
||||
return all
|
||||
.Where(c => UnusableReason(c, now) is null && Matches(identity, c))
|
||||
.OrderByDescending(c => c.NotBefore)
|
||||
.ThenByDescending(c => c.NotAfter)
|
||||
.FirstOrDefault();
|
||||
}
|
||||
|
||||
public static IReadOnlyList<string> DnsNames(X509Certificate2 certificate)
|
||||
=> certificate.Extensions.OfType<X509SubjectAlternativeNameExtension>().FirstOrDefault() is { } san
|
||||
? [.. san.EnumerateDnsNames().Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase)]
|
||||
: [];
|
||||
|
||||
public static IReadOnlyList<string> IpAddresses(X509Certificate2 certificate)
|
||||
=> certificate.Extensions.OfType<X509SubjectAlternativeNameExtension>().FirstOrDefault() is { } san
|
||||
? [.. san.EnumerateIPAddresses().Select(a => a.ToString())]
|
||||
: [];
|
||||
|
||||
/// <summary>The certificate template (its OID, or a v1 template's name), or null.</summary>
|
||||
public static string? Template(X509Certificate2 certificate)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (certificate.Extensions[TemplateV2] is { } v2)
|
||||
{
|
||||
var sequence = new AsnReader(v2.RawData, AsnEncodingRules.DER).ReadSequence();
|
||||
return sequence.ReadObjectIdentifier();
|
||||
}
|
||||
|
||||
if (certificate.Extensions[TemplateV1] is { } v1)
|
||||
{
|
||||
var reader = new AsnReader(v1.RawData, AsnEncodingRules.DER);
|
||||
return reader.ReadCharacterString(UniversalTagNumber.BMPString);
|
||||
}
|
||||
}
|
||||
catch (AsnContentException)
|
||||
{
|
||||
// Malformed: treated as no template.
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The thumbprint Windows recorded as this certificate's renewal (auto-enrollment sets it when it archives the old one).</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
public static string? RenewedBy(X509Certificate2 certificate)
|
||||
{
|
||||
try
|
||||
{
|
||||
uint size = 0;
|
||||
if (!CertGetCertificateContextProperty(certificate.Handle, RenewalProperty, null, ref size) || size == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var hash = new byte[size];
|
||||
return CertGetCertificateContextProperty(certificate.Handle, RenewalProperty, hash, ref size)
|
||||
? Convert.ToHexString(hash, 0, (int)size)
|
||||
: null;
|
||||
}
|
||||
catch (Exception exception) when (exception is DllNotFoundException or EntryPointNotFoundException or CryptographicException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
[LibraryImport("crypt32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool CertGetCertificateContextProperty(IntPtr certificateContext, uint propertyId, [Out] byte[]? data, ref uint size);
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
using System.Net.Security;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
namespace Backend.Tls;
|
||||
|
||||
/// <summary>
|
||||
/// Serves a certificate the administrator provides instead of the managed
|
||||
/// chain: one in LocalMachine\My by thumbprint (Windows), or a file — a
|
||||
/// PFX/P12 (TLS_CERT_PASSWORD) or a PEM certificate with its key (in the same
|
||||
/// file or TLS_CERT_KEY_FILE; a fullchain PEM brings its intermediates).
|
||||
/// Checked every minute: a replaced file, or a store certificate renewed by
|
||||
/// auto-enrollment (the configured one archived or about to expire, its
|
||||
/// successor with the same subject and issuer), is picked up without a
|
||||
/// restart. A chain that is not publicly trusted (an enterprise CA) is
|
||||
/// distributed the same way as the managed one: GET /api/enrollment/ca serves
|
||||
/// it without the leaf, tokens carry its root's fingerprint, and the
|
||||
/// distribution folder holds it; a publicly trusted chain distributes nothing.
|
||||
/// </summary>
|
||||
public sealed class ProvidedTlsCertificate : IServerTlsSource
|
||||
{
|
||||
private const string ServerAuthentication = "1.3.6.1.5.5.7.3.1";
|
||||
private static readonly TimeSpan RenewalWindow = TimeSpan.FromDays(14);
|
||||
|
||||
private readonly TlsSettings settings;
|
||||
private readonly StoreLocation storeLocation;
|
||||
private readonly Func<X509Certificate2, bool, bool> isPublic;
|
||||
private Served? served;
|
||||
private string? fileStamp;
|
||||
private string? lastFailure;
|
||||
|
||||
/// <param name="settings">Source, thumbprint or file, password and distribution choice.</param>
|
||||
/// <param name="storeLocation">LocalMachine in service; tests use CurrentUser.</param>
|
||||
/// <param name="isPublic">Whether a root (and whether the chain built with the system's trust) counts as publicly trusted; tests replace it.</param>
|
||||
/// <param name="binding">A console binding: the store certificate is chosen by identity
|
||||
/// (<see cref="CertificateBindingRules.Choose"/>) instead of the configured thumbprint.</param>
|
||||
public ProvidedTlsCertificate(TlsSettings settings, StoreLocation storeLocation = StoreLocation.LocalMachine,
|
||||
Func<X509Certificate2, bool, bool>? isPublic = null, ServerCertificateBinding? binding = null)
|
||||
{
|
||||
if (settings.Source == TlsCertificateSource.SelfSigned)
|
||||
{
|
||||
throw new ArgumentException("A provided certificate needs TLS_CERT_SOURCE store or file.", nameof(settings));
|
||||
}
|
||||
|
||||
this.settings = settings;
|
||||
this.storeLocation = storeLocation;
|
||||
this.isPublic = isPublic ?? ((root, trusted) => trusted && IsPublicRoot(root));
|
||||
this.binding = binding;
|
||||
}
|
||||
|
||||
private readonly ServerCertificateBinding? binding;
|
||||
|
||||
/// <summary>When a renewal or reissue was last followed, and the certificate it replaced.</summary>
|
||||
public (DateTimeOffset At, string From)? LastSwitch { get; private set; }
|
||||
|
||||
private sealed record Served(X509Certificate2 Leaf, SslStreamCertificateContext? Context, IReadOnlyList<X509Certificate2> Intermediates, IReadOnlyList<X509Certificate2> Distributed, string? ChainPem, string? Fingerprint);
|
||||
|
||||
public TimeSpan RefreshInterval => TimeSpan.FromMinutes(1);
|
||||
|
||||
public X509Certificate2? ServerCertificate => Volatile.Read(ref served)?.Leaf;
|
||||
|
||||
public SslStreamCertificateContext? CertificateContext => Volatile.Read(ref served)?.Context;
|
||||
|
||||
public string? CaChainPem() => Volatile.Read(ref served)?.ChainPem;
|
||||
|
||||
public string? CaFingerprint() => Volatile.Read(ref served)?.Fingerprint;
|
||||
|
||||
/// <summary>The CA certificates handed to agents (intermediates then root); empty when none are.</summary>
|
||||
public IReadOnlyList<X509Certificate2> DistributedCertificates => Volatile.Read(ref served)?.Distributed ?? [];
|
||||
|
||||
/// <summary>
|
||||
/// Loads the certificate, or picks up a replacement. The first load throws
|
||||
/// with the reason (the server must not start without its certificate);
|
||||
/// later failures — a file caught half-written, a key not readable — are
|
||||
/// logged once and the current certificate stays in service.
|
||||
/// </summary>
|
||||
public bool Refresh(ILogger logger)
|
||||
{
|
||||
var current = Volatile.Read(ref served);
|
||||
string? stamp = null;
|
||||
X509Certificate2 leaf;
|
||||
X509Certificate2Collection extras;
|
||||
try
|
||||
{
|
||||
if (settings.Source == TlsCertificateSource.File)
|
||||
{
|
||||
stamp = FileStamp();
|
||||
if (current is not null && stamp == fileStamp)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
(leaf, extras) = LoadFromFile();
|
||||
}
|
||||
else
|
||||
{
|
||||
(leaf, extras) = LoadFromStore(current?.Leaf, logger);
|
||||
}
|
||||
|
||||
CheckUsable(leaf);
|
||||
}
|
||||
catch (Exception exception) when (current is not null
|
||||
&& exception is CryptographicException or IOException or InvalidOperationException or UnauthorizedAccessException)
|
||||
{
|
||||
if (exception.Message != lastFailure)
|
||||
{
|
||||
lastFailure = exception.Message;
|
||||
logger.LogWarning("TLS: the provided certificate could not be reloaded ({Reason}); still serving {Thumbprint}", exception.Message, current.Leaf.Thumbprint);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
lastFailure = null;
|
||||
fileStamp = stamp;
|
||||
if (current is not null && current.Leaf.Thumbprint == leaf.Thumbprint)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var next = Build(leaf, extras, logger);
|
||||
if (current is not null)
|
||||
{
|
||||
LastSwitch = (DateTimeOffset.UtcNow, current.Leaf.Thumbprint);
|
||||
}
|
||||
|
||||
Volatile.Write(ref served, next);
|
||||
logger.LogInformation("TLS: serving {Subject} ({Thumbprint}, valid to {NotAfter:u}) from {Source}{Distribution}",
|
||||
leaf.Subject, leaf.Thumbprint, leaf.NotAfter.ToUniversalTime(),
|
||||
settings.Source == TlsCertificateSource.Store ? $"{storeLocation}\\My" : settings.CertificateFile,
|
||||
next.ChainPem is null ? "; its chain is publicly trusted, so agents are given nothing" : "; agents are given its issuing chain");
|
||||
TlsDistribution.Write(settings.DistributionDirectory, next.Distributed, logger);
|
||||
if (OperatingSystem.IsWindows() && settings.UseWindowsStore && storeLocation == StoreLocation.LocalMachine)
|
||||
{
|
||||
InstallIntermediates(next.Intermediates, logger);
|
||||
}
|
||||
|
||||
MirrorForNats(leaf, next.Intermediates, logger);
|
||||
return true;
|
||||
}
|
||||
|
||||
private Served Build(X509Certificate2 leaf, X509Certificate2Collection extras, ILogger logger)
|
||||
{
|
||||
using var chain = new X509Chain();
|
||||
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
||||
chain.ChainPolicy.ExtraStore.AddRange(extras);
|
||||
var trusted = chain.Build(leaf);
|
||||
var cas = chain.ChainElements.Skip(1).Select(e => X509CertificateLoader.LoadCertificate(e.Certificate.RawData)).ToList();
|
||||
var root = cas.LastOrDefault(ServerTls.IsSelfIssued);
|
||||
var intermediates = cas.Where(c => !ServerTls.IsSelfIssued(c)).ToList();
|
||||
var context = ServerTls.CreateContext(leaf, intermediates);
|
||||
|
||||
var distribute = settings.DistributeCa ?? (root is not null && !isPublic(root, trusted));
|
||||
if (distribute && root is null)
|
||||
{
|
||||
logger.LogWarning(
|
||||
"TLS: the root that issued {Subject} is neither in the certificate file nor in this server's stores, so agents cannot be given it; add the full chain to the file or trust the root here",
|
||||
leaf.Subject);
|
||||
distribute = false;
|
||||
}
|
||||
|
||||
if (!distribute)
|
||||
{
|
||||
return new Served(leaf, context, intermediates, [], null, null);
|
||||
}
|
||||
|
||||
List<X509Certificate2> distributed = [.. intermediates, root!];
|
||||
return new Served(leaf, context, intermediates, distributed, ServerTls.ChainPem(distributed), ServerTls.Fingerprint(root!));
|
||||
}
|
||||
|
||||
private static void CheckUsable(X509Certificate2 leaf)
|
||||
{
|
||||
if (!leaf.HasPrivateKey)
|
||||
{
|
||||
throw new InvalidOperationException($"The certificate {leaf.Thumbprint} has no private key this server can use.");
|
||||
}
|
||||
|
||||
if (leaf.Extensions.OfType<X509EnhancedKeyUsageExtension>().FirstOrDefault() is { } eku
|
||||
&& !eku.EnhancedKeyUsages.Cast<Oid>().Any(o => o.Value == ServerAuthentication))
|
||||
{
|
||||
throw new InvalidOperationException($"The certificate {leaf.Thumbprint} is not for server authentication (its Enhanced Key Usage lacks {ServerAuthentication}).");
|
||||
}
|
||||
}
|
||||
|
||||
private string FileStamp()
|
||||
{
|
||||
var files = new[] { settings.CertificateFile!, settings.KeyFile }.Where(f => f is { Length: > 0 }).Select(f => new FileInfo(f!)).ToList();
|
||||
foreach (var file in files.Where(f => !f.Exists))
|
||||
{
|
||||
throw new FileNotFoundException($"The certificate file {file.FullName} does not exist.", file.FullName);
|
||||
}
|
||||
|
||||
return string.Join('|', files.Select(f => $"{f.FullName}:{f.Length}:{f.LastWriteTimeUtc.Ticks}"));
|
||||
}
|
||||
|
||||
private (X509Certificate2 Leaf, X509Certificate2Collection Extras) LoadFromFile()
|
||||
{
|
||||
var path = settings.CertificateFile!;
|
||||
X509Certificate2Collection all;
|
||||
X509Certificate2 leaf;
|
||||
if (IsPem(path))
|
||||
{
|
||||
var keyPath = settings.KeyFile is { Length: > 0 } key ? key : path;
|
||||
var pem = settings.CertificatePassword is { } password
|
||||
? X509Certificate2.CreateFromEncryptedPemFile(path, password, keyPath)
|
||||
: X509Certificate2.CreateFromPemFile(path, keyPath);
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
// SChannel refuses ephemeral PEM keys; round-trip through PKCS#12.
|
||||
using (pem)
|
||||
{
|
||||
leaf = X509CertificateLoader.LoadPkcs12(pem.Export(X509ContentType.Pfx), null, X509KeyStorageFlags.Exportable);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
leaf = pem;
|
||||
}
|
||||
|
||||
all = [];
|
||||
all.ImportFromPemFile(path);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Exportable: the PEM mirror for an exposed NATS WebSocket needs the key.
|
||||
all = X509CertificateLoader.LoadPkcs12CollectionFromFile(path, settings.CertificatePassword, X509KeyStorageFlags.Exportable);
|
||||
leaf = all.Cast<X509Certificate2>()
|
||||
.Where(c => c.HasPrivateKey)
|
||||
.OrderBy(c => ServerTls.IsCertificateAuthority(c) ? 1 : 0)
|
||||
.ThenByDescending(c => c.NotAfter)
|
||||
.FirstOrDefault()
|
||||
?? throw new InvalidOperationException($"{path} holds no certificate with a private key.");
|
||||
}
|
||||
|
||||
X509Certificate2Collection extras = [.. all.Cast<X509Certificate2>().Where(c => c.Thumbprint != leaf.Thumbprint)];
|
||||
return (leaf, extras);
|
||||
}
|
||||
|
||||
private static bool IsPem(string path)
|
||||
{
|
||||
if (Path.GetExtension(path).ToLowerInvariant() is ".pfx" or ".p12")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
using var stream = File.OpenRead(path);
|
||||
var head = new byte[Math.Min(4096, stream.Length)];
|
||||
stream.ReadExactly(head);
|
||||
return System.Text.Encoding.ASCII.GetString(head).Contains("-----BEGIN", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The configured thumbprint, or its renewal: auto-enrollment archives the
|
||||
/// old certificate and adds a new one with the same subject and issuer, so
|
||||
/// when the configured one is archived, missing or inside the renewal
|
||||
/// window, the newest current certificate with that subject and issuer and
|
||||
/// a private key is served instead (and the thumbprint to set is logged).
|
||||
/// </summary>
|
||||
private (X509Certificate2 Leaf, X509Certificate2Collection Extras) LoadFromStore(X509Certificate2? servedLeaf, ILogger logger)
|
||||
{
|
||||
using var store = new X509Store(StoreName.My, storeLocation);
|
||||
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly | OpenFlags.IncludeArchived);
|
||||
var now = DateTime.Now;
|
||||
if (binding?.Identity is { } identity)
|
||||
{
|
||||
// A console binding follows its identity, not a thumbprint.
|
||||
var last = servedLeaf?.Thumbprint ?? binding.Thumbprint;
|
||||
var chosen = CertificateBindingRules.Choose(identity, last, store.Certificates.Cast<X509Certificate2>(), now)
|
||||
?? throw new InvalidOperationException($"No usable certificate in {storeLocation}\\My matches the binding ({identity.Subject}, issued by {identity.Issuer}).");
|
||||
if (last is not null && !string.Equals(chosen.Thumbprint, last, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
logger.LogInformation("TLS: the bound certificate was renewed or reissued; following {Previous} to {Thumbprint}", last, chosen.Thumbprint);
|
||||
}
|
||||
|
||||
return (chosen, []);
|
||||
}
|
||||
|
||||
var thumbprint = settings.StoreThumbprint!;
|
||||
var configured = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false)
|
||||
.Cast<X509Certificate2>().FirstOrDefault();
|
||||
var usable = configured is { HasPrivateKey: true, Archived: false } && configured.NotAfter > now + RenewalWindow;
|
||||
if (usable)
|
||||
{
|
||||
return (configured!, []);
|
||||
}
|
||||
|
||||
var template = configured ?? servedLeaf;
|
||||
var renewal = template is null
|
||||
? null
|
||||
: store.Certificates.Cast<X509Certificate2>()
|
||||
.Where(c => !c.Archived && c.HasPrivateKey && c.Thumbprint != thumbprint
|
||||
&& c.Subject == template.Subject && c.Issuer == template.Issuer
|
||||
&& c.NotBefore <= now && c.NotAfter > (configured?.NotAfter ?? now))
|
||||
.MaxBy(c => c.NotAfter);
|
||||
if (renewal is not null)
|
||||
{
|
||||
if (servedLeaf?.Thumbprint != renewal.Thumbprint)
|
||||
{
|
||||
logger.LogWarning(
|
||||
"TLS: certificate {Configured} is {State}; serving its renewal {Renewal} (same subject and issuer). Set TLS_CERT_THUMBPRINT to {Renewal} to make it permanent.",
|
||||
thumbprint, configured is null ? "missing" : configured.Archived ? "archived" : "about to expire", renewal.Thumbprint, renewal.Thumbprint);
|
||||
}
|
||||
|
||||
return (renewal, []);
|
||||
}
|
||||
|
||||
if (configured is { HasPrivateKey: true, Archived: false } && configured.NotAfter > now)
|
||||
{
|
||||
return (configured, []);
|
||||
}
|
||||
|
||||
throw new InvalidOperationException(configured is null
|
||||
? $"There is no certificate {thumbprint} in {storeLocation}\\My."
|
||||
: $"The certificate {thumbprint} in {storeLocation}\\My is {(configured.Archived ? "archived" : !configured.HasPrivateKey ? "without a private key" : "expired")} and has no renewal there.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publicly trusted: on Windows the root is in the Third-Party Root
|
||||
/// Certification Authorities store, where Windows Update puts the public
|
||||
/// roots (an enterprise root is in Trusted Root only); elsewhere it is in
|
||||
/// the system bundle and not one of the locally added anchors. A wrong
|
||||
/// "private" only costs agents a CA they already trust; a wrong "public"
|
||||
/// would leave devices outside the domain unable to connect.
|
||||
/// </summary>
|
||||
internal static bool IsPublicRoot(X509Certificate2 root)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
using var store = new X509Store(StoreName.AuthRoot, StoreLocation.LocalMachine);
|
||||
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
|
||||
return store.Certificates.Find(X509FindType.FindByThumbprint, root.Thumbprint, validOnly: false).Count > 0;
|
||||
}
|
||||
|
||||
foreach (var directory in new[] { "/usr/local/share/ca-certificates", "/etc/pki/ca-trust/source/anchors", "/etc/ca-certificates/trust-source/anchors" })
|
||||
{
|
||||
if (!Directory.Exists(directory))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var file in Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
try
|
||||
{
|
||||
X509Certificate2Collection anchors = [];
|
||||
anchors.ImportFromPemFile(file);
|
||||
if (anchors.Cast<X509Certificate2>().Any(a => a.Thumbprint == root.Thumbprint))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Not a certificate.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static void InstallIntermediates(IEnumerable<X509Certificate2> intermediates, ILogger logger)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var store = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine);
|
||||
store.Open(OpenFlags.ReadWrite);
|
||||
foreach (var intermediate in intermediates)
|
||||
{
|
||||
if (store.Certificates.Find(X509FindType.FindByThumbprint, intermediate.Thumbprint, validOnly: false).Count == 0)
|
||||
{
|
||||
store.Add(intermediate);
|
||||
logger.LogInformation("TLS: added {Subject} to LocalMachine\\CA so the handshake sends the whole chain", intermediate.Subject);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogDebug(exception, "TLS: intermediates not added to LocalMachine\\CA");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An exposed NATS WebSocket serves the same certificate from PEM files (nats.conf names server.crt/server.key).</summary>
|
||||
private void MirrorForNats(X509Certificate2 leaf, IEnumerable<X509Certificate2> intermediates, ILogger logger)
|
||||
{
|
||||
if (settings.LeafMirrorDirectory is not { } directory)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
string key;
|
||||
using (var rsa = leaf.GetRSAPrivateKey())
|
||||
using (var ecdsa = rsa is null ? leaf.GetECDsaPrivateKey() : null)
|
||||
{
|
||||
key = rsa?.ExportPkcs8PrivateKeyPem() ?? ecdsa?.ExportPkcs8PrivateKeyPem()
|
||||
?? throw new CryptographicException("Only RSA and ECDSA keys can be mirrored.");
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(directory);
|
||||
var keyPath = Path.Combine(directory, "server.key");
|
||||
File.WriteAllText(keyPath, key);
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
File.SetUnixFileMode(keyPath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
|
||||
File.WriteAllText(Path.Combine(directory, "server.crt"),
|
||||
leaf.ExportCertificatePem() + '\n' + string.Concat(intermediates.Select(c => c.ExportCertificatePem() + '\n')));
|
||||
}
|
||||
catch (Exception exception) when (exception is CryptographicException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
logger.LogWarning("TLS: the NATS WebSocket cannot serve the provided certificate ({Reason}); its key must be exportable", exception.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net.Security;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
@@ -27,16 +28,28 @@ public sealed record TlsLifetimes(
|
||||
/// 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.
|
||||
/// restart). Windows persists to the machine certificate stores (root in
|
||||
/// Trusted Roots, intermediate in Intermediate CAs, leaf in Personal), so the
|
||||
/// server itself trusts the chain; everywhere else (or with TLS_CERT_DIR set)
|
||||
/// the chain is PEM files. Every settle also refreshes the distribution
|
||||
/// folder (root + intermediate only) for Group Policy.
|
||||
/// </summary>
|
||||
public sealed class SelfSignedTlsManager
|
||||
public sealed class SelfSignedTlsManager : IServerTlsSource
|
||||
{
|
||||
private readonly Lock gate = new();
|
||||
private readonly TlsSettings settings;
|
||||
private readonly TlsLifetimes lifetimes;
|
||||
private readonly ITlsPersistence persistence;
|
||||
private X509Certificate2? leaf;
|
||||
private SslStreamCertificateContext? context;
|
||||
private string? chainPem;
|
||||
private string? fingerprint;
|
||||
|
||||
public TimeSpan RefreshInterval => TimeSpan.FromHours(6);
|
||||
|
||||
public SslStreamCertificateContext? CertificateContext => Volatile.Read(ref context);
|
||||
|
||||
public bool Refresh(ILogger logger) => EnsureChain(logger);
|
||||
|
||||
public SelfSignedTlsManager(TlsSettings settings, TlsLifetimes? lifetimes = null)
|
||||
{
|
||||
@@ -65,20 +78,7 @@ public sealed class SelfSignedTlsManager
|
||||
/// to agents so they can validate the leaf and keep trusting it across
|
||||
/// renewals. Null before the chain exists. Contains no private keys.
|
||||
/// </summary>
|
||||
public string? CaChainPem()
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
var root = persistence.Load(TlsRole.Root);
|
||||
var intermediate = persistence.Load(TlsRole.Intermediate);
|
||||
if (root is null || intermediate is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return intermediate.ExportCertificatePem() + '\n' + root.ExportCertificatePem() + '\n';
|
||||
}
|
||||
}
|
||||
public string? CaChainPem() => Volatile.Read(ref chainPem);
|
||||
|
||||
/// <summary>
|
||||
/// SHA-256 (lowercase hex) of the root CA's public key (SubjectPublicKeyInfo).
|
||||
@@ -88,17 +88,7 @@ public sealed class SelfSignedTlsManager
|
||||
/// in-place root renewal (which re-issues the cert but keeps the key). Null
|
||||
/// before the chain exists.
|
||||
/// </summary>
|
||||
public string? CaFingerprint()
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
var root = persistence.Load(TlsRole.Root);
|
||||
return root is null
|
||||
? null
|
||||
: Convert.ToHexStringLower(
|
||||
System.Security.Cryptography.SHA256.HashData(root.PublicKey.ExportSubjectPublicKeyInfo()));
|
||||
}
|
||||
}
|
||||
public string? CaFingerprint() => Volatile.Read(ref fingerprint);
|
||||
|
||||
/// <summary>
|
||||
/// Creates or re-issues whatever links are missing, expiring, or no longer
|
||||
@@ -160,7 +150,15 @@ public sealed class SelfSignedTlsManager
|
||||
}
|
||||
|
||||
persistence.Complete(root, intermediate, current);
|
||||
if (changed || Volatile.Read(ref context) is null)
|
||||
{
|
||||
Volatile.Write(ref context, ServerTls.CreateContext(current, [intermediate]));
|
||||
}
|
||||
|
||||
Volatile.Write(ref chainPem, ServerTls.ChainPem([intermediate, root]));
|
||||
Volatile.Write(ref fingerprint, ServerTls.Fingerprint(root));
|
||||
Volatile.Write(ref leaf, current);
|
||||
TlsDistribution.Write(settings.DistributionDirectory, [intermediate, root], logger);
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Backend.Auth;
|
||||
using Backend.Data;
|
||||
using Backend.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shared.Contracts.Api;
|
||||
|
||||
namespace Backend.Tls;
|
||||
|
||||
public sealed record CertificateDetailsDto(
|
||||
string Subject, string Issuer, IReadOnlyList<string> DnsNames, IReadOnlyList<string> IpAddresses,
|
||||
DateTimeOffset NotBefore, DateTimeOffset NotAfter, string Thumbprint, string? Template);
|
||||
|
||||
public sealed record ChainCertificateDto(string Subject, string Thumbprint, DateTimeOffset NotAfter, bool Root);
|
||||
|
||||
public sealed record CertificateBindingDto(
|
||||
string Mode, CertificateIdentity? Identity, string? BoundThumbprint, DateTimeOffset BoundUtc, string? BoundBy,
|
||||
bool Applied, bool FollowingRenewals, string? ServedThumbprint, DateTimeOffset? LastSwitchedUtc, string? PreviousThumbprint);
|
||||
|
||||
public sealed record StoreCertificateDto(
|
||||
string Thumbprint, string Subject, string Issuer, IReadOnlyList<string> DnsNames, DateTimeOffset NotAfter,
|
||||
string? Template, string? FriendlyName, bool Usable, string? Reason, bool InUse, bool MatchesBinding);
|
||||
|
||||
/// <summary>
|
||||
/// The Server Certificate settings page: what this replica serves, and on
|
||||
/// Windows the LocalMachine\My certificates it could serve instead.
|
||||
/// <see cref="Source"/> is self-signed, store, file or none (plain HTTP);
|
||||
/// <see cref="Trust"/> is public (agents are given nothing) or private.
|
||||
/// </summary>
|
||||
public sealed record ServerCertificateStatusDto(
|
||||
bool TlsEnabled,
|
||||
string Source,
|
||||
bool Bound,
|
||||
string? ForcedBy,
|
||||
bool StoreAvailable,
|
||||
string? Problem,
|
||||
CertificateDetailsDto? Certificate,
|
||||
IReadOnlyList<ChainCertificateDto> Chain,
|
||||
string Trust,
|
||||
bool AgentsPinned,
|
||||
string? RootFingerprint,
|
||||
string? DistributionFolder,
|
||||
CertificateBindingDto? Binding,
|
||||
DateTimeOffset? RootChangedUtc,
|
||||
string Replica,
|
||||
IReadOnlyList<StoreCertificateDto> StoreCertificates);
|
||||
|
||||
public sealed record BindCertificateRequest(string? Thumbprint);
|
||||
|
||||
/// <summary>
|
||||
/// Settings › Server Certificate (settings.manage, audited): bind a
|
||||
/// LocalMachine\My certificate by identity so renewals and reissues are
|
||||
/// followed, switch to the managed self-signed chain, or clear the binding
|
||||
/// to serve the configured source again.
|
||||
/// </summary>
|
||||
public static class ServerCertificateEndpoints
|
||||
{
|
||||
/// <summary>How long a new private root is called out on the page.</summary>
|
||||
public static readonly TimeSpan RootChangeNotice = TimeSpan.FromDays(30);
|
||||
|
||||
public static void Map(WebApplication app)
|
||||
{
|
||||
app.MapGet(ApiRoutes.ServerCertificate, Get).RequirePermission(Permissions.SettingsManage);
|
||||
app.MapPost(ApiRoutes.ServerCertificateBind, BindAsync).RequirePermission(Permissions.SettingsManage);
|
||||
app.MapPost(ApiRoutes.ServerCertificateSelfSigned, SelfSignedAsync).RequirePermission(Permissions.SettingsManage);
|
||||
app.MapDelete(ApiRoutes.ServerCertificateBinding, ClearAsync).RequirePermission(Permissions.SettingsManage);
|
||||
}
|
||||
|
||||
private static IResult Get(HttpContext context, TlsSettings settings)
|
||||
=> Results.Ok(Describe(context.RequestServices.GetService<ServerTlsSwitch>(), settings));
|
||||
|
||||
private static async Task<IResult> BindAsync(BindCertificateRequest? request, HttpContext context, TlsSettings settings, AppDbContext db,
|
||||
AuditService audit, ILogger<ServerTlsSwitch> logger, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Unavailable(context, out var tls) is { } refused)
|
||||
{
|
||||
return refused;
|
||||
}
|
||||
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
return Results.BadRequest(new { error = "This server is not on Windows, so it has no Windows certificate store." });
|
||||
}
|
||||
|
||||
var thumbprint = TlsSettings.NormalizeThumbprint(request?.Thumbprint);
|
||||
X509Certificate2? certificate;
|
||||
using (var store = new X509Store(StoreName.My, tls.StoreLocation))
|
||||
{
|
||||
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
|
||||
certificate = thumbprint is null ? null : store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false).Cast<X509Certificate2>().FirstOrDefault();
|
||||
}
|
||||
|
||||
if (certificate is null)
|
||||
{
|
||||
return Results.BadRequest(new { error = $"There is no certificate {thumbprint} in {tls.StoreLocation}\\My." });
|
||||
}
|
||||
|
||||
if (CertificateBindingRules.UnusableReason(certificate, DateTime.Now) is { } reason)
|
||||
{
|
||||
return Results.BadRequest(new { error = reason });
|
||||
}
|
||||
|
||||
var actor = context.User.Identity?.Name;
|
||||
await SaveAsync(db, new ServerCertificateBinding
|
||||
{
|
||||
Mode = ServerCertificateBinding.StoreMode,
|
||||
Identity = CertificateIdentity.From(certificate),
|
||||
Thumbprint = certificate.Thumbprint,
|
||||
BoundUtc = DateTimeOffset.UtcNow,
|
||||
BoundBy = actor,
|
||||
}, actor, cancellationToken);
|
||||
await audit.LogAsync(AuditCategories.Settings, "tls.certificate.bind", actor,
|
||||
detail: $"subject={certificate.Subject} issuer={certificate.Issuer} thumbprint={certificate.Thumbprint}", cancellationToken: cancellationToken);
|
||||
tls.Refresh(logger);
|
||||
return Results.Ok(Describe(tls, settings));
|
||||
}
|
||||
|
||||
private static async Task<IResult> SelfSignedAsync(HttpContext context, TlsSettings settings, AppDbContext db, AuditService audit,
|
||||
ILogger<ServerTlsSwitch> logger, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Unavailable(context, out var tls) is { } refused)
|
||||
{
|
||||
return refused;
|
||||
}
|
||||
|
||||
var actor = context.User.Identity?.Name;
|
||||
await SaveAsync(db, new ServerCertificateBinding
|
||||
{
|
||||
Mode = ServerCertificateBinding.SelfSignedMode,
|
||||
BoundUtc = DateTimeOffset.UtcNow,
|
||||
BoundBy = actor,
|
||||
}, actor, cancellationToken);
|
||||
await audit.LogAsync(AuditCategories.Settings, "tls.certificate.self-signed", actor, cancellationToken: cancellationToken);
|
||||
tls.Refresh(logger);
|
||||
return Results.Ok(Describe(tls, settings));
|
||||
}
|
||||
|
||||
private static async Task<IResult> ClearAsync(HttpContext context, TlsSettings settings, AppDbContext db, AuditService audit,
|
||||
ILogger<ServerTlsSwitch> logger, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Unavailable(context, out var tls) is { } refused)
|
||||
{
|
||||
return refused;
|
||||
}
|
||||
|
||||
var row = await db.AppSettings.SingleOrDefaultAsync(s => s.Key == ServerCertificateBinding.Key, cancellationToken);
|
||||
if (row is not null)
|
||||
{
|
||||
db.AppSettings.Remove(row);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
await audit.LogAsync(AuditCategories.Settings, "tls.certificate.unbind", context.User.Identity?.Name, cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
tls.Refresh(logger);
|
||||
return Results.Ok(Describe(tls, settings));
|
||||
}
|
||||
|
||||
private static IResult? Unavailable(HttpContext context, out ServerTlsSwitch tls)
|
||||
{
|
||||
tls = context.RequestServices.GetService<ServerTlsSwitch>()!;
|
||||
if (tls is null)
|
||||
{
|
||||
return Results.Conflict(new { error = "This server serves plain HTTP; turn TLS on (setup, or TLS_SELF_SIGNED=1) and restart it to serve a certificate." });
|
||||
}
|
||||
|
||||
return tls.ForcedBy is { } forced
|
||||
? Results.Conflict(new { error = $"{forced} is set in this server's environment, which decides its certificate." })
|
||||
: null;
|
||||
}
|
||||
|
||||
private static async Task SaveAsync(AppDbContext db, ServerCertificateBinding binding, string? actor, CancellationToken cancellationToken)
|
||||
{
|
||||
var row = await SettingsDocuments.LoadAsync(db, ServerCertificateBinding.Key, cancellationToken);
|
||||
SettingsDocuments.Stage(db, row, ServerCertificateBinding.Key, null, binding, actor, always: true);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The page's view of <paramref name="tls"/> (null: plain HTTP).</summary>
|
||||
public static ServerCertificateStatusDto Describe(ServerTlsSwitch? tls, TlsSettings settings, DateTimeOffset? now = null)
|
||||
{
|
||||
var at = now ?? DateTimeOffset.UtcNow;
|
||||
var leaf = tls?.ServerCertificate;
|
||||
var fingerprint = tls?.CaFingerprint();
|
||||
var source = tls is null
|
||||
? "none"
|
||||
: tls.Served switch
|
||||
{
|
||||
ServedSource.SelfSigned => "self-signed",
|
||||
ServedSource.Store => "store",
|
||||
_ => settings.Source switch
|
||||
{
|
||||
TlsCertificateSource.Store => "store",
|
||||
TlsCertificateSource.File => "file",
|
||||
_ => "self-signed",
|
||||
},
|
||||
};
|
||||
|
||||
var (chain, publicChain) = leaf is null ? ([], false) : Chain(leaf, tls!);
|
||||
var binding = tls?.Binding is { } b
|
||||
? new CertificateBindingDto(b.Mode, b.Identity, b.Thumbprint, b.BoundUtc, b.BoundBy,
|
||||
Applied: tls.Served != ServedSource.Configured,
|
||||
FollowingRenewals: tls.Served == ServedSource.Store && tls.Problem is null,
|
||||
ServedThumbprint: tls.Served == ServedSource.Store ? leaf?.Thumbprint : null,
|
||||
tls.ReplicaState?.LastSwitchedUtc, tls.ReplicaState?.PreviousThumbprint)
|
||||
: null;
|
||||
|
||||
return new ServerCertificateStatusDto(
|
||||
TlsEnabled: tls is not null,
|
||||
Source: source,
|
||||
Bound: tls is not null && tls.Served != ServedSource.Configured,
|
||||
ForcedBy: tls?.ForcedBy,
|
||||
StoreAvailable: OperatingSystem.IsWindows(),
|
||||
Problem: tls?.Problem,
|
||||
Certificate: leaf is null ? null : Details(leaf),
|
||||
Chain: chain,
|
||||
Trust: fingerprint is null && publicChain ? "public" : "private",
|
||||
AgentsPinned: fingerprint is not null,
|
||||
RootFingerprint: fingerprint,
|
||||
DistributionFolder: fingerprint is null ? null : settings.DistributionDirectory,
|
||||
Binding: binding,
|
||||
RootChangedUtc: tls?.RootChange is { } change && change.ChangedUtc > at - RootChangeNotice ? change.ChangedUtc : null,
|
||||
Replica: tls?.ReplicaName ?? Environment.MachineName,
|
||||
StoreCertificates: tls is not null && OperatingSystem.IsWindows() ? StoreCertificates(tls, leaf) : []);
|
||||
}
|
||||
|
||||
private static CertificateDetailsDto Details(X509Certificate2 certificate)
|
||||
=> new(certificate.Subject, certificate.Issuer, CertificateBindingRules.DnsNames(certificate), CertificateBindingRules.IpAddresses(certificate),
|
||||
certificate.NotBefore.ToUniversalTime(), certificate.NotAfter.ToUniversalTime(), certificate.Thumbprint, CertificateBindingRules.Template(certificate));
|
||||
|
||||
/// <summary>The issuing chain (leaf excluded) and whether it builds against the system's trust.</summary>
|
||||
private static (IReadOnlyList<ChainCertificateDto> Chain, bool Public) Chain(X509Certificate2 leaf, IServerTlsSource tls)
|
||||
{
|
||||
using var chain = new X509Chain();
|
||||
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
||||
if (tls.CertificateContext is { } context)
|
||||
{
|
||||
chain.ChainPolicy.ExtraStore.AddRange(context.IntermediateCertificates.ToArray());
|
||||
}
|
||||
|
||||
if (tls.CaChainPem() is { } pem)
|
||||
{
|
||||
X509Certificate2Collection distributed = [];
|
||||
distributed.ImportFromPem(pem);
|
||||
chain.ChainPolicy.ExtraStore.AddRange(distributed);
|
||||
}
|
||||
|
||||
var built = chain.Build(leaf);
|
||||
var elements = chain.ChainElements.Skip(1)
|
||||
.Select(e => new ChainCertificateDto(e.Certificate.Subject, e.Certificate.Thumbprint, e.Certificate.NotAfter.ToUniversalTime(), ServerTls.IsSelfIssued(e.Certificate)))
|
||||
.ToList();
|
||||
return (elements, built);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<StoreCertificateDto> StoreCertificates(ServerTlsSwitch tls, X509Certificate2? inUse)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var store = new X509Store(StoreName.My, tls.StoreLocation);
|
||||
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
|
||||
var now = DateTime.Now;
|
||||
var identity = tls.Binding?.Mode == ServerCertificateBinding.StoreMode ? tls.Binding.Identity : null;
|
||||
// CA certificates (basic constraints say so) are not server certificates; everything else is listed, unusable ones with why.
|
||||
return [.. store.Certificates.Cast<X509Certificate2>()
|
||||
.Where(c => c.Extensions.OfType<X509BasicConstraintsExtension>().FirstOrDefault() is not { CertificateAuthority: true })
|
||||
.Select(c =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var reason = CertificateBindingRules.UnusableReason(c, now);
|
||||
return new StoreCertificateDto(c.Thumbprint, c.Subject, c.Issuer, CertificateBindingRules.DnsNames(c), c.NotAfter.ToUniversalTime(),
|
||||
CertificateBindingRules.Template(c), string.IsNullOrEmpty(c.FriendlyName) ? null : c.FriendlyName,
|
||||
reason is null, reason, c.Thumbprint == inUse?.Thumbprint, identity is not null && CertificateBindingRules.Matches(identity, c));
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// One certificate the platform cannot read must not hide the others.
|
||||
return new StoreCertificateDto(c.Thumbprint, c.Subject, c.Issuer, [], c.NotAfter.ToUniversalTime(), null, null,
|
||||
false, $"Cannot be read: {exception.Message}", c.Thumbprint == inUse?.Thumbprint, false);
|
||||
}
|
||||
})
|
||||
.OrderByDescending(c => c.Usable)
|
||||
.ThenBy(c => c.Subject, StringComparer.OrdinalIgnoreCase)
|
||||
.ThenByDescending(c => c.NotAfter)];
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
using System.Net.Security;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Https;
|
||||
|
||||
namespace Backend.Tls;
|
||||
|
||||
/// <summary>Where the listener's certificate comes from.</summary>
|
||||
public enum TlsCertificateSource
|
||||
{
|
||||
/// <summary>The managed self-signed chain (root > intermediate > leaf), the default.</summary>
|
||||
SelfSigned,
|
||||
|
||||
/// <summary>A certificate in LocalMachine\My, by thumbprint (Windows).</summary>
|
||||
Store,
|
||||
|
||||
/// <summary>A PFX/P12, or a PEM certificate and key.</summary>
|
||||
File,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The certificate the listener serves and what agents are given to trust it.
|
||||
/// Kestrel reads <see cref="CertificateContext"/> on every handshake, so a
|
||||
/// renewal or replacement found by <see cref="Refresh"/> needs no restart.
|
||||
/// </summary>
|
||||
public interface IServerTlsSource
|
||||
{
|
||||
/// <summary>The current server certificate; null until the first <see cref="Refresh"/>.</summary>
|
||||
X509Certificate2? ServerCertificate { get; }
|
||||
|
||||
/// <summary>The leaf with its intermediates, so the handshake sends the chain.</summary>
|
||||
SslStreamCertificateContext? CertificateContext { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The issuing chain agents are given (intermediates then root, PEM, public
|
||||
/// certificates only, never the leaf), or null when there is nothing to
|
||||
/// distribute (a publicly trusted chain): GET /api/enrollment/ca is then 404.
|
||||
/// </summary>
|
||||
string? CaChainPem();
|
||||
|
||||
/// <summary>
|
||||
/// SHA-256 (lowercase hex) of the distributed root's SubjectPublicKeyInfo,
|
||||
/// appended to bootstrap tokens; null with nothing distributed.
|
||||
/// </summary>
|
||||
string? CaFingerprint();
|
||||
|
||||
/// <summary>How often <see cref="Refresh"/> runs.</summary>
|
||||
TimeSpan RefreshInterval { get; }
|
||||
|
||||
/// <summary>Loads, renews or picks up a replaced certificate. Returns true when the served certificate changed.</summary>
|
||||
bool Refresh(ILogger logger);
|
||||
}
|
||||
|
||||
/// <summary>Helpers shared by the certificate sources.</summary>
|
||||
public static class ServerTls
|
||||
{
|
||||
/// <summary>Hashes the SubjectPublicKeyInfo, the pin bootstrap tokens carry.</summary>
|
||||
public static string Fingerprint(X509Certificate2 certificate)
|
||||
=> Convert.ToHexStringLower(SHA256.HashData(certificate.PublicKey.ExportSubjectPublicKeyInfo()));
|
||||
|
||||
public static bool IsSelfIssued(X509Certificate2 certificate)
|
||||
=> certificate.SubjectName.RawData.AsSpan().SequenceEqual(certificate.IssuerName.RawData);
|
||||
|
||||
public static bool IsCertificateAuthority(X509Certificate2 certificate)
|
||||
=> certificate.Extensions.OfType<X509BasicConstraintsExtension>().FirstOrDefault() is { CertificateAuthority: true }
|
||||
|| (IsSelfIssued(certificate) && certificate.Extensions.OfType<X509BasicConstraintsExtension>().FirstOrDefault() is null);
|
||||
|
||||
/// <summary>
|
||||
/// The leaf with its intermediates for the handshake, or null when the
|
||||
/// platform cannot build the context (Windows' chain engine fails now and
|
||||
/// then with "an unknown chain building error"): Kestrel's selector then
|
||||
/// serves the bare certificate, and the next refresh tries again.
|
||||
/// </summary>
|
||||
public static SslStreamCertificateContext? CreateContext(X509Certificate2 leaf, IReadOnlyList<X509Certificate2> intermediates)
|
||||
{
|
||||
for (var attempt = 0; attempt < 3; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SslStreamCertificateContext.Create(leaf, [.. intermediates], offline: true);
|
||||
}
|
||||
catch (CryptographicException)
|
||||
{
|
||||
Thread.Sleep(50);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Intermediates then root, as GET /api/enrollment/ca serves them.</summary>
|
||||
public static string ChainPem(IEnumerable<X509Certificate2> caCertificates)
|
||||
=> string.Concat(caCertificates.Select(c => c.ExportCertificatePem() + '\n'));
|
||||
|
||||
/// <summary>
|
||||
/// Serves <paramref name="source"/> on every HTTPS endpoint. The selector
|
||||
/// satisfies Kestrel's configuration check; each handshake then takes the
|
||||
/// current certificate context, which carries the intermediates (a bare
|
||||
/// certificate only sends what the OS can find in its own stores).
|
||||
/// </summary>
|
||||
public static void UseSource(HttpsConnectionAdapterOptions https, IServerTlsSource source)
|
||||
{
|
||||
https.ServerCertificateSelector = (_, _) => source.ServerCertificate;
|
||||
https.OnAuthenticate = (_, options) =>
|
||||
{
|
||||
if (source.CertificateContext is { } context)
|
||||
{
|
||||
options.ServerCertificateSelectionCallback = null;
|
||||
options.ServerCertificate = null;
|
||||
options.ServerCertificateContext = context;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The distribution folder: the root and intermediate certificates (never
|
||||
/// the leaf, never a private key) as DER .cer (Group Policy's import format)
|
||||
/// and PEM, plus ca-chain.pem, rewritten whenever the chain changes so an
|
||||
/// administrator can push them to devices that do not run the agent, or ahead
|
||||
/// of it. Emptied when the served chain is publicly trusted.
|
||||
/// </summary>
|
||||
public static class TlsDistribution
|
||||
{
|
||||
private const string Marker = "ca-chain.pem";
|
||||
|
||||
/// <summary>Writes the files for <paramref name="caCertificates"/> (intermediates then root); none clears the folder. Returns true when anything changed.</summary>
|
||||
public static bool Write(string? directory, IReadOnlyList<X509Certificate2> caCertificates, ILogger logger)
|
||||
{
|
||||
if (directory is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var wanted = new Dictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase);
|
||||
var intermediates = caCertificates.Where(c => !ServerTls.IsSelfIssued(c)).ToList();
|
||||
for (var i = 0; i < intermediates.Count; i++)
|
||||
{
|
||||
var name = intermediates.Count == 1 ? "intermediate-ca" : $"intermediate-ca-{i + 1}";
|
||||
wanted[name + ".cer"] = intermediates[i].RawData;
|
||||
wanted[name + ".pem"] = System.Text.Encoding.ASCII.GetBytes(intermediates[i].ExportCertificatePem() + '\n');
|
||||
}
|
||||
|
||||
if (caCertificates.FirstOrDefault(ServerTls.IsSelfIssued) is { } root)
|
||||
{
|
||||
wanted["root-ca.cer"] = root.RawData;
|
||||
wanted["root-ca.pem"] = System.Text.Encoding.ASCII.GetBytes(root.ExportCertificatePem() + '\n');
|
||||
}
|
||||
|
||||
if (wanted.Count > 0)
|
||||
{
|
||||
wanted[Marker] = System.Text.Encoding.ASCII.GetBytes(ServerTls.ChainPem(caCertificates));
|
||||
}
|
||||
|
||||
var changed = false;
|
||||
if (Directory.Exists(directory))
|
||||
{
|
||||
foreach (var stale in Directory.EnumerateFiles(directory)
|
||||
.Where(f => IsOurs(Path.GetFileName(f)) && !wanted.ContainsKey(Path.GetFileName(f))))
|
||||
{
|
||||
File.Delete(stale);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (wanted.Count > 0)
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
foreach (var (name, content) in wanted)
|
||||
{
|
||||
var path = Path.Combine(directory, name);
|
||||
if (!File.Exists(path) || !File.ReadAllBytes(path).AsSpan().SequenceEqual(content))
|
||||
{
|
||||
File.WriteAllBytes(path, content);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed && wanted.Count > 0)
|
||||
{
|
||||
logger.LogInformation("TLS: CA certificates for distribution (root and intermediate, no keys) are in {Directory}", directory);
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
logger.LogWarning(exception, "TLS: could not refresh the CA certificates in {Directory}", directory);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsOurs(string name)
|
||||
=> name.Equals(Marker, StringComparison.OrdinalIgnoreCase)
|
||||
|| ((name.StartsWith("root-ca", StringComparison.OrdinalIgnoreCase) || name.StartsWith("intermediate-ca", StringComparison.OrdinalIgnoreCase))
|
||||
&& (name.EndsWith(".cer", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".pem", StringComparison.OrdinalIgnoreCase)));
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
using System.Net.Security;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Backend.Auth;
|
||||
using Backend.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Backend.Tls;
|
||||
|
||||
/// <summary>Which source a <see cref="ServerTlsSwitch"/> serves.</summary>
|
||||
public enum ServedSource
|
||||
{
|
||||
/// <summary>The configured source (appsettings.json / environment).</summary>
|
||||
Configured,
|
||||
|
||||
/// <summary>The console bound the managed self-signed chain.</summary>
|
||||
SelfSigned,
|
||||
|
||||
/// <summary>The console bound a certificate in LocalMachine\My by identity.</summary>
|
||||
Store,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The listener's certificate source, switchable without a restart. It serves
|
||||
/// the configured source (TLS_* in appsettings.json or the environment)
|
||||
/// unless the console's binding (<see cref="ServerCertificateBinding"/>, a
|
||||
/// settings document every replica reads each minute) says otherwise: a
|
||||
/// certificate in this replica's LocalMachine\My followed by identity, or the
|
||||
/// managed self-signed chain. A certificate setting in the process
|
||||
/// environment (<see cref="TlsSettings.ForcedByEnvironment"/>) wins over the
|
||||
/// binding. A binding that cannot be applied here — a Linux replica, no
|
||||
/// matching certificate — leaves the current source serving and says why
|
||||
/// (<see cref="Problem"/>).
|
||||
/// </summary>
|
||||
public sealed class ServerTlsSwitch : IServerTlsSource
|
||||
{
|
||||
private static readonly TimeSpan ManagedInterval = TimeSpan.FromHours(6);
|
||||
|
||||
private readonly Lock gate = new();
|
||||
private readonly TlsSettings settings;
|
||||
private readonly IServerTlsSource configured;
|
||||
private readonly StoreLocation storeLocation;
|
||||
private readonly Func<X509Certificate2, bool, bool>? isPublic;
|
||||
private readonly string replica;
|
||||
private IServiceScopeFactory? scopes;
|
||||
private IServerTlsSource active;
|
||||
private string activeKey = "configured";
|
||||
private DateTimeOffset lastInnerRefresh = DateTimeOffset.MinValue;
|
||||
private SelfSignedTlsManager? managed;
|
||||
|
||||
public ServerTlsSwitch(TlsSettings settings, IServerTlsSource configured, string? forcedBy,
|
||||
StoreLocation storeLocation = StoreLocation.LocalMachine, Func<X509Certificate2, bool, bool>? isPublic = null, string? replica = null)
|
||||
{
|
||||
this.settings = settings;
|
||||
this.configured = configured;
|
||||
this.storeLocation = storeLocation;
|
||||
this.isPublic = isPublic;
|
||||
this.replica = replica ?? Environment.MachineName;
|
||||
ForcedBy = forcedBy;
|
||||
active = configured;
|
||||
managed = configured as SelfSignedTlsManager;
|
||||
}
|
||||
|
||||
/// <summary>The environment variable that fixes the source, or null.</summary>
|
||||
public string? ForcedBy { get; }
|
||||
|
||||
public TlsSettings Settings => settings;
|
||||
|
||||
public IServerTlsSource Configured => configured;
|
||||
|
||||
public IServerTlsSource Active => Volatile.Read(ref active);
|
||||
|
||||
public ServedSource Served { get; private set; } = ServedSource.Configured;
|
||||
|
||||
/// <summary>The binding last read from the database (applied or not).</summary>
|
||||
public ServerCertificateBinding? Binding { get; private set; }
|
||||
|
||||
/// <summary>This replica's certificate for the binding.</summary>
|
||||
public ReplicaCertificate? ReplicaState => Binding?.Replicas?.GetValueOrDefault(replica);
|
||||
|
||||
public ServerRootChange? RootChange { get; private set; }
|
||||
|
||||
/// <summary>Why the binding is not what this replica serves, or null.</summary>
|
||||
public string? Problem { get; private set; }
|
||||
|
||||
public string ReplicaName => replica;
|
||||
|
||||
public StoreLocation StoreLocation => storeLocation;
|
||||
|
||||
public TimeSpan RefreshInterval => TimeSpan.FromMinutes(1);
|
||||
|
||||
public X509Certificate2? ServerCertificate => Active.ServerCertificate;
|
||||
|
||||
public SslStreamCertificateContext? CertificateContext => Active.CertificateContext;
|
||||
|
||||
public string? CaChainPem() => Active.CaChainPem();
|
||||
|
||||
public string? CaFingerprint() => Active.CaFingerprint();
|
||||
|
||||
/// <summary>Reads (and records) the binding from this database from now on.</summary>
|
||||
public void UseDatabase(IServiceScopeFactory scopeFactory) => scopes = scopeFactory;
|
||||
|
||||
public bool Refresh(ILogger logger)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
ReadDocuments(logger);
|
||||
var (key, problem) = Desired(ForcedBy is null ? Binding : null);
|
||||
Problem = ForcedBy is not null && Binding is not null
|
||||
? $"{ForcedBy} is set in the environment, so the console binding is not applied."
|
||||
: problem;
|
||||
|
||||
var current = Active;
|
||||
var hadCertificate = current.ServerCertificate is not null;
|
||||
var rootBefore = current.CaFingerprint();
|
||||
bool changed;
|
||||
if (key != activeKey)
|
||||
{
|
||||
changed = Switch(key, logger);
|
||||
}
|
||||
else if (current is SelfSignedTlsManager && hadCertificate && DateTimeOffset.UtcNow - lastInnerRefresh < ManagedInterval)
|
||||
{
|
||||
changed = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
changed = current.Refresh(logger);
|
||||
lastInnerRefresh = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
if (changed && hadCertificate)
|
||||
{
|
||||
RecordRootChange(rootBefore, Active.CaFingerprint(), logger);
|
||||
}
|
||||
|
||||
if (Served == ServedSource.Store)
|
||||
{
|
||||
RecordReplica(logger);
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
|
||||
private (string Key, string? Problem) Desired(ServerCertificateBinding? binding)
|
||||
{
|
||||
if (binding is null)
|
||||
{
|
||||
return ("configured", null);
|
||||
}
|
||||
|
||||
if (binding.Mode == ServerCertificateBinding.SelfSignedMode)
|
||||
{
|
||||
return ("self-signed", null);
|
||||
}
|
||||
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
return ("configured", "This server is not on Windows, so it cannot use the Windows certificate store; it serves its configured certificate.");
|
||||
}
|
||||
|
||||
return binding.Identity is null
|
||||
? ("configured", "The binding names no certificate.")
|
||||
: ($"store:{binding.Identity.Subject}|{binding.Identity.Issuer}|{binding.Identity.Template}|{string.Join(',', binding.Identity.DnsNames)}", null);
|
||||
}
|
||||
|
||||
private bool Switch(string key, ILogger logger)
|
||||
{
|
||||
IServerTlsSource next = key switch
|
||||
{
|
||||
"configured" => configured,
|
||||
"self-signed" => managed ??= new SelfSignedTlsManager(settings.WithSource(TlsCertificateSource.SelfSigned)),
|
||||
// Renewal links start from what this replica served last (thumbprints differ per machine).
|
||||
_ => new ProvidedTlsCertificate(settings.WithSource(TlsCertificateSource.Store), storeLocation, isPublic,
|
||||
Binding! with { Thumbprint = ReplicaState?.Thumbprint ?? Binding!.Thumbprint }),
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
next.Refresh(logger);
|
||||
if (next.ServerCertificate is null)
|
||||
{
|
||||
throw new InvalidOperationException("No certificate was loaded.");
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (key != "configured")
|
||||
{
|
||||
Problem = exception.Message;
|
||||
logger.LogWarning("TLS: the console's certificate binding cannot be applied here ({Reason}); still serving the current certificate", exception.Message);
|
||||
if (Active.ServerCertificate is not null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// First start: fall back to the configured source (which stops the server with its own reason if it cannot load either).
|
||||
next = configured;
|
||||
next.Refresh(logger);
|
||||
key = "configured";
|
||||
}
|
||||
|
||||
Volatile.Write(ref active, next);
|
||||
activeKey = key;
|
||||
Served = key switch { "configured" => ServedSource.Configured, "self-signed" => ServedSource.SelfSigned, _ => ServedSource.Store };
|
||||
lastInnerRefresh = DateTimeOffset.UtcNow;
|
||||
logger.LogInformation("TLS: now serving {Source} ({Thumbprint})", Served, next.ServerCertificate?.Thumbprint);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ReadDocuments(ILogger logger)
|
||||
{
|
||||
if (scopes is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
var rows = db.AppSettings.AsNoTracking()
|
||||
.Where(s => s.Key == ServerCertificateBinding.Key || s.Key == ServerRootChange.Key)
|
||||
.ToList();
|
||||
Binding = SettingsDocuments.ParseOrNull<ServerCertificateBinding>(rows.FirstOrDefault(r => r.Key == ServerCertificateBinding.Key)?.Value);
|
||||
RootChange = SettingsDocuments.ParseOrNull<ServerRootChange>(rows.FirstOrDefault(r => r.Key == ServerRootChange.Key)?.Value);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// The database is down or not migrated yet: keep what was read last.
|
||||
logger.LogDebug(exception, "TLS: the certificate binding could not be read");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A private root agents had not been given before: say so until the chain is publicly trusted again.</summary>
|
||||
private void RecordRootChange(string? before, string? after, ILogger logger)
|
||||
{
|
||||
if (before == after)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var change = after is null ? null : new ServerRootChange(after, before, DateTimeOffset.UtcNow);
|
||||
if (change is not null)
|
||||
{
|
||||
logger.LogWarning(
|
||||
"TLS: the served chain has a new root ({Fingerprint}); agents enrolled before cannot validate it until it is pushed to them or they get a new bootstrap token",
|
||||
after);
|
||||
}
|
||||
|
||||
Write(ServerRootChange.Key, change, logger);
|
||||
RootChange = change;
|
||||
}
|
||||
|
||||
/// <summary>Notes the certificate this replica serves for the binding, and when it followed a renewal.</summary>
|
||||
private void RecordReplica(ILogger logger)
|
||||
{
|
||||
if (Binding is null || Active.ServerCertificate is not { } leaf)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var previous = ReplicaState;
|
||||
if (previous is not null && previous.Thumbprint == leaf.Thumbprint)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var last = previous?.Thumbprint ?? Binding.Thumbprint;
|
||||
var followed = last is not null && last != leaf.Thumbprint;
|
||||
var state = new ReplicaCertificate(leaf.Thumbprint, followed ? DateTimeOffset.UtcNow : previous?.LastSwitchedUtc, followed ? last : previous?.PreviousThumbprint);
|
||||
var replicas = new Dictionary<string, ReplicaCertificate>(Binding.Replicas ?? new Dictionary<string, ReplicaCertificate>(), StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
[replica] = state,
|
||||
};
|
||||
var updated = Binding with { Replicas = replicas };
|
||||
if (Write(ServerCertificateBinding.Key, updated, logger, expectedEtag: true))
|
||||
{
|
||||
Binding = updated;
|
||||
}
|
||||
}
|
||||
|
||||
private bool Write<T>(string key, T? value, ILogger logger, bool expectedEtag = false)
|
||||
where T : class
|
||||
{
|
||||
if (scopes is null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
var row = db.AppSettings.SingleOrDefault(s => s.Key == key);
|
||||
if (value is null)
|
||||
{
|
||||
if (row is not null)
|
||||
{
|
||||
db.AppSettings.Remove(row);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (expectedEtag && row is null)
|
||||
{
|
||||
// The binding was cleared meanwhile.
|
||||
return false;
|
||||
}
|
||||
|
||||
SettingsDocuments.Stage(db, row, key, null, value, $"tls:{replica}", always: true);
|
||||
}
|
||||
|
||||
db.SaveChanges();
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogDebug(exception, "TLS: {Key} could not be recorded", key);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,29 @@
|
||||
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.
|
||||
/// Keeps the served certificate current without a restart: re-runs the
|
||||
/// source's idempotent refresh periodically — the managed chain is re-issued
|
||||
/// well before expiry (every 6 hours checked), a provided certificate's
|
||||
/// replacement or renewal is picked up within a minute — and Kestrel takes
|
||||
/// the new one on the next handshake.
|
||||
/// </summary>
|
||||
public sealed class TlsRenewalService(SelfSignedTlsManager manager, ILogger<TlsRenewalService> logger)
|
||||
public sealed class TlsRenewalService(IServerTlsSource source, ILogger<TlsRenewalService> logger)
|
||||
: BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromHours(6));
|
||||
using var timer = new PeriodicTimer(source.RefreshInterval);
|
||||
try
|
||||
{
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken))
|
||||
{
|
||||
try
|
||||
{
|
||||
manager.EnsureChain(logger);
|
||||
source.Refresh(logger);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Self-signed TLS renewal check failed; will retry");
|
||||
logger.LogError(ex, "TLS certificate refresh failed; will retry");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,8 +12,52 @@ namespace Backend.Tls;
|
||||
/// </summary>
|
||||
public sealed class TlsSettings
|
||||
{
|
||||
/// <summary>The distribution folder's name under the data directory.</summary>
|
||||
public const string DistributionFolderName = "ca-certificates";
|
||||
|
||||
public bool Enabled { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Where the server certificate comes from (TLS_CERT_SOURCE): the managed
|
||||
/// self-signed chain (the default), LocalMachine\My by thumbprint
|
||||
/// (TLS_CERT_THUMBPRINT, Windows), or a file (TLS_CERT_FILE: PFX/PKCS#12
|
||||
/// with TLS_CERT_PASSWORD, or PEM with TLS_CERT_KEY_FILE).
|
||||
/// </summary>
|
||||
public TlsCertificateSource Source { get; init; } = TlsCertificateSource.SelfSigned;
|
||||
|
||||
/// <summary>LocalMachine\My thumbprint (Source = Store).</summary>
|
||||
public string? StoreThumbprint { get; init; }
|
||||
|
||||
/// <summary>PFX/P12 or PEM certificate file (Source = File).</summary>
|
||||
public string? CertificateFile { get; init; }
|
||||
|
||||
/// <summary>PEM private key file; empty when the key is in <see cref="CertificateFile"/> (or a PFX).</summary>
|
||||
public string? KeyFile { get; init; }
|
||||
|
||||
/// <summary>PFX password, or an encrypted PEM key's password.</summary>
|
||||
public string? CertificatePassword { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// TLS_DISTRIBUTE_CA: whether a provided certificate's issuing chain is
|
||||
/// handed to agents (GET /api/enrollment/ca, the token fingerprint and the
|
||||
/// distribution folder). Null decides by itself: only a chain that is not
|
||||
/// publicly trusted is distributed.
|
||||
/// </summary>
|
||||
public bool? DistributeCa { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The root and intermediate certificates (never the leaf, never a key),
|
||||
/// as .cer and .pem, for administrators to push by Group Policy. Null
|
||||
/// writes nothing. Defaults to <data>/ca-certificates.
|
||||
/// </summary>
|
||||
public string? DistributionDirectory { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Where a provided certificate is mirrored as server.crt/server.key PEM for
|
||||
/// an exposed NATS WebSocket (NATS_TLS_CERT's folder); null mirrors nothing.
|
||||
/// </summary>
|
||||
public string? LeafMirrorDirectory { get; init; }
|
||||
|
||||
/// <summary>PEM storage directory (file mode). Defaults to <data>/tls.</summary>
|
||||
public required string CertificateDirectory { get; init; }
|
||||
|
||||
@@ -28,22 +72,92 @@ public sealed class TlsSettings
|
||||
|
||||
public IReadOnlyList<IPAddress> IpAddresses { get; init; } = [];
|
||||
|
||||
/// <summary>These settings serving another source (a console binding).</summary>
|
||||
public TlsSettings WithSource(TlsCertificateSource source) => new()
|
||||
{
|
||||
Enabled = Enabled,
|
||||
Source = source,
|
||||
StoreThumbprint = StoreThumbprint,
|
||||
CertificateFile = CertificateFile,
|
||||
KeyFile = KeyFile,
|
||||
CertificatePassword = CertificatePassword,
|
||||
DistributeCa = DistributeCa,
|
||||
DistributionDirectory = DistributionDirectory,
|
||||
LeafMirrorDirectory = LeafMirrorDirectory,
|
||||
CertificateDirectory = CertificateDirectory,
|
||||
UseWindowsStore = UseWindowsStore,
|
||||
DnsNames = DnsNames,
|
||||
IpAddresses = IpAddresses,
|
||||
};
|
||||
|
||||
/// <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.
|
||||
/// The certificate setting the process environment sets, which no console
|
||||
/// binding overrides (a container or service definition is authoritative);
|
||||
/// values from appsettings.json — what setup and the MSI write — are only
|
||||
/// the default. Null when none is set.
|
||||
/// </summary>
|
||||
public static string? ForcedByEnvironment(Func<string, string?>? read = null)
|
||||
{
|
||||
read ??= Environment.GetEnvironmentVariable;
|
||||
return new[] { "TLS_CERT_SOURCE", "TLS_CERT_THUMBPRINT", "TLS_CERT_FILE" }.FirstOrDefault(name => read(name) is { Length: > 0 });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when this request reached this server's own listener directly and
|
||||
/// the listener serves a chain devices may not trust yet (the managed
|
||||
/// self-signed chain, or a provided certificate from a private CA) — HTTPS
|
||||
/// served here with no forwarded headers consumed (a proxied request
|
||||
/// carries X-Original-* after UseForwardedHeaders). Generated install
|
||||
/// commands then accept the certificate for the script fetch; the script
|
||||
/// and the agent pin the CA to the token's fingerprint from there.
|
||||
/// </summary>
|
||||
public bool IsSelfSignedDirect(HttpContext context)
|
||||
=> Enabled
|
||||
&& context.Request.IsHttps
|
||||
&& !context.Request.Headers.ContainsKey("X-Original-Proto")
|
||||
&& !context.Request.Headers.ContainsKey("X-Original-For");
|
||||
&& !context.Request.Headers.ContainsKey("X-Original-For")
|
||||
&& (context.RequestServices.GetService<IServerTlsSource>() is not { } source || source.CaChainPem() is not null);
|
||||
|
||||
/// <summary>TLS_CERT_SOURCE: self-signed (or managed), store, file; empty infers it from which certificate setting is set.</summary>
|
||||
public static TlsCertificateSource ParseSource(string? value, string? thumbprint, string? file)
|
||||
=> value?.Trim().Replace("-", string.Empty).Replace("_", string.Empty).ToLowerInvariant() switch
|
||||
{
|
||||
null or "" => thumbprint is { Length: > 0 } ? TlsCertificateSource.Store
|
||||
: file is { Length: > 0 } ? TlsCertificateSource.File
|
||||
: TlsCertificateSource.SelfSigned,
|
||||
"selfsigned" or "managed" => TlsCertificateSource.SelfSigned,
|
||||
"store" or "windowsstore" or "certificatestore" => TlsCertificateSource.Store,
|
||||
"file" or "pfx" or "pem" => TlsCertificateSource.File,
|
||||
_ => throw new InvalidOperationException($"TLS_CERT_SOURCE must be self-signed, store or file (got '{value}')."),
|
||||
};
|
||||
|
||||
/// <summary>Thumbprints copied from the certificate console carry spaces and an invisible left-to-right mark.</summary>
|
||||
public static string? NormalizeThumbprint(string? thumbprint)
|
||||
=> thumbprint is null ? null : new string([.. thumbprint.Where(Uri.IsHexDigit)]).ToUpperInvariant() is { Length: > 0 } clean ? clean : null;
|
||||
|
||||
public static TlsSettings FromConfiguration(IConfiguration configuration)
|
||||
{
|
||||
var enabled = configuration["TLS_SELF_SIGNED"] != "0";
|
||||
var thumbprint = NormalizeThumbprint(configuration["TLS_CERT_THUMBPRINT"]);
|
||||
var certificateFile = configuration["TLS_CERT_FILE"] is { Length: > 0 } f ? f.Trim().Trim('"') : null;
|
||||
var source = ParseSource(configuration["TLS_CERT_SOURCE"], thumbprint, certificateFile);
|
||||
if (source == TlsCertificateSource.Store && thumbprint is null)
|
||||
{
|
||||
throw new InvalidOperationException("TLS_CERT_SOURCE=store needs TLS_CERT_THUMBPRINT (a certificate in LocalMachine\\My).");
|
||||
}
|
||||
|
||||
if (source == TlsCertificateSource.Store && !OperatingSystem.IsWindows())
|
||||
{
|
||||
throw new InvalidOperationException("TLS_CERT_SOURCE=store is for Windows; elsewhere use TLS_CERT_FILE.");
|
||||
}
|
||||
|
||||
if (source == TlsCertificateSource.File && certificateFile is null)
|
||||
{
|
||||
throw new InvalidOperationException("TLS_CERT_SOURCE=file needs TLS_CERT_FILE (a PFX/P12, or a PEM with TLS_CERT_KEY_FILE).");
|
||||
}
|
||||
|
||||
// A provided certificate turns TLS on by itself; TLS_SELF_SIGNED=0 only opts out of the managed chain.
|
||||
var enabled = source != TlsCertificateSource.SelfSigned || configuration["TLS_SELF_SIGNED"] != "0";
|
||||
var selfSigned = enabled && source == TlsCertificateSource.SelfSigned;
|
||||
var certDir = configuration["TLS_CERT_DIR"];
|
||||
// Prefer the explicit data root; otherwise fall back to the database's
|
||||
// directory. The DB now lives in data/db, so deriving from it alone
|
||||
@@ -86,7 +200,7 @@ public sealed class TlsSettings
|
||||
// public address validates. Best-effort and time-bounded, and only
|
||||
// when we're actually generating a self-signed cert (never in tests
|
||||
// or when TLS is off) so it makes no network calls otherwise.
|
||||
if (enabled)
|
||||
if (selfSigned)
|
||||
{
|
||||
AddPublicIpAddresses(ipAddresses);
|
||||
}
|
||||
@@ -135,6 +249,21 @@ public sealed class TlsSettings
|
||||
return new TlsSettings
|
||||
{
|
||||
Enabled = enabled,
|
||||
Source = source,
|
||||
StoreThumbprint = thumbprint,
|
||||
CertificateFile = certificateFile,
|
||||
KeyFile = configuration["TLS_CERT_KEY_FILE"] is { Length: > 0 } key ? key.Trim().Trim('"') : null,
|
||||
CertificatePassword = configuration["TLS_CERT_PASSWORD"] is { Length: > 0 } password ? password : null,
|
||||
DistributeCa = configuration["TLS_DISTRIBUTE_CA"]?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"1" or "true" or "yes" => true,
|
||||
"0" or "false" or "no" => false,
|
||||
_ => null,
|
||||
},
|
||||
DistributionDirectory = Path.Combine(dataDir, DistributionFolderName),
|
||||
LeafMirrorDirectory = source != TlsCertificateSource.SelfSigned && configuration["NATS_TLS_CERT"] is { Length: > 0 } natsCertificate
|
||||
? Path.GetDirectoryName(Path.GetFullPath(natsCertificate))
|
||||
: null,
|
||||
CertificateDirectory = certDir is { Length: > 0 } ? certDir : Path.Combine(dataDir, "tls"),
|
||||
UseWindowsStore = OperatingSystem.IsWindows() && certDir is not { Length: > 0 },
|
||||
DnsNames = dnsNames,
|
||||
|
||||
@@ -66,7 +66,7 @@ LABEL org.opencontainers.image.title="ExecuteR Control Plane Backend" \
|
||||
org.opencontainers.image.url="${SOURCE_URL}" \
|
||||
org.opencontainers.image.documentation="${SOURCE_URL}/wiki" \
|
||||
org.opencontainers.image.vendor="ExecuteR" \
|
||||
org.opencontainers.image.licenses="LicenseRef-GraceSolutions-Proprietary"
|
||||
org.opencontainers.image.licenses="LicenseRef-EndexaSolutions-Proprietary"
|
||||
|
||||
# curl is used by the compose health check.
|
||||
RUN apt-get update \
|
||||
|
||||
@@ -29,7 +29,7 @@ LABEL org.opencontainers.image.title="ExecuteR Control Plane WebUI" \
|
||||
org.opencontainers.image.url="${SOURCE_URL}" \
|
||||
org.opencontainers.image.documentation="${SOURCE_URL}/wiki" \
|
||||
org.opencontainers.image.vendor="ExecuteR" \
|
||||
org.opencontainers.image.licenses="LicenseRef-GraceSolutions-Proprietary"
|
||||
org.opencontainers.image.licenses="LicenseRef-EndexaSolutions-Proprietary"
|
||||
|
||||
# The console is a static SPA; server.mjs (no dependencies) serves dist/ with
|
||||
# an index.html fallback for client-side routes.
|
||||
|
||||
@@ -1,30 +1,43 @@
|
||||
<Wix xmlns="http://wixtoolset.org/schemas/v4/wxs"
|
||||
xmlns:util="http://wixtoolset.org/schemas/v4/wxs/util"
|
||||
xmlns:ui="http://wixtoolset.org/schemas/v4/wxs/ui">
|
||||
xmlns:util="http://wixtoolset.org/schemas/v4/wxs/util">
|
||||
|
||||
<!--
|
||||
ExecuteR Server MSI: the standalone combined server (UI + API + messaging
|
||||
relay + NATS sidecar) as a Windows service.
|
||||
relay + NATS sidecar) as a Windows service. `msiexec /i Server.msi /qn` ends
|
||||
in the same state as running the binary's own `setup` and `service install`.
|
||||
|
||||
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:
|
||||
Public properties for the listeners, all defaulted so a next-next-next
|
||||
install works:
|
||||
|
||||
ExecuteR-Server.exe setup (with the admin user/password flags)
|
||||
ExecuteR-Server.exe service install
|
||||
BINDADDRESS=<ip> the address the server binds (0.0.0.0, every interface)
|
||||
HTTPPORT=<port> console, API and agents (9080)
|
||||
NATSPORT NATSWSPORT NATSMONITORPORT NATSBIND
|
||||
the NATS sidecar (4222/9222/8222 on 127.0.0.1)
|
||||
|
||||
The certificate (the Certificate page; ServerUI.wxs):
|
||||
|
||||
ENABLETLS=1 HTTPS, on by default; ENABLETLS="" serves plain HTTP
|
||||
TLSSOURCE=selfsigned the managed self-signed chain (the default), auto-renewed
|
||||
TLSSOURCE=store TLSTHUMBPRINT=<hex>
|
||||
a certificate in LocalMachine\My
|
||||
TLSSOURCE=file TLSCERTFILE=<path> [TLSKEYFILE=<path>] [TLSCERTPASSWORD=<pw>]
|
||||
a PFX (with its password) or a PEM certificate and key
|
||||
|
||||
The first administrator is no longer asked for: the first start generates a
|
||||
one-time password, writes it to data\initial-admin-password.txt (readable by
|
||||
Administrators and SYSTEM only) and requires a new one at the first sign-in.
|
||||
`ExecuteR-Server reset-admin` gives a new one any time. For scripted installs
|
||||
that set their own, ADMINUSERNAME and ADMINPASSWORD are still honoured on
|
||||
the command line (ADMINPASSWORD and TLSCERTPASSWORD are hidden from the log,
|
||||
and the setup command that carries them runs without logging its line).
|
||||
|
||||
setup is idempotent (keys/config/appsettings are only generated when
|
||||
absent), so upgrades never overwrite an existing configuration and the
|
||||
admin properties only take effect on the very first install.
|
||||
absent), so upgrades never overwrite an existing configuration and these
|
||||
properties only take effect on the very first install.
|
||||
-->
|
||||
|
||||
<Package Name="ExecuteR Server"
|
||||
Manufacturer="ExecuteR"
|
||||
Manufacturer="Endexa Solutions"
|
||||
Version="$(MsiProductVersion)"
|
||||
UpgradeCode="b4e6a7c9-52d1-4f3e-8a20-9c15d7b64e88"
|
||||
Scope="perMachine"
|
||||
@@ -49,6 +62,7 @@
|
||||
<!-- The full version (X.Y.Z or X.Y.Z.N), for FindNewerRelease and ARP. -->
|
||||
<Property Id="UNIFIEDVERSION" Value="$(UnifiedVersion)" />
|
||||
<Property Id="ARPCOMMENTS" Value="ExecuteR Server $(UnifiedVersion)" />
|
||||
<Property Id="ARPNOMODIFY" Value="1" />
|
||||
|
||||
<Binary Id="ExecuteRCustomActions" SourceFile="$(var.Installer.CustomActions.TargetDir)Installer.CustomActions.CA.dll" />
|
||||
<CustomAction Id="FindNewerRelease" BinaryRef="ExecuteRCustomActions" DllEntry="FindNewerRelease"
|
||||
@@ -67,31 +81,34 @@
|
||||
<Icon Id="AppIcon" SourceFile="$(AppIconPath)" />
|
||||
<Property Id="ARPPRODUCTICON" Value="AppIcon" />
|
||||
|
||||
<Property Id="ADMINUSERNAME" Value="admin" />
|
||||
<Property Id="ADMINPASSWORD" Value="admin" Hidden="yes" />
|
||||
<!-- Scripted installs only: the wizard never asks; empty means generate and record. -->
|
||||
<Property Id="ADMINUSERNAME" Secure="yes" />
|
||||
<Property Id="ADMINPASSWORD" Secure="yes" Hidden="yes" />
|
||||
|
||||
<!-- Listen configuration defaults. -->
|
||||
<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" />
|
||||
<Property Id="BINDADDRESS" Value="0.0.0.0" Secure="yes" />
|
||||
<Property Id="HTTPPORT" Value="9080" Secure="yes" />
|
||||
<Property Id="NATSPORT" Value="4222" Secure="yes" />
|
||||
<Property Id="NATSWSPORT" Value="9222" Secure="yes" />
|
||||
<Property Id="NATSMONITORPORT" Value="8222" Secure="yes" />
|
||||
<!-- The NATS WebSocket listener binds here (core + monitor always stay on
|
||||
loopback). Loopback by default — the server relays /messaging/* over
|
||||
loopback. Set to 0.0.0.0 only when an edge proxy on another host must
|
||||
reach the WebSocket directly; over self-signed TLS it reuses the
|
||||
managed leaf certificate. -->
|
||||
<Property Id="NATSBIND" Value="127.0.0.1" />
|
||||
reach the WebSocket directly; over TLS it reuses the server's leaf. -->
|
||||
<Property Id="NATSBIND" Value="127.0.0.1" Secure="yes" />
|
||||
|
||||
<!-- 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" />
|
||||
<!-- TLS: on by default with the managed self-signed chain; the Certificate
|
||||
page (or the properties) picks a certificate of the administrator's own. -->
|
||||
<Property Id="ENABLETLS" Value="1" Secure="yes" />
|
||||
<Property Id="TLSSOURCE" Value="selfsigned" Secure="yes" />
|
||||
<Property Id="TLSTHUMBPRINT" Secure="yes" />
|
||||
<Property Id="TLSCERTFILE" Secure="yes" />
|
||||
<Property Id="TLSKEYFILE" Secure="yes" />
|
||||
<Property Id="TLSCERTPASSWORD" Secure="yes" Hidden="yes" />
|
||||
|
||||
<!-- Finish page: open the UI in the browser (checked by default). The
|
||||
<!-- Finish page: open the console 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"
|
||||
@@ -112,8 +129,8 @@
|
||||
</ComponentGroup>
|
||||
|
||||
<!-- Record the install location so tools can find it later, and put the
|
||||
binary on the system PATH. Both the registry value and the PATH entry
|
||||
are removed on uninstall (Permanent="no"). -->
|
||||
binary on the system PATH (so `ExecuteR-Server reset-admin` works from
|
||||
any elevated prompt). Both are removed on uninstall (Permanent="no"). -->
|
||||
<ComponentGroup Id="ServerRegistration" Directory="INSTALLFOLDER">
|
||||
<Component Id="ServerRegistration" Guid="7a1e3c92-4b6d-4e11-9f28-2c5a7d0b9e34">
|
||||
<RegistryValue Root="HKLM" Key="SOFTWARE\ExecuteR\Server" Name="InstallDir"
|
||||
@@ -128,20 +145,50 @@
|
||||
<ComponentGroupRef Id="ServerRegistration" />
|
||||
</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. -->
|
||||
<!-- The wizard on an interactive install (ServerUI.wxs). -->
|
||||
<UIRef Id="ServerUI" />
|
||||
|
||||
<!--
|
||||
First-boot init through the binary's own cross-platform CLI. Only the
|
||||
properties given become options; short aliases keep the formatted command
|
||||
inside the 255-character CustomAction column (ICE03). The quotes around
|
||||
ENABLETLS are load-bearing: unchecked formats to an empty quoted argument,
|
||||
which setup reads as off.
|
||||
-->
|
||||
<Property Id="SetupAdminPassword" Hidden="yes" />
|
||||
<Property Id="SetupTls" Hidden="yes" />
|
||||
<Property Id="RunServerSetup" Hidden="yes" />
|
||||
<Property Id="RunServerSetupSilent" Hidden="yes" />
|
||||
<SetProperty Id="SetupAdminUser" Value=" --admin-user "[ADMINUSERNAME]"" Before="InstallInitialize" Sequence="execute"
|
||||
Condition="ADMINUSERNAME" />
|
||||
<SetProperty Id="SetupAdminPassword" Value=" --admin-password "[ADMINPASSWORD]"" Before="InstallInitialize" Sequence="execute"
|
||||
Condition="ADMINPASSWORD" />
|
||||
<SetProperty Id="SetupTls" Action="SetSetupTlsStore" Value=" --ts store --tt "[TLSTHUMBPRINT]"" Before="InstallInitialize" Sequence="execute"
|
||||
Condition="TLSSOURCE = "store"" />
|
||||
<SetProperty Id="SetupTls" Action="SetSetupTlsFile" Value=" --ts file --tf "[TLSCERTFILE]" --tk "[TLSKEYFILE]" --tp "[TLSCERTPASSWORD]""
|
||||
Before="InstallInitialize" Sequence="execute" Condition="TLSSOURCE = "file"" />
|
||||
<SetProperty Id="RunServerSetup"
|
||||
Value=""[INSTALLFOLDER]ExecuteR-Server.exe" setup --admin-user "[ADMINUSERNAME]" --admin-password "[ADMINPASSWORD]" --bind "[BINDADDRESS]" --http [HTTPPORT] --nats [NATSPORT] --ws [NATSWSPORT] --monitor [NATSMONITORPORT] --nb "[NATSBIND]" --tls "[ENABLETLS]""
|
||||
Value=""[INSTALLFOLDER]ExecuteR-Server.exe" setup --bind "[BINDADDRESS]" --http [HTTPPORT] --nats [NATSPORT] --ws [NATSWSPORT] --monitor [NATSMONITORPORT] --nb "[NATSBIND]" --tls "[ENABLETLS]"[SetupAdminUser][SetupTls]"
|
||||
Sequence="execute"
|
||||
Before="RunServerSetup" />
|
||||
<SetProperty Id="RunServerSetupSilent"
|
||||
Value=""[INSTALLFOLDER]ExecuteR-Server.exe" setup --bind "[BINDADDRESS]" --http [HTTPPORT] --nats [NATSPORT] --ws [NATSWSPORT] --monitor [NATSMONITORPORT] --nb "[NATSBIND]" --tls "[ENABLETLS]"[SetupAdminUser][SetupAdminPassword][SetupTls]"
|
||||
Sequence="execute"
|
||||
Before="RunServerSetupSilent" />
|
||||
<!-- A password on the command line: the same setup without its line (or output) in the log. -->
|
||||
<CustomAction Id="RunServerSetup"
|
||||
BinaryRef="Wix4UtilCA_X64"
|
||||
DllEntry="WixQuietExec64"
|
||||
Execute="deferred"
|
||||
Impersonate="no"
|
||||
Return="check" />
|
||||
<CustomAction Id="RunServerSetupSilent"
|
||||
BinaryRef="Wix4UtilCA_X64"
|
||||
DllEntry="WixSilentExec64"
|
||||
Execute="deferred"
|
||||
Impersonate="no"
|
||||
Return="check"
|
||||
HideTarget="yes" />
|
||||
|
||||
<SetProperty Id="InstallServerService"
|
||||
Value=""[INSTALLFOLDER]ExecuteR-Server.exe" service install"
|
||||
@@ -170,7 +217,7 @@
|
||||
the directory. Set after costing, when [INSTALLFOLDER] is resolved. -->
|
||||
<SetProperty Id="ARPINSTALLLOCATION" Value="[INSTALLFOLDER]" After="CostFinalize" />
|
||||
|
||||
<!-- Clean uninstall: PURGEDATA=1 (the Remove page checkbox in the full
|
||||
<!-- Clean uninstall: PURGEDATA=1 (the Remove Data page in the full
|
||||
wizard, or a property on a command-line/silent uninstall) forgets the
|
||||
self-signed chain and deletes the generated
|
||||
data/logs/secrets/appsettings. Runs while the binary still exists
|
||||
@@ -189,166 +236,6 @@
|
||||
Impersonate="no"
|
||||
Return="ignore" />
|
||||
|
||||
<!--
|
||||
Interactive UI: Welcome → Administrator account → Verify → Progress.
|
||||
The account page edits the same ADMINUSERNAME / ADMINPASSWORD public
|
||||
properties the command line sets; silent installs pass them as
|
||||
properties and never show UI.
|
||||
-->
|
||||
<ui:WixUI Id="WixUI_InstallDir" InstallDirectory="INSTALLFOLDER" />
|
||||
<UI>
|
||||
<Dialog Id="ServerConfigDlg" 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}Administrator account" />
|
||||
<Control Id="Description" Type="Text" X="25" Y="23" Width="330" Height="15"
|
||||
Transparent="yes" NoPrefix="yes"
|
||||
Text="The initial sign-in created the first time the server starts." />
|
||||
<Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
|
||||
|
||||
<Control Id="UserLabel" Type="Text" X="20" Y="60" Width="330" Height="12"
|
||||
NoPrefix="yes" Text="Administrator username:" />
|
||||
<Control Id="UserEdit" Type="Edit" X="20" Y="74" Width="330" Height="17"
|
||||
Property="ADMINUSERNAME" />
|
||||
|
||||
<Control Id="PasswordLabel" Type="Text" X="20" Y="100" Width="330" Height="12"
|
||||
NoPrefix="yes" Text="Administrator password:" />
|
||||
<Control Id="PasswordEdit" Type="Edit" X="20" Y="114" Width="330" Height="17"
|
||||
Property="ADMINPASSWORD" Password="yes" />
|
||||
|
||||
<Control Id="Note" Type="Text" X="20" Y="142" Width="330" Height="60" NoPrefix="yes"
|
||||
Text="Keeping the default (admin / admin) forces a password reset at first sign-in. Created on first install only; upgrades keep existing configuration. Silent: ADMINUSERNAME=... ADMINPASSWORD=..." />
|
||||
|
||||
<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>
|
||||
|
||||
<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 = every interface; 127.0.0.1 = this machine only):" />
|
||||
<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 (UI, API, agent enrollment):" />
|
||||
<Control Id="HttpEdit" Type="Edit" X="20" Y="104" Width="70" Height="16"
|
||||
Property="HTTPPORT" />
|
||||
|
||||
<Control Id="NatsLabel" Type="Text" X="20" Y="128" Width="330" Height="12" NoPrefix="yes"
|
||||
Text="NATS ports; WS bind opens the WebSocket for a remote edge proxy (core/monitor stay local):" />
|
||||
<Control Id="NatsBindLabel" Type="Text" X="20" Y="143" Width="85" Height="10" NoPrefix="yes" Text="WS bind" />
|
||||
<Control Id="NatsBindEdit" Type="Edit" X="20" Y="154" Width="85" Height="16" Property="NATSBIND" />
|
||||
<Control Id="NatsCoreLabel" Type="Text" X="115" Y="143" Width="55" Height="10" NoPrefix="yes" Text="Core" />
|
||||
<Control Id="NatsCoreEdit" Type="Edit" X="115" Y="154" Width="55" Height="16" Property="NATSPORT" />
|
||||
<Control Id="NatsWsLabel" Type="Text" X="180" Y="143" Width="55" Height="10" NoPrefix="yes" Text="WebSocket" />
|
||||
<Control Id="NatsWsEdit" Type="Edit" X="180" Y="154" Width="55" Height="16" Property="NATSWSPORT" />
|
||||
<Control Id="NatsMonLabel" Type="Text" X="245" Y="143" Width="55" Height="10" NoPrefix="yes" Text="Monitor" />
|
||||
<Control Id="NatsMonEdit" Type="Edit" X="245" Y="154" Width="55" Height="16" Property="NATSMONITORPORT" />
|
||||
|
||||
<Control Id="TlsCheck" Type="CheckBox" X="20" Y="176" Width="330" Height="12"
|
||||
Property="ENABLETLS" CheckBoxValue="1"
|
||||
Text="Enable Self-Signed TLS (auto-renewed)" />
|
||||
<Control Id="TlsNote" Type="Text" X="32" Y="190" Width="318" Height="20" NoPrefix="yes"
|
||||
Text="Serves the listener over HTTPS with a locally managed certificate chain that renews itself. Browsers on the server trust it automatically." />
|
||||
|
||||
<Control Id="Note" Type="Text" X="20" Y="214" Width="330" Height="18" NoPrefix="yes"
|
||||
Text="Settings persist in appsettings.json next to the binary." />
|
||||
|
||||
<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>
|
||||
|
||||
<!-- Uninstall: offer a clean removal (data, keys, self-signed certs). -->
|
||||
<Dialog Id="PurgeDlg" 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}Remove ExecuteR Server" />
|
||||
<Control Id="Description" Type="Text" X="25" Y="23" Width="330" Height="15"
|
||||
Transparent="yes" NoPrefix="yes"
|
||||
Text="Choose whether to leave data behind or remove everything." />
|
||||
<Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
|
||||
|
||||
<Control Id="PurgeCheck" Type="CheckBox" X="20" Y="70" Width="330" Height="14"
|
||||
Property="PURGEDATA" CheckBoxValue="1"
|
||||
Text="Also remove all data, keys and self-signed certificates" />
|
||||
<Control Id="PurgeNote" Type="Text" X="32" Y="88" Width="318" Height="60" NoPrefix="yes"
|
||||
Text="Leave unchecked to keep the database, sign-in and generated certificates for a reinstall. Checked deletes appsettings.json, data, logs and secrets, and removes the managed self-signed chain from the Windows certificate stores. This cannot be undone." />
|
||||
|
||||
<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="MaintenanceTypeDlg" Control="RemoveButton" Event="NewDialog" Value="PurgeDlg"
|
||||
Order="99" Condition="1" />
|
||||
<Publish Dialog="PurgeDlg" Control="Back" Event="NewDialog" Value="MaintenanceTypeDlg" />
|
||||
<Publish Dialog="PurgeDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg" />
|
||||
<Publish Dialog="ServerConfigDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg" />
|
||||
<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" />
|
||||
<Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="PurgeDlg"
|
||||
Order="98" Condition="Installed AND REMOVE="ALL"" />
|
||||
|
||||
<!-- 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>
|
||||
|
||||
<InstallUISequence>
|
||||
<Custom Action="FindNewerRelease" After="FindRelatedProducts" Condition="NOT Installed" />
|
||||
</InstallUISequence>
|
||||
@@ -357,9 +244,12 @@
|
||||
<Custom Action="FindNewerRelease" After="FindRelatedProducts" Condition="NOT Installed" />
|
||||
<Custom Action="RunServerSetup"
|
||||
After="InstallFiles"
|
||||
Condition="NOT (REMOVE="ALL")" />
|
||||
<Custom Action="InstallServerService"
|
||||
Condition="NOT (REMOVE="ALL") AND NOT ADMINPASSWORD AND NOT TLSCERTPASSWORD" />
|
||||
<Custom Action="RunServerSetupSilent"
|
||||
After="RunServerSetup"
|
||||
Condition="NOT (REMOVE="ALL") AND (ADMINPASSWORD OR TLSCERTPASSWORD)" />
|
||||
<Custom Action="InstallServerService"
|
||||
After="RunServerSetupSilent"
|
||||
Condition="NOT (REMOVE="ALL")" />
|
||||
<Custom Action="UninstallServerService"
|
||||
After="InstallInitialize"
|
||||
|
||||
@@ -28,4 +28,17 @@
|
||||
<ProjectReference Include="..\Installer.CustomActions\Installer.CustomActions.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- ServerUI.wxl is the one culture: the MSI stays in bin/<platform>/<configuration>/, not an en-US folder. -->
|
||||
<Target Name="SingleCultureOutput" AfterTargets="AssignTargetPaths">
|
||||
<ItemGroup>
|
||||
<CultureGroup>
|
||||
<OutputFolder></OutputFolder>
|
||||
</CultureGroup>
|
||||
</ItemGroup>
|
||||
<PropertyGroup>
|
||||
<TargetPath>$(TargetDir)$(TargetFileName)</TargetPath>
|
||||
<TargetPdbPath>$(TargetPdbDir)$(TargetPdbFileName)</TargetPdbPath>
|
||||
</PropertyGroup>
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
<!-- The stock dialogs' titles in Title Case and their descriptions short (the console's UI rules); every other string is the extension's. -->
|
||||
<WixLocalization Culture="en-US" xmlns="http://wixtoolset.org/schemas/v4/wxl">
|
||||
<String Id="WelcomeDlgDescription" Value="Installs [ProductName] [UNIFIEDVERSION] on this computer." />
|
||||
<String Id="WelcomeUpdateDlgDescriptionUpdate" Value="Upgrades [ProductName] to [UNIFIEDVERSION], keeping its settings and data." />
|
||||
<String Id="MaintenanceWelcomeDlgDescription" Value="Repairs or removes [ProductName] [UNIFIEDVERSION]." />
|
||||
<String Id="MaintenanceTypeDlgTitle" Value="{\WixUI_Font_Title}Change, Repair, or Remove" />
|
||||
<String Id="MaintenanceTypeDlgRepairText" Value="Reinstalls the files; settings and data are kept." />
|
||||
<String Id="MaintenanceTypeDlgRemoveText" Value="Removes [ProductName]; the next page offers to remove its data too." />
|
||||
<String Id="VerifyReadyDlgInstallTitle" Value="{\WixUI_Font_Title}Ready to Install [ProductName]" />
|
||||
<String Id="VerifyReadyDlgInstallText" Value="Click Install to begin." />
|
||||
<String Id="VerifyReadyDlgRepairTitle" Value="{\WixUI_Font_Title}Ready to Repair [ProductName]" />
|
||||
<String Id="VerifyReadyDlgRepairText" Value="Click Repair to begin." />
|
||||
<String Id="VerifyReadyDlgRemoveTitle" Value="{\WixUI_Font_Title}Ready to Remove [ProductName]" />
|
||||
<String Id="VerifyReadyDlgRemoveText" Value="Click Remove to remove [ProductName] from this computer." />
|
||||
<String Id="ExitDialogDescription" Value="Click Finish to close the wizard." />
|
||||
</WixLocalization>
|
||||
@@ -0,0 +1,226 @@
|
||||
<!--
|
||||
The server MSI's wizard: the WiX UI extension's stock dialogs with three pages of our own. A silent install (/qn, /qb) never runs it, so the
|
||||
properties on its command line behave as before.
|
||||
|
||||
Install: Welcome › Server Address › Certificate › Ready to Install › Progress › Finish
|
||||
Upgrade: Welcome › Ready to Install › Progress › Finish (setup keeps the configuration in effect)
|
||||
Repair: Welcome › Repair › Ready to Repair › Progress › Finish
|
||||
Remove: Welcome › Remove › Remove Data › Ready to Remove › Progress › Finish
|
||||
|
||||
No administrator page: the first start generates a one-time password and records it where only administrators can read it; Finish says
|
||||
where. Server Address edits BINDADDRESS (as Listen On), HTTPPORT and the NATS sidecar's properties. Certificate picks TLSSOURCE (and ENABLETLS
|
||||
for None): the managed self-signed chain, a certificate in LocalMachine\My by thumbprint, or a PFX/PEM file. Labels are Title Case and short;
|
||||
the detail is in each control's tooltip.
|
||||
-->
|
||||
<Wix xmlns="http://wixtoolset.org/schemas/v4/wxs">
|
||||
<?define Wildcard = (BINDADDRESS = "0.0.0.0" OR BINDADDRESS = "::" OR BINDADDRESS = "[::]") ?>
|
||||
<?define Https = (ENABLETLS = "1" OR TLSSOURCE = "store" OR TLSSOURCE = "file") ?>
|
||||
<Fragment>
|
||||
<!-- The pages' own state, filled from the public properties so a command line preselects them. -->
|
||||
<Property Id="ServerListenMode" Value="All" />
|
||||
<Property Id="ServerListenText" Hidden="yes" />
|
||||
<Property Id="CertificateChoice" Value="selfsigned" />
|
||||
<Property Id="WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT" Value="Open the Console" />
|
||||
<Property Id="WIXUI_EXITDIALOGOPTIONALCHECKBOX" Value="1" />
|
||||
|
||||
<SetProperty Id="ServerListenMode" Action="SetServerListenLocal" Value="Local" After="CostFinalize" Sequence="ui"
|
||||
Condition="BINDADDRESS = "127.0.0.1"" />
|
||||
<SetProperty Id="ServerListenMode" Action="SetServerListenSpecific" Value="Specific" After="SetServerListenLocal" Sequence="ui"
|
||||
Condition="BINDADDRESS AND BINDADDRESS <> "127.0.0.1" AND NOT $(Wildcard)" />
|
||||
<SetProperty Id="ServerListenText" Value="[BINDADDRESS]" After="SetServerListenSpecific" Sequence="ui"
|
||||
Condition="BINDADDRESS AND BINDADDRESS <> "127.0.0.1" AND NOT $(Wildcard)" />
|
||||
<SetProperty Id="CertificateChoice" Action="SetCertificateStore" Value="store" After="CostFinalize" Sequence="ui" Condition="TLSSOURCE = "store"" />
|
||||
<SetProperty Id="CertificateChoice" Action="SetCertificateFile" Value="file" After="SetCertificateStore" Sequence="ui" Condition="TLSSOURCE = "file"" />
|
||||
<SetProperty Id="CertificateChoice" Action="SetCertificateNone" Value="none" After="SetCertificateFile" Sequence="ui"
|
||||
Condition="ENABLETLS <> "1" AND TLSSOURCE <> "store" AND TLSSOURCE <> "file"" />
|
||||
|
||||
<!-- The one-time password is written at the first start of an empty database, so only a first install mentions it. -->
|
||||
<SetProperty Id="WIXUI_EXITDIALOGOPTIONALTEXT" After="CostFinalize" Sequence="ui"
|
||||
Condition="NOT Installed AND NOT WIX_UPGRADE_DETECTED AND NOT ADMINPASSWORD"
|
||||
Value="First sign-in: the one-time admin password is in [INSTALLFOLDER]data\initial-admin-password.txt (administrators only). Locked out later? Run ExecuteR-Server reset-admin." />
|
||||
|
||||
<UI Id="ServerUI">
|
||||
<TextStyle Id="WixUI_Font_Normal" FaceName="Tahoma" Size="8" />
|
||||
<TextStyle Id="WixUI_Font_Bigger" FaceName="Tahoma" Size="12" />
|
||||
<TextStyle Id="WixUI_Font_Title" FaceName="Tahoma" Size="9" Bold="yes" />
|
||||
<Property Id="DefaultUIFont" Value="WixUI_Font_Normal" />
|
||||
|
||||
<DialogRef Id="ErrorDlg" />
|
||||
<DialogRef Id="FatalError" />
|
||||
<DialogRef Id="FilesInUse" />
|
||||
<DialogRef Id="MsiRMFilesInUse" />
|
||||
<DialogRef Id="PrepareDlg" />
|
||||
<DialogRef Id="ProgressDlg" />
|
||||
<DialogRef Id="ResumeDlg" />
|
||||
<DialogRef Id="UserExit" />
|
||||
|
||||
<Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="ServerAddressDlg" Order="2" Condition="NOT Installed AND NOT WIX_UPGRADE_DETECTED" />
|
||||
<Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg" Order="2" Condition="(NOT Installed AND WIX_UPGRADE_DETECTED) OR (Installed AND PATCH)" />
|
||||
|
||||
<Publish Dialog="MaintenanceWelcomeDlg" Control="Next" Event="NewDialog" Value="MaintenanceTypeDlg" />
|
||||
<Publish Dialog="MaintenanceTypeDlg" Control="RepairButton" Event="NewDialog" Value="VerifyReadyDlg" />
|
||||
<Publish Dialog="MaintenanceTypeDlg" Control="RemoveButton" Event="NewDialog" Value="RemoveDataDlg" />
|
||||
<Publish Dialog="MaintenanceTypeDlg" Control="Back" Event="NewDialog" Value="MaintenanceWelcomeDlg" />
|
||||
|
||||
<Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="CertificateDlg" Order="1"
|
||||
Condition="NOT Installed AND NOT WIX_UPGRADE_DETECTED" />
|
||||
<Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg" Order="2"
|
||||
Condition="(NOT Installed AND WIX_UPGRADE_DETECTED) OR (Installed AND PATCH)" />
|
||||
<Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="RemoveDataDlg" Order="3"
|
||||
Condition="Installed AND NOT PATCH AND WixUI_InstallMode = "Remove"" />
|
||||
<Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="MaintenanceTypeDlg" Order="4"
|
||||
Condition="Installed AND NOT PATCH AND WixUI_InstallMode <> "Remove"" />
|
||||
|
||||
<!-- Open the console on Finish: wildcard binds resolve to localhost and the scheme follows TLS. With the managed chain the root
|
||||
sits in the machine's Trusted Roots, 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 NOT $(Https) AND $(Wildcard)" />
|
||||
<Publish Dialog="ExitDialog" Control="Finish" Property="WixShellExecTarget" Value="http://[BINDADDRESS]:[HTTPPORT]/" Order="2"
|
||||
Condition="WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 AND NOT Installed AND NOT $(Https) AND NOT $(Wildcard)" />
|
||||
<Publish Dialog="ExitDialog" Control="Finish" Property="WixShellExecTarget" Value="https://localhost:[HTTPPORT]/" Order="3"
|
||||
Condition="WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 AND NOT Installed AND $(Https) AND $(Wildcard)" />
|
||||
<Publish Dialog="ExitDialog" Control="Finish" Property="WixShellExecTarget" Value="https://[BINDADDRESS]:[HTTPPORT]/" Order="4"
|
||||
Condition="WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 AND NOT Installed AND $(Https) AND NOT $(Wildcard)" />
|
||||
<Publish Dialog="ExitDialog" Control="Finish" Event="DoAction" Value="LaunchBrowser" Order="5"
|
||||
Condition="WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 AND NOT Installed" />
|
||||
<Publish Dialog="ExitDialog" Control="Finish" Event="EndDialog" Value="Return" Order="999" />
|
||||
|
||||
<!-- Server Address: where the console, API, agents and the NATS sidecar listen. -->
|
||||
<RadioButtonGroup Property="ServerListenMode">
|
||||
<RadioButton Value="All" X="0" Y="0" Width="130" Height="14" Text="&All Addresses" ToolTip="Every interface (0.0.0.0)" />
|
||||
<RadioButton Value="Local" X="0" Y="15" Width="130" Height="14" Text="This &Machine Only (127.0.0.1)"
|
||||
ToolTip="For a reverse proxy on this machine" />
|
||||
<RadioButton Value="Specific" X="0" Y="30" Width="100" Height="14" Text="&Specific Address:" />
|
||||
</RadioButtonGroup>
|
||||
<Dialog Id="ServerAddressDlg" Width="370" Height="270" Title="[ProductName] Setup">
|
||||
<Control Id="BannerBitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="44" TabSkip="no" Text="WixUI_Bmp_Banner" />
|
||||
<Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
|
||||
<Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
|
||||
<Control Id="Title" Type="Text" X="15" Y="6" Width="200" Height="15" Transparent="yes" NoPrefix="yes" Text="{\WixUI_Font_Title}Server Address" />
|
||||
<Control Id="Description" Type="Text" X="25" Y="23" Width="280" Height="15" Transparent="yes" NoPrefix="yes"
|
||||
Text="Ports and addresses the server listens on." />
|
||||
|
||||
<Control Id="HttpPortLabel" Type="Text" X="20" Y="58" Width="70" Height="10" Text="&Port:" />
|
||||
<Control Id="HttpPort" Type="Edit" X="95" Y="55" Width="50" Height="15" Property="HTTPPORT" Text="{5}"
|
||||
ToolTip="Console, API and agents" />
|
||||
|
||||
<Control Id="ListenLabel" Type="Text" X="20" Y="82" Width="70" Height="10" Text="&Listen On:" />
|
||||
<Control Id="ListenMode" Type="RadioButtonGroup" X="95" Y="80" Width="130" Height="44" Property="ServerListenMode" />
|
||||
<Control Id="ListenAddress" Type="Edit" X="228" Y="108" Width="122" Height="15" Property="ServerListenText" Text="{64}"
|
||||
ToolTip="An IP address of this computer"
|
||||
DisableCondition="ServerListenMode <> "Specific"" EnableCondition="ServerListenMode = "Specific"" />
|
||||
|
||||
<Control Id="MessagingGroup" Type="GroupBox" X="15" Y="132" Width="340" Height="62" Text="Messaging" />
|
||||
<Control Id="NatsBindLabel" Type="Text" X="25" Y="148" Width="80" Height="10" Text="&WebSocket Bind:" />
|
||||
<Control Id="NatsBind" Type="Edit" X="25" Y="161" Width="85" Height="15" Property="NATSBIND" Text="{64}"
|
||||
ToolTip="0.0.0.0 opens it to an edge proxy elsewhere" />
|
||||
<Control Id="NatsCoreLabel" Type="Text" X="125" Y="148" Width="55" Height="10" Text="&Core:" />
|
||||
<Control Id="NatsCore" Type="Edit" X="125" Y="161" Width="55" Height="15" Property="NATSPORT" Text="{5}"
|
||||
ToolTip="NATS client port, always on 127.0.0.1" />
|
||||
<Control Id="NatsWsLabel" Type="Text" X="190" Y="148" Width="65" Height="10" Text="W&ebSocket:" />
|
||||
<Control Id="NatsWs" Type="Edit" X="190" Y="161" Width="55" Height="15" Property="NATSWSPORT" Text="{5}"
|
||||
ToolTip="NATS WebSocket port, at the WebSocket bind" />
|
||||
<Control Id="NatsMonitorLabel" Type="Text" X="265" Y="148" Width="55" Height="10" Text="M&onitor:" />
|
||||
<Control Id="NatsMonitor" Type="Edit" X="265" Y="161" Width="55" Height="15" Property="NATSMONITORPORT" Text="{5}"
|
||||
ToolTip="NATS monitoring port, always on 127.0.0.1" />
|
||||
|
||||
<Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17" Text="!(loc.WixUIBack)">
|
||||
<Publish Event="NewDialog" Value="WelcomeDlg" />
|
||||
</Control>
|
||||
<Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17" Default="yes" Text="!(loc.WixUINext)"
|
||||
DisableCondition="ServerListenMode = "Specific" AND NOT ServerListenText" EnableCondition="ServerListenMode <> "Specific" OR ServerListenText">
|
||||
<Publish Property="BINDADDRESS" Value="0.0.0.0" Order="1" Condition="ServerListenMode = "All"" />
|
||||
<Publish Property="BINDADDRESS" Value="127.0.0.1" Order="1" Condition="ServerListenMode = "Local"" />
|
||||
<Publish Property="BINDADDRESS" Value="[ServerListenText]" Order="1" Condition="ServerListenMode = "Specific"" />
|
||||
<Publish Event="NewDialog" Value="CertificateDlg" Order="2" />
|
||||
</Control>
|
||||
<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>
|
||||
|
||||
<!-- Certificate: what the server presents to browsers and agents. Agents that do not trust it yet are given its issuing CA,
|
||||
pinned to the token, unless it is publicly trusted. -->
|
||||
<RadioButtonGroup Property="CertificateChoice">
|
||||
<RadioButton Value="selfsigned" X="0" Y="0" Width="110" Height="14" Text="Se&lf-Signed"
|
||||
ToolTip="Managed and renewed; agents trust it as is" />
|
||||
<RadioButton Value="store" X="0" Y="20" Width="110" Height="14" Text="Certificate &Store"
|
||||
ToolTip="Local Computer, Personal; renewals followed" />
|
||||
<RadioButton Value="file" X="0" Y="42" Width="110" Height="14" Text="&File"
|
||||
ToolTip="A PFX, or a PEM certificate and key" />
|
||||
<RadioButton Value="none" X="0" Y="104" Width="110" Height="14" Text="&None (HTTP Only)"
|
||||
ToolTip="For a TLS-terminating proxy on this machine" />
|
||||
</RadioButtonGroup>
|
||||
<Dialog Id="CertificateDlg" Width="370" Height="270" Title="[ProductName] Setup">
|
||||
<Control Id="BannerBitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="44" TabSkip="no" Text="WixUI_Bmp_Banner" />
|
||||
<Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
|
||||
<Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
|
||||
<Control Id="Title" Type="Text" X="15" Y="6" Width="200" Height="15" Transparent="yes" NoPrefix="yes" Text="{\WixUI_Font_Title}Certificate" />
|
||||
<Control Id="Description" Type="Text" X="25" Y="23" Width="300" Height="15" Transparent="yes" NoPrefix="yes"
|
||||
Text="What the server presents to browsers and agents." />
|
||||
|
||||
<!-- The choices on the left, each one's fields on the right, so no control overlaps the radio group. -->
|
||||
<Control Id="Choice" Type="RadioButtonGroup" X="20" Y="56" Width="110" Height="125" Property="CertificateChoice" />
|
||||
|
||||
<Control Id="ThumbprintLabel" Type="Text" X="135" Y="79" Width="52" Height="10" Text="&Thumbprint:" />
|
||||
<Control Id="Thumbprint" Type="Edit" X="190" Y="76" Width="160" Height="15" Property="TLSTHUMBPRINT" Text="{128}"
|
||||
ToolTip="From the certificate's Details tab"
|
||||
DisableCondition="CertificateChoice <> "store"" EnableCondition="CertificateChoice = "store"" />
|
||||
|
||||
<Control Id="CertFileLabel" Type="Text" X="135" Y="101" Width="52" Height="10" Text="&Path:" />
|
||||
<Control Id="CertFile" Type="Edit" X="190" Y="98" Width="160" Height="15" Property="TLSCERTFILE" Text="{260}"
|
||||
ToolTip="A .pfx/.p12, or a PEM (fullchain is fine)"
|
||||
DisableCondition="CertificateChoice <> "file"" EnableCondition="CertificateChoice = "file"" />
|
||||
<Control Id="KeyFileLabel" Type="Text" X="135" Y="120" Width="52" Height="10" Text="&Key File:" />
|
||||
<Control Id="KeyFile" Type="Edit" X="190" Y="117" Width="160" Height="15" Property="TLSKEYFILE" Text="{260}"
|
||||
ToolTip="PEM key; empty when the file holds it"
|
||||
DisableCondition="CertificateChoice <> "file"" EnableCondition="CertificateChoice = "file"" />
|
||||
<Control Id="PasswordLabel" Type="Text" X="135" Y="139" Width="52" Height="10" Text="Pass&word:" />
|
||||
<Control Id="Password" Type="Edit" X="190" Y="136" Width="110" Height="15" Property="TLSCERTPASSWORD" Password="yes" Text="{128}"
|
||||
ToolTip="PFX or PEM key password, if any"
|
||||
DisableCondition="CertificateChoice <> "file"" EnableCondition="CertificateChoice = "file"" />
|
||||
|
||||
<Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17" Text="!(loc.WixUIBack)">
|
||||
<Publish Event="NewDialog" Value="ServerAddressDlg" />
|
||||
</Control>
|
||||
<Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17" Default="yes" Text="!(loc.WixUINext)"
|
||||
DisableCondition="(CertificateChoice = "store" AND NOT TLSTHUMBPRINT) OR (CertificateChoice = "file" AND NOT TLSCERTFILE)"
|
||||
EnableCondition="NOT ((CertificateChoice = "store" AND NOT TLSTHUMBPRINT) OR (CertificateChoice = "file" AND NOT TLSCERTFILE))">
|
||||
<Publish Property="TLSSOURCE" Value="[CertificateChoice]" Order="1" Condition="CertificateChoice = "store" OR CertificateChoice = "file"" />
|
||||
<Publish Property="TLSSOURCE" Value="selfsigned" Order="1" Condition="CertificateChoice = "selfsigned" OR CertificateChoice = "none"" />
|
||||
<Publish Property="ENABLETLS" Value="1" Order="2" Condition="CertificateChoice <> "none"" />
|
||||
<Publish Property="ENABLETLS" Value="{}" Order="2" Condition="CertificateChoice = "none"" />
|
||||
<Publish Event="NewDialog" Value="VerifyReadyDlg" Order="3" />
|
||||
</Control>
|
||||
<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>
|
||||
|
||||
<!-- Remove Data: keep everything for a reinstall (the default), or remove it all. -->
|
||||
<Dialog Id="RemoveDataDlg" Width="370" Height="270" Title="[ProductName] Setup">
|
||||
<Control Id="BannerBitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="44" TabSkip="no" Text="WixUI_Bmp_Banner" />
|
||||
<Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
|
||||
<Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
|
||||
<Control Id="Title" Type="Text" X="15" Y="6" Width="200" Height="15" Transparent="yes" NoPrefix="yes" Text="{\WixUI_Font_Title}Remove Data" />
|
||||
<Control Id="Description" Type="Text" X="25" Y="23" Width="280" Height="15" Transparent="yes" NoPrefix="yes"
|
||||
Text="Keep the data for a reinstall, or remove it." />
|
||||
|
||||
<Control Id="PurgeCheck" Type="CheckBox" X="20" Y="58" Width="330" Height="17" Property="PURGEDATA" CheckBoxValue="1"
|
||||
Text="&Remove All Data, Keys and Self-Signed Certificates"
|
||||
ToolTip="Cannot be undone" />
|
||||
|
||||
<Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17" Text="!(loc.WixUIBack)">
|
||||
<Publish Event="NewDialog" Value="MaintenanceTypeDlg" />
|
||||
</Control>
|
||||
<Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17" Default="yes" Text="!(loc.WixUINext)">
|
||||
<Publish Event="NewDialog" Value="VerifyReadyDlg" />
|
||||
</Control>
|
||||
<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>
|
||||
</UI>
|
||||
<UIRef Id="WixUI_Common" />
|
||||
</Fragment>
|
||||
</Wix>
|
||||
@@ -22,7 +22,7 @@
|
||||
<?define AgentRegKey = "SOFTWARE\ExecuteR" ?>
|
||||
|
||||
<Package Name="ExecuteR Agent"
|
||||
Manufacturer="ExecuteR"
|
||||
Manufacturer="Endexa Solutions"
|
||||
Version="$(MsiProductVersion)"
|
||||
UpgradeCode="7f9c1a52-3f89-4bd4-9e11-2a67c33a5f10"
|
||||
Scope="perMachine"
|
||||
|
||||
@@ -38,6 +38,8 @@ public static class ApiRoutes
|
||||
public const string DeviceInventory = "/api/devices/{clientId}/inventory";
|
||||
public const string DeviceHistory = "/api/devices/{clientId}/history";
|
||||
public const string DeviceShell = "/api/devices/{clientId}/shell";
|
||||
public const string DeviceScreen = "/api/devices/{clientId}/screen";
|
||||
public const string ScreenPolicy = "/api/settings/remote-screen";
|
||||
public const string DeviceFiles = "/api/devices/{clientId}/files";
|
||||
public const string DeviceFsRoots = "/api/devices/{clientId}/fs/roots";
|
||||
public const string DeviceFsList = "/api/devices/{clientId}/fs/list";
|
||||
@@ -51,6 +53,7 @@ public static class ApiRoutes
|
||||
|
||||
public const string Scripts = "/api/scripts";
|
||||
public const string Script = "/api/scripts/{id}";
|
||||
public const string ScriptParametersParse = "/api/scripts/parameters/parse";
|
||||
|
||||
public const string FunctionModules = "/api/functions";
|
||||
public const string FunctionModule = "/api/functions/{id}";
|
||||
@@ -61,6 +64,9 @@ public static class ApiRoutes
|
||||
public const string GroupMove = "/api/groups/{id}/move";
|
||||
public const string GroupPreview = "/api/groups/preview";
|
||||
public const string GroupFields = "/api/groups/fields";
|
||||
|
||||
/// <summary>Known values of one rule field (<c>?field=&prefix=&limit=</c>), from the caller's devices.</summary>
|
||||
public const string GroupFieldValues = "/api/groups/fields/values";
|
||||
public const string DeviceTags = "/api/devices/{clientId}/tags";
|
||||
|
||||
public const string Triggers = "/api/triggers";
|
||||
@@ -74,9 +80,21 @@ public static class ApiRoutes
|
||||
public const string SecretsProviderNames = "/api/secrets/providers/{id}/secret-names";
|
||||
public const string SecretsProviderFolders = "/api/secrets/providers/{id}/folders";
|
||||
|
||||
public const string Vault = "/api/secrets/vault";
|
||||
public const string VaultFolders = "/api/secrets/vault/folders";
|
||||
public const string VaultFolderMove = "/api/secrets/vault/folders/move";
|
||||
public const string VaultSecrets = "/api/secrets/vault/secrets";
|
||||
public const string VaultSecret = "/api/secrets/vault/secrets/{id}";
|
||||
public const string VaultSecretReveal = "/api/secrets/vault/secrets/{id}/reveal";
|
||||
|
||||
public const string ServerInfo = "/api/settings/server";
|
||||
public const string ServerCertificate = "/api/settings/server-certificate";
|
||||
public const string ServerCertificateBind = "/api/settings/server-certificate/bind";
|
||||
public const string ServerCertificateSelfSigned = "/api/settings/server-certificate/self-signed";
|
||||
public const string ServerCertificateBinding = "/api/settings/server-certificate/binding";
|
||||
public const string S3Settings = "/api/settings/s3";
|
||||
public const string S3SettingsTest = "/api/settings/s3/test";
|
||||
public const string S3EmbeddedCredentials = "/api/settings/s3/built-in/credentials";
|
||||
public const string S3Objects = "/api/s3/objects";
|
||||
public const string S3ObjectContent = "/api/s3/objects/content";
|
||||
public const string S3ObjectStat = "/api/s3/objects/stat";
|
||||
@@ -161,6 +179,7 @@ public static class ApiRoutes
|
||||
public static string AgentUpgradeCancel(Guid id) => $"/api/agent-upgrades/{id:D}/cancel";
|
||||
public static string AgentPackageBySha(string sha256) => $"/api/agent-packages/{Uri.EscapeDataString(sha256)}";
|
||||
public static string DeviceShell(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}/shell";
|
||||
public static string DeviceScreen(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}/screen";
|
||||
public static string DeviceFiles(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}/files";
|
||||
public static string DeviceFs(string clientId, string leaf) => $"/api/devices/{Uri.EscapeDataString(clientId)}/fs/{leaf}";
|
||||
public static string Script(Guid id) => $"/api/scripts/{id:D}";
|
||||
@@ -173,6 +192,8 @@ public static class ApiRoutes
|
||||
public static string TriggerRun(Guid id) => $"/api/triggers/{id:D}/run";
|
||||
public static string SecretsProvider(Guid id) => $"/api/secrets/providers/{id:D}";
|
||||
public static string SecretsProviderNames(Guid id) => $"/api/secrets/providers/{id:D}/secret-names";
|
||||
public static string VaultSecret(Guid id) => $"/api/secrets/vault/secrets/{id:D}";
|
||||
public static string VaultSecretReveal(Guid id) => $"/api/secrets/vault/secrets/{id:D}/reveal";
|
||||
public static string Job(Guid jobId) => $"/api/jobs/{jobId:D}";
|
||||
public static string JobOutput(Guid jobId) => $"/api/jobs/{jobId:D}/output";
|
||||
public static string JobOutputDownload(Guid jobId) => $"/api/jobs/{jobId:D}/output/download";
|
||||
|
||||
@@ -10,11 +10,7 @@ public sealed record RemoveDevicesRequest(
|
||||
IReadOnlyList<Guid>? GroupIds = null,
|
||||
string? Reason = null);
|
||||
|
||||
/// <summary>
|
||||
/// One device's removal. <c>ShowInDeviceList</c> is true for the first
|
||||
/// <c>DeviceRemovalDefaults.VisibleInDeviceList</c> after <c>UpdatedUtc</c>; after
|
||||
/// that only the Removals filter shows it.
|
||||
/// </summary>
|
||||
/// <summary>One device's removal: what the Removals filter lists, the device itself having left the list.</summary>
|
||||
public sealed record DeviceRemovalDto(
|
||||
Guid Id,
|
||||
string ClientId,
|
||||
@@ -31,8 +27,7 @@ public sealed record DeviceRemovalDto(
|
||||
DateTimeOffset UpdatedUtc,
|
||||
DateTimeOffset? SentUtc,
|
||||
DateTimeOffset? LastSeenUtc,
|
||||
DateTimeOffset? FinishedUtc,
|
||||
bool ShowInDeviceList);
|
||||
DateTimeOffset? FinishedUtc);
|
||||
|
||||
/// <summary>A device a removal request left out, and why.</summary>
|
||||
public sealed record DeviceRemovalSkipDto(string ClientId, string? Hostname, string Reason);
|
||||
|
||||
@@ -58,12 +58,22 @@ public sealed record UpdateGroupMembersRequest(
|
||||
/// <summary>POST /api/groups/preview request body: evaluate rules without saving.</summary>
|
||||
public sealed record PreviewGroupRequest(GroupRuleSet Rules);
|
||||
|
||||
/// <summary>
|
||||
/// One known value of a rule field (GET /api/groups/fields/values), with how
|
||||
/// many of the caller's devices hold it now.
|
||||
/// </summary>
|
||||
public sealed record GroupFieldValueDto(string Value, int Devices);
|
||||
|
||||
/// <summary>PUT /api/devices/{clientId}/tags request body.</summary>
|
||||
public sealed record UpdateDeviceTagsRequest(IReadOnlyList<string> Tags);
|
||||
|
||||
/// <summary>
|
||||
/// Unified script trigger: when (event or schedule) + target (device/group/all)
|
||||
/// + optional captured arguments. Replaces the separate schedule concept.
|
||||
/// <c>Arguments</c> holds only the values set on the trigger; the rest follow
|
||||
/// the script's defaults at each firing. <c>ArgumentsProblem</c> says why a
|
||||
/// firing would not run against the script as it is now (a required value
|
||||
/// missing, a value that no longer fits its parameter).
|
||||
/// </summary>
|
||||
public sealed record ScriptTriggerDto(
|
||||
Guid Id,
|
||||
@@ -87,7 +97,8 @@ public sealed record ScriptTriggerDto(
|
||||
IReadOnlyDictionary<string, System.Text.Json.JsonElement>? Arguments = null,
|
||||
string? CreatedBy = null,
|
||||
int StaggerSeconds = 0,
|
||||
int StaggerBatchSize = 1);
|
||||
int StaggerBatchSize = 1,
|
||||
string? ArgumentsProblem = null);
|
||||
|
||||
/// <summary>
|
||||
/// POST /api/triggers and PUT /api/triggers/{id}. Target: exactly one of
|
||||
@@ -273,6 +284,34 @@ public sealed record SaveScriptRequest(
|
||||
ScriptEngine Engine = ScriptEngine.PowerShell,
|
||||
IReadOnlyList<ScriptFileBinding>? FileBindings = null);
|
||||
|
||||
/// <summary>
|
||||
/// POST /api/scripts/parameters/parse: reads a PowerShell script's
|
||||
/// <c>param()</c> block (parsed, never run) and merges it into
|
||||
/// <paramref name="Current"/>, the parameters as the editor has them.
|
||||
/// </summary>
|
||||
public sealed record ParseScriptParametersRequest(
|
||||
string? Content,
|
||||
ScriptEngine Engine = ScriptEngine.PowerShell,
|
||||
IReadOnlyList<ScriptParameter>? Current = null);
|
||||
|
||||
/// <summary>
|
||||
/// The merged parameters and what the code says about each. When the code
|
||||
/// has syntax errors nothing is merged: <c>Parameters</c> is the current list
|
||||
/// unchanged and <c>Diagnostics</c> says why.
|
||||
/// </summary>
|
||||
public sealed record ScriptParametersParseDto(
|
||||
bool Merged,
|
||||
bool HasParamBlock,
|
||||
IReadOnlyList<ScriptParameter> Parameters,
|
||||
IReadOnlyList<DeclaredParameterDto> Declared,
|
||||
IReadOnlyList<ScriptDiagnosticDto> Diagnostics);
|
||||
|
||||
/// <summary>One parameter as the code declares it: whether its description comes from help text.</summary>
|
||||
public sealed record DeclaredParameterDto(string Name, bool DescriptionFromCode);
|
||||
|
||||
/// <summary>A parse error or warning, 1-based line and column.</summary>
|
||||
public sealed record ScriptDiagnosticDto(string Severity, string Message, int Line, int Column);
|
||||
|
||||
/// <summary>
|
||||
/// Configured secrets provider. <c>Config</c> is driver-specific and sanitized:
|
||||
/// secret fields are omitted, with <c>SecretFieldsSet</c> reporting which of
|
||||
@@ -285,7 +324,8 @@ public sealed record SecretsProviderDto(
|
||||
IReadOnlyDictionary<string, string?> Config,
|
||||
IReadOnlyList<string> SecretFieldsSet,
|
||||
DateTimeOffset UpdatedUtc,
|
||||
string? UpdatedBy);
|
||||
string? UpdatedBy,
|
||||
bool BuiltIn = false);
|
||||
|
||||
/// <summary>
|
||||
/// POST/PUT /api/secrets/providers body. Empty/null secret config fields keep
|
||||
@@ -305,6 +345,49 @@ public sealed record TestSecretsProviderRequest(
|
||||
/// <summary>Result of a secrets provider connectivity test.</summary>
|
||||
public sealed record SecretsTestResultDto(bool Ok, IReadOnlyList<S3TestStepDto> Steps);
|
||||
|
||||
/// <summary>
|
||||
/// One secret in the built-in vault: name, folder and history, never the
|
||||
/// value (that takes a separate, audited reveal).
|
||||
/// </summary>
|
||||
public sealed record VaultSecretDto(
|
||||
Guid Id,
|
||||
string Path,
|
||||
string Name,
|
||||
int Version,
|
||||
DateTimeOffset CreatedUtc,
|
||||
string? CreatedBy,
|
||||
DateTimeOffset UpdatedUtc,
|
||||
string? UpdatedBy);
|
||||
|
||||
/// <summary>A child folder of the browsed path.</summary>
|
||||
public sealed record VaultFolderDto(string Path, string Name);
|
||||
|
||||
/// <summary>GET /api/secrets/vault: one level of the built-in vault.</summary>
|
||||
public sealed record VaultListingDto(
|
||||
string Path,
|
||||
IReadOnlyList<VaultFolderDto> Folders,
|
||||
IReadOnlyList<VaultSecretDto> Secrets);
|
||||
|
||||
/// <summary>
|
||||
/// POST/PUT /api/secrets/vault/secrets body. On update a null value keeps the
|
||||
/// stored one (so a path or name change alone never needs the value), and
|
||||
/// <c>Version</c>, when given, must match the stored version.
|
||||
/// </summary>
|
||||
public sealed record SaveVaultSecretRequest(
|
||||
string Path,
|
||||
string Name,
|
||||
string? Value = null,
|
||||
int? Version = null);
|
||||
|
||||
/// <summary>POST /api/secrets/vault/folders body.</summary>
|
||||
public sealed record VaultFolderRequest(string Path);
|
||||
|
||||
/// <summary>POST /api/secrets/vault/folders/move body: renames or moves a folder with everything in it.</summary>
|
||||
public sealed record MoveVaultFolderRequest(string From, string To);
|
||||
|
||||
/// <summary>POST /api/secrets/vault/secrets/{id}/reveal response.</summary>
|
||||
public sealed record RevealedVaultSecretDto(string Value, int Version);
|
||||
|
||||
/// <summary>Reusable PowerShell function module (prepended to scripts that reference it).</summary>
|
||||
public sealed record FunctionModuleDto(
|
||||
Guid Id,
|
||||
@@ -460,10 +543,18 @@ public sealed record S3EmbeddedStatusDto(
|
||||
long? FreeBytes,
|
||||
string? LastError);
|
||||
|
||||
/// <summary>
|
||||
/// GET /api/settings/s3/built-in/credentials: the built-in store's keys, for an
|
||||
/// S3 client on the server itself (the store listens on loopback, or inside the
|
||||
/// stack). Admin-only and audited; nothing else ever returns them.
|
||||
/// </summary>
|
||||
public sealed record S3EmbeddedCredentialsDto(string Endpoint, string Bucket, string Region, string AccessKey, string SecretKey);
|
||||
|
||||
/// <summary>
|
||||
/// GET/PUT /api/settings/s3. The secret key is never returned; a non-null
|
||||
/// value on PUT replaces it, null leaves the stored secret untouched. The
|
||||
/// fields are the external store's: the built-in one's are never shown.
|
||||
/// fields are the external store's: the built-in one's keys come only from
|
||||
/// <see cref="S3EmbeddedCredentialsDto"/>.
|
||||
/// </summary>
|
||||
public sealed record S3SettingsDto(
|
||||
bool Enabled,
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Shared.Contracts.Api;
|
||||
|
||||
/// <summary>
|
||||
/// POST /api/devices/{clientId}/screen request body. <c>Mode</c> is a
|
||||
/// <see cref="ScreenModes"/> value; <c>Monitor</c> -1 = all screens.
|
||||
/// </summary>
|
||||
public sealed record CreateScreenRequest(
|
||||
string BrowserSessionId,
|
||||
string? Mode = ScreenModes.View,
|
||||
int Monitor = -1,
|
||||
string? Quality = ScreenQualities.Balanced);
|
||||
|
||||
/// <summary>
|
||||
/// POST /api/devices/{clientId}/screen response body. <c>CanControl</c>: the
|
||||
/// caller holds <c>screen.control</c> and may switch a view session to control.
|
||||
/// <c>Policy</c> is the server policy sent to the agent (the agent may tighten it).
|
||||
/// </summary>
|
||||
public sealed record CreateScreenResponse(
|
||||
Guid ScreenSessionId,
|
||||
string ClientId,
|
||||
string Hostname,
|
||||
string Mode,
|
||||
bool CanControl,
|
||||
ScreenSessionPolicy Policy,
|
||||
DateTimeOffset ExpiresUtc);
|
||||
|
||||
/// <summary>
|
||||
/// A per-group override of the remote screen policy; null fields follow the
|
||||
/// default. When a device is in several overriding groups, On wins.
|
||||
/// </summary>
|
||||
public sealed record ScreenGroupPolicyDto(
|
||||
Guid GroupId,
|
||||
string? GroupName,
|
||||
bool? Notify,
|
||||
bool? AskFirst,
|
||||
bool? AllowUnattended);
|
||||
|
||||
/// <summary>GET/PUT /api/settings/remote-screen.</summary>
|
||||
public sealed record ScreenPolicySettingsDto(
|
||||
ScreenSessionPolicy Default,
|
||||
IReadOnlyList<ScreenGroupPolicyDto> Groups);
|
||||
@@ -24,11 +24,18 @@ public static class MessageTypes
|
||||
public const string CommandShellResize = "command.shell.resize";
|
||||
public const string CommandShellClose = "command.shell.close";
|
||||
public const string CommandFiles = "command.files";
|
||||
public const string CommandScreenOpen = "command.screen.open";
|
||||
public const string CommandScreenInput = "command.screen.input";
|
||||
public const string CommandScreenClose = "command.screen.close";
|
||||
|
||||
public const string ShellOutput = "shell.output";
|
||||
public const string ShellState = "shell.state";
|
||||
public const string ShellInput = "shell.input";
|
||||
|
||||
public const string ScreenState = "screen.state";
|
||||
public const string ScreenClipboard = "screen.clipboard";
|
||||
public const string ScreenInput = "screen.input";
|
||||
|
||||
public const string JobProgress = "job.progress";
|
||||
public const string JobOutput = "job.output";
|
||||
public const string JobState = "job.state";
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
using System.Buffers.Binary;
|
||||
|
||||
namespace Shared.Contracts.Messages;
|
||||
|
||||
/// <summary>
|
||||
/// Binary layout of a screen frame chunk on <c>agent.<clientId>.screen.<sessionId>.frame</c>
|
||||
/// (relayed byte-for-byte to <c>browser.<sid>.screen.<id>.frame</c>). Frames are
|
||||
/// raw bytes, not JSON envelopes. All integers are little-endian.
|
||||
/// <code>
|
||||
/// Chunk header (16 bytes)
|
||||
/// 0 4 magic "ERSF"
|
||||
/// 4 1 version (1)
|
||||
/// 5 1 flags: bit0 key frame (every tile), bit1 last chunk of this frame
|
||||
/// 6 2 tile count in this chunk (u16)
|
||||
/// 8 4 frame sequence (u32, same in every chunk of a frame)
|
||||
/// 12 2 frame width (u16)
|
||||
/// 14 2 frame height (u16)
|
||||
/// Tile (16-byte header + data), repeated tile-count times
|
||||
/// 0 2 x (u16, frame pixels)
|
||||
/// 2 2 y
|
||||
/// 4 2 width
|
||||
/// 6 2 height
|
||||
/// 8 1 encoding (<see cref="ScreenTileEncoding"/>)
|
||||
/// 9 3 reserved (0)
|
||||
/// 12 4 data length (u32)
|
||||
/// 16 … data
|
||||
/// </code>
|
||||
/// Solid: 3 bytes R,G,B. Rgb24 / Rgb565 / Rgb332: raw DEFLATE (no zlib header;
|
||||
/// the browser's DecompressionStream("deflate-raw")) of width×height pixels,
|
||||
/// rows top-down — RGB bytes; little-endian u16 RRRRRGGGGGGBBBBB; one byte RRRGGGBB.
|
||||
/// The browser acks the sequence of each frame it has drawn (ScreenInputKinds.Ack).
|
||||
/// </summary>
|
||||
public static class ScreenFrameFormat
|
||||
{
|
||||
public static ReadOnlySpan<byte> Magic => "ERSF"u8;
|
||||
|
||||
public const byte Version = 1;
|
||||
public const int ChunkHeaderSize = 16;
|
||||
public const int TileHeaderSize = 16;
|
||||
|
||||
public const byte FlagKeyFrame = 0x01;
|
||||
public const byte FlagEndOfFrame = 0x02;
|
||||
|
||||
/// <summary>Chunk budget: well under the NATS default max_payload of 1 MiB.</summary>
|
||||
public const int MaxChunkBytes = 512 * 1024;
|
||||
|
||||
/// <summary>Tile edge in pixels (edge tiles are smaller).</summary>
|
||||
public const int TileSize = 64;
|
||||
|
||||
/// <summary>Frames the agent sends ahead of the browser's last ack.</summary>
|
||||
public const int MaxFramesInFlight = 2;
|
||||
|
||||
public static void WriteChunkHeader(Span<byte> destination, byte flags, int tileCount, uint sequence, int width, int height)
|
||||
{
|
||||
Magic.CopyTo(destination);
|
||||
destination[4] = Version;
|
||||
destination[5] = flags;
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(destination[6..], checked((ushort)tileCount));
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(destination[8..], sequence);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(destination[12..], checked((ushort)width));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(destination[14..], checked((ushort)height));
|
||||
}
|
||||
|
||||
public static void WriteTileHeader(Span<byte> destination, int x, int y, int width, int height, ScreenTileEncoding encoding, int dataLength)
|
||||
{
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(destination, checked((ushort)x));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(destination[2..], checked((ushort)y));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(destination[4..], checked((ushort)width));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(destination[6..], checked((ushort)height));
|
||||
destination[8] = (byte)encoding;
|
||||
destination[9] = destination[10] = destination[11] = 0;
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(destination[12..], checked((uint)dataLength));
|
||||
}
|
||||
|
||||
/// <summary>Reads a chunk header; false when the bytes are not a version-1 chunk.</summary>
|
||||
public static bool TryReadChunkHeader(ReadOnlySpan<byte> source, out byte flags, out int tileCount, out uint sequence, out int width, out int height)
|
||||
{
|
||||
flags = 0;
|
||||
tileCount = width = height = 0;
|
||||
sequence = 0;
|
||||
if (source.Length < ChunkHeaderSize || !source[..4].SequenceEqual(Magic) || source[4] != Version)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
flags = source[5];
|
||||
tileCount = BinaryPrimitives.ReadUInt16LittleEndian(source[6..]);
|
||||
sequence = BinaryPrimitives.ReadUInt32LittleEndian(source[8..]);
|
||||
width = BinaryPrimitives.ReadUInt16LittleEndian(source[12..]);
|
||||
height = BinaryPrimitives.ReadUInt16LittleEndian(source[14..]);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tile pixel encodings (see <see cref="ScreenFrameFormat"/>).</summary>
|
||||
public enum ScreenTileEncoding : byte
|
||||
{
|
||||
Solid = 0,
|
||||
Rgb24 = 1,
|
||||
Rgb565 = 2,
|
||||
Rgb332 = 3,
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Shared.Contracts.Messages;
|
||||
|
||||
/// <summary>
|
||||
/// Starts a remote screen session; sent on <c>agent.<clientId>.command.screen.open</c>.
|
||||
/// <c>Operator</c> is the name shown to the user in the notice and the prompt.
|
||||
/// <c>Monitor</c>: -1 = all screens, otherwise a <see cref="ScreenMonitor.Index"/>.
|
||||
/// </summary>
|
||||
public sealed record ScreenOpenCommandPayload(
|
||||
Guid SessionId,
|
||||
string Mode,
|
||||
string Operator,
|
||||
ScreenSessionPolicy Policy,
|
||||
int Monitor = -1,
|
||||
string Quality = ScreenQualities.Balanced,
|
||||
int MaxFps = 15);
|
||||
|
||||
/// <summary>
|
||||
/// One browser input or control message for a session, on
|
||||
/// <c>browser.<sid>.screen.<id>.input</c> (from the browser) and
|
||||
/// <c>agent.<clientId>.command.screen.input</c> (backend → agent). Which
|
||||
/// fields apply depends on <see cref="Kind"/> (<see cref="ScreenInputKinds"/>).
|
||||
/// </summary>
|
||||
public sealed record ScreenInputPayload(
|
||||
Guid SessionId,
|
||||
string Kind,
|
||||
int? X = null,
|
||||
int? Y = null,
|
||||
int? Button = null,
|
||||
bool? Down = null,
|
||||
int? DeltaX = null,
|
||||
int? DeltaY = null,
|
||||
string? Code = null,
|
||||
string? Text = null,
|
||||
long? Seq = null,
|
||||
string? Quality = null,
|
||||
int? Monitor = null,
|
||||
int? MaxFps = null,
|
||||
string? Mode = null);
|
||||
|
||||
/// <summary>Ends a session; on <c>agent.<clientId>.command.screen.close</c>.</summary>
|
||||
public sealed record ScreenClosePayload(
|
||||
Guid SessionId,
|
||||
string? Reason);
|
||||
|
||||
/// <summary>
|
||||
/// Session state on <c>agent.<clientId>.screen.<sessionId>.state</c>,
|
||||
/// relayed to the owning browser. Sent on every change and whenever the monitor
|
||||
/// layout, mode, desktop or input lock changes.
|
||||
/// </summary>
|
||||
/// <param name="Attended">True when a user was signed in and the session unlocked at start.</param>
|
||||
/// <param name="Desktop">"default", "winlogon" (logon / lock / UAC screen) or another input desktop name.</param>
|
||||
/// <param name="WinPe">The device runs Windows PE (no consent, no notice).</param>
|
||||
public sealed record ScreenStatePayload(
|
||||
Guid SessionId,
|
||||
ScreenSessionState State,
|
||||
string? Message = null,
|
||||
IReadOnlyList<ScreenMonitor>? Monitors = null,
|
||||
int? Monitor = null,
|
||||
string? Mode = null,
|
||||
string? Quality = null,
|
||||
bool? Attended = null,
|
||||
string? Desktop = null,
|
||||
bool? InputLocked = null,
|
||||
bool? WinPe = null,
|
||||
string? User = null);
|
||||
|
||||
/// <summary>Device clipboard text on <c>agent.<clientId>.screen.<sessionId>.clipboard</c>.</summary>
|
||||
public sealed record ScreenClipboardPayload(
|
||||
Guid SessionId,
|
||||
string Text);
|
||||
@@ -28,9 +28,9 @@ public static class DeviceRemovalStates
|
||||
/// <summary>Why a removal failed, or what the agent could not do.</summary>
|
||||
public static class DeviceRemovalReasons
|
||||
{
|
||||
/// <summary>The agent is too old to take a remove command: uninstall it by hand, or upgrade it first.</summary>
|
||||
/// <summary>The agent is too old to take a remove command: removed from the system at once, the agent left on the device.</summary>
|
||||
public const string AgentTooOld = "agent-too-old";
|
||||
/// <summary>The agent cannot remove itself here (foreground or development run, container).</summary>
|
||||
/// <summary>The agent cannot remove itself here (foreground or development run, container): removed from the system, the agent left on the device.</summary>
|
||||
public const string Unsupported = "unsupported";
|
||||
/// <summary>An agent upgrade is in progress; the server asks again.</summary>
|
||||
public const string Busy = "busy";
|
||||
@@ -45,12 +45,6 @@ public static class DeviceRemovalReasons
|
||||
/// <summary>Timings shared by the server's removal scheduler and the console.</summary>
|
||||
public static class DeviceRemovalDefaults
|
||||
{
|
||||
/// <summary>
|
||||
/// How long a removal shows in the default Devices list after its last
|
||||
/// change. After that only the Removals status filter shows it, so the main
|
||||
/// list stays uncluttered while nothing is lost.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan VisibleInDeviceList = TimeSpan.FromDays(7);
|
||||
/// <summary>Silence after "uninstalling" that counts as gone: nobody is left to report success.</summary>
|
||||
public static readonly TimeSpan UninstallSilence = TimeSpan.FromMinutes(15);
|
||||
/// <summary>The first agent release that understands the remove command and renews its credential.</summary>
|
||||
|
||||
@@ -57,8 +57,10 @@ public sealed record RuleCondition(
|
||||
bool Negate = false);
|
||||
|
||||
/// <summary>
|
||||
/// A group of conditions (and optionally nested groups) combined with AND/OR.
|
||||
/// <paramref name="Negate"/> inverts the whole group.
|
||||
/// A group of conditions and nested groups combined with AND/OR (All of / Any
|
||||
/// of). <paramref name="Negate"/> inverts the whole group. A group with neither
|
||||
/// conditions nor groups matches nothing. Writes are held to
|
||||
/// <see cref="GroupRuleLimits"/>.
|
||||
/// </summary>
|
||||
public sealed record RuleGroup(
|
||||
RuleCombine Combine = RuleCombine.And,
|
||||
@@ -67,57 +69,117 @@ public sealed record RuleGroup(
|
||||
bool Negate = false);
|
||||
|
||||
/// <summary>
|
||||
/// A dynamic group's membership rules: one or more condition groups combined
|
||||
/// with AND/OR.
|
||||
/// A dynamic group's membership rule: the outermost group. It holds conditions
|
||||
/// and nested groups like any <see cref="RuleGroup"/>, with its own All/Any
|
||||
/// (<paramref name="Combine"/>) and Not (<paramref name="Negate"/>). Rule sets
|
||||
/// saved before it held conditions of its own carry only
|
||||
/// <paramref name="Groups"/>, and read and evaluate exactly as they always did.
|
||||
/// An empty rule set matches no devices (safer than every device).
|
||||
/// </summary>
|
||||
public sealed record GroupRuleSet(
|
||||
RuleCombine Combine = RuleCombine.And,
|
||||
IReadOnlyList<RuleGroup>? Groups = null)
|
||||
IReadOnlyList<RuleGroup>? Groups = null,
|
||||
IReadOnlyList<RuleCondition>? Conditions = null,
|
||||
bool Negate = false)
|
||||
{
|
||||
public static GroupRuleSet Empty { get; } = new(RuleCombine.And, []);
|
||||
|
||||
/// <summary>The rule set as the group it is, so one walk serves both.</summary>
|
||||
public RuleGroup AsGroup() => new(Combine, Conditions, Groups, Negate);
|
||||
}
|
||||
|
||||
/// <summary>Field names usable in rules, with the kind of comparison they support.</summary>
|
||||
/// <summary>Bounds on a rule set, enforced when one is saved or previewed.</summary>
|
||||
public static class GroupRuleLimits
|
||||
{
|
||||
/// <summary>Levels of grouping, the rule itself being the first: the rule, its groups, theirs…</summary>
|
||||
public const int MaxDepth = 8;
|
||||
|
||||
/// <summary>Conditions in one rule set, every level together.</summary>
|
||||
public const int MaxConditions = 200;
|
||||
}
|
||||
|
||||
/// <summary>What a field holds: it decides the operators and the value input the console offers.</summary>
|
||||
public enum GroupFieldType
|
||||
{
|
||||
Text,
|
||||
Number,
|
||||
|
||||
/// <summary>Ordered as versions (1.10 after 1.9) by the comparison operators.</summary>
|
||||
Version,
|
||||
|
||||
/// <summary>IP addresses: the subnet (CIDR) operators apply.</summary>
|
||||
Address,
|
||||
|
||||
/// <summary>"true" or "false".</summary>
|
||||
Boolean,
|
||||
|
||||
/// <summary>One of a fixed set (<see cref="GroupFieldDescriptor.Choices"/>).</summary>
|
||||
Choice,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A field usable in rules. <paramref name="Type"/>, <paramref name="Choices"/>
|
||||
/// and <paramref name="Description"/> drive the console's field picker,
|
||||
/// operator list and value input; <paramref name="Numeric"/> and
|
||||
/// <paramref name="MultiValue"/> stay for older readers.
|
||||
/// </summary>
|
||||
public sealed record GroupFieldDescriptor(
|
||||
string Field,
|
||||
string DisplayName,
|
||||
string Category,
|
||||
bool Numeric = false,
|
||||
bool MultiValue = false);
|
||||
bool MultiValue = false,
|
||||
GroupFieldType Type = GroupFieldType.Text,
|
||||
IReadOnlyList<string>? Choices = null,
|
||||
string? Description = null);
|
||||
|
||||
/// <summary>The catalogue of rule-addressable device fields (also drives the UI).</summary>
|
||||
public static class GroupFields
|
||||
{
|
||||
private static GroupFieldDescriptor Number(string field, string name, string category, string description)
|
||||
=> new(field, name, category, Numeric: true, Type: GroupFieldType.Number, Description: description);
|
||||
|
||||
private static GroupFieldDescriptor Addresses(string field, string name, string description)
|
||||
=> new(field, name, "Network", MultiValue: true, Type: GroupFieldType.Address, Description: description);
|
||||
|
||||
public static readonly IReadOnlyList<GroupFieldDescriptor> All =
|
||||
[
|
||||
new("hostname", "Hostname", "Identity"),
|
||||
new("clientId", "Client ID", "Identity"),
|
||||
new("status", "Status (online/stale/offline)", "Identity"),
|
||||
new("tags", "Tags", "Identity", MultiValue: true),
|
||||
new("agentVersion", "Agent version", "Identity"),
|
||||
new("manufacturer", "Manufacturer", "Hardware"),
|
||||
new("model", "Model", "Hardware"),
|
||||
new("serialNumber", "Serial number", "Hardware"),
|
||||
new("biosVersion", "BIOS version", "Hardware"),
|
||||
new("systemType", "System type", "Hardware"),
|
||||
new("domain", "Domain / workgroup", "Identity"),
|
||||
new("partOfDomain", "Domain joined", "Identity"),
|
||||
new("os.platform", "Platform (windows/linux/macos)", "Operating system"),
|
||||
new("os.caption", "OS name", "Operating system"),
|
||||
new("os.version", "OS version", "Operating system"),
|
||||
new("os.build", "OS build", "Operating system"),
|
||||
new("os.architecture", "OS architecture", "Operating system"),
|
||||
new("os.edition", "OS edition", "Operating system"),
|
||||
new("cpu.name", "CPU name", "Hardware"),
|
||||
new("cpu.cores", "CPU cores", "Hardware", Numeric: true),
|
||||
new("cpu.logicalProcessors", "CPU logical processors", "Hardware", Numeric: true),
|
||||
new("memory.totalGb", "Memory total (GB)", "Hardware", Numeric: true),
|
||||
new("disk.count", "Disk count", "Storage", Numeric: true),
|
||||
new("disk.totalGb", "Disk total (GB)", "Storage", Numeric: true),
|
||||
new("volume.freeGb", "Smallest volume free (GB)", "Storage", Numeric: true),
|
||||
new("network.ipv4", "IPv4 address", "Network", MultiValue: true),
|
||||
new("network.mac", "MAC address", "Network", MultiValue: true),
|
||||
new("network.dns", "DNS server", "Network", MultiValue: true),
|
||||
new("network.interface", "Interface name", "Network", MultiValue: true),
|
||||
new("hostname", "Hostname", "Identity", Description: "The device's computer name."),
|
||||
new("clientId", "Client ID", "Identity", Description: "The agent's enrolled identity."),
|
||||
new("status", "Status", "Identity", Type: GroupFieldType.Choice, Choices: ["online", "stale", "offline"],
|
||||
Description: "Online, stale or offline, from when the agent was last heard."),
|
||||
new("tags", "Tags", "Identity", MultiValue: true, Description: "Tags set on the device; matches when any tag does."),
|
||||
new("agentVersion", "Agent version", "Identity", Type: GroupFieldType.Version,
|
||||
Description: "Compared as versions: 1.10 is newer than 1.9."),
|
||||
new("domain", "Domain / workgroup", "Identity", Description: "The domain or workgroup the device is in."),
|
||||
new("partOfDomain", "Domain joined", "Identity", Type: GroupFieldType.Boolean, Choices: ["true", "false"],
|
||||
Description: "Whether the device is joined to a domain."),
|
||||
new("manufacturer", "Manufacturer", "Hardware", Description: "System manufacturer, as the firmware reports it."),
|
||||
new("model", "Model", "Hardware", Description: "System model."),
|
||||
new("serialNumber", "Serial number", "Hardware", Description: "System serial number."),
|
||||
new("biosVersion", "BIOS version", "Hardware", Description: "Firmware version."),
|
||||
new("systemType", "System type", "Hardware", Description: "x64-based PC, ARM64-based PC…"),
|
||||
new("cpu.name", "CPU name", "Hardware", Description: "Processor model."),
|
||||
Number("cpu.cores", "CPU cores", "Hardware", "Physical processor cores."),
|
||||
Number("cpu.logicalProcessors", "CPU logical processors", "Hardware", "Logical processors (threads)."),
|
||||
Number("memory.totalGb", "Memory total (GB)", "Hardware", "Installed memory, in GB."),
|
||||
new("os.platform", "Platform", "Operating system", Type: GroupFieldType.Choice, Choices: ["windows", "linux", "macos"],
|
||||
Description: "Windows, Linux or macOS."),
|
||||
new("os.caption", "OS name", "Operating system", Description: "Windows 11 Pro, Ubuntu 24.04 LTS…"),
|
||||
new("os.version", "OS version", "Operating system", Description: "10.0.26100, 24.04…"),
|
||||
new("os.build", "OS build", "Operating system", Description: "The OS build."),
|
||||
new("os.architecture", "OS architecture", "Operating system", Description: "64-bit, ARM64…"),
|
||||
new("os.edition", "OS edition", "Operating system", Description: "Professional, Enterprise, Server…"),
|
||||
Number("disk.count", "Disk count", "Storage", "Physical disks."),
|
||||
Number("disk.totalGb", "Disk total (GB)", "Storage", "Every disk together, in GB."),
|
||||
Number("volume.freeGb", "Smallest volume free (GB)", "Storage", "Free space on the fullest volume, in GB."),
|
||||
Addresses("network.ipv4", "IPv4 address", "Any of the device's IPv4 addresses."),
|
||||
new("network.mac", "MAC address", "Network", MultiValue: true, Description: "Any adapter's MAC address."),
|
||||
Addresses("network.dns", "DNS server", "Any DNS server an adapter uses."),
|
||||
new("network.interface", "Interface name", "Network", MultiValue: true, Description: "Any adapter's interface name."),
|
||||
];
|
||||
|
||||
/// <summary>The descriptor for a field name, matched as rules match it (ignoring case); null when unknown.</summary>
|
||||
public static GroupFieldDescriptor? Find(string? field)
|
||||
=> All.FirstOrDefault(f => string.Equals(f.Field, field, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
namespace Shared.Contracts.Models;
|
||||
|
||||
/// <summary>Remote screen session lifecycle states.</summary>
|
||||
public enum ScreenSessionState
|
||||
{
|
||||
/// <summary>The backend asked the agent to start the session.</summary>
|
||||
Requested,
|
||||
|
||||
/// <summary>The signed-in user is being asked to accept (full Windows, "ask first").</summary>
|
||||
AwaitingConsent,
|
||||
|
||||
/// <summary>Frames are flowing.</summary>
|
||||
Open,
|
||||
|
||||
/// <summary>The signed-in user declined, or did not answer in time.</summary>
|
||||
Declined,
|
||||
|
||||
/// <summary>Ended normally (operator, user, lifetime or idle).</summary>
|
||||
Closed,
|
||||
|
||||
/// <summary>Could not start or broke (policy, platform, no session, helper died).</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>Session modes. <c>view</c> never forwards input; <c>control</c> needs <c>screen.control</c>.</summary>
|
||||
public static class ScreenModes
|
||||
{
|
||||
public const string View = "view";
|
||||
public const string Control = "control";
|
||||
|
||||
public static string? Normalize(string? mode) => mode?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
null or "" or View => View,
|
||||
Control => Control,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Colour depth of streamed tiles (all lossless deflate over reduced colour):
|
||||
/// <c>full</c> 24-bit, <c>balanced</c> 16-bit (RGB565), <c>low</c> 8-bit (RGB332).
|
||||
/// </summary>
|
||||
public static class ScreenQualities
|
||||
{
|
||||
public const string Full = "full";
|
||||
public const string Balanced = "balanced";
|
||||
public const string Low = "low";
|
||||
|
||||
public static readonly IReadOnlyList<string> All = [Full, Balanced, Low];
|
||||
|
||||
public static string Normalize(string? quality) => quality?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
Full => Full,
|
||||
Low => Low,
|
||||
_ => Balanced,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The server-side policy resolved for one device when a session opens, sent in
|
||||
/// the open command. The agent may only make it stricter (its local
|
||||
/// RemoteScreen* policy values), and ignores consent entirely in Windows PE.
|
||||
/// </summary>
|
||||
/// <param name="Notify">Show a notice in the user's session while a session is active.</param>
|
||||
/// <param name="AskFirst">Ask the signed-in user to accept before the session starts.</param>
|
||||
/// <param name="AskTimeoutSeconds">How long the user has to answer; no answer is a decline.</param>
|
||||
/// <param name="AllowUnattended">Allow sessions when nobody is signed in, or the session is locked (logon screen, break-fix).</param>
|
||||
public sealed record ScreenSessionPolicy(
|
||||
bool Notify,
|
||||
bool AskFirst,
|
||||
int AskTimeoutSeconds,
|
||||
bool AllowUnattended)
|
||||
{
|
||||
public static ScreenSessionPolicy Default { get; } = new(Notify: true, AskFirst: false, AskTimeoutSeconds: 30, AllowUnattended: false);
|
||||
}
|
||||
|
||||
/// <summary>One display on the device, in virtual-screen pixels.</summary>
|
||||
public sealed record ScreenMonitor(
|
||||
int Index,
|
||||
string Name,
|
||||
int X,
|
||||
int Y,
|
||||
int Width,
|
||||
int Height,
|
||||
bool Primary);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Shared.Contracts.Messages.ScreenInputPayload.Kind"/> values.
|
||||
/// Everything except <c>ack</c>, <c>refresh</c>, <c>settings</c> (without a mode
|
||||
/// change to control) and <c>clipboard.get</c> is control input and is dropped
|
||||
/// by the backend for a view-only session.
|
||||
/// </summary>
|
||||
public static class ScreenInputKinds
|
||||
{
|
||||
/// <summary>X, Y in frame pixels.</summary>
|
||||
public const string PointerMove = "pointer.move";
|
||||
|
||||
/// <summary>X, Y, Button (0 left, 1 middle, 2 right, 3 back, 4 forward), Down.</summary>
|
||||
public const string PointerButton = "pointer.button";
|
||||
|
||||
/// <summary>X, Y, DeltaX, DeltaY in wheel notches × 120 (WHEEL_DELTA), positive = up / right.</summary>
|
||||
public const string PointerWheel = "pointer.wheel";
|
||||
|
||||
/// <summary>Code (KeyboardEvent.code, layout independent → scan code), Down.</summary>
|
||||
public const string Key = "key";
|
||||
|
||||
/// <summary>Text typed as Unicode keystrokes (works at the logon screen and in Windows PE).</summary>
|
||||
public const string Text = "text";
|
||||
|
||||
/// <summary>Text: replace the device clipboard.</summary>
|
||||
public const string ClipboardSet = "clipboard.set";
|
||||
|
||||
/// <summary>Ask the agent to send the device clipboard (answered on the clipboard subject).</summary>
|
||||
public const string ClipboardGet = "clipboard.get";
|
||||
|
||||
/// <summary>Ctrl+Alt+Del (SendSAS from the agent service).</summary>
|
||||
public const string SecureAttention = "sas";
|
||||
|
||||
/// <summary>Down = true blocks the device's own keyboard and mouse; false releases.</summary>
|
||||
public const string LockInput = "lock-input";
|
||||
|
||||
/// <summary>Seq: the last frame drawn. Also the browser's heartbeat (every few seconds).</summary>
|
||||
public const string Ack = "ack";
|
||||
|
||||
/// <summary>Ask for a key frame (every tile).</summary>
|
||||
public const string Refresh = "refresh";
|
||||
|
||||
/// <summary>Any of Quality, Monitor (-1 = all screens), MaxFps, Mode.</summary>
|
||||
public const string Settings = "settings";
|
||||
|
||||
public static bool IsControl(string kind) => kind is PointerMove or PointerButton or PointerWheel
|
||||
or Key or Text or ClipboardSet or SecureAttention or LockInput;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Shared.Contracts.Models;
|
||||
|
||||
/// <summary>
|
||||
/// One rule for "no value", shared by the server's checks and the agent's
|
||||
/// binding: null, blank text, an empty list or an empty hashtable is the same
|
||||
/// as not giving the parameter at all. It then takes the script's default,
|
||||
/// or PowerShell's own, and a default that is itself empty does not count.
|
||||
/// </summary>
|
||||
public static class ScriptArgumentValue
|
||||
{
|
||||
public static bool IsEmpty(JsonElement? value) => value is not { } v || v.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Undefined or JsonValueKind.Null => true,
|
||||
JsonValueKind.String => string.IsNullOrWhiteSpace(v.GetString()),
|
||||
JsonValueKind.Array => v.GetArrayLength() == 0,
|
||||
JsonValueKind.Object => !v.EnumerateObject().Any(),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
@@ -59,7 +59,23 @@ public enum ValueExpansion
|
||||
/// run time — each key and value carries its own primitive type, preserved as
|
||||
/// native JSON and rebuilt by the agent. <see cref="Expansion"/> applies to
|
||||
/// string values (scalars, string array elements, string hashtable values).
|
||||
///
|
||||
/// Lifecycle: the script declares its parameters and their defaults; a run,
|
||||
/// schedule or trigger gives values. A value that is not given falls back to
|
||||
/// <see cref="DefaultValue"/> when the job is dispatched (so a schedule that
|
||||
/// never set one follows the script's current default), and with no default
|
||||
/// either, PowerShell applies its own (<see cref="DefaultExpression"/>).
|
||||
///
|
||||
/// For PowerShell engines the script's <c>param()</c> block is the source of
|
||||
/// truth (read by the server's parser): <see cref="DeclaredType"/>,
|
||||
/// <see cref="AllowedValues"/> and <see cref="DefaultExpression"/> come from it.
|
||||
/// </summary>
|
||||
/// <param name="AllowedValues">A <c>[ValidateSet()]</c>, offered as a pick list.</param>
|
||||
/// <param name="DeclaredType">The PowerShell type as written (<c>datetime</c>, <c>string[]</c>, <c>switch</c>).</param>
|
||||
/// <param name="DefaultExpression">
|
||||
/// A default the code computes (<c>$env:TEMP</c>): not imported as a value, so
|
||||
/// nothing is sent when no value is given and PowerShell evaluates it.
|
||||
/// </param>
|
||||
public sealed record ScriptParameter(
|
||||
string Name,
|
||||
ScriptParameterType Type,
|
||||
@@ -67,4 +83,7 @@ public sealed record ScriptParameter(
|
||||
string? Description = null,
|
||||
PrimitiveType? ElementType = null,
|
||||
JsonElement? DefaultValue = null,
|
||||
ValueExpansion Expansion = ValueExpansion.Auto);
|
||||
ValueExpansion Expansion = ValueExpansion.Auto,
|
||||
IReadOnlyList<string>? AllowedValues = null,
|
||||
string? DeclaredType = null,
|
||||
string? DefaultExpression = null);
|
||||
|
||||
@@ -14,3 +14,16 @@ public sealed record SecretBinding(
|
||||
Guid ProviderId,
|
||||
string SecretName,
|
||||
string? Path = null);
|
||||
|
||||
/// <summary>
|
||||
/// The built-in vault: a provider every server has, with no configuration and
|
||||
/// no stored provider row. Bindings reference it by this fixed id.
|
||||
/// </summary>
|
||||
public static class BuiltInVault
|
||||
{
|
||||
public const string Kind = "builtin";
|
||||
|
||||
public const string DisplayName = "Built-in Vault";
|
||||
|
||||
public static readonly Guid ProviderId = new("5ec7e700-0000-4000-8000-000000000001");
|
||||
}
|
||||
|
||||
@@ -30,6 +30,14 @@ public static class ProtocolDefaults
|
||||
public static readonly TimeSpan ShellIdleTimeout = TimeSpan.FromMinutes(15);
|
||||
public static readonly TimeSpan ShellMaxLifetime = TimeSpan.FromMinutes(60);
|
||||
|
||||
/// <summary>A screen session with no browser ack/heartbeat for this long is ended by the agent.</summary>
|
||||
public static readonly TimeSpan ScreenIdleTimeout = TimeSpan.FromSeconds(45);
|
||||
|
||||
/// <summary>Browser heartbeat (an ack of the last frame) while the screen is static.</summary>
|
||||
public static readonly TimeSpan ScreenHeartbeatInterval = TimeSpan.FromSeconds(10);
|
||||
|
||||
public static readonly TimeSpan ScreenMaxLifetime = TimeSpan.FromHours(4);
|
||||
|
||||
public static readonly TimeSpan BootstrapTokenDefaultLifetime = TimeSpan.FromHours(24);
|
||||
public const int BootstrapTokenDefaultMaxUses = 1;
|
||||
public const int BootstrapTokenEntropyBytes = 32;
|
||||
|
||||
@@ -22,17 +22,14 @@ public static class RuleEvaluator
|
||||
=> op is RuleOperator.NotEquals or RuleOperator.NotContains or RuleOperator.NotIn
|
||||
or RuleOperator.NotExists or RuleOperator.NotInCidr;
|
||||
|
||||
/// <summary>
|
||||
/// The rule set is the outermost group: its own conditions and groups,
|
||||
/// combined and optionally negated. A rule set saved with only groups (no
|
||||
/// conditions of its own, never negated) evaluates as it always has.
|
||||
/// </summary>
|
||||
public static bool Matches(GroupRuleSet? ruleSet, DeviceFieldBag fields)
|
||||
{
|
||||
var groups = ruleSet?.Groups;
|
||||
if (groups is null || groups.Count == 0)
|
||||
{
|
||||
// A dynamic group with no rules matches nothing (safer than everything).
|
||||
return false;
|
||||
}
|
||||
|
||||
return Combine(ruleSet!.Combine, groups.Select(g => Matches(g, fields)));
|
||||
}
|
||||
// A dynamic group with no rules matches nothing (safer than everything).
|
||||
=> ruleSet is not null && Matches(ruleSet.AsGroup(), fields);
|
||||
|
||||
public static bool Matches(RuleGroup group, DeviceFieldBag fields)
|
||||
{
|
||||
@@ -50,6 +47,7 @@ public static class RuleEvaluator
|
||||
|
||||
if (results.Count == 0)
|
||||
{
|
||||
// Empty matches nothing, negated or not.
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -181,7 +179,7 @@ public static class RuleEvaluator
|
||||
/// "10.30.9.27/24" means the same network as "10.30.9.0/24" (the strict
|
||||
/// BCL parser rejects non-zero host bits).
|
||||
/// </summary>
|
||||
private static bool TryParseNetwork(string cidr, out IPNetwork network)
|
||||
internal static bool TryParseNetwork(string cidr, out IPNetwork network)
|
||||
{
|
||||
network = default;
|
||||
var slash = cidr.IndexOf('/');
|
||||
@@ -261,6 +259,6 @@ public static class RuleEvaluator
|
||||
};
|
||||
}
|
||||
|
||||
private static IEnumerable<string> SplitList(string value)
|
||||
internal static IEnumerable<string> SplitList(string value)
|
||||
=> value.Split([',', ';', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Shared.Infrastructure.Grouping;
|
||||
|
||||
/// <summary>
|
||||
/// Checks a rule set before it is saved or previewed: nesting within
|
||||
/// <see cref="GroupRuleLimits.MaxDepth"/>, at most
|
||||
/// <see cref="GroupRuleLimits.MaxConditions"/> conditions, a field on every
|
||||
/// condition, and a value the operator can use (a pattern .NET compiles, CIDR
|
||||
/// ranges or addresses that parse). Problems are keyed by row path as the
|
||||
/// console's builder numbers its rows: within a group its conditions come
|
||||
/// first, then its groups, from 1; <c>2.1</c> is the first row of the group in
|
||||
/// row 2; the rule's own is <c>""</c>. A rule set saved before still loads and
|
||||
/// evaluates as it did; only one whose pattern or range never matched anything
|
||||
/// (it could not be read) is asked to change when saved again.
|
||||
/// </summary>
|
||||
public static class RuleValidator
|
||||
{
|
||||
public static Dictionary<string, string[]> Validate(GroupRuleSet? rules)
|
||||
{
|
||||
var errors = new Dictionary<string, string[]>(StringComparer.Ordinal);
|
||||
if (rules is null)
|
||||
{
|
||||
return errors;
|
||||
}
|
||||
|
||||
var conditions = 0;
|
||||
Walk(rules.AsGroup(), path: string.Empty, depth: 1, errors, ref conditions);
|
||||
if (conditions > GroupRuleLimits.MaxConditions)
|
||||
{
|
||||
Add(errors, string.Empty, $"A rule holds at most {GroupRuleLimits.MaxConditions} conditions; this one has {conditions}.");
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
/// <summary>Why the condition's value cannot work with its operator, or null when it can.</summary>
|
||||
public static string? ValueProblem(RuleCondition condition)
|
||||
{
|
||||
var value = condition.Value ?? string.Empty;
|
||||
switch (condition.Operator)
|
||||
{
|
||||
case RuleOperator.Regex:
|
||||
try
|
||||
{
|
||||
_ = new Regex(value, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
|
||||
return null;
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
// .NET says where and what: "Invalid pattern '(a' at offset 2. Not enough )'s."
|
||||
return ex.Message;
|
||||
}
|
||||
|
||||
case RuleOperator.InCidr:
|
||||
case RuleOperator.NotInCidr:
|
||||
var items = RuleEvaluator.SplitList(value).ToList();
|
||||
if (items.Count == 0)
|
||||
{
|
||||
return "Enter a range such as 10.0.0.0/8, or an address.";
|
||||
}
|
||||
|
||||
var bad = items.FirstOrDefault(item => item.Contains('/')
|
||||
? !RuleEvaluator.TryParseNetwork(item, out _)
|
||||
: !IPAddress.TryParse(item, out _));
|
||||
return bad is null ? null : $"“{bad}” is not a CIDR range or an IP address.";
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Walk(RuleGroup group, string path, int depth, Dictionary<string, string[]> errors, ref int conditions)
|
||||
{
|
||||
if (depth > GroupRuleLimits.MaxDepth)
|
||||
{
|
||||
// Below the limit is not walked: the one message says what to change.
|
||||
Add(errors, path, $"Groups nest at most {GroupRuleLimits.MaxDepth} levels deep, the rule included.");
|
||||
return;
|
||||
}
|
||||
|
||||
var row = 0;
|
||||
foreach (var condition in group.Conditions ?? [])
|
||||
{
|
||||
row++;
|
||||
conditions++;
|
||||
if (string.IsNullOrWhiteSpace(condition?.Field))
|
||||
{
|
||||
Add(errors, Child(path, row), "Choose a field.");
|
||||
}
|
||||
else if (ValueProblem(condition) is { } problem)
|
||||
{
|
||||
Add(errors, Child(path, row), problem);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var child in group.Groups ?? [])
|
||||
{
|
||||
row++;
|
||||
if (child is not null)
|
||||
{
|
||||
Walk(child, Child(path, row), depth + 1, errors, ref conditions);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string Child(string path, int row) => path.Length == 0 ? $"{row}" : $"{path}.{row}";
|
||||
|
||||
private static void Add(Dictionary<string, string[]> errors, string path, string message)
|
||||
=> errors[path] = errors.TryGetValue(path, out var existing) ? [.. existing, message] : [message];
|
||||
}
|
||||
@@ -24,6 +24,11 @@ public static class NatsSubjects
|
||||
public static string AgentCommandShellResize(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.shell.resize";
|
||||
public static string AgentCommandShellClose(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.shell.close";
|
||||
|
||||
// Remote screen: Core NATS only (live and lossy by design — a stale frame is worthless).
|
||||
public static string AgentCommandScreenOpen(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.screen.open";
|
||||
public static string AgentCommandScreenInput(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.screen.input";
|
||||
public static string AgentCommandScreenClose(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.screen.close";
|
||||
|
||||
// Core NATS, never JetStream: a request answers while someone waits, and a transfer ends with its browser request.
|
||||
public static string AgentCommandFilesRequest(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.files.request";
|
||||
public static string AgentCommandFilesStream(string clientId, Guid streamId)
|
||||
@@ -40,6 +45,16 @@ public static class NatsSubjects
|
||||
public static string AgentShellState(string clientId, Guid sessionId)
|
||||
=> $"agent.{SubjectIdentifier.Require(clientId)}.shell.{SubjectIdentifier.FromGuid(sessionId)}.state";
|
||||
|
||||
// ── Agent-published screen streams (frame = raw ScreenFrameFormat bytes) ──
|
||||
public static string AgentScreenFrame(string clientId, Guid sessionId)
|
||||
=> $"agent.{SubjectIdentifier.Require(clientId)}.screen.{SubjectIdentifier.FromGuid(sessionId)}.frame";
|
||||
|
||||
public static string AgentScreenState(string clientId, Guid sessionId)
|
||||
=> $"agent.{SubjectIdentifier.Require(clientId)}.screen.{SubjectIdentifier.FromGuid(sessionId)}.state";
|
||||
|
||||
public static string AgentScreenClipboard(string clientId, Guid sessionId)
|
||||
=> $"agent.{SubjectIdentifier.Require(clientId)}.screen.{SubjectIdentifier.FromGuid(sessionId)}.clipboard";
|
||||
|
||||
// ── Job streams ──────────────────────────────────────────────────────
|
||||
public static string JobProgress(Guid jobId) => $"job.{SubjectIdentifier.FromGuid(jobId)}.progress";
|
||||
public static string JobOutput(Guid jobId) => $"job.{SubjectIdentifier.FromGuid(jobId)}.output";
|
||||
@@ -59,6 +74,18 @@ public static class NatsSubjects
|
||||
public static string BrowserShellInput(string browserSessionId, Guid shellId)
|
||||
=> $"browser.{SubjectIdentifier.Require(browserSessionId)}.shell.{SubjectIdentifier.FromGuid(shellId)}.input";
|
||||
|
||||
/// <summary>Screen state and clipboard envelopes for the owning browser.</summary>
|
||||
public static string BrowserScreen(string browserSessionId, Guid screenId)
|
||||
=> $"browser.{SubjectIdentifier.Require(browserSessionId)}.screen.{SubjectIdentifier.FromGuid(screenId)}";
|
||||
|
||||
/// <summary>Raw frame chunks (ScreenFrameFormat) for the owning browser.</summary>
|
||||
public static string BrowserScreenFrame(string browserSessionId, Guid screenId)
|
||||
=> $"browser.{SubjectIdentifier.Require(browserSessionId)}.screen.{SubjectIdentifier.FromGuid(screenId)}.frame";
|
||||
|
||||
/// <summary>Browser-published screen input and acks, forwarded by the backend after ownership and mode checks.</summary>
|
||||
public static string BrowserScreenInput(string browserSessionId, Guid screenId)
|
||||
=> $"browser.{SubjectIdentifier.Require(browserSessionId)}.screen.{SubjectIdentifier.FromGuid(screenId)}.input";
|
||||
|
||||
/// <summary>Everything a browser session may subscribe/publish below.</summary>
|
||||
public static string BrowserSessionWildcard(string browserSessionId)
|
||||
=> $"browser.{SubjectIdentifier.Require(browserSessionId)}.>";
|
||||
@@ -75,6 +102,8 @@ public static class NatsSubjects
|
||||
public const string AllAgentProgress = "agent.*.progress";
|
||||
public const string AllAgentEvents = "agent.*.event";
|
||||
public const string AllAgentShellStreams = "agent.*.shell.>";
|
||||
public const string AllAgentScreenStreams = "agent.*.screen.>";
|
||||
public const string AllBrowserScreenInput = "browser.*.screen.*.input";
|
||||
public const string AllJobProgress = "job.*.progress";
|
||||
public const string AllJobOutput = "job.*.output";
|
||||
public const string AllJobState = "job.*.state";
|
||||
@@ -98,6 +127,9 @@ public static class NatsSubjects
|
||||
$"agent.{id}.event",
|
||||
$"agent.{id}.shell.*.output",
|
||||
$"agent.{id}.shell.*.state",
|
||||
$"agent.{id}.screen.*.frame",
|
||||
$"agent.{id}.screen.*.state",
|
||||
$"agent.{id}.screen.*.clipboard",
|
||||
AllJobProgress,
|
||||
AllJobOutput,
|
||||
AllJobState,
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
AgentUpgradeBatchDto,
|
||||
AgentUpgradeDto,
|
||||
AgentUpgradeSettingsDto,
|
||||
S3EmbeddedCredentialsDto,
|
||||
AgentVersionDto,
|
||||
BootstrapTokenDto,
|
||||
BrowserCredentialResponse,
|
||||
@@ -19,6 +20,7 @@ import type {
|
||||
ExecutionSummaryDto,
|
||||
FunctionModuleDto,
|
||||
GroupFieldDescriptor,
|
||||
GroupFieldValueDto,
|
||||
GroupRuleSet,
|
||||
GroupRunDto,
|
||||
JobDto,
|
||||
@@ -38,6 +40,7 @@ import type {
|
||||
ScriptDto,
|
||||
ScriptFileBinding,
|
||||
ScriptParameter,
|
||||
ScriptParametersParseDto,
|
||||
ScriptTriggerDto,
|
||||
SecretBinding,
|
||||
SecretsProviderDto,
|
||||
@@ -45,8 +48,13 @@ import type {
|
||||
SecretsTestResultDto,
|
||||
RemoveDevicesBody,
|
||||
ServerInfoDto,
|
||||
ServerCertificateStatusDto,
|
||||
StartAgentUpgradeBody,
|
||||
TriggerRunResultDto
|
||||
TriggerRunResultDto,
|
||||
RevealedVaultSecretDto,
|
||||
SaveVaultSecretBody,
|
||||
VaultFolderDto,
|
||||
VaultSecretDto
|
||||
} from './types';
|
||||
|
||||
export interface AgentUpgradeQuery {
|
||||
@@ -268,6 +276,9 @@ export const api = {
|
||||
createScript: (body: SaveScriptBody) => request<ScriptDto>('/api/scripts', json('POST', body)),
|
||||
updateScript: (id: string, body: SaveScriptBody) => request<ScriptDto>(`/api/scripts/${id}`, json('PUT', body)),
|
||||
deleteScript: (id: string) => request<void>(`/api/scripts/${id}`, { method: 'DELETE' }),
|
||||
/** Reads a PowerShell script's param() block (parsed, never run) and merges it into `current`. */
|
||||
parseScriptParameters: (body: { content: string; engine: string; current: ScriptParameter[] }, signal?: AbortSignal) =>
|
||||
request<ScriptParametersParseDto>('/api/scripts/parameters/parse', { ...json('POST', body), signal }),
|
||||
|
||||
// Function modules
|
||||
functions: () => request<FunctionModuleDto[]>('/api/functions'),
|
||||
@@ -303,6 +314,9 @@ export const api = {
|
||||
request<void>(`/api/groups/${id}/members`, json('POST', { add, remove })),
|
||||
previewGroup: (rules: GroupRuleSet) => request<DeviceDto[]>('/api/groups/preview', json('POST', { rules })),
|
||||
groupFields: () => request<GroupFieldDescriptor[]>('/api/groups/fields'),
|
||||
/** Values devices in the caller's scope report for a rule field, most common first. */
|
||||
groupFieldValues: (field: string, prefix: string, signal?: AbortSignal, limit = 25) =>
|
||||
request<GroupFieldValueDto[]>(`/api/groups/fields/values${qs({ field, prefix, limit })}`, { signal }),
|
||||
|
||||
// Schedules and event triggers
|
||||
triggers: () => request<ScriptTriggerDto[]>('/api/triggers'),
|
||||
@@ -329,6 +343,7 @@ export const api = {
|
||||
s3Settings: () => request<S3SettingsDto>('/api/settings/s3'),
|
||||
saveS3Settings: (body: S3SettingsDto) => request<S3SettingsDto>('/api/settings/s3', json('PUT', body)),
|
||||
testS3Settings: (body: S3SettingsDto) => request<S3TestResultDto>('/api/settings/s3/test', json('POST', body)),
|
||||
revealS3EmbeddedCredentials: () => request<S3EmbeddedCredentialsDto>('/api/settings/s3/built-in/credentials'),
|
||||
agentPackage: (type: 'msi' | 'zip' = 'msi') => request<AgentPackageStatusDto>(`/api/settings/agent-package?type=${type}`),
|
||||
offloadAgentPackage: (type: 'msi' | 'zip' = 'msi') =>
|
||||
request<{ message: string; status: AgentPackageStatusDto }>(`/api/settings/agent-package/offload?type=${type}`, { method: 'POST' }),
|
||||
@@ -344,8 +359,24 @@ export const api = {
|
||||
secretNames: (providerId: string, path?: string) => request<string[]>(`/api/secrets/providers/${providerId}/secret-names${qs({ path })}`),
|
||||
secretFolders: (providerId: string, path?: string) => request<string[]>(`/api/secrets/providers/${providerId}/folders${qs({ path })}`),
|
||||
|
||||
// Built-in vault
|
||||
createVaultFolder: (path: string) => request<VaultFolderDto>('/api/secrets/vault/folders', json('POST', { path })),
|
||||
moveVaultFolder: (from: string, to: string) => request<VaultFolderDto>('/api/secrets/vault/folders/move', json('POST', { from, to })),
|
||||
deleteVaultFolder: (path: string) => request<void>(`/api/secrets/vault/folders${qs({ path })}`, { method: 'DELETE' }),
|
||||
createVaultSecret: (body: SaveVaultSecretBody) => request<VaultSecretDto>('/api/secrets/vault/secrets', json('POST', body)),
|
||||
updateVaultSecret: (id: string, body: SaveVaultSecretBody) =>
|
||||
request<VaultSecretDto>(`/api/secrets/vault/secrets/${id}`, json('PUT', body)),
|
||||
deleteVaultSecret: (id: string) => request<void>(`/api/secrets/vault/secrets/${id}`, { method: 'DELETE' }),
|
||||
revealVaultSecret: (id: string) => request<RevealedVaultSecretDto>(`/api/secrets/vault/secrets/${id}/reveal`, { method: 'POST' }),
|
||||
|
||||
// Server info (public base URL for generated commands)
|
||||
serverInfo: () => request<ServerInfoDto>('/api/settings/server'),
|
||||
serverCertificate: () => request<ServerCertificateStatusDto>('/api/settings/server-certificate'),
|
||||
bindServerCertificate: (thumbprint: string) =>
|
||||
request<ServerCertificateStatusDto>('/api/settings/server-certificate/bind', { method: 'POST', body: JSON.stringify({ thumbprint }) }),
|
||||
serveSelfSignedCertificate: () => request<ServerCertificateStatusDto>('/api/settings/server-certificate/self-signed', { method: 'POST' }),
|
||||
clearServerCertificateBinding: () =>
|
||||
request<ServerCertificateStatusDto>('/api/settings/server-certificate/binding', { method: 'DELETE' }),
|
||||
|
||||
// Enrollment tokens
|
||||
bootstrapTokens: () => request<BootstrapTokenDto[]>('/api/admin/bootstrap-tokens'),
|
||||
@@ -407,6 +438,7 @@ export const keys = {
|
||||
agentVersions: '/api/agent-versions',
|
||||
agentUpgrades: (query: AgentUpgradeQuery = {}) => `/api/agent-upgrades${upgradeQuery(query)}`,
|
||||
agentUpgradeSettings: '/api/settings/agent-upgrades',
|
||||
serverCertificate: '/api/settings/server-certificate',
|
||||
groups: '/api/groups',
|
||||
groupFields: '/api/groups/fields',
|
||||
groupMembers: (id: string) => `/api/groups/${id}/members`,
|
||||
|
||||
+171
-1
@@ -71,17 +71,36 @@ export interface RuleGroup {
|
||||
negate?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The rule itself: the outermost group, with conditions and groups of its own.
|
||||
* Rules saved before it held conditions carry only `groups`.
|
||||
*/
|
||||
export interface GroupRuleSet {
|
||||
combine: RuleCombine;
|
||||
groups?: RuleGroup[];
|
||||
conditions?: RuleCondition[];
|
||||
negate?: boolean;
|
||||
}
|
||||
|
||||
/** What a rule field holds: it picks the operators and the value input. */
|
||||
export type GroupFieldType = 'text' | 'number' | 'version' | 'address' | 'boolean' | 'choice';
|
||||
|
||||
export interface GroupFieldDescriptor {
|
||||
field: string;
|
||||
displayName: string;
|
||||
category: string;
|
||||
numeric: boolean;
|
||||
multiValue: boolean;
|
||||
type?: GroupFieldType;
|
||||
/** Every value the field can hold, when that is fixed. */
|
||||
choices?: string[];
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/** GET /api/groups/fields/values: one value devices report for a field, and on how many of them. */
|
||||
export interface GroupFieldValueDto {
|
||||
value: string;
|
||||
devices: number;
|
||||
}
|
||||
|
||||
export interface DeviceGroupDto {
|
||||
@@ -138,6 +157,15 @@ export interface S3SettingsDto {
|
||||
embedded?: S3EmbeddedStatusDto;
|
||||
}
|
||||
|
||||
/** The built-in store's keys, from the audited reveal only. */
|
||||
export interface S3EmbeddedCredentialsDto {
|
||||
endpoint: string;
|
||||
bucket: string;
|
||||
region: string;
|
||||
accessKey: string;
|
||||
secretKey: string;
|
||||
}
|
||||
|
||||
export interface S3EmbeddedStatusDto {
|
||||
/** off | unavailable | starting | running | failed */
|
||||
state: string;
|
||||
@@ -270,7 +298,6 @@ export interface DeviceRemovalDto {
|
||||
sentUtc?: string | null;
|
||||
lastSeenUtc?: string | null;
|
||||
finishedUtc?: string | null;
|
||||
showInDeviceList: boolean;
|
||||
}
|
||||
|
||||
export interface RemoveDevicesBody {
|
||||
@@ -323,11 +350,14 @@ export interface ScriptTriggerDto {
|
||||
name?: string;
|
||||
/** Execution created by the last firing. */
|
||||
lastRunId?: string;
|
||||
/** Only the values set on it; the rest follow the script's defaults at each firing. */
|
||||
arguments?: Record<string, unknown>;
|
||||
createdBy?: string;
|
||||
/** Spreads each firing's starts over this long; 0 starts them all at once. */
|
||||
staggerSeconds?: number;
|
||||
staggerBatchSize?: number;
|
||||
/** Why a firing would not run against the script as it is now. */
|
||||
argumentsProblem?: string;
|
||||
}
|
||||
|
||||
/** POST /api/triggers and PUT /api/triggers/{id}. Target: clientId OR groupId, or neither for all devices. */
|
||||
@@ -458,6 +488,12 @@ export interface ScriptFileBinding {
|
||||
continueOnFailure?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Declared on the script, with its default; a run, schedule or trigger gives
|
||||
* the value. A value not given falls back to the default when the job is
|
||||
* sent, and with none PowerShell applies its own. For PowerShell scripts the
|
||||
* param() block is the source of truth (read on the server, never run).
|
||||
*/
|
||||
export interface ScriptParameter {
|
||||
name: string;
|
||||
type: ScriptParameterType;
|
||||
@@ -466,6 +502,22 @@ export interface ScriptParameter {
|
||||
elementType?: PrimitiveType;
|
||||
defaultValue?: unknown;
|
||||
expansion?: ValueExpansion;
|
||||
/** A [ValidateSet()]: offered as a pick list. */
|
||||
allowedValues?: string[];
|
||||
/** The PowerShell type as written: datetime, string[], switch. */
|
||||
declaredType?: string;
|
||||
/** A default the code computes ($env:TEMP); never sent, PowerShell evaluates it. */
|
||||
defaultExpression?: string;
|
||||
}
|
||||
|
||||
/** POST /api/scripts/parameters/parse: the param() block merged into `current`. */
|
||||
export interface ScriptParametersParseDto {
|
||||
/** False while the code has syntax errors: `parameters` is `current` unchanged. */
|
||||
merged: boolean;
|
||||
hasParamBlock: boolean;
|
||||
parameters: ScriptParameter[];
|
||||
declared: { name: string; descriptionFromCode: boolean }[];
|
||||
diagnostics: { severity: 'error' | 'warning'; message: string; line: number; column: number }[];
|
||||
}
|
||||
|
||||
/** Result of a group fan-out run: one job per eligible member. */
|
||||
@@ -580,12 +632,54 @@ export interface SecretsProviderDto {
|
||||
secretFieldsSet: string[];
|
||||
updatedUtc: string;
|
||||
updatedBy?: string;
|
||||
/** The built-in vault: always listed first, nothing to configure, cannot be edited or deleted. */
|
||||
builtIn?: boolean;
|
||||
}
|
||||
|
||||
export interface SecretsProviderKindDto {
|
||||
kind: string;
|
||||
displayName: string;
|
||||
fields: { name: string; label: string; secret: boolean; placeholder?: string }[];
|
||||
/** Not offered when adding a provider: the built-in vault is always there. */
|
||||
builtIn?: boolean;
|
||||
}
|
||||
|
||||
// ── Built-in vault ────────────────────────────────────────────────────
|
||||
|
||||
/** A vault secret's name, folder and history; the value takes a separate, audited reveal. */
|
||||
export interface VaultSecretDto {
|
||||
id: string;
|
||||
path: string;
|
||||
name: string;
|
||||
version: number;
|
||||
createdUtc: string;
|
||||
createdBy?: string;
|
||||
updatedUtc: string;
|
||||
updatedBy?: string;
|
||||
}
|
||||
|
||||
export interface VaultFolderDto {
|
||||
path: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface VaultListingDto {
|
||||
path: string;
|
||||
folders: VaultFolderDto[];
|
||||
secrets: VaultSecretDto[];
|
||||
}
|
||||
|
||||
/** On update, an omitted value keeps the stored one; `version` refuses a save over someone else's. */
|
||||
export interface SaveVaultSecretBody {
|
||||
path: string;
|
||||
name: string;
|
||||
value?: string;
|
||||
version?: number;
|
||||
}
|
||||
|
||||
export interface RevealedVaultSecretDto {
|
||||
value: string;
|
||||
version: number;
|
||||
}
|
||||
|
||||
export interface SecretsProvidersResponse {
|
||||
@@ -944,3 +1038,79 @@ export interface S3BrowseDto {
|
||||
objects: S3ObjectDto[];
|
||||
nextToken?: string;
|
||||
}
|
||||
|
||||
// ── Server certificate (Settings › Server Certificate) ─────────────────────
|
||||
|
||||
export interface CertificateIdentityDto {
|
||||
subject: string;
|
||||
issuer: string;
|
||||
dnsNames: string[];
|
||||
template: string | null;
|
||||
}
|
||||
|
||||
export interface CertificateDetailsDto {
|
||||
subject: string;
|
||||
issuer: string;
|
||||
dnsNames: string[];
|
||||
ipAddresses: string[];
|
||||
notBefore: string;
|
||||
notAfter: string;
|
||||
thumbprint: string;
|
||||
template: string | null;
|
||||
}
|
||||
|
||||
export interface ChainCertificateDto {
|
||||
subject: string;
|
||||
thumbprint: string;
|
||||
notAfter: string;
|
||||
root: boolean;
|
||||
}
|
||||
|
||||
export interface CertificateBindingDto {
|
||||
/** 'store' follows an identity in LocalMachine\My; 'self-signed' serves the managed chain. */
|
||||
mode: 'store' | 'self-signed';
|
||||
identity: CertificateIdentityDto | null;
|
||||
boundThumbprint: string | null;
|
||||
boundUtc: string;
|
||||
boundBy: string | null;
|
||||
/** This replica serves the binding (not when forced by the environment, or it cannot here). */
|
||||
applied: boolean;
|
||||
followingRenewals: boolean;
|
||||
servedThumbprint: string | null;
|
||||
lastSwitchedUtc: string | null;
|
||||
previousThumbprint: string | null;
|
||||
}
|
||||
|
||||
export interface StoreCertificateDto {
|
||||
thumbprint: string;
|
||||
subject: string;
|
||||
issuer: string;
|
||||
dnsNames: string[];
|
||||
notAfter: string;
|
||||
template: string | null;
|
||||
friendlyName: string | null;
|
||||
usable: boolean;
|
||||
reason: string | null;
|
||||
inUse: boolean;
|
||||
matchesBinding: boolean;
|
||||
}
|
||||
|
||||
export interface ServerCertificateStatusDto {
|
||||
tlsEnabled: boolean;
|
||||
source: 'self-signed' | 'store' | 'file' | 'none';
|
||||
bound: boolean;
|
||||
forcedBy: string | null;
|
||||
storeAvailable: boolean;
|
||||
problem: string | null;
|
||||
certificate: CertificateDetailsDto | null;
|
||||
chain: ChainCertificateDto[];
|
||||
trust: 'public' | 'private';
|
||||
agentsPinned: boolean;
|
||||
rootFingerprint: string | null;
|
||||
distributionFolder: string | null;
|
||||
binding: CertificateBindingDto | null;
|
||||
/** A new private root within the last 30 days: agents enrolled before need it pushed or a new token. */
|
||||
rootChangedUtc: string | null;
|
||||
replica: string;
|
||||
storeCertificates: StoreCertificateDto[];
|
||||
}
|
||||
|
||||
@@ -48,6 +48,8 @@ interface Props<T> {
|
||||
error?: string;
|
||||
empty?: ReactNode;
|
||||
onRowClick?: (row: T) => void;
|
||||
/** Right-click on a row; the browser's own menu is suppressed only when this is set. */
|
||||
onRowContextMenu?: (row: T, position: { top: number; left: number }) => void;
|
||||
selection?: Selection<T>;
|
||||
/** Filters and bulk actions, above the header row. */
|
||||
toolbar?: ReactNode;
|
||||
@@ -87,6 +89,7 @@ export default function DataTable<T>({
|
||||
error,
|
||||
empty,
|
||||
onRowClick,
|
||||
onRowContextMenu,
|
||||
selection,
|
||||
toolbar,
|
||||
defaultSort,
|
||||
@@ -210,6 +213,14 @@ export default function DataTable<T>({
|
||||
hover
|
||||
selected={isChosen || activeRowId === id}
|
||||
onClick={onRowClick ? () => onRowClick(row) : undefined}
|
||||
onContextMenu={
|
||||
onRowContextMenu
|
||||
? (e) => {
|
||||
e.preventDefault();
|
||||
onRowContextMenu(row, { top: e.clientY, left: e.clientX });
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
sx={{ cursor: onRowClick ? 'pointer' : 'default', ...(dimmedRow?.(row) && { '& > td': { opacity: 0.65 } }) }}
|
||||
>
|
||||
{selection && (
|
||||
|
||||
@@ -11,12 +11,14 @@ import Typography from '@mui/material/Typography';
|
||||
|
||||
// project imports
|
||||
import IconButton from 'components/@extended/IconButton';
|
||||
import { ArgumentDraft, HashEntry, newHashEntry } from 'utils/argumentValues';
|
||||
import ValueListEditor, { PrimitiveInput } from 'components/ValueListEditor';
|
||||
import { ArgumentDraft, HashEntry, hasDefault, isGiven, newHashEntry, resetToDefault, valueText } from 'utils/argumentValues';
|
||||
import type { PrimitiveType, ScriptParameter } from 'api/types';
|
||||
|
||||
// assets
|
||||
import CloseOutlined from '@ant-design/icons/CloseOutlined';
|
||||
import PlusOutlined from '@ant-design/icons/PlusOutlined';
|
||||
import UndoOutlined from '@ant-design/icons/UndoOutlined';
|
||||
|
||||
const PRIMITIVES: PrimitiveType[] = ['string', 'number', 'boolean'];
|
||||
|
||||
@@ -26,66 +28,47 @@ interface Props {
|
||||
onChange: (draft: ArgumentDraft) => void;
|
||||
errors?: Record<string, string>;
|
||||
disabled?: boolean;
|
||||
/** Hover text for a value that follows the default (schedules keep following it as the script changes). */
|
||||
defaultHint?: string;
|
||||
}
|
||||
|
||||
function PrimitiveInput({
|
||||
type,
|
||||
value,
|
||||
onChange,
|
||||
label,
|
||||
disabled
|
||||
}: {
|
||||
type?: PrimitiveType;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
label: string;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
if (type === 'boolean') {
|
||||
return (
|
||||
<TextField
|
||||
select
|
||||
size="small"
|
||||
value={value || 'false'}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
label={label}
|
||||
disabled={disabled}
|
||||
sx={{ minWidth: 110 }}
|
||||
>
|
||||
<MenuItem value="true">true</MenuItem>
|
||||
<MenuItem value="false">false</MenuItem>
|
||||
</TextField>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<TextField
|
||||
size="small"
|
||||
type={type === 'number' ? 'number' : 'text'}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
label={label}
|
||||
disabled={disabled}
|
||||
fullWidth
|
||||
/>
|
||||
);
|
||||
const DEFAULT_HINT = "Not set here: the script's default applies when it runs.";
|
||||
|
||||
/** The default as one line of text ("a, b" for a list). */
|
||||
const defaultText = (p: ScriptParameter) =>
|
||||
Array.isArray(p.defaultValue) ? p.defaultValue.map(valueText).join(', ') : valueText(p.defaultValue);
|
||||
|
||||
/** What an emptied input falls back to. */
|
||||
function fallback(p: ScriptParameter): string | undefined {
|
||||
if (hasDefault(p)) return `Default: ${defaultText(p)}`;
|
||||
if (p.defaultExpression) return `Set by the script: ${p.defaultExpression}`;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// ==============================|| SCRIPT PARAMETER INPUTS ||============================== //
|
||||
|
||||
/** Typed inputs for a script's parameters (controlled; see utils/argumentValues for the model). */
|
||||
export default function ParameterInputs({ parameters, draft, onChange, errors = {}, disabled }: Props) {
|
||||
export default function ParameterInputs({ parameters, draft, onChange, errors = {}, disabled, defaultHint = DEFAULT_HINT }: Props) {
|
||||
if (parameters.length === 0) return null;
|
||||
|
||||
const setScalar = (name: string, value: string) => onChange({ ...draft, scalars: { ...draft.scalars, [name]: value } });
|
||||
const setBool = (name: string, value: boolean) => onChange({ ...draft, bools: { ...draft.bools, [name]: value } });
|
||||
const setArray = (name: string, items: string[]) => onChange({ ...draft, arrays: { ...draft.arrays, [name]: items } });
|
||||
const setHash = (name: string, rows: HashEntry[]) => onChange({ ...draft, hashes: { ...draft.hashes, [name]: rows } });
|
||||
// Any edit makes the value explicit: it is sent, and kept on a schedule.
|
||||
const touched = (name: string) => ({ ...draft.explicit, [name]: true });
|
||||
const setScalar = (name: string, value: string) =>
|
||||
onChange({ ...draft, scalars: { ...draft.scalars, [name]: value }, explicit: touched(name) });
|
||||
const setBool = (name: string, value: boolean) =>
|
||||
onChange({ ...draft, bools: { ...draft.bools, [name]: value }, explicit: touched(name) });
|
||||
const setArray = (name: string, items: string[]) =>
|
||||
onChange({ ...draft, arrays: { ...draft.arrays, [name]: items }, explicit: touched(name) });
|
||||
const setHash = (name: string, rows: HashEntry[]) =>
|
||||
onChange({ ...draft, hashes: { ...draft.hashes, [name]: rows }, explicit: touched(name) });
|
||||
|
||||
return (
|
||||
<Stack sx={{ gap: 2.5 }}>
|
||||
{parameters.map((p) => {
|
||||
const error = errors[p.name];
|
||||
const typeLabel = p.type === 'array' ? `array<${p.elementType ?? 'string'}>` : p.type;
|
||||
const typeLabel = p.declaredType ?? (p.type === 'array' ? `array<${p.elementType ?? 'string'}>` : p.type);
|
||||
const given = isGiven(p, draft);
|
||||
const hasFallback = hasDefault(p) || Boolean(p.defaultExpression);
|
||||
return (
|
||||
<Stack key={p.name} sx={{ gap: 1 }}>
|
||||
<Stack direction="row" sx={{ alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
|
||||
@@ -104,11 +87,33 @@ export default function ParameterInputs({ parameters, draft, onChange, errors =
|
||||
<Chip size="small" variant="light" color="warning" label="Literal" />
|
||||
</Tooltip>
|
||||
)}
|
||||
{hasFallback &&
|
||||
(given ? (
|
||||
<Tooltip title="Use the Default">
|
||||
<span>
|
||||
<IconButton
|
||||
size="small"
|
||||
color="secondary"
|
||||
aria-label={`Use the default for ${p.name}`}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange(resetToDefault(draft, p))}
|
||||
>
|
||||
<UndoOutlined />
|
||||
</IconButton>
|
||||
</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Tooltip title={p.defaultExpression && !hasDefault(p) ? `Computed by the script: ${p.defaultExpression}` : defaultHint}>
|
||||
<Chip size="small" variant="light" color="secondary" label="Default" />
|
||||
</Tooltip>
|
||||
))}
|
||||
</Stack>
|
||||
{p.description && (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{p.description}
|
||||
</Typography>
|
||||
<Tooltip title={p.description} placement="bottom-start">
|
||||
<Typography variant="caption" color="text.secondary" noWrap sx={{ maxWidth: 560 }}>
|
||||
{p.description}
|
||||
</Typography>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
{p.type === 'boolean' && (
|
||||
@@ -121,68 +126,35 @@ export default function ParameterInputs({ parameters, draft, onChange, errors =
|
||||
)}
|
||||
|
||||
{(p.type === 'string' || p.type === 'number') && (
|
||||
<TextField
|
||||
id={`param-${p.name}`}
|
||||
size="small"
|
||||
type={p.type === 'number' ? 'number' : 'text'}
|
||||
value={draft.scalars[p.name] ?? ''}
|
||||
onChange={(e) => setScalar(p.name, e.target.value)}
|
||||
error={Boolean(error)}
|
||||
helperText={error}
|
||||
disabled={disabled}
|
||||
fullWidth
|
||||
/>
|
||||
<Stack sx={{ gap: 0.5 }}>
|
||||
<PrimitiveInput
|
||||
id={`param-${p.name}`}
|
||||
type={p.type}
|
||||
value={draft.scalars[p.name] ?? ''}
|
||||
onChange={(value) => setScalar(p.name, value)}
|
||||
allowedValues={p.allowedValues}
|
||||
placeholder={fallback(p)}
|
||||
error={Boolean(error)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
{error && (
|
||||
<Typography variant="caption" color="error.main">
|
||||
{error}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{p.type === 'array' && (
|
||||
<Stack sx={{ gap: 1 }}>
|
||||
{(draft.arrays[p.name] ?? []).map((item, i) => (
|
||||
<Stack key={i} direction="row" sx={{ gap: 1, alignItems: 'center' }}>
|
||||
<PrimitiveInput
|
||||
type={p.elementType}
|
||||
value={item}
|
||||
label={`Item ${i + 1}`}
|
||||
disabled={disabled}
|
||||
onChange={(value) =>
|
||||
setArray(
|
||||
p.name,
|
||||
(draft.arrays[p.name] ?? []).map((v, idx) => (idx === i ? value : v))
|
||||
)
|
||||
}
|
||||
/>
|
||||
<IconButton
|
||||
size="small"
|
||||
color="secondary"
|
||||
aria-label={`Remove item ${i + 1}`}
|
||||
disabled={disabled}
|
||||
onClick={() =>
|
||||
setArray(
|
||||
p.name,
|
||||
(draft.arrays[p.name] ?? []).filter((_, idx) => idx !== i)
|
||||
)
|
||||
}
|
||||
>
|
||||
<CloseOutlined />
|
||||
</IconButton>
|
||||
</Stack>
|
||||
))}
|
||||
<Stack direction="row" sx={{ alignItems: 'center', gap: 1 }}>
|
||||
<Button
|
||||
size="small"
|
||||
variant="dashed"
|
||||
startIcon={<PlusOutlined />}
|
||||
disabled={disabled}
|
||||
onClick={() => setArray(p.name, [...(draft.arrays[p.name] ?? []), ''])}
|
||||
>
|
||||
Add Item
|
||||
</Button>
|
||||
{error && (
|
||||
<Typography variant="caption" color="error.main">
|
||||
{error}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
</Stack>
|
||||
<ValueListEditor
|
||||
items={draft.arrays[p.name] ?? []}
|
||||
onChange={(items) => setArray(p.name, items)}
|
||||
elementType={p.elementType}
|
||||
allowedValues={p.allowedValues}
|
||||
disabled={disabled}
|
||||
error={error}
|
||||
emptyText={fallback(p) ?? 'No Items'}
|
||||
/>
|
||||
)}
|
||||
|
||||
{p.type === 'hashtable' && (
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
// material-ui
|
||||
import Button from '@mui/material/Button';
|
||||
import MenuItem from '@mui/material/MenuItem';
|
||||
import Stack from '@mui/material/Stack';
|
||||
import TextField from '@mui/material/TextField';
|
||||
import Tooltip from '@mui/material/Tooltip';
|
||||
import Typography from '@mui/material/Typography';
|
||||
|
||||
// project imports
|
||||
import IconButton from 'components/@extended/IconButton';
|
||||
import type { PrimitiveType } from 'api/types';
|
||||
|
||||
// assets
|
||||
import ArrowDownOutlined from '@ant-design/icons/ArrowDownOutlined';
|
||||
import ArrowUpOutlined from '@ant-design/icons/ArrowUpOutlined';
|
||||
import CloseOutlined from '@ant-design/icons/CloseOutlined';
|
||||
import PlusOutlined from '@ant-design/icons/PlusOutlined';
|
||||
|
||||
interface PrimitiveInputProps {
|
||||
type?: PrimitiveType;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
label?: string;
|
||||
placeholder?: string;
|
||||
/** A [ValidateSet()]: pick from these instead of typing. */
|
||||
allowedValues?: string[];
|
||||
disabled?: boolean;
|
||||
error?: boolean;
|
||||
id?: string;
|
||||
}
|
||||
|
||||
/** One typed value: true/false or a pick list as a select, numbers and text as a field. */
|
||||
export function PrimitiveInput({ type, value, onChange, label, placeholder, allowedValues, disabled, error, id }: PrimitiveInputProps) {
|
||||
if (type === 'boolean' || allowedValues?.length) {
|
||||
const options = type === 'boolean' ? ['true', 'false'] : allowedValues!;
|
||||
return (
|
||||
<TextField
|
||||
id={id}
|
||||
select
|
||||
size="small"
|
||||
value={type === 'boolean' ? value || 'false' : value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
label={label}
|
||||
disabled={disabled}
|
||||
error={error}
|
||||
fullWidth={type !== 'boolean'}
|
||||
sx={{ minWidth: 110 }}
|
||||
slotProps={{ select: { displayEmpty: Boolean(placeholder) } }}
|
||||
>
|
||||
{type !== 'boolean' && (
|
||||
<MenuItem value="">
|
||||
<Typography variant="body2" color="text.secondary" component="span">
|
||||
{placeholder ?? 'None'}
|
||||
</Typography>
|
||||
</MenuItem>
|
||||
)}
|
||||
{options.map((option) => (
|
||||
<MenuItem key={option} value={option}>
|
||||
{option}
|
||||
</MenuItem>
|
||||
))}
|
||||
</TextField>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<TextField
|
||||
id={id}
|
||||
size="small"
|
||||
type={type === 'number' ? 'number' : 'text'}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
label={label}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
error={error}
|
||||
fullWidth
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface Props {
|
||||
items: string[];
|
||||
onChange: (items: string[]) => void;
|
||||
elementType?: PrimitiveType;
|
||||
allowedValues?: string[];
|
||||
disabled?: boolean;
|
||||
/** Shown under the list (validation). */
|
||||
error?: string;
|
||||
/** Shown while the list is empty, e.g. what the default is. */
|
||||
emptyText?: string;
|
||||
}
|
||||
|
||||
// ==============================|| VALUE LIST EDITOR ||============================== //
|
||||
|
||||
/** A list of typed items that can be added, removed and reordered. */
|
||||
export default function ValueListEditor({ items, onChange, elementType, allowedValues, disabled, error, emptyText }: Props) {
|
||||
const set = (index: number, value: string) => onChange(items.map((v, i) => (i === index ? value : v)));
|
||||
const move = (index: number, by: number) => {
|
||||
const next = [...items];
|
||||
[next[index], next[index + by]] = [next[index + by], next[index]];
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack sx={{ gap: 1 }}>
|
||||
{items.length === 0 && emptyText && (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{emptyText}
|
||||
</Typography>
|
||||
)}
|
||||
{items.map((item, i) => (
|
||||
<Stack key={i} direction="row" sx={{ gap: 0.5, alignItems: 'center' }}>
|
||||
<PrimitiveInput
|
||||
type={elementType}
|
||||
value={item}
|
||||
label={`Item ${i + 1}`}
|
||||
allowedValues={allowedValues}
|
||||
disabled={disabled}
|
||||
onChange={(value) => set(i, value)}
|
||||
/>
|
||||
<Tooltip title="Move Up">
|
||||
<span>
|
||||
<IconButton
|
||||
size="small"
|
||||
color="secondary"
|
||||
aria-label={`Move item ${i + 1} up`}
|
||||
disabled={disabled || i === 0}
|
||||
onClick={() => move(i, -1)}
|
||||
>
|
||||
<ArrowUpOutlined />
|
||||
</IconButton>
|
||||
</span>
|
||||
</Tooltip>
|
||||
<Tooltip title="Move Down">
|
||||
<span>
|
||||
<IconButton
|
||||
size="small"
|
||||
color="secondary"
|
||||
aria-label={`Move item ${i + 1} down`}
|
||||
disabled={disabled || i === items.length - 1}
|
||||
onClick={() => move(i, 1)}
|
||||
>
|
||||
<ArrowDownOutlined />
|
||||
</IconButton>
|
||||
</span>
|
||||
</Tooltip>
|
||||
<Tooltip title="Remove">
|
||||
<span>
|
||||
<IconButton
|
||||
size="small"
|
||||
color="secondary"
|
||||
aria-label={`Remove item ${i + 1}`}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange(items.filter((_, idx) => idx !== i))}
|
||||
>
|
||||
<CloseOutlined />
|
||||
</IconButton>
|
||||
</span>
|
||||
</Tooltip>
|
||||
</Stack>
|
||||
))}
|
||||
<Stack direction="row" sx={{ alignItems: 'center', gap: 1 }}>
|
||||
<Button
|
||||
size="small"
|
||||
variant="dashed"
|
||||
startIcon={<PlusOutlined />}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange([...items, elementType === 'boolean' ? 'false' : ''])}
|
||||
>
|
||||
Add Item
|
||||
</Button>
|
||||
{error && (
|
||||
<Typography variant="caption" color="error.main">
|
||||
{error}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { ReactNode, useEffect, useState } from 'react';
|
||||
|
||||
// material-ui
|
||||
import Box from '@mui/material/Box';
|
||||
import Button from '@mui/material/Button';
|
||||
import FormControlLabel from '@mui/material/FormControlLabel';
|
||||
import Stack from '@mui/material/Stack';
|
||||
import Switch from '@mui/material/Switch';
|
||||
import Tooltip from '@mui/material/Tooltip';
|
||||
import Typography from '@mui/material/Typography';
|
||||
|
||||
// project imports
|
||||
import CodeEditor, { type CodeLanguage } from 'components/CodeEditor';
|
||||
import { setEditorPref, useEditorPrefs } from './prefs';
|
||||
import SaveButton, { type SaveControl } from './SaveButton';
|
||||
|
||||
// assets
|
||||
import FullscreenExitOutlined from '@ant-design/icons/FullscreenExitOutlined';
|
||||
import FullscreenOutlined from '@ant-design/icons/FullscreenOutlined';
|
||||
|
||||
// types
|
||||
import type { CompletionContext } from 'utils/monaco/powershell-language';
|
||||
|
||||
const DEFAULT_HINT = 'Context-aware completions, hover cards and checks for cmdlets, parameters and variables.';
|
||||
|
||||
interface Props {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
language: CodeLanguage;
|
||||
readOnly?: boolean;
|
||||
/** The saved text: change bars in the gutter and Compare with Saved. */
|
||||
original?: string;
|
||||
/** Names the code can use besides its own ($Param, $Secrets.X, attached functions). */
|
||||
completionContext?: CompletionContext;
|
||||
/** What is being edited, shown above the code while it fills the window. */
|
||||
title: string;
|
||||
/** Hover text for the IntelliSense switch. */
|
||||
intellisenseHint?: string;
|
||||
/** Height in the page (CSS length or px); popped out, it fills the window. */
|
||||
height?: number | string;
|
||||
/** Extra controls at the start of the toolbar's right-hand group. */
|
||||
toolbar?: ReactNode;
|
||||
/** Save, shown in the toolbar while the editor fills the window and hides the page's own. */
|
||||
save?: SaveControl;
|
||||
}
|
||||
|
||||
// ==============================|| CODE WORKSPACE ||============================== //
|
||||
|
||||
/** The code pane every script and function editor shares: toolbar, IntelliSense, pop-out and the Monaco editor. */
|
||||
export default function CodeWorkspace({
|
||||
value,
|
||||
onChange,
|
||||
language,
|
||||
readOnly = false,
|
||||
original,
|
||||
completionContext,
|
||||
title,
|
||||
intellisenseHint = DEFAULT_HINT,
|
||||
height = 'max(380px, 56vh)',
|
||||
toolbar,
|
||||
save
|
||||
}: Props) {
|
||||
const prefs = useEditorPrefs();
|
||||
const [fullscreen, setFullscreen] = useState(false);
|
||||
const powershell = language === 'powershell';
|
||||
|
||||
useEffect(() => {
|
||||
if (!fullscreen) return;
|
||||
const onKey = (event: KeyboardEvent) => event.key === 'Escape' && setFullscreen(false);
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [fullscreen]);
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={
|
||||
fullscreen
|
||||
? {
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
zIndex: (theme) => theme.zIndex.modal,
|
||||
bgcolor: 'background.paper',
|
||||
p: 2,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 1.5
|
||||
}
|
||||
: { display: 'flex', flexDirection: 'column', gap: 1.5 }
|
||||
}
|
||||
>
|
||||
<Stack direction="row" sx={{ gap: 1, alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap' }}>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ fontFamily: 'var(--font-mono)' }}>
|
||||
{fullscreen ? `${title} · ` : ''}
|
||||
{language === 'shell' ? 'bash' : language}
|
||||
</Typography>
|
||||
<Stack direction="row" sx={{ gap: 1, alignItems: 'center' }}>
|
||||
{toolbar}
|
||||
<Tooltip title={powershell ? intellisenseHint : 'Completions are for PowerShell.'}>
|
||||
<FormControlLabel
|
||||
disabled={!powershell}
|
||||
control={
|
||||
<Switch
|
||||
size="small"
|
||||
checked={prefs.intellisense && powershell}
|
||||
onChange={() => setEditorPref('intellisense', !prefs.intellisense)}
|
||||
/>
|
||||
}
|
||||
label={<Typography variant="body2">IntelliSense</Typography>}
|
||||
sx={{ mr: 0 }}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip title={fullscreen ? 'Return to the page (Esc)' : 'Fill the window with the editor'}>
|
||||
<Button
|
||||
size="small"
|
||||
color="secondary"
|
||||
startIcon={fullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
|
||||
onClick={() => setFullscreen((on) => !on)}
|
||||
>
|
||||
{fullscreen ? 'Restore' : 'Pop Out'}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
{fullscreen && save && <SaveButton control={save} size="small" />}
|
||||
</Stack>
|
||||
</Stack>
|
||||
<Box sx={fullscreen ? { flex: 1, minHeight: 0 } : undefined}>
|
||||
<CodeEditor
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
language={language}
|
||||
readOnly={readOnly}
|
||||
height={fullscreen ? '100%' : height}
|
||||
intellisense={prefs.intellisense && powershell}
|
||||
completionContext={completionContext}
|
||||
original={original}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// material-ui
|
||||
import Tooltip from '@mui/material/Tooltip';
|
||||
|
||||
// project imports
|
||||
import GatedButton from 'components/GatedButton';
|
||||
|
||||
// assets
|
||||
import SaveOutlined from '@ant-design/icons/SaveOutlined';
|
||||
|
||||
export interface SaveControl {
|
||||
onSave: () => void;
|
||||
saving: boolean;
|
||||
/** Nothing to save yet (or not ready). */
|
||||
disabled: boolean;
|
||||
/** Why this person cannot save (undefined when they can). */
|
||||
gate?: string;
|
||||
}
|
||||
|
||||
// ==============================|| CODE EDITOR - SAVE BUTTON ||============================== //
|
||||
|
||||
/** The editor's Save, in the page header and in the toolbar when the editor fills the window. */
|
||||
export default function SaveButton({ control, size }: { control: SaveControl; size?: 'small' | 'medium' }) {
|
||||
const { onSave, saving, disabled, gate } = control;
|
||||
return (
|
||||
<Tooltip title={gate ? '' : 'Ctrl+S'}>
|
||||
<span>
|
||||
<GatedButton
|
||||
size={size}
|
||||
variant="contained"
|
||||
startIcon={<SaveOutlined />}
|
||||
gate={gate}
|
||||
disabled={disabled || saving}
|
||||
onClick={onSave}
|
||||
>
|
||||
{saving ? 'Saving…' : 'Save'}
|
||||
</GatedButton>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -5,14 +5,19 @@ export interface EditorPrefs {
|
||||
minimap: boolean;
|
||||
wordWrap: boolean;
|
||||
stickyScroll: boolean;
|
||||
/** Completions, hover cards and context-aware checks (PowerShell). */
|
||||
intellisense: boolean;
|
||||
}
|
||||
|
||||
const KEY = 'editor-prefs';
|
||||
const DEFAULTS: EditorPrefs = { minimap: false, wordWrap: false, stickyScroll: true };
|
||||
const DEFAULTS: EditorPrefs = { minimap: false, wordWrap: false, stickyScroll: true, intellisense: true };
|
||||
/** Where IntelliSense was remembered before it joined these. */
|
||||
const LEGACY_INTELLISENSE_KEY = 'editor-intellisense';
|
||||
|
||||
function read(): EditorPrefs {
|
||||
try {
|
||||
return { ...DEFAULTS, ...JSON.parse(localStorage.getItem(KEY) ?? '{}') };
|
||||
const intellisense = localStorage.getItem(LEGACY_INTELLISENSE_KEY) !== '0';
|
||||
return { ...DEFAULTS, intellisense, ...JSON.parse(localStorage.getItem(KEY) ?? '{}') };
|
||||
} catch {
|
||||
return DEFAULTS;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user