ExecuteR MVP: agent, control plane, WebUI, grouping, deployment #1
@@ -0,0 +1,222 @@
|
||||
# Docker Compose Stack Specification
|
||||
|
||||
## File Header
|
||||
```yaml
|
||||
#=============================================================================
|
||||
# {STACK_NAME} - {Description}
|
||||
# {URL}
|
||||
#=============================================================================
|
||||
#
|
||||
# CREDENTIALS:
|
||||
# {credential format}
|
||||
#
|
||||
# PRODUCTION SETUP:
|
||||
# 1. {step}
|
||||
# 2. {step}
|
||||
#
|
||||
# ENDPOINTS:
|
||||
# - {endpoint}: {url}
|
||||
#
|
||||
#=============================================================================
|
||||
|
||||
name: '${STACK_NAME:-stk-{name}-00001}'
|
||||
```
|
||||
|
||||
## Networks
|
||||
```yaml
|
||||
networks:
|
||||
EXTERNAL:
|
||||
name: {STACKNAME}-EXTERNAL
|
||||
driver: bridge
|
||||
internal: false
|
||||
attachable: true
|
||||
INTERNAL:
|
||||
name: {STACKNAME}-INTERNAL
|
||||
driver: bridge
|
||||
internal: true
|
||||
attachable: true
|
||||
```
|
||||
|
||||
## Services
|
||||
|
||||
### Container Naming
|
||||
- Format: `{STACKNAME}-{TIER}-00001`
|
||||
- Tiers: `DB`, `CACHE`, `APP`, `WORKER`, `PROXY`
|
||||
- Example: `NETBOX-DB-00001`, `CLOUDREVE-APP-00001`
|
||||
|
||||
### No Hostnames
|
||||
- Do NOT use `hostname:` - use compose service names for internal networking
|
||||
- Reference other services by service name: `DB`, `Cache`, `App`
|
||||
|
||||
### Ports vs Expose
|
||||
- Services on INTERNAL network only: use `expose:` — NO host `ports:` binding
|
||||
- Services on EXTERNAL network (or needing host access): use `ports:` for host-bound ports
|
||||
- Exception: if the Docker daemon must reach the container (e.g. syslog driver), a loopback `ports:` bind is required even on INTERNAL
|
||||
```yaml
|
||||
# INTERNAL-only service — expose only, no host port
|
||||
expose:
|
||||
- '{port}'
|
||||
|
||||
# EXTERNAL service or host-accessible — bind to host
|
||||
ports:
|
||||
- '${APP_PORT:-18080}:8080'
|
||||
|
||||
# Exception: loopback-only for Docker daemon access (e.g. syslog collector)
|
||||
# NOTE: Host port required - Docker syslog driver sends from host daemon to this container
|
||||
ports:
|
||||
- '127.0.0.1:1514:10514'
|
||||
```
|
||||
|
||||
### Published Port Selection
|
||||
Host-published ports must avoid well-known/commonly-conflicting ports to prevent collisions
|
||||
when multiple stacks coexist on the same host.
|
||||
- DO NOT publish on `80`, `443`, `8080`, `8000`, `8443`, `3000`, `5000`, `9000`, `9090`, `9443`
|
||||
- Pick a random uncommon port in the high range (e.g. `10000`–`29999`) that is not
|
||||
already used by another stack in this repository
|
||||
- The container-internal port stays at the application's native value
|
||||
(e.g. `:80` for a webserver) — only the host-side is remapped
|
||||
- Both the compose default and the `.env` value should use the same uncommon port
|
||||
(port values are NOT secrets and need not differ)
|
||||
```yaml
|
||||
# Good — host-side mapped to an uncommon port, container-side untouched
|
||||
ports:
|
||||
- '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${HTTP_PORT:-18472}:80'
|
||||
|
||||
# Bad — publishes on a commonly-used host port
|
||||
ports:
|
||||
- '${HTTP_PORT:-80}:80'
|
||||
```
|
||||
|
||||
### Standard Service Block
|
||||
```yaml
|
||||
{ServiceName}:
|
||||
image: '${IMAGE:-default/image}:${VERSION:-tag}'
|
||||
container_name: {STACKNAME}-{TIER}-00001
|
||||
restart: unless-stopped
|
||||
stop_signal: SIGTERM
|
||||
stop_grace_period: 30s
|
||||
user: "${PUID:-1000}:${PGID:-1000}"
|
||||
logging:
|
||||
driver: 'local'
|
||||
networks:
|
||||
INTERNAL:
|
||||
expose:
|
||||
- '{port}'
|
||||
environment:
|
||||
VAR_NAME: '${VAR_NAME:-DefaultValue}'
|
||||
volumes:
|
||||
- /etc/timezone:/etc/timezone:ro
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
- "${STACK_BINDMOUNTROOT:-/mnt/docker/stacks}/${STACK_NAME:-stk-name-00001}/{Tier}/Data:/container/path:rw"
|
||||
healthcheck:
|
||||
test: ["CMD", "command", "args"]
|
||||
start_period: 30s
|
||||
interval: 10s
|
||||
retries: 5
|
||||
timeout: 5s
|
||||
labels:
|
||||
com.centurylinklabs.watchtower.enable: '${ENABLEAUTOMATICUPDATES:-false}'
|
||||
```
|
||||
|
||||
## Bind Mounts
|
||||
- Format: `"${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-name-00001}/{Tier}/Data:/container/path:rw"`
|
||||
- Tiers: `App`, `DB`, `Cache`
|
||||
- Always use `:rw` or `:ro` suffix
|
||||
|
||||
## Secrets & Defaults
|
||||
- Compose defaults MUST differ from .env values
|
||||
- Both must be actual secure random strings (not placeholder text)
|
||||
- Generate with: `openssl rand -base64 24` (passwords) or `openssl rand -base64 50` (keys)
|
||||
- Compose: `${PASSWORD:-xK9mZ7vQ3wL8nP2jR5tY0uA4}` (random default)
|
||||
- .env: `PASSWORD=bH3nF6kM9pL2sW5xY8cD1eG4` (different random value)
|
||||
|
||||
## Image Variables
|
||||
```yaml
|
||||
image: '${IMAGE_NAME:-default/image}:${IMAGE_VERSION:-tag}'
|
||||
```
|
||||
Examples:
|
||||
- `'${POSTGRES_IMAGE:-postgres}:${POSTGRES_VERSION:-17-alpine}'`
|
||||
- `'${VALKEY_IMAGE:-valkey/valkey}:${VALKEY_VERSION:-9.0-alpine}'`
|
||||
|
||||
## SHA256 Image Pinning
|
||||
Pin critical infrastructure images (DB, cache, message brokers, init/dependency
|
||||
containers) to a specific digest for reproducibility and security:
|
||||
```yaml
|
||||
image: '${IMAGE:-default/image}:${VERSION:-tag@sha256:abc123...}'
|
||||
```
|
||||
- Always pin: database images (Postgres, MySQL, MongoDB, MSSQL, etc.),
|
||||
cache images (Valkey, Redis-compatible), message brokers (NATS, RabbitMQ),
|
||||
search/index stores (Quickwit, Meilisearch, Elasticsearch), object stores
|
||||
(MinIO), and any other dependency/init container where image drift could
|
||||
cause data corruption, schema mismatches, or silent breakage
|
||||
- The `@sha256:` digest goes AFTER the tag in the VERSION variable
|
||||
- Compose default AND .env value must both include the same digest
|
||||
|
||||
### Obtaining the Correct Digest
|
||||
ONLY use a digest obtained from a successful local pull. NEVER copy a digest
|
||||
from the Docker Hub web UI tag list — that view shows multiple manifests per
|
||||
tag (per-arch images PLUS attestation manifests), and attestation manifests
|
||||
are served with media type `application/octet-stream` / `application/vnd.in-toto+json`
|
||||
which containerd cannot unpack as an image. Symptom:
|
||||
```
|
||||
failed to unpack image on snapshotter overlayfs: unexpected media type
|
||||
application/octet-stream for sha256:<digest>: not found
|
||||
```
|
||||
Correct procedure:
|
||||
```bash
|
||||
# 1. Pull the tag (resolves the multi-arch index to your host's image manifest)
|
||||
docker pull image:tag
|
||||
|
||||
# 2. Read back the digest of the actual image manifest that was pulled
|
||||
docker inspect --format='{{index .RepoDigests 0}}' image:tag
|
||||
# -> image@sha256:<correct-image-manifest-digest>
|
||||
|
||||
# 3. Verify the digest is pullable on its own before committing it
|
||||
docker pull image@sha256:<digest>
|
||||
```
|
||||
Update workflow when bumping a pinned image: re-run the three steps above,
|
||||
then update both the compose default and the matching `.env` value.
|
||||
|
||||
Examples:
|
||||
- `'${POSTGRES_VERSION:-17@sha256:2203e6282d9e7de7c24d7da234e2a744fb325df366a3fd8ed940e8abbee39527}'`
|
||||
- `'${VALKEY_VERSION:-9.0-alpine@sha256:d1cc70645bbcef743615463a2fa4616e841407545e18f560aed0c49671a90147}'`
|
||||
- `'${HARBOR_DB_VERSION:-v2.15.0@sha256:b54e48a70a7b...}'`
|
||||
|
||||
## Cache (Valkey)
|
||||
Always use Valkey, never Redis:
|
||||
```yaml
|
||||
Cache:
|
||||
image: '${VALKEY_IMAGE:-valkey/valkey}:${VALKEY_VERSION:-9.0-alpine}'
|
||||
container_name: {STACKNAME}-CACHE-00001
|
||||
command: ["valkey-server", "--appendonly", "yes", "--requirepass", "${REDIS_PASSWORD:-DefaultCachePass123}"]
|
||||
```
|
||||
|
||||
## Network References
|
||||
- Internal services reference each other by **service name**: `DB`, `Cache`, `App`
|
||||
- NOT by container name: ~~`NETBOX-DB-00001`~~
|
||||
|
||||
## Reverse Proxy / Nginx Inclusion
|
||||
A dedicated `Proxy` (nginx) service is only included when it serves a real
|
||||
runtime role in the stack. Do NOT add nginx solely to "front" an app that
|
||||
already listens on HTTP — publish the app directly with an uncommon host port.
|
||||
|
||||
Include an in-stack nginx (or equivalent) ONLY when:
|
||||
- It acts as the application's **webserver** (e.g. serves static assets,
|
||||
PHP-FPM upstream, runtime SSI/auth_request, app-specific URL rewrites that
|
||||
the app image itself does not provide), OR
|
||||
- It acts as an **internal reverse proxy that fans out edge requests** across
|
||||
multiple in-stack services (e.g. routes `/api` → backend, `/` → frontend,
|
||||
`/ws` → websocket service, or merges multiple sibling services behind a
|
||||
single host port).
|
||||
|
||||
Do NOT include nginx when:
|
||||
- The app image already exposes a single HTTP port that can be published directly
|
||||
- The only goal is TLS termination or a public hostname — that belongs to the
|
||||
host-level edge proxy (NPM, Traefik, Caddy, etc.), not the stack
|
||||
- The app embeds its own webserver/router and no fan-out is required
|
||||
|
||||
When nginx is included, it follows the standard service block conventions:
|
||||
- Service name `Proxy`, container `{STACKNAME}-PROXY-00001`
|
||||
- Sits on `EXTERNAL` + `INTERNAL`, publishes on an uncommon host port
|
||||
- Config is bind-mounted from `${STACK_BINDMOUNTROOT}/${STACK_NAME}/Proxy/Config/...:ro`
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
# Environment File Specification
|
||||
|
||||
## File Header
|
||||
```bash
|
||||
#=============================================================================
|
||||
# {STACK_NAME} - {Description}
|
||||
#=============================================================================
|
||||
#
|
||||
# CREDENTIALS:
|
||||
# {credential format}
|
||||
#
|
||||
# ACCESS URL: {url}
|
||||
#
|
||||
# PRODUCTION SETUP:
|
||||
# 1. {step}
|
||||
# 2. {step}
|
||||
#
|
||||
#=============================================================================
|
||||
```
|
||||
|
||||
## Required Variables
|
||||
|
||||
### Stack Identity
|
||||
```bash
|
||||
# Stack Identity
|
||||
STACK_NAME=stk-{name}-00001
|
||||
STACK_BINDMOUNTROOT=/mnt/data/docker/stacks
|
||||
```
|
||||
|
||||
### Container User/Group
|
||||
```bash
|
||||
# Container User/Group
|
||||
PUID=0
|
||||
PGID=0
|
||||
```
|
||||
- Default in compose: `${PUID:-1000}:${PGID:-1000}`
|
||||
- Set to `0` for root, or match host user UID/GID
|
||||
|
||||
## Images
|
||||
```bash
|
||||
# Images
|
||||
{APP}_IMAGE={default/image}
|
||||
{APP}_VERSION={tag}
|
||||
POSTGRES_IMAGE=postgres
|
||||
POSTGRES_VERSION=17@sha256:2203e6282d9e7de7c24d7da234e2a744fb325df366a3fd8ed940e8abbee39527
|
||||
VALKEY_IMAGE=valkey/valkey
|
||||
VALKEY_VERSION=9.0-alpine@sha256:{digest}
|
||||
BUSYBOX_IMAGE=busybox
|
||||
BUSYBOX_VERSION=latest
|
||||
```
|
||||
- Always SHA256 pin dependency/infrastructure images for reproducibility:
|
||||
databases (Postgres, MySQL, MongoDB, MSSQL), cache (Valkey), message brokers
|
||||
(NATS, RabbitMQ), search/index stores (Quickwit, Meilisearch, Elasticsearch),
|
||||
object stores (MinIO), and any init/sidecar container
|
||||
- Format: `{tag}@sha256:{digest}` — the tag is retained for readability, the digest locks the exact build
|
||||
- Obtain the digest via a real pull, NOT by copying from the Docker Hub web UI
|
||||
(those listings include attestation manifests that are not pullable images
|
||||
and fail at unpack with `unexpected media type application/octet-stream`):
|
||||
```bash
|
||||
docker pull image:tag
|
||||
docker inspect --format='{{index .RepoDigests 0}}' image:tag
|
||||
docker pull image@sha256:<digest> # sanity-check the digest resolves
|
||||
```
|
||||
- When bumping a pinned image, repeat the three commands above and update both
|
||||
the compose default and this `.env` value to the new digest in lockstep
|
||||
|
||||
## Ports
|
||||
```bash
|
||||
# Ports
|
||||
{APP}_PORT={port}
|
||||
```
|
||||
|
||||
## Database
|
||||
```bash
|
||||
# Database
|
||||
POSTGRES_USER={appname}
|
||||
POSTGRES_PASSWORD={SecurePassword}
|
||||
POSTGRES_DB={appname}
|
||||
```
|
||||
|
||||
## Cache
|
||||
```bash
|
||||
# Cache (Valkey/Redis)
|
||||
REDIS_PASSWORD={SecurePassword}
|
||||
```
|
||||
|
||||
## Secrets
|
||||
```bash
|
||||
# Secrets (regenerate for production)
|
||||
SECRET_KEY={50+ character random string}
|
||||
```
|
||||
Generate with: `openssl rand -base64 50`
|
||||
|
||||
## Automatic Updates
|
||||
```bash
|
||||
# Automatic Updates (Watchtower)
|
||||
{APP}_ENABLEAUTOMATICUPDATES=false
|
||||
POSTGRES_ENABLEAUTOMATICUPDATES=false
|
||||
VALKEY_ENABLEAUTOMATICUPDATES=false
|
||||
```
|
||||
|
||||
## Secret Value Rules
|
||||
|
||||
### .env vs Compose Defaults
|
||||
| Location | Purpose | Example |
|
||||
|----------|---------|---------|
|
||||
| .env | Actual random secret | `bH3nF6kM9pL2sW5xY8cD1eG4` |
|
||||
| Compose default | Different random secret | `xK9mZ7vQ3wL8nP2jR5tY0uA4` |
|
||||
|
||||
### Generation
|
||||
```bash
|
||||
# Passwords (24 chars)
|
||||
openssl rand -base64 24
|
||||
|
||||
# Secret keys (50+ chars)
|
||||
openssl rand -base64 50
|
||||
|
||||
# Hash salts (hex)
|
||||
openssl rand -hex 16
|
||||
```
|
||||
|
||||
### Why Different?
|
||||
- Both are real secrets, but different values
|
||||
- If .env is missing, stack still runs but with different credentials
|
||||
- Logs/debugging can identify which secret source is active
|
||||
|
||||
## Example Complete .env
|
||||
```bash
|
||||
#=============================================================================
|
||||
# NETBOX - Network Documentation & IPAM
|
||||
#=============================================================================
|
||||
#
|
||||
# CREDENTIALS:
|
||||
# Username: admin
|
||||
# Password: Adm1n5ecur3P@ss2024
|
||||
#
|
||||
# ACCESS URL: http://localhost:8000/
|
||||
#
|
||||
#=============================================================================
|
||||
|
||||
# Stack Identity
|
||||
STACK_NAME=stk-netbox-00001
|
||||
STACK_BINDMOUNTROOT=/mnt/data/docker/stacks
|
||||
|
||||
# Container User/Group
|
||||
PUID=0
|
||||
PGID=0
|
||||
|
||||
# Images
|
||||
NETBOX_IMAGE=netboxcommunity/netbox
|
||||
NETBOX_VERSION=v4.2
|
||||
POSTGRES_IMAGE=postgres
|
||||
POSTGRES_VERSION=17@sha256:2203e6282d9e7de7c24d7da234e2a744fb325df366a3fd8ed940e8abbee39527
|
||||
VALKEY_IMAGE=valkey/valkey
|
||||
VALKEY_VERSION=9.0-alpine
|
||||
BUSYBOX_IMAGE=busybox
|
||||
BUSYBOX_VERSION=latest
|
||||
|
||||
# Ports
|
||||
NETBOX_PORT=8000
|
||||
|
||||
# Database
|
||||
POSTGRES_USER=netbox
|
||||
POSTGRES_PASSWORD=N3tb0x5ecur3P@ssw0rd2024
|
||||
POSTGRES_DB=netbox
|
||||
|
||||
# Cache
|
||||
REDIS_PASSWORD=V@lk3yN3tb0xP@ss2024
|
||||
|
||||
# Secrets
|
||||
SECRET_KEY=Kx9mZ7vQ3wL8nP2jR5tY0uA4cF6hB1dE9sW3xN7mJ2kP5vT8yG0qC4rU6iO1aM3z
|
||||
|
||||
# Superuser
|
||||
SUPERUSER_NAME=admin
|
||||
SUPERUSER_EMAIL=admin@example.com
|
||||
SUPERUSER_PASSWORD=Adm1n5ecur3P@ss2024
|
||||
SKIP_SUPERUSER=false
|
||||
|
||||
# Automatic Updates
|
||||
NETBOX_ENABLEAUTOMATICUPDATES=true
|
||||
POSTGRES_ENABLEAUTOMATICUPDATES=false
|
||||
VALKEY_ENABLEAUTOMATICUPDATES=false
|
||||
```
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
indent_style = space
|
||||
|
||||
[*.{cs,csx}]
|
||||
indent_size = 4
|
||||
end_of_line = crlf
|
||||
|
||||
dotnet_sort_system_directives_first = true
|
||||
dotnet_style_qualification_for_field = false:suggestion
|
||||
dotnet_style_qualification_for_property = false:suggestion
|
||||
dotnet_style_qualification_for_method = false:suggestion
|
||||
dotnet_style_require_accessibility_modifiers = always:warning
|
||||
dotnet_style_readonly_field = true:warning
|
||||
|
||||
csharp_style_namespace_declarations = file_scoped:warning
|
||||
csharp_style_var_for_built_in_types = true:suggestion
|
||||
csharp_style_var_when_type_is_apparent = true:suggestion
|
||||
csharp_style_var_elsewhere = true:suggestion
|
||||
csharp_new_line_before_open_brace = all
|
||||
csharp_prefer_braces = true:warning
|
||||
csharp_style_prefer_primary_constructors = false:none
|
||||
|
||||
[*.{json,yml,yaml}]
|
||||
indent_size = 2
|
||||
|
||||
[*.{js,ts,svelte,css,html}]
|
||||
indent_size = 2
|
||||
|
||||
[*.{ps1,psm1}]
|
||||
indent_size = 4
|
||||
|
||||
[*.{csproj,props,targets,wixproj,wxs}]
|
||||
indent_size = 2
|
||||
@@ -0,0 +1,146 @@
|
||||
#=============================================================================
|
||||
# ExecuteR - Windows endpoint management control plane
|
||||
#=============================================================================
|
||||
#
|
||||
# CREDENTIALS:
|
||||
# Initial admin: INITIAL_ADMIN_USERNAME / INITIAL_ADMIN_PASSWORD (below)
|
||||
# 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
|
||||
# external reverse proxy (e.g. https://control.example.com)
|
||||
#
|
||||
# PRODUCTION SETUP:
|
||||
# 1. cp .env.example .env (or run scripts/New-LocalSecrets.ps1)
|
||||
# 2. Fill INITIAL_ADMIN_PASSWORD and NATS_ACCOUNT_SIGNING_SEED
|
||||
# 3. docker compose up -d --build
|
||||
#
|
||||
#=============================================================================
|
||||
|
||||
# ── Stack identity ─────────────────────────────────────────────────────────
|
||||
# Compose project name and bind-mount root. Container and network names are
|
||||
# static (EXECUTER-API-00001, EXECUTER-EXTERNAL, ...) and not derived from these.
|
||||
STACK_NAME=stk-executer-00001
|
||||
STACK_BINDMOUNTROOT=/mnt/data/docker/stacks
|
||||
|
||||
# ── Images ─────────────────────────────────────────────────────────────────
|
||||
# Published by CI to Gitea's OWN container registry, which lives on the Gitea
|
||||
# host itself. REGISTRY is "<gitea-host>/<owner>", all lowercase — e.g.
|
||||
# git.example.com/platform
|
||||
# deploy.sh pulls these and builds from source only if the pull fails.
|
||||
REGISTRY=git.example.com/owner
|
||||
BACKEND_IMAGE=executer-backend
|
||||
WEBUI_IMAGE=executer-webui
|
||||
BACKEND_VERSION=latest
|
||||
WEBUI_VERSION=latest
|
||||
# missing = use local/pull once; always = re-pull every deploy; never = local only
|
||||
IMAGE_PULL_POLICY=missing
|
||||
|
||||
# Needed only to PULL from a private repo's packages. Any Gitea account token
|
||||
# works as the password. CI does not need these — Actions injects its own.
|
||||
REGISTRY_USERNAME=
|
||||
REGISTRY_TOKEN=
|
||||
|
||||
# Infrastructure images are pinned by digest.
|
||||
NATS_IMAGE=nats
|
||||
NATS_VERSION=2.12-alpine@sha256:7cef1bd3fed6034e95cf6e6bc9c28c5afa6dc58e9fb778dd7924a1ac62569f2d
|
||||
|
||||
# Optional in-stack reverse proxy (docker-compose.proxy.yml, opt-in)
|
||||
NGINX_IMAGE=nginx
|
||||
NGINX_VERSION=1.29-alpine
|
||||
PROXY_HTTP_PORT=18080
|
||||
PROXY_HTTPS_PORT=18443
|
||||
PROXY_PUBLIC_HOSTNAME=control.example.com
|
||||
|
||||
# ── Host-published ports (uncommon range; front with the edge proxy) ───────
|
||||
BIND_EXTERNAL_ADDRESS=0.0.0.0
|
||||
WEBUI_PORT=13080
|
||||
BACKEND_PORT=19080
|
||||
NATS_WS_PORT=19222
|
||||
|
||||
# ── Public edge ────────────────────────────────────────────────────────────
|
||||
# The single public https URL served by your existing reverse proxy.
|
||||
PUBLIC_SERVER_URL=https://control.example.com
|
||||
|
||||
# ── Reverse proxy trust ────────────────────────────────────────────────────
|
||||
# At least one of TRUSTED_PROXIES / TRUSTED_NETWORKS is required when
|
||||
# TRUST_PROXY=1 outside development mode.
|
||||
TRUST_PROXY=1
|
||||
TRUSTED_PROXIES=
|
||||
TRUSTED_NETWORKS=172.16.0.0/12
|
||||
TRUSTED_HOSTS=control.example.com
|
||||
FORWARD_LIMIT=1
|
||||
|
||||
# ── Initial local admin (first startup only) ───────────────────────────────
|
||||
INITIAL_ADMIN_USERNAME=admin
|
||||
# Generate: openssl rand -base64 24
|
||||
INITIAL_ADMIN_PASSWORD=
|
||||
|
||||
# ── OIDC (optional) ────────────────────────────────────────────────────────
|
||||
OIDC_ENABLED=0
|
||||
OIDC_AUTHORITY=
|
||||
OIDC_CLIENT_ID=
|
||||
OIDC_CLIENT_SECRET=
|
||||
OIDC_CALLBACK_PATH=/signin-oidc
|
||||
OIDC_SCOPES=openid profile email
|
||||
OIDC_NAME_CLAIM=
|
||||
OIDC_ROLE_CLAIM=
|
||||
OIDC_ADMIN_ROLE=
|
||||
|
||||
# ── NATS decentralized auth (generated — do NOT hand-edit) ─────────────────
|
||||
# These MUST be real Ed25519 NKeys from scripts/New-LocalSecrets.ps1
|
||||
# (or `dotnet run --project src/Backend -- nats-auth init`). A random string
|
||||
# here will not work — the signing seed must match the resolver's account.
|
||||
NATS_ACCOUNT_SIGNING_SEED=
|
||||
NATS_ACCOUNT_PUBLIC_KEY=
|
||||
NATS_OPERATOR_PUBLIC_KEY=
|
||||
|
||||
# ── S3 file delivery (optional) ────────────────────────────────────────────
|
||||
# Enables presigned-URL file downloads to devices. Any S3-compatible store
|
||||
# (AWS S3, MinIO, Backblaze B2, etc.).
|
||||
S3_ENABLED=0
|
||||
S3_ENDPOINT=
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=
|
||||
S3_ACCESS_KEY=
|
||||
S3_SECRET_KEY=
|
||||
S3_FORCE_PATH_STYLE=1
|
||||
S3_PRESIGN_EXPIRY_SECONDS=900
|
||||
|
||||
# ── Database ───────────────────────────────────────────────────────────────
|
||||
# sqlite (default, uses DATABASE_PATH) | postgres | sqlserver
|
||||
# For postgres/sqlserver set DATABASE_CONNECTION_STRING, e.g.
|
||||
# postgres: Host=db;Port=5432;Database=executer;Username=executer;Password=...
|
||||
# sqlserver: Server=db;Database=executer;User Id=sa;Password=...;TrustServerCertificate=True
|
||||
DATABASE_PROVIDER=sqlite
|
||||
DATABASE_CONNECTION_STRING=
|
||||
|
||||
# ── Logging (Serilog: console + rolling file) ──────────────────────────────
|
||||
# Server defaults: roll at 10 MB, keep the last 7 files (~70 MB ceiling).
|
||||
# The agent defaults to 5 MB / 3 files and is configured via GPO or registry.
|
||||
LOG_LEVEL=Information
|
||||
LOG_JSON=0
|
||||
LOG_DIRECTORY=/data/logs
|
||||
LOG_RETAIN_FILES=7
|
||||
LOG_MAX_BYTES=10485760
|
||||
|
||||
# ── Agent package for URL install (irm | iex) ──────────────────────────────
|
||||
# Directory (inside the backend container) holding Agent.msi / Agent.zip that
|
||||
# the URL install command downloads. Defaults to /data/agent (under API data).
|
||||
AGENT_PACKAGE_PATH=/data/agent
|
||||
|
||||
# ── Build / version ────────────────────────────────────────────────────────
|
||||
# Set by CI; local builds derive it via scripts/Build.ps1.
|
||||
UNIFIED_VERSION=
|
||||
|
||||
# ── Device lifecycle ───────────────────────────────────────────────────────
|
||||
# A device silent for this many days is orphaned: refused credential refresh
|
||||
# and job dispatch until it re-enrolls with a fresh bootstrap token.
|
||||
# Set to 0 to disable orphaning, so silent devices simply go Stale then
|
||||
# Offline and reconnect on their own. Default (unset) is 30.
|
||||
DEVICE_ORPHAN_AFTER_DAYS=30
|
||||
|
||||
# ── Automatic updates (Watchtower) ─────────────────────────────────────────
|
||||
NATS_ENABLEAUTOMATICUPDATES=false
|
||||
BACKEND_ENABLEAUTOMATICUPDATES=false
|
||||
WEBUI_ENABLEAUTOMATICUPDATES=false
|
||||
PROXY_ENABLEAUTOMATICUPDATES=false
|
||||
@@ -0,0 +1,148 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
push:
|
||||
branches: [dev, main]
|
||||
|
||||
jobs:
|
||||
build-test:
|
||||
# Windows is required to build/test the agent (CIM, ConPTY, DPAPI, service).
|
||||
runs-on: windows
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup .NET 10
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Compute unified version
|
||||
id: ver
|
||||
shell: pwsh
|
||||
run: |
|
||||
$v = & ./scripts/Get-UnifiedVersion.ps1
|
||||
"version=$v" | Out-File -FilePath $env:GITHUB_OUTPUT -Append
|
||||
Write-Host "Unified version: $v"
|
||||
|
||||
- name: Restore
|
||||
run: dotnet restore ExecuteR.slnx
|
||||
|
||||
- name: Build
|
||||
run: dotnet build ExecuteR.slnx -c Release --no-restore "-p:UnifiedVersion=${{ steps.ver.outputs.version }}"
|
||||
|
||||
- name: Unit tests
|
||||
run: |
|
||||
dotnet test tests/Shared.Tests -c Release --no-build --nologo
|
||||
dotnet test tests/Agent.Tests -c Release --no-build --nologo
|
||||
dotnet test tests/Backend.Tests -c Release --no-build --nologo
|
||||
|
||||
- name: Integration tests
|
||||
run: dotnet test tests/Integration.Tests -c Release --no-build --nologo
|
||||
|
||||
- name: WebUI install
|
||||
run: npm ci
|
||||
working-directory: src/WebUI
|
||||
|
||||
- name: WebUI check
|
||||
run: npm run check
|
||||
working-directory: src/WebUI
|
||||
|
||||
- name: WebUI build
|
||||
env:
|
||||
PUBLIC_BUILD_VERSION: ${{ steps.ver.outputs.version }}
|
||||
run: npm run build
|
||||
working-directory: src/WebUI
|
||||
|
||||
images:
|
||||
# Build the backend + webui images and publish them to the Gitea container
|
||||
# registry. Image names match what docker-compose.yml pulls:
|
||||
# <gitea-host>/<owner>/executer-backend:<tag>
|
||||
# <gitea-host>/<owner>/executer-webui:<tag>
|
||||
needs: build-test
|
||||
if: ${{ github.event_name == 'push' }}
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
# Gitea's built-in container registry lives on the Gitea host itself and
|
||||
# needs no configuration: Actions injects GITEA_TOKEN per run and it is
|
||||
# accepted as the registry password for the triggering actor.
|
||||
# The REGISTRY_* secrets are only an override for an EXTERNAL registry.
|
||||
REGISTRY_HOST: ${{ secrets.REGISTRY_HOST }}
|
||||
REGISTRY_USER: ${{ secrets.REGISTRY_USERNAME }}
|
||||
REGISTRY_PASS: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
SERVER_URL: ${{ github.server_url }}
|
||||
ACTOR: ${{ github.actor }}
|
||||
BUILTIN_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
OWNER: ${{ github.repository_owner }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Resolve version and registry target
|
||||
id: ver
|
||||
shell: bash
|
||||
run: |
|
||||
set -e
|
||||
echo "version=$(date -u +%Y.%m.%d.%H%M)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Default to Gitea's own registry on this instance; fall back to the
|
||||
# REGISTRY_* secrets only when an external registry is configured.
|
||||
if [ -n "$REGISTRY_HOST" ]; then
|
||||
HOST="$REGISTRY_HOST"; USER="$REGISTRY_USER"; PASS="$REGISTRY_PASS"
|
||||
echo "Using external registry $HOST"
|
||||
else
|
||||
HOST="$(echo "$SERVER_URL" | sed -E 's#^https?://##; s#/$##')"
|
||||
USER="$ACTOR"; PASS="$BUILTIN_TOKEN"
|
||||
echo "Using the built-in Gitea registry at $HOST"
|
||||
fi
|
||||
|
||||
# Gitea package paths are lowercase.
|
||||
OWNER_LC="$(echo "$OWNER" | tr '[:upper:]' '[:lower:]')"
|
||||
|
||||
{
|
||||
echo "host=$HOST"
|
||||
echo "user=$USER"
|
||||
echo "prefix=${HOST}/${OWNER_LC}/executer"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
echo "::add-mask::$PASS"
|
||||
echo "REGISTRY_LOGIN_PASSWORD=$PASS" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Registry login
|
||||
run: echo "$REGISTRY_LOGIN_PASSWORD" | docker login "${{ steps.ver.outputs.host }}" -u "${{ steps.ver.outputs.user }}" --password-stdin
|
||||
|
||||
- name: Build images
|
||||
env:
|
||||
VERSION: ${{ steps.ver.outputs.version }}
|
||||
PREFIX: ${{ steps.ver.outputs.prefix }}
|
||||
run: |
|
||||
set -e
|
||||
docker build -f src/Infra/backend/Dockerfile --build-arg UNIFIED_VERSION="$VERSION" -t "${PREFIX}-backend:$VERSION" .
|
||||
docker build -f src/Infra/webui/Dockerfile --build-arg UNIFIED_VERSION="$VERSION" -t "${PREFIX}-webui:$VERSION" .
|
||||
|
||||
- name: Tag and push
|
||||
env:
|
||||
VERSION: ${{ steps.ver.outputs.version }}
|
||||
PREFIX: ${{ steps.ver.outputs.prefix }}
|
||||
REF_NAME: ${{ github.ref_name }}
|
||||
run: |
|
||||
set -e
|
||||
for svc in backend webui; do
|
||||
docker push "${PREFIX}-${svc}:$VERSION"
|
||||
if [ "$REF_NAME" = "main" ]; then
|
||||
docker tag "${PREFIX}-${svc}:$VERSION" "${PREFIX}-${svc}:latest"
|
||||
docker push "${PREFIX}-${svc}:latest"
|
||||
else
|
||||
docker tag "${PREFIX}-${svc}:$VERSION" "${PREFIX}-${svc}:dev"
|
||||
docker tag "${PREFIX}-${svc}:$VERSION" "${PREFIX}-${svc}:${VERSION}-dev"
|
||||
docker push "${PREFIX}-${svc}:dev"
|
||||
docker push "${PREFIX}-${svc}:${VERSION}-dev"
|
||||
fi
|
||||
done
|
||||
echo "Published ${PREFIX}-backend and ${PREFIX}-webui"
|
||||
@@ -0,0 +1,47 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
agent-artifacts:
|
||||
# Publishes the self-contained agent, MSI and checksums, then attaches them
|
||||
# to a Gitea release for the unified version (when GITEA_TOKEN is available).
|
||||
runs-on: windows
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup .NET 10
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: Compute unified version
|
||||
id: ver
|
||||
shell: pwsh
|
||||
run: |
|
||||
$v = & ./scripts/Get-UnifiedVersion.ps1
|
||||
"version=$v" | Out-File -FilePath $env:GITHUB_OUTPUT -Append
|
||||
|
||||
- name: Generate icon
|
||||
shell: pwsh
|
||||
run: ./scripts/Generate-Icons.ps1
|
||||
|
||||
- name: Package agent (exe zip + MSI + checksums)
|
||||
shell: pwsh
|
||||
run: ./scripts/Package-Agent.ps1 -Version ${{ steps.ver.outputs.version }}
|
||||
|
||||
- name: Create Gitea release and upload assets
|
||||
shell: pwsh
|
||||
env:
|
||||
# GITEA_TOKEN is injected automatically by Gitea Actions; SERVER_URL
|
||||
# is seeded by scripts/Initialize-GiteaSecrets.ps1 and falls back to
|
||||
# the instance URL the runner already knows.
|
||||
GITEA_URL: ${{ vars.SERVER_URL || github.server_url }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
GITEA_OWNER: ${{ github.repository_owner }}
|
||||
GITEA_REPOSITORY: ${{ github.event.repository.name }}
|
||||
VERSION: ${{ steps.ver.outputs.version }}
|
||||
run: ./scripts/Publish-Release.ps1 -Version $env:VERSION
|
||||
@@ -0,0 +1,40 @@
|
||||
# Build results
|
||||
bin/
|
||||
obj/
|
||||
artifacts/
|
||||
publish/
|
||||
TestResults/
|
||||
*.binlog
|
||||
|
||||
# .NET tooling
|
||||
.vs/
|
||||
.vscode/
|
||||
*.user
|
||||
*.suo
|
||||
|
||||
# Node / SvelteKit
|
||||
node_modules/
|
||||
.svelte-kit/
|
||||
src/WebUI/build/
|
||||
npm-debug.log*
|
||||
|
||||
# Local state
|
||||
.local/
|
||||
|
||||
# Secrets — never commit generated secret material
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
secrets/*
|
||||
!secrets/README.md
|
||||
*.pfx
|
||||
*.key
|
||||
*.seed
|
||||
*.creds
|
||||
|
||||
# Generated icons (build artifacts)
|
||||
assets/*.ico
|
||||
|
||||
# OS noise
|
||||
Thumbs.db
|
||||
.DS_Store
|
||||
@@ -0,0 +1,27 @@
|
||||
<Project>
|
||||
|
||||
<!--
|
||||
Unified versioning: yyyy.MM.dd.HHmm (UTC).
|
||||
CI and scripts/Build.ps1 compute the version ONCE and pass it as
|
||||
-p:UnifiedVersion=... so every artifact in a build shares one version.
|
||||
The fallback below only applies to ad-hoc IDE/local builds.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<UnifiedVersion Condition="'$(UnifiedVersion)' == ''">$([System.DateTime]::get_UtcNow().ToString('yyyy.MM.dd.HHmm'))</UnifiedVersion>
|
||||
<Version>$(UnifiedVersion)</Version>
|
||||
<AssemblyVersion>$(UnifiedVersion)</AssemblyVersion>
|
||||
<FileVersion>$(UnifiedVersion)</FileVersion>
|
||||
<InformationalVersion>$(UnifiedVersion)</InformationalVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
<InvariantGlobalization>false</InvariantGlobalization>
|
||||
<AccelerateBuildsInVisualStudio>true</AccelerateBuildsInVisualStudio>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,57 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Transitive pins for known-vulnerability fixes (NU1903). -->
|
||||
<PackageVersion Include="SQLitePCLRaw.lib.e_sqlite3" Version="2.1.12" />
|
||||
<PackageVersion Include="System.Security.Cryptography.Xml" Version="10.0.10" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Messaging -->
|
||||
<PackageVersion Include="NATS.Net" Version="3.1.0" />
|
||||
<PackageVersion Include="NATS.Jwt" Version="1.0.1" />
|
||||
<PackageVersion Include="NATS.NKeys" Version="1.0.2" />
|
||||
|
||||
<!-- Hosting -->
|
||||
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="10.0.10" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.10" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.10" />
|
||||
|
||||
<!-- Logging (centralized Serilog configuration in Shared.Infrastructure) -->
|
||||
<PackageVersion Include="Serilog" Version="4.4.0" />
|
||||
<PackageVersion Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
<PackageVersion Include="Serilog.Extensions.Hosting" Version="10.0.0" />
|
||||
<PackageVersion Include="Serilog.Sinks.Console" Version="6.1.1" />
|
||||
<PackageVersion Include="Serilog.Sinks.File" Version="7.0.0" />
|
||||
<PackageVersion Include="Serilog.Formatting.Compact" Version="3.0.0" />
|
||||
<PackageVersion Include="Serilog.Enrichers.Environment" Version="3.0.1" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="10.0.10" />
|
||||
|
||||
<!-- Backend -->
|
||||
<PackageVersion Include="AWSSDK.S3" Version="4.0.102" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.10" />
|
||||
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.10" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.10" />
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="10.0.10" />
|
||||
|
||||
<!-- Agent -->
|
||||
<PackageVersion Include="Microsoft.PowerShell.SDK" Version="7.6.4" />
|
||||
<PackageVersion Include="System.ServiceProcess.ServiceController" Version="10.0.10" />
|
||||
<PackageVersion Include="System.Management" Version="10.0.10" />
|
||||
<PackageVersion Include="System.Security.Cryptography.ProtectedData" Version="10.0.10" />
|
||||
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.10" />
|
||||
|
||||
<!-- Installer -->
|
||||
<PackageVersion Include="WixToolset.Util.wixext" Version="5.0.2" />
|
||||
|
||||
<!-- Tests -->
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.8.1" />
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.10" />
|
||||
<PackageVersion Include="xunit.v3" Version="3.2.2" />
|
||||
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,14 @@
|
||||
<Solution>
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/Agent/Agent.csproj" />
|
||||
<Project Path="src/Backend/Backend.csproj" />
|
||||
<Project Path="src/Shared.Contracts/Shared.Contracts.csproj" />
|
||||
<Project Path="src/Shared.Infrastructure/Shared.Infrastructure.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
<Project Path="tests/Agent.Tests/Agent.Tests.csproj" />
|
||||
<Project Path="tests/Backend.Tests/Backend.Tests.csproj" />
|
||||
<Project Path="tests/Integration.Tests/Integration.Tests.csproj" />
|
||||
<Project Path="tests/Shared.Tests/Shared.Tests.csproj" />
|
||||
</Folder>
|
||||
</Solution>
|
||||
@@ -1,2 +1,792 @@
|
||||
# ExecuteR
|
||||
|
||||
Secure Windows endpoint management: a self-contained .NET agent enrolls over
|
||||
ordinary HTTPS, establishes **scoped NATS messaging over WebSocket** through the
|
||||
same reverse-proxy edge, publishes live state, accepts durable work, runs
|
||||
PowerShell in-process, and provides a secured interactive terminal — while the
|
||||
browser uses a WebSocket-connected NATS client for near-real-time UI updates
|
||||
with **no SignalR, SSE, or polling**.
|
||||
|
||||
- **Agent** — single self-contained Windows x64 executable / Windows service
|
||||
(.NET 10). Deterministic hardware identity, secure one-time bootstrap,
|
||||
CIM inventory, in-process PowerShell (System.Management.Automation), ConPTY
|
||||
remote shell, presigned-URL file delivery.
|
||||
- **Backend** — ASP.NET Core control plane: REST API, SQLite, local + OIDC
|
||||
auth, RBAC, NATS operator/JWT issuance, JetStream command dispatch, live
|
||||
event relay.
|
||||
- **WebUI** — SvelteKit dashboard: live device status, Monaco PowerShell editor
|
||||
with typed parameters and reusable function modules, live job output and
|
||||
progress, xterm.js remote shell.
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## Table of contents
|
||||
|
||||
1. [Architecture](#architecture)
|
||||
2. [Component flow](#component-flow)
|
||||
3. [Agent-to-component flow](#agent-to-component-flow)
|
||||
4. [Prerequisites](#prerequisites)
|
||||
5. [Local development](#local-development)
|
||||
6. [Required secrets](#required-secrets)
|
||||
7. [Generating local secrets](#generating-local-secrets)
|
||||
8. [Docker Compose](#docker-compose)
|
||||
9. [Reverse proxy routes](#reverse-proxy-routes)
|
||||
10. [Agent foreground mode and service lifecycle](#agent-foreground-mode-and-service-lifecycle)
|
||||
11. [MSI public properties](#msi-public-properties)
|
||||
12. [Registry paths and GPO precedence](#registry-paths-and-gpo-precedence)
|
||||
13. [Bootstrap and URL install](#bootstrap-and-url-install)
|
||||
14. [Local login and OIDC](#local-login-and-oidc)
|
||||
15. [Typed script parameters and function modules](#typed-script-parameters-and-function-modules)
|
||||
16. [Device groups and script triggers](#device-groups-and-script-triggers)
|
||||
17. [Database providers](#database-providers)
|
||||
18. [Logging](#logging)
|
||||
19. [Device lifecycle: reconnect or orphan](#device-lifecycle-reconnect-or-orphan)
|
||||
20. [S3 file delivery](#s3-file-delivery)
|
||||
21. [CI/CD and GITEA_* variables](#cicd-and-gitea_-variables)
|
||||
22. [Versioning](#versioning)
|
||||
23. [MVP demo sequence](#mvp-demo-sequence)
|
||||
24. [Troubleshooting](#troubleshooting)
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
**Network topology** — every arrow crossing the edge is HTTP/HTTPS on port 443.
|
||||
Agents and browsers never contact NATS directly: their NATS client speaks
|
||||
WebSocket to the reverse proxy, which forwards to the NATS WebSocket listener.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["Windows Agent"]
|
||||
B["Browser / SvelteKit"]
|
||||
P["Reverse Proxy :443"]
|
||||
|
||||
A -->|"HTTPS: bootstrap, install"| P
|
||||
A <-->|"WSS: NATS session"| P
|
||||
B -->|"HTTPS: REST API"| P
|
||||
B <-->|"WSS: NATS session"| P
|
||||
|
||||
subgraph Stack ["Docker stack (private network)"]
|
||||
UI["SvelteKit WebUI"]
|
||||
API["ASP.NET Core Backend"]
|
||||
N["NATS: WebSocket + TCP"]
|
||||
DB[("SQLite / Postgres / SQL Server")]
|
||||
JS[("JetStream")]
|
||||
end
|
||||
|
||||
P -->|"/"| UI
|
||||
P -->|"/api/*"| API
|
||||
P -->|"/messaging/agent"| N
|
||||
P -->|"/messaging/browser"| N
|
||||
|
||||
API <-->|"NATS TCP (internal only)"| N
|
||||
API --> DB
|
||||
N --- JS
|
||||
```
|
||||
|
||||
The only externally reachable route is HTTP/HTTPS on the edge proxy. NATS TCP
|
||||
(4222) is never published to the public network.
|
||||
|
||||
**Message flow over those sessions** — once the WSS sessions above are
|
||||
established, messages travel in both directions on them. The subjects each
|
||||
party may use are enforced by its NATS JWT.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["Agent"]
|
||||
N["NATS"]
|
||||
API["Backend"]
|
||||
B["Browser"]
|
||||
|
||||
A -->|"presence, inventory, job output/progress/state, shell output"| N
|
||||
N -->|"durable commands: script, inventory, file, shell"| A
|
||||
N <--> API
|
||||
API -->|"republished, session-scoped events"| N
|
||||
N -->|"browser.session.* only"| B
|
||||
B -->|"browser.session.shell.input only"| N
|
||||
```
|
||||
|
||||
Both agent and browser traffic in this second diagram physically rides the
|
||||
proxied WebSocket session from the topology diagram.
|
||||
|
||||
---
|
||||
|
||||
## Component flow
|
||||
|
||||
How a request or event moves through the internal components.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Browser
|
||||
UI["SvelteKit pages"]
|
||||
BN["Browser NATS client (WSS)"]
|
||||
end
|
||||
|
||||
subgraph Backend
|
||||
REST["REST API + Auth + RBAC"]
|
||||
ISS["NATS credential issuer"]
|
||||
DISP["Command dispatcher (JetStream)"]
|
||||
WORK["Messaging workers"]
|
||||
BR["Browser event broadcaster"]
|
||||
SB["Shell bridge"]
|
||||
S3["S3 presign service"]
|
||||
EF[("EF Core / SQLite")]
|
||||
end
|
||||
|
||||
subgraph Fabric
|
||||
CORE["NATS Core"]
|
||||
JSS["JetStream: COMMANDS, JOB_EVENTS"]
|
||||
end
|
||||
|
||||
UI -->|"login, CRUD, run"| REST
|
||||
UI -->|"POST /api/messaging/credential"| ISS
|
||||
BN -->|"subscribe browser session subjects (via proxy)"| CORE
|
||||
REST --> EF
|
||||
REST --> DISP
|
||||
DISP --> JSS
|
||||
WORK -->|"consume presence/inventory/output/state"| CORE
|
||||
WORK --> EF
|
||||
WORK --> BR
|
||||
BR -->|"publish browser session events"| CORE
|
||||
CORE --> BN
|
||||
SB -->|"forward shell input, relay output"| CORE
|
||||
REST --> SB
|
||||
REST --> S3
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Agent-to-component flow
|
||||
|
||||
What the agent does after it starts, and which backend component handles each
|
||||
message.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant A as "Agent"
|
||||
participant API as "Backend REST"
|
||||
participant N as "NATS / JetStream"
|
||||
participant W as "Messaging workers"
|
||||
participant DB as "SQLite"
|
||||
participant U as "Browser"
|
||||
|
||||
A->>A: "CIM fingerprint to deterministic ClientId"
|
||||
A->>A: "Generate User NKey (seed stays local)"
|
||||
A->>API: "POST /api/enrollment/bootstrap"
|
||||
API->>DB: "Consume token, bind device, audit"
|
||||
API-->>A: "Scoped NATS user JWT"
|
||||
A->>N: "WSS connect (JWT + NKey)"
|
||||
A->>N: "presence (30s), inventory (start + interval)"
|
||||
N->>W: "presence / inventory"
|
||||
W->>DB: "upsert device + inventory"
|
||||
W->>U: "authorized browser session events"
|
||||
API->>N: "durable script/file command (JetStream)"
|
||||
N->>A: "command (explicit ack after durable record)"
|
||||
A->>N: "job output / progress / state"
|
||||
N->>W: "persist + relay"
|
||||
W->>U: "live job updates"
|
||||
```
|
||||
|
||||
Full script-execution, enrollment, and remote-shell sequence diagrams are in
|
||||
[docs/sequences.md](docs/sequences.md).
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **.NET SDK 10** (`dotnet --version` gives 10.x)
|
||||
- **Node.js LTS** (20+) and npm — for the WebUI
|
||||
- **Docker + Docker Compose** — to run the stack
|
||||
- **Windows** — required to build/run the agent (CIM, ConPTY, DPAPI, Windows
|
||||
service). The backend and WebUI are cross-platform.
|
||||
- **WiX Toolset v5** (restored automatically) — for the MSI
|
||||
- **ImageMagick** — installed on demand by `scripts/Generate-Icons.ps1`
|
||||
|
||||
---
|
||||
|
||||
## Local development
|
||||
|
||||
```powershell
|
||||
# One-time setup: restores packages, installs WebUI deps, generates secrets
|
||||
./scripts/Initialize-Repository.ps1
|
||||
|
||||
# Build everything with one unified version
|
||||
./scripts/Build.ps1 -IncludeWebUI
|
||||
|
||||
# Run tests
|
||||
./scripts/Test.ps1 # unit
|
||||
./scripts/Test.ps1 -IncludeWebUI # + svelte-check
|
||||
```
|
||||
|
||||
Run the stack:
|
||||
|
||||
```powershell
|
||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d --build
|
||||
```
|
||||
|
||||
On a server, deploy straight from the repository — no clone needed. This pulls
|
||||
the published images and falls back to building only if the pull fails:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://git.example.com/owner/ExecuteR/raw/branch/main/scripts/deploy.sh | bash
|
||||
|
||||
# ...or let the stack run its own nginx edge (opt-in):
|
||||
curl -fsSL https://.../deploy.sh | bash -s -- --with-proxy --host control.example.com
|
||||
```
|
||||
|
||||
The script writes `.env` with a generated admin password, prepares the
|
||||
bind-mount tree, and generates real NATS keys by running the backend image's
|
||||
own `nats-auth` CLI, so the host needs nothing but Docker.
|
||||
|
||||
Run pieces directly for a fast inner loop:
|
||||
|
||||
```powershell
|
||||
# Backend (Development seeds a demo script; DEV_SEED=1 adds sample devices/jobs)
|
||||
$env:ASPNETCORE_ENVIRONMENT='Development'; $env:ASPNETCORE_URLS='http://127.0.0.1:19080'
|
||||
$env:INITIAL_ADMIN_USERNAME='admin'; $env:INITIAL_ADMIN_PASSWORD='DemoPass123!'
|
||||
dotnet run --project src/Backend
|
||||
|
||||
# WebUI (proxies /api and /messaging to the backend + NATS)
|
||||
npm --prefix src/WebUI run dev
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Required secrets
|
||||
|
||||
Committed: `.env.example`, `secrets/README.md`, `scripts/New-LocalSecrets.ps1`.
|
||||
Never commit generated secrets (enforced by `.gitignore`).
|
||||
|
||||
| Secret | Purpose |
|
||||
|--------|---------|
|
||||
| `INITIAL_ADMIN_PASSWORD` | First-boot local admin password |
|
||||
| `NATS_OPERATOR_SEED` | NATS operator identity |
|
||||
| `NATS_ACCOUNT_SEED` | Application account identity |
|
||||
| `NATS_ACCOUNT_SIGNING_SEED` | Backend signs user JWTs with this |
|
||||
| `OIDC_CLIENT_SECRET` | Only when OIDC is enabled |
|
||||
| `GITEA_TOKEN` | CI release/push automation |
|
||||
| `S3_SECRET_KEY` | Only when S3 file delivery is enabled |
|
||||
|
||||
Non-secret identifiers (`NATS_*_PUBLIC_KEY`, `GITEA_URL`, `GITEA_OWNER`,
|
||||
`GITEA_REPOSITORY`, `CONTAINER_REGISTRY`) may live in `.env`.
|
||||
|
||||
---
|
||||
|
||||
## Generating local secrets
|
||||
|
||||
```powershell
|
||||
./scripts/New-LocalSecrets.ps1
|
||||
```
|
||||
|
||||
This generates **real Ed25519 NATS keys** (operator, APP account, account
|
||||
signing key, SYS account/user) and the resolver preload using the backend's
|
||||
`nats-auth` CLI — the same NATS.Jwt/NATS.NKeys code the backend uses at runtime,
|
||||
so no fake seeds:
|
||||
|
||||
```powershell
|
||||
dotnet run --project src/Backend -- nats-auth init --output secrets/nats
|
||||
```
|
||||
|
||||
It writes `.env` (with a random admin password and the account signing seed)
|
||||
and `secrets/nats/resolver.conf` (mounted into the NATS container).
|
||||
|
||||
---
|
||||
|
||||
## Docker Compose
|
||||
|
||||
Services follow the stack conventions: `EXTERNAL` + `INTERNAL` bridge networks,
|
||||
container names `EXECUTER-{NATS,API,WEB}-00001`, service-name networking, and
|
||||
uncommon host ports.
|
||||
|
||||
| Service | Container | Host port | Internal |
|
||||
|---------|-----------|-----------|----------|
|
||||
| nats | `EXECUTER-NATS-00001` | `19222` (WebSocket) | 4222 TCP, 8222 monitor |
|
||||
| backend | `EXECUTER-API-00001` | `19080` | 8080 |
|
||||
| webui | `EXECUTER-WEB-00001` | `13080` | 3000 |
|
||||
|
||||
Volumes bind under `${STACK_BINDMOUNTROOT}/${STACK_NAME}/{Tier}/Data`. The NATS
|
||||
image is pinned by digest. See `.env.example` for every variable.
|
||||
|
||||
```powershell
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Reverse proxy routes
|
||||
|
||||
The stack assumes an existing external reverse proxy terminating TLS on `:443`
|
||||
and forwarding to the host ports above:
|
||||
|
||||
| Public path | Upstream |
|
||||
|-------------|----------|
|
||||
| `/` | webui `:13080` |
|
||||
| `/api/*` | backend `:19080` |
|
||||
| `/messaging/agent` | nats websocket `:19222` |
|
||||
| `/messaging/browser` | nats websocket `:19222` |
|
||||
|
||||
The proxy must preserve the WebSocket upgrade and send `X-Forwarded-For`,
|
||||
`X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Forwarded-Prefix`. The backend
|
||||
processes forwarded headers before auth and trusts them only from configured
|
||||
`TRUSTED_PROXIES` / `TRUSTED_NETWORKS`. If path-based proxying conflicts with
|
||||
your NATS WebSocket config, use dedicated hostnames behind the same `:443` edge.
|
||||
|
||||
A ready-to-adapt nginx site (nginx-ui style, with shared snippets, edge rate
|
||||
limiting, long-lived WebSocket timeouts and commented IP allow-lists) is in
|
||||
[src/Infra/nginx](src/Infra/nginx).
|
||||
|
||||
---
|
||||
|
||||
## Agent foreground mode and service lifecycle
|
||||
|
||||
The one binary supports:
|
||||
|
||||
```text
|
||||
Agent.exe foreground run interactively (console logging)
|
||||
Agent.exe install create/update the Windows service (idempotent)
|
||||
Agent.exe start start the service
|
||||
Agent.exe stop stop the service
|
||||
Agent.exe initialize install + start
|
||||
Agent.exe remove stop + remove the service
|
||||
Agent.exe status machine- and human-readable state
|
||||
Agent.exe version unified build version
|
||||
```
|
||||
|
||||
Launched by the SCM with no argument, it runs as a service (`LocalSystem`,
|
||||
Automatic Delayed Start, restart-on-failure recovery). Service manipulation uses
|
||||
the Windows service APIs (`advapi32` / `ServiceController`) — never `sc.exe`.
|
||||
|
||||
---
|
||||
|
||||
## MSI public properties
|
||||
|
||||
```text
|
||||
msiexec /i Agent.msi /qn SERVERURL=https://control.example.com BOOTSTRAPTOKEN=<token>
|
||||
```
|
||||
|
||||
| Property | Registry value |
|
||||
|----------|----------------|
|
||||
| `SERVERURL` | `ServerURL` |
|
||||
| `BOOTSTRAPTOKEN` | `BootstrapToken` (erased after enrollment) |
|
||||
| `LOGLEVEL` | `LogLevel` |
|
||||
| `ALLOWREMOTESHELL` | `AllowRemoteShell` |
|
||||
| `ALLOWSCRIPTEXECUTION` | `AllowScriptExecution` |
|
||||
|
||||
The installer never overwrites a non-blank existing value with a blank property,
|
||||
preserves configuration on upgrade, and removes runtime credentials only on a
|
||||
real uninstall (never during an upgrade).
|
||||
|
||||
---
|
||||
|
||||
## Registry paths and GPO precedence
|
||||
|
||||
```text
|
||||
Normal config: HKLM\SOFTWARE\ExecuteR
|
||||
Runtime state: HKLM\SOFTWARE\ExecuteR\Runtime
|
||||
GPO policy: HKLM\SOFTWARE\Policies\ExecuteR
|
||||
```
|
||||
|
||||
Effective configuration precedence is **GroupPolicy > normal registry >
|
||||
dev-only environment > compiled defaults** (each value carries its provenance).
|
||||
Group Policy templates live in
|
||||
[src/Installer/Policies](src/Installer/Policies) (`ExecuteR.admx` +
|
||||
`en-US/ExecuteR.adml`).
|
||||
|
||||
---
|
||||
|
||||
## Bootstrap and URL install
|
||||
|
||||
1. Sign in as admin, open **Settings**, and generate a one-time bootstrap token.
|
||||
2. Deploy the agent one of two ways.
|
||||
|
||||
MSI:
|
||||
|
||||
```text
|
||||
msiexec /i Agent.msi /qn SERVERURL=https://control.example.com BOOTSTRAPTOKEN=<token>
|
||||
```
|
||||
|
||||
URL one-liner (elevated PowerShell on the target; requires `Agent.msi` in the
|
||||
backend's `AGENT_PACKAGE_PATH`):
|
||||
|
||||
```powershell
|
||||
iwr https://control.example.com/api/enrollment/install?token=<token> -UseBasicParsing | iex
|
||||
```
|
||||
|
||||
The agent generates its NKey locally (the private seed never leaves the device),
|
||||
bootstraps over HTTPS, receives a scoped NATS JWT, erases the token, and
|
||||
connects over WSS. The device appears in the UI within seconds.
|
||||
|
||||
---
|
||||
|
||||
## Local login and OIDC
|
||||
|
||||
Local auth uses ASP.NET Core `PasswordHasher` (no compiled default password).
|
||||
The initial admin is created on first boot from `INITIAL_ADMIN_USERNAME` /
|
||||
`INITIAL_ADMIN_PASSWORD`. Sessions are HTTP-only cookies with double-submit CSRF
|
||||
protection on state-changing calls; login is rate limited.
|
||||
|
||||
Generic OIDC (any compliant provider — Authentik, Keycloak, Entra ID, Okta):
|
||||
|
||||
```text
|
||||
OIDC_ENABLED=1
|
||||
OIDC_AUTHORITY=https://idp.example.com/application/o/executer/
|
||||
OIDC_CLIENT_ID=executer
|
||||
OIDC_CLIENT_SECRET=<secret>
|
||||
OIDC_SCOPES=openid profile email
|
||||
OIDC_ROLE_CLAIM=groups
|
||||
OIDC_ADMIN_ROLE=executer-admins
|
||||
```
|
||||
|
||||
Roles: **Admin** (everything), **Operator** (view, scripts, run, remote shell,
|
||||
file delivery), **Viewer** (read-only). A matching `OIDC_ADMIN_ROLE` claim
|
||||
grants Admin; otherwise OIDC users are Operators.
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## Typed script parameters and function modules
|
||||
|
||||
Scripts can declare typed parameters whose editor input changes by type:
|
||||
string, number, boolean, array (with element type), and hashtable (with
|
||||
**per-key and per-value primitive types**). Values are bound to the script with
|
||||
`AddParameter`, so PowerShell receives real `[int]`, `[bool]`, `[string[]]`, and
|
||||
`[hashtable]` values.
|
||||
|
||||
Reusable **function modules** (managed under **Functions**) can be attached to a
|
||||
script; the backend prepends them as a prelude executed first in the same
|
||||
runspace, so individual scripts stay small and duplication is avoided.
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## Device groups and script triggers
|
||||
|
||||
Groups are either **static** (an explicit member list) or **dynamic** (rules
|
||||
evaluated against live device data).
|
||||
|
||||
Rules are one or more **condition groups**. Conditions inside a group combine
|
||||
with AND or OR, the groups themselves combine with AND or OR, groups can nest,
|
||||
and both conditions and groups have an independent **NOT**.
|
||||
|
||||
Operators: `equals`, `notEquals`, `contains`, `notContains`, `startsWith`,
|
||||
`endsWith`, `regex`, `in`, `notIn`, `>`, `>=`, `<`, `<=`, `exists`,
|
||||
`notExists`.
|
||||
|
||||
Fields come from hardware inventory, tags, hostname/identity, and live status —
|
||||
the full catalogue is served by `GET /api/groups/fields`, so the rule builder
|
||||
always matches what the server can evaluate:
|
||||
|
||||
| Category | Examples |
|
||||
|----------|----------|
|
||||
| Identity | `hostname`, `clientId`, `status`, `tags`, `agentVersion`, `domain` |
|
||||
| Hardware | `manufacturer`, `model`, `serialNumber`, `cpu.cores`, `memory.totalGb` |
|
||||
| Operating system | `os.caption`, `os.version`, `os.build`, `os.architecture` |
|
||||
| Storage | `disk.count`, `disk.totalGb`, `volume.freeGb` |
|
||||
| Network | `network.ipv4`, `network.mac`, `network.dns` |
|
||||
|
||||
Multi-valued fields (tags, IPs, MACs, DNS) match when **any** value satisfies a
|
||||
positive operator, and require **all** values for the negative ones. A missing
|
||||
field satisfies only the negative operators. Invalid or runaway regex never
|
||||
matches and never throws.
|
||||
|
||||
**Preview** evaluates candidate rules against live devices before you save.
|
||||
|
||||

|
||||
|
||||
**Script triggers** run a script automatically on a device lifecycle event,
|
||||
targeted at a group (or all devices):
|
||||
|
||||
| Trigger | Fires when |
|
||||
|---------|-----------|
|
||||
| `onRegistration` | A device completes enrollment |
|
||||
| `onAgentReady` | The agent is connected *and* its durable command consumer is bound — genuinely ready for jobs |
|
||||
|
||||
Triggers default to **once per device** (recorded durably), and triggered runs
|
||||
use the normal job pipeline, so they carry the script's function-module prelude
|
||||
and typed parameters and appear alongside manual runs.
|
||||
|
||||
---
|
||||
|
||||
## Database providers
|
||||
|
||||
SQLite is the default and needs no configuration. Postgres and SQL Server are
|
||||
selected with environment variables:
|
||||
|
||||
```text
|
||||
DATABASE_PROVIDER=sqlite # or: postgres | sqlserver
|
||||
DATABASE_PATH=/data/app.db # sqlite only
|
||||
|
||||
DATABASE_PROVIDER=postgres
|
||||
DATABASE_CONNECTION_STRING=Host=db;Port=5432;Database=executer;Username=executer;Password=...
|
||||
|
||||
DATABASE_PROVIDER=sqlserver
|
||||
DATABASE_CONNECTION_STRING=Server=db;Database=executer;User Id=sa;Password=...;TrustServerCertificate=True
|
||||
```
|
||||
|
||||
Each provider carries its own EF Core migration set, applied automatically at
|
||||
startup. SQLite stores timestamps as UTC ticks (it cannot order
|
||||
`DateTimeOffset` natively); Postgres and SQL Server use native timestamp
|
||||
columns.
|
||||
|
||||
Adding a migration touches all three:
|
||||
|
||||
```powershell
|
||||
dotnet ef migrations add <Name> --project src/Backend --context SqliteAppDbContext --output-dir Data/Migrations/Sqlite
|
||||
dotnet ef migrations add <Name> --project src/Backend --context PostgresAppDbContext --output-dir Data/Migrations/Postgres
|
||||
dotnet ef migrations add <Name> --project src/Backend --context SqlServerAppDbContext --output-dir Data/Migrations/SqlServer
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Logging
|
||||
|
||||
All services share one Serilog pipeline (`Shared.Infrastructure/Logging`):
|
||||
console plus a **daily rolling file** with a size cap and retention.
|
||||
|
||||
Rotation defaults are set centrally per role in `LogDefaults`, because
|
||||
endpoints are numerous and disk-constrained while the server is neither:
|
||||
|
||||
| Role | Roll at | Keep | Ceiling |
|
||||
|------|---------|------|---------|
|
||||
| Agent | 5 MB | 3 files | ~15 MB |
|
||||
| Backend | 10 MB | 7 files | ~70 MB |
|
||||
|
||||
```text
|
||||
LOG_LEVEL=Information # Verbose|Debug|Information|Warning|Error|Fatal
|
||||
LOG_JSON=0 # 1 = compact JSON (for log shippers)
|
||||
LOG_DIRECTORY=/data/logs # empty disables file logging
|
||||
LOG_RETAIN_FILES=7 # server default; agent default is 3
|
||||
LOG_MAX_BYTES=10485760 # server default 10 MB; agent default 5 MB
|
||||
```
|
||||
|
||||
Files also roll daily, so the size cap is an upper bound rather than the usual
|
||||
trigger.
|
||||
|
||||
Framework noise is pinned to Warning regardless of `LOG_LEVEL`, and health
|
||||
probes log at Verbose so they do not flood the file. Requests are logged once
|
||||
each with the effective (proxy-aware) client IP and the authenticated user.
|
||||
Correlation fields (`CorrelationId`, `ClientId`, `JobId`, `ShellSessionId`,
|
||||
`BrowserSessionId`, `RemoteIp`) flow through as structured properties.
|
||||
|
||||
The agent takes its level from its own configuration precedence
|
||||
(GPO > registry > default) and writes to `%ProgramData%\ExecuteR\logs`. A bad
|
||||
log path degrades to console logging rather than failing startup.
|
||||
|
||||
Secrets are never logged: tokens, passwords, client secrets, NKey seeds, JWTs,
|
||||
cookies and authorization headers.
|
||||
|
||||
---
|
||||
|
||||
## Device lifecycle: reconnect or orphan
|
||||
|
||||
A device silent for longer than the orphan window is **orphaned**. The window
|
||||
is centrally defaulted to **30 days** (`ProtocolDefaults.DefaultOrphanAfterDays`)
|
||||
and controlled with one setting:
|
||||
|
||||
```text
|
||||
DEVICE_ORPHAN_AFTER_DAYS=30 # default when unset
|
||||
DEVICE_ORPHAN_AFTER_DAYS=0 # disable orphaning entirely
|
||||
```
|
||||
|
||||
With orphaning **disabled**, a device that stops checking in just ages through
|
||||
**Online → Stale → Offline**, keeps its credentials, and reconnects entirely on
|
||||
its own whenever it comes back — nothing to do.
|
||||
|
||||
An orphaned device is refused credential refresh and job dispatch, and is *not*
|
||||
resurrected merely by reappearing — presence from it is logged and ignored.
|
||||
Recovery is deliberate:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
O["Silent past the window"] --> M["Backend marks device orphaned"]
|
||||
M --> R["Refuses credential refresh and job dispatch"]
|
||||
R --> T["Admin pushes a new bootstrap token (GPO, MSI, URL install)"]
|
||||
T --> E["Agent sees the token and re-enrolls"]
|
||||
E --> B["Same device record, orphan flag cleared, back in service"]
|
||||
```
|
||||
|
||||
The agent side needs no special mode: a bootstrap token is erased after every
|
||||
successful enrollment, so the presence of one is by definition a deliberate
|
||||
instruction. When an already-enrolled agent finds a token, it discards its
|
||||
stored credentials and re-enrolls. Enrollment is idempotent by client id, so
|
||||
the device keeps its history, groups and tags.
|
||||
|
||||
---
|
||||
|
||||
## S3 file delivery
|
||||
|
||||
Enable an S3-compatible store (`S3_ENABLED=1`; AWS S3, MinIO, Backblaze B2) and
|
||||
push files from **Device → Actions → Send file**. Credentials stay on the
|
||||
server — the endpoint only ever sees a short-lived URL.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as "Operator"
|
||||
participant API as "Backend"
|
||||
participant S3 as "S3 store"
|
||||
participant N as "NATS / JetStream"
|
||||
participant A as "Agent"
|
||||
|
||||
U->>API: "POST /api/devices/{id}/files (objectKey, destination, sha256?)"
|
||||
API->>S3: "presign GET (expires in S3_PRESIGN_EXPIRY_SECONDS)"
|
||||
S3-->>API: "signed URL"
|
||||
API->>N: "durable file command (URL, destination, hash)"
|
||||
N->>A: "command.file"
|
||||
A->>A: "already have it? (hash, then ETag)"
|
||||
A->>S3: "GET signed URL (If-None-Match when cached)"
|
||||
S3-->>A: "200 body, or 304 Not Modified"
|
||||
A->>N: "progress, then Succeeded"
|
||||
N->>API: "persist, relay to browser"
|
||||
```
|
||||
|
||||
**Downloads are skipped when nothing changed**, in two escalating steps:
|
||||
|
||||
1. **Hash match, no request at all.** If the destination already exists and the
|
||||
caller supplied `sha256`, the agent hashes the local file; if it matches,
|
||||
the job succeeds immediately with "Already up to date".
|
||||
2. **Let S3 decide.** Otherwise the agent sends the ETag it stored last time as
|
||||
`If-None-Match`. An unchanged object returns **304 Not Modified** and costs
|
||||
no transfer; a changed object returns the new body.
|
||||
|
||||
The agent keeps a small local cache (destination path → ETag, SHA-256, size) in
|
||||
its SQLite store, so this survives restarts. Every completed download is hashed
|
||||
regardless — verifying the transfer when an expected hash was given, and
|
||||
seeding the cache when it was not. Writes are atomic (temp file, then move), so
|
||||
a failed or interrupted download never leaves a half-written file in place.
|
||||
|
||||
Configuration:
|
||||
|
||||
```text
|
||||
S3_ENABLED=1
|
||||
S3_ENDPOINT=https://s3.example.com # blank for AWS
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=executer-payloads
|
||||
S3_ACCESS_KEY=...
|
||||
S3_SECRET_KEY=...
|
||||
S3_FORCE_PATH_STYLE=1 # 1 for MinIO and most self-hosted
|
||||
S3_PRESIGN_EXPIRY_SECONDS=900
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CI/CD and GITEA_* variables
|
||||
|
||||
Images are published to **Gitea's own container registry**, which lives on the
|
||||
Gitea host itself — `<gitea-host>/<owner>/executer-backend` and
|
||||
`…/executer-webui`. No registry configuration is required: Gitea Actions
|
||||
injects a `GITEA_TOKEN` per run that the registry accepts as the triggering
|
||||
actor's password, and the host is derived from the instance URL.
|
||||
|
||||
Seed the remaining repository secrets and variables once (idempotent; never
|
||||
prints values):
|
||||
|
||||
```powershell
|
||||
$env:GITEA_URL='https://git.example.com'; $env:GITEA_API_TOKEN='<token>'
|
||||
./scripts/Initialize-GiteaSecrets.ps1
|
||||
```
|
||||
|
||||
It derives owner/repo from the git remote, reads values from `.env` and
|
||||
`secrets/nats`, and writes the NATS signing seed, admin password and OIDC/S3
|
||||
secrets, plus `REGISTRY` and `SERVER_URL` variables. The token needs
|
||||
repository admin scope.
|
||||
|
||||
To publish somewhere other than this Gitea instance, add `-ExternalRegistry`
|
||||
(with `-RegistryUsername`/`-RegistryPassword`); CI then uses those credentials
|
||||
instead of the built-in token.
|
||||
|
||||
Two Gitea API quirks worth knowing if you script against it yourself: the
|
||||
secrets endpoint takes `{"data": …}` while variables take `{"value": …}`, and
|
||||
secret names may not begin with `GITEA_` or `GITHUB_`.
|
||||
|
||||
Pulling images on a deployment host only needs credentials when the repository
|
||||
is private — set `REGISTRY_USERNAME` and `REGISTRY_TOKEN` in `.env` and
|
||||
`deploy.sh` logs in before pulling.
|
||||
|
||||
Gitea Actions workflows live in `.gitea/workflows`:
|
||||
|
||||
- **Pull request to `main`** — restore, build, unit + integration tests, Svelte
|
||||
check. No image push, no release.
|
||||
- **Push to `dev`** — build + test, agent binary + MSI, backend/webui images
|
||||
tagged `dev` and `<version>-dev`.
|
||||
- **Push to `main`** — build + test, agent + MSI, images tagged `<version>` and
|
||||
`latest`, and a Gitea release with the agent ZIP, MSI and checksums.
|
||||
|
||||
Scripts discover context from optional environment variables and fall back
|
||||
gracefully when run locally:
|
||||
|
||||
```text
|
||||
GITEA_URL GITEA_TOKEN GITEA_OWNER GITEA_REPOSITORY GITEA_SHA GITEA_REF
|
||||
GITEA_REF_NAME GITEA_RUN_NUMBER GITEA_ACTOR GITEA_CONTAINER_REGISTRY
|
||||
GITEA_CONTAINER_REGISTRY_USERNAME GITEA_CONTAINER_REGISTRY_PASSWORD
|
||||
```
|
||||
|
||||
Token values are never printed. `dev` is not merged into `main` automatically.
|
||||
|
||||
---
|
||||
|
||||
## Versioning
|
||||
|
||||
All artifacts share one unified version, `yyyy.MM.dd.HHmm` (UTC), computed once
|
||||
per build (`scripts/Get-UnifiedVersion.ps1`) and embedded into the agent, the
|
||||
backend assembly, Docker image labels/tags, the MSI (via a deterministic
|
||||
MSI-compatible numeric transform, with the full version retained in display
|
||||
metadata), and the frontend build metadata.
|
||||
|
||||
---
|
||||
|
||||
## MVP demo sequence
|
||||
|
||||
1. `docker compose up -d` — backend, NATS and WebUI become healthy.
|
||||
2. Sign in locally as the initial admin.
|
||||
3. Generate a one-time bootstrap token (Settings).
|
||||
4. Install the agent (`SERVERURL`, `BOOTSTRAPTOKEN`) via MSI or the URL one-liner.
|
||||
5. The device appears within seconds; presence keeps status live without refresh.
|
||||
6. Inventory populates the device detail tabs.
|
||||
7. Author/save a PowerShell script; select the device; run.
|
||||
8. Job state goes Running, output and a progress bar advance live; job Succeeds.
|
||||
9. Open the remote shell; run `hostname`, `whoami`, `Get-Process | Select -First 5`.
|
||||
10. Resize and disconnect cleanly; restart the service — it reconnects without a
|
||||
token; rerun and verify no duplicate execution from redelivery.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Check |
|
||||
|---------|-------|
|
||||
| Device never appears | Agent log: bootstrap HTTP status; token not expired/consumed; `ServerURL` scheme is http/https (agent derives ws/wss) |
|
||||
| `/api/ready` returns 503 | Database reachable, NATS connected, `NATS_ACCOUNT_SIGNING_SEED` loaded |
|
||||
| Browser shows "Offline" | `POST /api/messaging/credential` succeeds; proxy preserves the WebSocket upgrade on `/messaging/browser` |
|
||||
| Agent will not connect to NATS | `resolver.conf` account matches `NATS_ACCOUNT_*`; WSS path reachable through the proxy |
|
||||
| Remote shell disabled | `AllowRemoteShell=1` (policy or registry) and the agent is online |
|
||||
| Script "disabled by policy" | `AllowScriptExecution` not set to 0 by GPO/registry |
|
||||
| CSRF 403 | The SPA sends `X-CSRF-Token`; ensure the `csrf_token` cookie is present |
|
||||
| File delivery 503 | `S3_ENABLED=1` and S3 credentials/bucket configured |
|
||||
| Job creation returns 409 | Device is orphaned — push a new bootstrap token so the agent re-enrolls |
|
||||
| Download "skipped" unexpectedly | Local file already matches the supplied `sha256`, or S3 returned 304 for the stored ETag. Change the object (new ETag) or pass the new hash |
|
||||
| `docker compose pull` fails | Set `REGISTRY` in `.env` and run `scripts/Initialize-GiteaSecrets.ps1` so CI has published images; `deploy.sh` falls back to building from source |
|
||||
|
||||
---
|
||||
|
||||
## Screenshots
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
|  **Dashboard** |  **Devices** |
|
||||
|  **Device overview, tags and groups** |  **Hardware inventory** |
|
||||
|  **Network inventory** |  **Device actions and file delivery** |
|
||||
|  **Groups** |  **Static group membership** |
|
||||
|  **Monaco PowerShell editor** |  **Typed parameters** |
|
||||
|  **Jobs and stored output** |  **Function modules** |
|
||||
|  **Bootstrap token and install command** |  **Light theme** |
|
||||
|
||||
---
|
||||
|
||||
Built to prove one idea cleanly: secure HTTPS enrollment, scoped NATS over
|
||||
WebSocket through one proxy edge, durable work, in-process PowerShell, and a
|
||||
secured terminal — with a browser that updates in real time over NATS, no
|
||||
SignalR or SSE.
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# assets/
|
||||
|
||||
`icon-source.png` is the canonical square icon source (512×512 or larger).
|
||||
|
||||
`scripts/Generate-Icons.ps1` converts it to a multi-resolution
|
||||
`artifacts/icons/app.ico` (256/128/64/48/32/16) using ImageMagick and the
|
||||
build embeds it into the Agent executable via `ApplicationIcon`. The
|
||||
script installs ImageMagick silently (winget) when missing; if it is
|
||||
already installed nothing is reinstalled — generation is idempotent.
|
||||
|
||||
Generated `.ico` files are build artifacts and are not committed.
|
||||
|
After Width: | Height: | Size: 20 KiB |
@@ -0,0 +1,15 @@
|
||||
# Development overrides:
|
||||
# docker compose -f docker-compose.yml -f docker-compose.dev.yml up
|
||||
#
|
||||
# Exposes internal NATS TCP + monitoring on loopback for local tooling and
|
||||
# integration tests, and runs the backend in Development mode.
|
||||
services:
|
||||
nats:
|
||||
ports:
|
||||
- '127.0.0.1:14222:4222'
|
||||
- '127.0.0.1:18222:8222'
|
||||
|
||||
backend:
|
||||
environment:
|
||||
ASPNETCORE_ENVIRONMENT: 'Development'
|
||||
LOG_JSON: '0'
|
||||
@@ -0,0 +1,51 @@
|
||||
# Optional in-stack reverse proxy.
|
||||
#
|
||||
# docker compose -f docker-compose.yml -f docker-compose.proxy.yml up -d
|
||||
# ./scripts/deploy.sh --with-proxy
|
||||
#
|
||||
# NOT included by default: most deployments already have an edge proxy (NPM,
|
||||
# Traefik, Caddy, an existing nginx). Use this only when you want the stack to
|
||||
# own its own TLS edge.
|
||||
#
|
||||
# Provide certificates at:
|
||||
# ${STACK_BINDMOUNTROOT}/${STACK_NAME}/Proxy/Certs/fullchain.pem
|
||||
# ${STACK_BINDMOUNTROOT}/${STACK_NAME}/Proxy/Certs/private.key
|
||||
# and a site config at:
|
||||
# ${STACK_BINDMOUNTROOT}/${STACK_NAME}/Proxy/Config/executer.conf
|
||||
# (deploy.sh writes one derived from src/Infra/nginx/executer.conf).
|
||||
|
||||
services:
|
||||
proxy:
|
||||
image: '${NGINX_IMAGE:-nginx}:${NGINX_VERSION:-1.29-alpine}'
|
||||
container_name: EXECUTER-PROXY-00001
|
||||
restart: unless-stopped
|
||||
stop_signal: SIGQUIT
|
||||
stop_grace_period: 30s
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
webui:
|
||||
condition: service_started
|
||||
logging:
|
||||
driver: 'local'
|
||||
networks:
|
||||
EXTERNAL:
|
||||
INTERNAL:
|
||||
ports:
|
||||
- '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${PROXY_HTTP_PORT:-18080}:80'
|
||||
- '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${PROXY_HTTPS_PORT:-18443}:443'
|
||||
volumes:
|
||||
- /etc/timezone:/etc/timezone:ro
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
- "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/Proxy/Config:/etc/nginx/conf.d:ro"
|
||||
- "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/Proxy/Certs:/etc/nginx/ssl:ro"
|
||||
- "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/Proxy/Logs:/var/log/nginx:rw"
|
||||
- "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/Proxy/Acme:/var/www/acme:rw"
|
||||
healthcheck:
|
||||
test: ["CMD", "nginx", "-t"]
|
||||
start_period: 15s
|
||||
interval: 30s
|
||||
retries: 3
|
||||
timeout: 5s
|
||||
labels:
|
||||
com.centurylinklabs.watchtower.enable: '${PROXY_ENABLEAUTOMATICUPDATES:-false}'
|
||||
@@ -0,0 +1,185 @@
|
||||
#=============================================================================
|
||||
# ExecuteR - Windows endpoint management control plane
|
||||
# Agent + NATS-over-WebSocket + ASP.NET Core backend + SvelteKit web UI
|
||||
#=============================================================================
|
||||
#
|
||||
# CREDENTIALS:
|
||||
# Initial admin: INITIAL_ADMIN_USERNAME / INITIAL_ADMIN_PASSWORD (.env)
|
||||
# NATS decentralized auth: seeds generated by scripts/New-LocalSecrets.ps1
|
||||
#
|
||||
# PRODUCTION SETUP:
|
||||
# 1. ./scripts/New-LocalSecrets.ps1 # generate .env + NATS keys
|
||||
# 2. docker compose up -d --build # start nats, backend, webui
|
||||
# 3. Point the external reverse proxy at the published host ports below
|
||||
#
|
||||
# ENDPOINTS (host-published; front with your external reverse proxy):
|
||||
# - WebUI: http://<host>:${WEBUI_PORT} -> /
|
||||
# - Backend API: http://<host>:${BACKEND_PORT} -> /api/*
|
||||
# - NATS WebSocket: ws://<host>:${NATS_WS_PORT} -> /messaging/agent,/messaging/browser
|
||||
#
|
||||
#=============================================================================
|
||||
|
||||
name: '${STACK_NAME:-stk-executer-00001}'
|
||||
|
||||
networks:
|
||||
EXTERNAL:
|
||||
name: EXECUTER-EXTERNAL
|
||||
driver: bridge
|
||||
internal: false
|
||||
attachable: true
|
||||
INTERNAL:
|
||||
name: EXECUTER-INTERNAL
|
||||
driver: bridge
|
||||
internal: true
|
||||
attachable: true
|
||||
|
||||
services:
|
||||
|
||||
nats:
|
||||
image: '${NATS_IMAGE:-nats}:${NATS_VERSION:-2.12-alpine@sha256:7cef1bd3fed6034e95cf6e6bc9c28c5afa6dc58e9fb778dd7924a1ac62569f2d}'
|
||||
container_name: EXECUTER-NATS-00001
|
||||
command: ["-c", "/etc/nats/nats.conf"]
|
||||
restart: unless-stopped
|
||||
stop_signal: SIGTERM
|
||||
stop_grace_period: 30s
|
||||
logging:
|
||||
driver: 'local'
|
||||
networks:
|
||||
INTERNAL:
|
||||
EXTERNAL:
|
||||
expose:
|
||||
- '4222'
|
||||
ports:
|
||||
# WebSocket listener — the external reverse proxy maps /messaging/* here.
|
||||
- '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${NATS_WS_PORT:-19222}:9222'
|
||||
volumes:
|
||||
- /etc/timezone:/etc/timezone:ro
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
- ./src/Infra/nats/nats.conf:/etc/nats/nats.conf:ro
|
||||
- ./secrets/nats/resolver.conf:/etc/nats/resolver.conf:ro
|
||||
- "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/NATS/JetStream:/data/jetstream:rw"
|
||||
- "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/NATS/Resolver:/data/resolver:rw"
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "-", "http://127.0.0.1:8222/healthz"]
|
||||
start_period: 20s
|
||||
interval: 10s
|
||||
retries: 5
|
||||
timeout: 5s
|
||||
labels:
|
||||
com.centurylinklabs.watchtower.enable: '${NATS_ENABLEAUTOMATICUPDATES:-false}'
|
||||
|
||||
backend:
|
||||
# Published image by default; `build` is the fallback used when the image
|
||||
# is not present locally and cannot be pulled (pull_policy: missing).
|
||||
# scripts/deploy.sh pulls first and builds only if the pull fails.
|
||||
image: '${REGISTRY:-git.example.com/owner}/${BACKEND_IMAGE:-executer-backend}:${BACKEND_VERSION:-${UNIFIED_VERSION:-latest}}'
|
||||
pull_policy: '${IMAGE_PULL_POLICY:-missing}'
|
||||
container_name: EXECUTER-API-00001
|
||||
build:
|
||||
context: .
|
||||
dockerfile: src/Infra/backend/Dockerfile
|
||||
args:
|
||||
UNIFIED_VERSION: ${UNIFIED_VERSION:-0.0.0.0}
|
||||
restart: unless-stopped
|
||||
stop_signal: SIGTERM
|
||||
stop_grace_period: 30s
|
||||
depends_on:
|
||||
nats:
|
||||
condition: service_healthy
|
||||
logging:
|
||||
driver: 'local'
|
||||
networks:
|
||||
INTERNAL:
|
||||
EXTERNAL:
|
||||
expose:
|
||||
- '8080'
|
||||
ports:
|
||||
- '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${BACKEND_PORT:-19080}:8080'
|
||||
environment:
|
||||
ASPNETCORE_URLS: 'http://0.0.0.0:8080'
|
||||
DATABASE_PROVIDER: '${DATABASE_PROVIDER:-sqlite}'
|
||||
DATABASE_PATH: '/data/app.db'
|
||||
DATABASE_CONNECTION_STRING: '${DATABASE_CONNECTION_STRING:-}'
|
||||
NATS_URL: 'nats://nats:4222'
|
||||
LOG_LEVEL: '${LOG_LEVEL:-Information}'
|
||||
LOG_JSON: '${LOG_JSON:-0}'
|
||||
LOG_DIRECTORY: '${LOG_DIRECTORY:-/data/logs}'
|
||||
LOG_RETAIN_FILES: '${LOG_RETAIN_FILES:-7}'
|
||||
LOG_MAX_BYTES: '${LOG_MAX_BYTES:-10485760}'
|
||||
DEVICE_ORPHAN_AFTER_DAYS: '${DEVICE_ORPHAN_AFTER_DAYS:-30}'
|
||||
TRUST_PROXY: '${TRUST_PROXY:-1}'
|
||||
TRUSTED_PROXIES: '${TRUSTED_PROXIES:-}'
|
||||
TRUSTED_NETWORKS: '${TRUSTED_NETWORKS:-}'
|
||||
TRUSTED_HOSTS: '${TRUSTED_HOSTS:-}'
|
||||
FORWARD_LIMIT: '${FORWARD_LIMIT:-1}'
|
||||
PUBLIC_SERVER_URL: '${PUBLIC_SERVER_URL:-}'
|
||||
INITIAL_ADMIN_USERNAME: '${INITIAL_ADMIN_USERNAME:-}'
|
||||
INITIAL_ADMIN_PASSWORD: '${INITIAL_ADMIN_PASSWORD:-}'
|
||||
OIDC_ENABLED: '${OIDC_ENABLED:-0}'
|
||||
OIDC_AUTHORITY: '${OIDC_AUTHORITY:-}'
|
||||
OIDC_CLIENT_ID: '${OIDC_CLIENT_ID:-}'
|
||||
OIDC_CLIENT_SECRET: '${OIDC_CLIENT_SECRET:-}'
|
||||
OIDC_CALLBACK_PATH: '${OIDC_CALLBACK_PATH:-/signin-oidc}'
|
||||
OIDC_SCOPES: '${OIDC_SCOPES:-openid profile email}'
|
||||
OIDC_NAME_CLAIM: '${OIDC_NAME_CLAIM:-}'
|
||||
OIDC_ROLE_CLAIM: '${OIDC_ROLE_CLAIM:-}'
|
||||
OIDC_ADMIN_ROLE: '${OIDC_ADMIN_ROLE:-}'
|
||||
NATS_ACCOUNT_SIGNING_SEED: '${NATS_ACCOUNT_SIGNING_SEED:-}'
|
||||
NATS_ACCOUNT_PUBLIC_KEY: '${NATS_ACCOUNT_PUBLIC_KEY:-}'
|
||||
AGENT_PACKAGE_PATH: '${AGENT_PACKAGE_PATH:-/data/agent}'
|
||||
S3_ENABLED: '${S3_ENABLED:-0}'
|
||||
S3_ENDPOINT: '${S3_ENDPOINT:-}'
|
||||
S3_REGION: '${S3_REGION:-us-east-1}'
|
||||
S3_BUCKET: '${S3_BUCKET:-}'
|
||||
S3_ACCESS_KEY: '${S3_ACCESS_KEY:-}'
|
||||
S3_SECRET_KEY: '${S3_SECRET_KEY:-}'
|
||||
S3_FORCE_PATH_STYLE: '${S3_FORCE_PATH_STYLE:-1}'
|
||||
S3_PRESIGN_EXPIRY_SECONDS: '${S3_PRESIGN_EXPIRY_SECONDS:-900}'
|
||||
volumes:
|
||||
- /etc/timezone:/etc/timezone:ro
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
- "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/API/Data:/data:rw"
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-fsS", "http://127.0.0.1:8080/api/health"]
|
||||
start_period: 30s
|
||||
interval: 10s
|
||||
retries: 5
|
||||
timeout: 5s
|
||||
labels:
|
||||
com.centurylinklabs.watchtower.enable: '${BACKEND_ENABLEAUTOMATICUPDATES:-false}'
|
||||
|
||||
webui:
|
||||
image: '${REGISTRY:-git.example.com/owner}/${WEBUI_IMAGE:-executer-webui}:${WEBUI_VERSION:-${UNIFIED_VERSION:-latest}}'
|
||||
pull_policy: '${IMAGE_PULL_POLICY:-missing}'
|
||||
container_name: EXECUTER-WEB-00001
|
||||
build:
|
||||
context: .
|
||||
dockerfile: src/Infra/webui/Dockerfile
|
||||
args:
|
||||
UNIFIED_VERSION: ${UNIFIED_VERSION:-0.0.0.0}
|
||||
restart: unless-stopped
|
||||
stop_signal: SIGTERM
|
||||
stop_grace_period: 30s
|
||||
logging:
|
||||
driver: 'local'
|
||||
networks:
|
||||
EXTERNAL:
|
||||
expose:
|
||||
- '3000'
|
||||
ports:
|
||||
- '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${WEBUI_PORT:-13080}:3000'
|
||||
environment:
|
||||
PORT: '3000'
|
||||
NODE_ENV: 'production'
|
||||
ORIGIN: '${PUBLIC_SERVER_URL:-http://localhost:13080}'
|
||||
volumes:
|
||||
- /etc/timezone:/etc/timezone:ro
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3000/').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
|
||||
start_period: 20s
|
||||
interval: 10s
|
||||
retries: 5
|
||||
timeout: 5s
|
||||
labels:
|
||||
com.centurylinklabs.watchtower.enable: '${WEBUI_ENABLEAUTOMATICUPDATES:-false}'
|
||||
|
After Width: | Height: | Size: 112 KiB |
|
After Width: | Height: | Size: 111 KiB |
|
After Width: | Height: | Size: 155 KiB |
|
After Width: | Height: | Size: 204 KiB |
|
After Width: | Height: | Size: 163 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 134 KiB |
|
After Width: | Height: | Size: 126 KiB |
|
After Width: | Height: | Size: 206 KiB |
|
After Width: | Height: | Size: 211 KiB |
|
After Width: | Height: | Size: 166 KiB |
|
After Width: | Height: | Size: 153 KiB |
|
After Width: | Height: | Size: 148 KiB |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 150 KiB |
|
After Width: | Height: | Size: 175 KiB |
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 200 KiB |
|
After Width: | Height: | Size: 115 KiB |
@@ -0,0 +1,81 @@
|
||||
# Sequence diagrams
|
||||
|
||||
## Script execution
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as "Browser"
|
||||
participant API as "Backend"
|
||||
participant N as "NATS / JetStream"
|
||||
participant A as "Agent"
|
||||
participant PS as "System.Management.Automation"
|
||||
|
||||
U->>API: "POST /api/jobs"
|
||||
API->>N: "durable script command"
|
||||
N->>A: "agent command.script"
|
||||
A->>A: "record JobId idempotently"
|
||||
A-->>N: "Ack command"
|
||||
A->>PS: "Runspace + prelude + AddScript + AddParameter"
|
||||
PS-->>A: "Output / Progress / Errors"
|
||||
A->>N: "job output / progress"
|
||||
N->>API: "consume job events"
|
||||
API->>N: "browser session job event"
|
||||
N-->>U: "live WebSocket event"
|
||||
PS-->>A: "completion"
|
||||
A->>N: "job state = Succeeded/Failed"
|
||||
N->>API: "persist state"
|
||||
API->>N: "browser session update"
|
||||
N-->>U: "final state"
|
||||
```
|
||||
|
||||
## Enrollment
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant A as "Agent"
|
||||
participant API as "Backend"
|
||||
participant N as "NATS"
|
||||
|
||||
A->>A: "CIM stable hardware fingerprint"
|
||||
A->>A: "SHA-256 deterministic ClientId"
|
||||
A->>A: "Generate User NKey pair"
|
||||
A->>API: "HTTPS bootstrap: token + ClientId + public NKey"
|
||||
API->>API: "Validate/consume bootstrap token"
|
||||
API->>API: "Issue scoped NATS user JWT"
|
||||
API-->>A: "EnrollmentId + User JWT"
|
||||
A->>A: "DPAPI protect private seed + JWT"
|
||||
A->>A: "Clear BootstrapToken registry value"
|
||||
A->>N: "WSS connect using JWT + NKey proof"
|
||||
N-->>A: "authenticated"
|
||||
A->>N: "presence + inventory"
|
||||
```
|
||||
|
||||
## Remote shell
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as "Browser / xterm"
|
||||
participant API as "Backend"
|
||||
participant N as "NATS"
|
||||
participant A as "Agent"
|
||||
participant C as "ConPTY"
|
||||
|
||||
U->>API: "create shell for ClientId"
|
||||
API->>API: "authorize"
|
||||
API->>N: "privileged shell.open command"
|
||||
N->>A: "shell.open"
|
||||
A->>C: "create pseudoconsole + shell"
|
||||
A->>N: "shell state = open"
|
||||
API->>N: "browser session state/output bridge"
|
||||
N-->>U: "shell open"
|
||||
U->>N: "browser session shell input"
|
||||
N->>API: "input"
|
||||
API->>N: "authorized agent shell.input"
|
||||
N->>A: "input"
|
||||
A->>C: "write input"
|
||||
C-->>A: "terminal output"
|
||||
A->>N: "shell output"
|
||||
N->>API: "output"
|
||||
API->>N: "browser shell output"
|
||||
N-->>U: "live terminal output"
|
||||
```
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": 1,
|
||||
"isRoot": true,
|
||||
"tools": {
|
||||
"dotnet-ef": {
|
||||
"version": "10.0.10",
|
||||
"commands": [
|
||||
"dotnet-ef"
|
||||
],
|
||||
"rollForward": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sdk": {
|
||||
"version": "10.0.100",
|
||||
"rollForward": "latestFeature"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Builds the full solution (and optionally the WebUI) with one unified version.
|
||||
|
||||
.EXAMPLE
|
||||
./scripts/Build.ps1
|
||||
./scripts/Build.ps1 -Configuration Release -IncludeWebUI
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[ValidateSet('Debug', 'Release')]
|
||||
[string]$Configuration = 'Release',
|
||||
[string]$Version,
|
||||
[switch]$IncludeWebUI
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$Version = & (Join-Path $PSScriptRoot 'Get-UnifiedVersion.ps1') -Version $Version
|
||||
|
||||
Write-Host "Unified version: $Version"
|
||||
|
||||
dotnet build (Join-Path $repoRoot 'ExecuteR.slnx') -c $Configuration --nologo "-p:UnifiedVersion=$Version"
|
||||
if ($LASTEXITCODE -ne 0) { throw "dotnet build failed ($LASTEXITCODE)." }
|
||||
|
||||
if ($IncludeWebUI) {
|
||||
Push-Location (Join-Path $repoRoot 'src/WebUI')
|
||||
try {
|
||||
if (-not (Test-Path 'node_modules')) {
|
||||
npm ci
|
||||
if ($LASTEXITCODE -ne 0) { throw "npm ci failed ($LASTEXITCODE)." }
|
||||
}
|
||||
$env:PUBLIC_BUILD_VERSION = $Version
|
||||
npm run build
|
||||
if ($LASTEXITCODE -ne 0) { throw "WebUI build failed ($LASTEXITCODE)." }
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Build complete ($Version)."
|
||||
@@ -0,0 +1,44 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Generates artifacts/icons/app.ico from assets/icon-source.png using ImageMagick.
|
||||
Installs ImageMagick silently (winget) only when it is missing. Idempotent:
|
||||
skips generation when the .ico is newer than the source.
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$Force
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$source = Join-Path $repoRoot 'assets/icon-source.png'
|
||||
$outputDir = Join-Path $repoRoot 'artifacts/icons'
|
||||
$output = Join-Path $outputDir 'app.ico'
|
||||
|
||||
if (-not (Test-Path $source)) {
|
||||
throw "Icon source not found: $source"
|
||||
}
|
||||
|
||||
if (-not $Force -and (Test-Path $output) -and
|
||||
(Get-Item $output).LastWriteTimeUtc -ge (Get-Item $source).LastWriteTimeUtc) {
|
||||
Write-Host "Icon already up to date: $output"
|
||||
return
|
||||
}
|
||||
|
||||
$magick = Get-Command magick -ErrorAction SilentlyContinue
|
||||
if (-not $magick) {
|
||||
Write-Host 'ImageMagick not found — installing via winget...'
|
||||
winget install ImageMagick.ImageMagick --silent --accept-package-agreements --accept-source-agreements --disable-interactivity
|
||||
if ($LASTEXITCODE -ne 0) { throw "winget install of ImageMagick failed ($LASTEXITCODE)." }
|
||||
|
||||
# Refresh PATH for this session.
|
||||
$env:Path = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' +
|
||||
[Environment]::GetEnvironmentVariable('Path', 'User')
|
||||
$magick = Get-Command magick -ErrorAction Stop
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force $outputDir | Out-Null
|
||||
& $magick.Source $source -define icon:auto-resize=256,128,64,48,32,16 $output
|
||||
if ($LASTEXITCODE -ne 0) { throw "ImageMagick icon generation failed ($LASTEXITCODE)." }
|
||||
|
||||
Write-Host "Generated $output"
|
||||
@@ -0,0 +1,21 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Computes the unified build version (yyyy.MM.dd.HHmm, UTC) exactly once per build.
|
||||
Honors an explicit -Version argument or the UNIFIED_VERSION environment variable
|
||||
(as set by CI) so every artifact in one pipeline shares the same version.
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Version
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
if (-not $Version) { $Version = $env:UNIFIED_VERSION }
|
||||
if (-not $Version) { $Version = [DateTime]::UtcNow.ToString('yyyy.MM.dd.HHmm') }
|
||||
|
||||
if ($Version -notmatch '^\d{4}\.\d{2}\.\d{2}\.\d{4}$') {
|
||||
throw "Unified version '$Version' does not match yyyy.MM.dd.HHmm."
|
||||
}
|
||||
|
||||
$Version
|
||||
@@ -0,0 +1,171 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Creates/updates the Gitea Actions repository secrets and variables that CI/CD
|
||||
needs, using the Gitea REST API. Idempotent: re-running overwrites values.
|
||||
|
||||
.DESCRIPTION
|
||||
Secrets are read from the local .env / secrets directory (or parameters) and
|
||||
pushed with:
|
||||
PUT /api/v1/repos/{owner}/{repo}/actions/secrets/{name}
|
||||
PUT /api/v1/repos/{owner}/{repo}/actions/variables/{name}
|
||||
|
||||
Secret VALUES are never printed — only names and the resulting status.
|
||||
|
||||
.EXAMPLE
|
||||
$env:GITEA_URL='https://git.example.com'; $env:GITEA_API_TOKEN='...'
|
||||
./scripts/Initialize-GiteaSecrets.ps1 -Owner platform -Repository ExecuteR
|
||||
|
||||
.NOTES
|
||||
The token needs repository admin scope (write:repository) to manage secrets.
|
||||
#>
|
||||
[CmdletBinding(SupportsShouldProcess)]
|
||||
param(
|
||||
[string]$GiteaUrl = $env:GITEA_URL,
|
||||
[string]$Token = $(if ($env:GITEA_TOKEN) { $env:GITEA_TOKEN } else { $env:GITEA_API_TOKEN }),
|
||||
[string]$Owner = $env:GITEA_OWNER,
|
||||
[string]$Repository = $env:GITEA_REPOSITORY,
|
||||
[string]$RegistryUsername,
|
||||
[string]$RegistryPassword,
|
||||
# Publish to a registry other than this Gitea instance's built-in one.
|
||||
# Without this switch no registry credentials are written at all — CI uses
|
||||
# the token Gitea Actions injects automatically.
|
||||
[switch]$ExternalRegistry,
|
||||
[switch]$SkipNats
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
|
||||
# ── Resolve context from git when not supplied ──────────────────────────────
|
||||
if (-not $GiteaUrl -or -not $Owner -or -not $Repository) {
|
||||
$remote = (git -C $repoRoot remote get-url origin 2>$null)
|
||||
if ($remote -match '^(?<base>https?://[^/]+)/(?<owner>[^/]+)/(?<repo>[^/]+?)(\.git)?$') {
|
||||
if (-not $GiteaUrl) { $GiteaUrl = $Matches.base }
|
||||
if (-not $Owner) { $Owner = $Matches.owner }
|
||||
if (-not $Repository) { $Repository = $Matches.repo }
|
||||
Write-Host "Derived from git remote: $GiteaUrl/$Owner/$Repository"
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $GiteaUrl) { throw 'GITEA_URL is required (or a git remote to derive it from).' }
|
||||
if (-not $Token) { throw 'GITEA_TOKEN / GITEA_API_TOKEN is required.' }
|
||||
if (-not $Owner) { throw 'GITEA_OWNER is required.' }
|
||||
if (-not $Repository) { throw 'GITEA_REPOSITORY is required.' }
|
||||
|
||||
$apiBase = "$($GiteaUrl.TrimEnd('/'))/api/v1/repos/$Owner/$Repository"
|
||||
$headers = @{ Authorization = "token $Token" }
|
||||
|
||||
# ── Collect values: .env first, then generated secrets, then parameters ─────
|
||||
$values = @{}
|
||||
$envFile = Join-Path $repoRoot '.env'
|
||||
if (Test-Path $envFile) {
|
||||
foreach ($line in Get-Content $envFile) {
|
||||
if ($line -match '^\s*([A-Z0-9_]+)\s*=\s*(.*)$') {
|
||||
$values[$Matches[1]] = $Matches[2].Trim()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$natsDir = Join-Path $repoRoot 'secrets/nats'
|
||||
if (-not $SkipNats -and (Test-Path $natsDir)) {
|
||||
$signing = Join-Path $natsDir 'account-signing.nk'
|
||||
$accountPub = Join-Path $natsDir 'account.pub'
|
||||
if (Test-Path $signing) { $values['NATS_ACCOUNT_SIGNING_SEED'] = (Get-Content $signing -Raw).Trim() }
|
||||
if (Test-Path $accountPub) { $values['NATS_ACCOUNT_PUBLIC_KEY'] = (Get-Content $accountPub -Raw).Trim() }
|
||||
}
|
||||
|
||||
# The registry credentials CI uses to push images. Default to the API token,
|
||||
# which Gitea accepts as a container-registry password.
|
||||
if (-not $RegistryUsername) { $RegistryUsername = if ($values['GITEA_ACTOR']) { $values['GITEA_ACTOR'] } else { $Owner } }
|
||||
if (-not $RegistryPassword) { $RegistryPassword = $Token }
|
||||
|
||||
$registryHost = ([Uri]$GiteaUrl).Host
|
||||
|
||||
# ── Secrets (encrypted, never readable back) ────────────────────────────────
|
||||
# NOTE: Gitea reserves the GITEA_ and GITHUB_ prefixes for Actions secret
|
||||
# names and rejects them with HTTP 400, so these use neutral names.
|
||||
#
|
||||
# Nothing here is needed for Gitea's OWN container registry: Actions injects a
|
||||
# GITEA_TOKEN per run which the registry accepts as the actor's password, and
|
||||
# the host is derived from the instance URL. REGISTRY_HOST/USERNAME/PASSWORD
|
||||
# are written only with -ExternalRegistry, to publish somewhere else.
|
||||
$secrets = @{}
|
||||
|
||||
if ($ExternalRegistry) {
|
||||
$secrets['REGISTRY_HOST'] = $registryHost
|
||||
$secrets['REGISTRY_USERNAME'] = $RegistryUsername
|
||||
$secrets['REGISTRY_PASSWORD'] = $RegistryPassword
|
||||
}
|
||||
|
||||
foreach ($name in @('NATS_ACCOUNT_SIGNING_SEED', 'INITIAL_ADMIN_PASSWORD', 'OIDC_CLIENT_SECRET', 'S3_SECRET_KEY')) {
|
||||
if ($values[$name]) { $secrets[$name] = $values[$name] }
|
||||
}
|
||||
|
||||
# ── Variables (plain, readable in the UI) ───────────────────────────────────
|
||||
$variables = @{
|
||||
'REGISTRY' = "$registryHost/$($Owner.ToLowerInvariant())"
|
||||
'SERVER_URL' = $GiteaUrl.TrimEnd('/')
|
||||
}
|
||||
foreach ($name in @('NATS_ACCOUNT_PUBLIC_KEY', 'NATS_OPERATOR_PUBLIC_KEY')) {
|
||||
if ($values[$name]) { $variables[$name] = $values[$name] }
|
||||
}
|
||||
|
||||
function Set-GiteaItem {
|
||||
param([string]$Kind, [string]$Name, [string]$Value)
|
||||
|
||||
$uri = "$apiBase/actions/$Kind/$([uri]::EscapeDataString($Name))"
|
||||
|
||||
# The two endpoints disagree on the payload field: secrets take "data",
|
||||
# variables take "value". Sending the wrong one returns HTTP 422.
|
||||
$body = if ($Kind -eq 'secrets') {
|
||||
@{ data = $Value } | ConvertTo-Json -Compress
|
||||
}
|
||||
else {
|
||||
@{ value = $Value } | ConvertTo-Json -Compress
|
||||
}
|
||||
|
||||
if (-not $PSCmdlet.ShouldProcess("$Kind/$Name", 'PUT')) { return }
|
||||
|
||||
try {
|
||||
Invoke-RestMethod -Method Put -Uri $uri -Headers $headers -ContentType 'application/json' -Body $body | Out-Null
|
||||
Write-Host (" {0,-36} set" -f $Name)
|
||||
}
|
||||
catch {
|
||||
$status = $_.Exception.Response.StatusCode.value__
|
||||
if ($status -eq 404 -and $Kind -eq 'variables') {
|
||||
# Older Gitea: variables endpoint may need POST to create.
|
||||
try {
|
||||
Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -ContentType 'application/json' -Body $body | Out-Null
|
||||
Write-Host (" {0,-36} created" -f $Name)
|
||||
return
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
Write-Warning (" {0,-36} FAILED (HTTP {1})" -f $Name, $status)
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Configuring Actions secrets on $Owner/$Repository"
|
||||
if (-not $ExternalRegistry) {
|
||||
Write-Host ' (built-in Gitea registry: no registry credentials needed)'
|
||||
}
|
||||
|
||||
foreach ($entry in $secrets.GetEnumerator() | Sort-Object Name) {
|
||||
if ([string]::IsNullOrWhiteSpace($entry.Value)) {
|
||||
Write-Host (" {0,-36} skipped (no value)" -f $entry.Name)
|
||||
continue
|
||||
}
|
||||
|
||||
Set-GiteaItem -Kind 'secrets' -Name $entry.Name -Value $entry.Value
|
||||
}
|
||||
|
||||
Write-Host "Configuring Actions variables"
|
||||
foreach ($entry in $variables.GetEnumerator() | Sort-Object Name) {
|
||||
if ([string]::IsNullOrWhiteSpace($entry.Value)) { continue }
|
||||
Set-GiteaItem -Kind 'variables' -Name $entry.Name -Value $entry.Value
|
||||
}
|
||||
|
||||
Write-Host ''
|
||||
Write-Host 'Done. CI can now log in to the registry and publish images.'
|
||||
Write-Host 'No secret values were printed.'
|
||||
@@ -0,0 +1,44 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
One-time developer setup: verifies prerequisites, restores dependencies and
|
||||
generates local secrets when missing.
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param()
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
|
||||
Write-Host '── Checking prerequisites ──'
|
||||
$dotnet = Get-Command dotnet -ErrorAction SilentlyContinue
|
||||
if (-not $dotnet) { throw '.NET SDK 10.x is required (https://dotnet.microsoft.com).' }
|
||||
Write-Host "dotnet $(dotnet --version)"
|
||||
|
||||
$node = Get-Command node -ErrorAction SilentlyContinue
|
||||
if (-not $node) { throw 'Node.js LTS is required (https://nodejs.org).' }
|
||||
Write-Host "node $(node --version)"
|
||||
|
||||
Write-Host '── Restoring .NET packages ──'
|
||||
dotnet restore (Join-Path $repoRoot 'ExecuteR.slnx')
|
||||
if ($LASTEXITCODE -ne 0) { throw "dotnet restore failed ($LASTEXITCODE)." }
|
||||
|
||||
Write-Host '── Installing WebUI packages ──'
|
||||
Push-Location (Join-Path $repoRoot 'src/WebUI')
|
||||
try {
|
||||
npm ci
|
||||
if ($LASTEXITCODE -ne 0) { throw "npm ci failed ($LASTEXITCODE)." }
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
if (-not (Test-Path (Join-Path $repoRoot '.env'))) {
|
||||
Write-Host '── Generating local secrets ──'
|
||||
& (Join-Path $PSScriptRoot 'New-LocalSecrets.ps1')
|
||||
}
|
||||
|
||||
Write-Host ''
|
||||
Write-Host 'Repository initialized. Next steps:'
|
||||
Write-Host ' docker compose up -d # NATS + backend + webui'
|
||||
Write-Host ' ./scripts/Build.ps1 # build everything'
|
||||
Write-Host ' ./scripts/Test.ps1 # run tests'
|
||||
@@ -0,0 +1,61 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Generates strong local development secrets:
|
||||
- .env (from .env.example) with a random initial admin password
|
||||
- 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
|
||||
|
||||
Idempotent: existing secrets are kept unless -Force is specified.
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$Force
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$envFile = Join-Path $repoRoot '.env'
|
||||
$envExample = Join-Path $repoRoot '.env.example'
|
||||
$natsSecretsDir = Join-Path $repoRoot 'secrets/nats'
|
||||
|
||||
if ((Test-Path $envFile) -and (Test-Path (Join-Path $natsSecretsDir 'resolver.conf')) -and -not $Force) {
|
||||
Write-Host 'Secrets already exist. Use -Force to regenerate.'
|
||||
return
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force $natsSecretsDir | Out-Null
|
||||
|
||||
# ── NATS operator/account keys via backend CLI ────────────────────────────
|
||||
Write-Host 'Generating NATS operator/account keys and resolver preload...'
|
||||
dotnet run --project (Join-Path $repoRoot 'src/Backend') -- nats-auth init --output $natsSecretsDir
|
||||
if ($LASTEXITCODE -ne 0) { throw "nats-auth init failed ($LASTEXITCODE)." }
|
||||
|
||||
$accountSigningSeed = (Get-Content (Join-Path $natsSecretsDir 'account-signing.nk') -Raw).Trim()
|
||||
$accountPublic = (Get-Content (Join-Path $natsSecretsDir 'account.pub') -Raw).Trim()
|
||||
$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] })
|
||||
}
|
||||
|
||||
$adminPassword = New-RandomPassword
|
||||
|
||||
$content = Get-Content $envExample
|
||||
$content = $content -replace '^INITIAL_ADMIN_PASSWORD=.*$', "INITIAL_ADMIN_PASSWORD=$adminPassword"
|
||||
$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"
|
||||
$content = $content -replace '^PUBLIC_SERVER_URL=.*$', 'PUBLIC_SERVER_URL=http://localhost:8080'
|
||||
$content = $content -replace '^TRUSTED_HOSTS=.*$', 'TRUSTED_HOSTS=localhost'
|
||||
Set-Content -Path $envFile -Value $content -Encoding utf8NoBOM
|
||||
|
||||
Write-Host ''
|
||||
Write-Host "Wrote $envFile"
|
||||
Write-Host "Initial admin: admin / $adminPassword"
|
||||
Write-Host 'NATS material written below secrets/nats (seeds are SECRET).'
|
||||
@@ -0,0 +1,75 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Publishes the self-contained single-file Agent executable, zips it, and
|
||||
builds the MSI when the WiX project is present.
|
||||
|
||||
.EXAMPLE
|
||||
./scripts/Package-Agent.ps1
|
||||
./scripts/Package-Agent.ps1 -Version 2026.08.06.2151 -SkipMsi
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Version,
|
||||
[switch]$SkipMsi,
|
||||
[switch]$SkipIcon
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$Version = & (Join-Path $PSScriptRoot 'Get-UnifiedVersion.ps1') -Version $Version
|
||||
$artifacts = Join-Path $repoRoot 'artifacts'
|
||||
$publishDir = Join-Path $artifacts "agent/$Version"
|
||||
|
||||
Write-Host "Packaging Agent $Version"
|
||||
|
||||
if (-not $SkipIcon) {
|
||||
& (Join-Path $PSScriptRoot 'Generate-Icons.ps1')
|
||||
}
|
||||
|
||||
dotnet publish (Join-Path $repoRoot 'src/Agent/Agent.csproj') `
|
||||
-c Release `
|
||||
-r win-x64 `
|
||||
--self-contained true `
|
||||
-p:PublishSingleFile=true `
|
||||
-p:IncludeNativeLibrariesForSelfExtract=true `
|
||||
-p:EnableCompressionInSingleFile=true `
|
||||
"-p:UnifiedVersion=$Version" `
|
||||
-o $publishDir
|
||||
if ($LASTEXITCODE -ne 0) { throw "Agent publish failed ($LASTEXITCODE)." }
|
||||
|
||||
$zipPath = Join-Path $artifacts "Agent-$Version-win-x64.zip"
|
||||
if (Test-Path $zipPath) { Remove-Item $zipPath -Force }
|
||||
Compress-Archive -Path (Join-Path $publishDir '*') -DestinationPath $zipPath
|
||||
Write-Host "Created $zipPath"
|
||||
|
||||
$wixProject = Join-Path $repoRoot 'src/Installer/Agent.Installer.wixproj'
|
||||
if (-not $SkipMsi -and (Test-Path $wixProject)) {
|
||||
# Deterministic MSI ProductVersion transform (see BuildVersion.ToMsiProductVersion):
|
||||
# yyyy.MM.dd.HHmm -> (yyyy-2000).(MM).((dd-1)*1440 + HH*60 + mm)
|
||||
$parts = $Version.Split('.')
|
||||
$hhmm = [int]$parts[3]
|
||||
$msiVersion = '{0}.{1}.{2}' -f ([int]$parts[0] - 2000), [int]$parts[1],
|
||||
((([int]$parts[2] - 1) * 1440) + ([math]::Floor($hhmm / 100) * 60) + ($hhmm % 100))
|
||||
Write-Host "MSI ProductVersion: $msiVersion"
|
||||
|
||||
dotnet build $wixProject -c Release --nologo `
|
||||
"-p:UnifiedVersion=$Version" `
|
||||
"-p:MsiProductVersion=$msiVersion" `
|
||||
"-p:AgentPublishDir=$publishDir"
|
||||
if ($LASTEXITCODE -ne 0) { throw "MSI build failed ($LASTEXITCODE)." }
|
||||
|
||||
$msi = Get-ChildItem (Join-Path $repoRoot 'src/Installer/bin/Release') -Filter '*.msi' -Recurse |
|
||||
Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1
|
||||
if ($msi) {
|
||||
$msiTarget = Join-Path $artifacts "Agent-$Version.msi"
|
||||
Copy-Item $msi.FullName $msiTarget -Force
|
||||
Write-Host "Created $msiTarget"
|
||||
}
|
||||
}
|
||||
|
||||
# Checksums for release attachment.
|
||||
$checksums = Join-Path $artifacts "Agent-$Version-checksums.txt"
|
||||
Get-ChildItem $artifacts -File | Where-Object { $_.Name -like "Agent-$Version*" -and $_.Extension -ne '.txt' } | ForEach-Object {
|
||||
"{0} {1}" -f (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant(), $_.Name
|
||||
} | Set-Content $checksums -Encoding utf8NoBOM
|
||||
Write-Host "Created $checksums"
|
||||
@@ -0,0 +1,66 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Creates (or reuses) a Gitea release for the unified version and uploads the
|
||||
agent artifacts from ./artifacts. No-ops with a clear message when GITEA_TOKEN
|
||||
or GITEA_URL are absent (local runs). Never prints the token.
|
||||
|
||||
.NOTES
|
||||
Uses the Gitea REST API:
|
||||
POST /api/v1/repos/{owner}/{repo}/releases
|
||||
POST /api/v1/repos/{owner}/{repo}/releases/{id}/assets
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Version
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$Version = & (Join-Path $PSScriptRoot 'Get-UnifiedVersion.ps1') -Version $Version
|
||||
|
||||
$giteaUrl = $env:GITEA_URL
|
||||
$token = $env:GITEA_TOKEN
|
||||
$owner = $env:GITEA_OWNER
|
||||
$repo = $env:GITEA_REPOSITORY
|
||||
|
||||
if (-not $giteaUrl -or -not $token -or -not $owner -or -not $repo) {
|
||||
Write-Host 'GITEA_URL/TOKEN/OWNER/REPOSITORY not all set; skipping release publish.'
|
||||
return
|
||||
}
|
||||
|
||||
$headers = @{ Authorization = "token $token" }
|
||||
$apiBase = "$($giteaUrl.TrimEnd('/'))/api/v1/repos/$owner/$repo"
|
||||
$tag = "v$Version"
|
||||
|
||||
Write-Host "Creating release $tag on $owner/$repo"
|
||||
$body = @{
|
||||
tag_name = $tag
|
||||
target_commitish = 'main'
|
||||
name = "ExecuteR $Version"
|
||||
body = "Automated release for unified version $Version."
|
||||
draft = $false
|
||||
prerelease = $false
|
||||
} | ConvertTo-Json
|
||||
|
||||
try {
|
||||
$release = Invoke-RestMethod -Method Post -Uri "$apiBase/releases" -Headers $headers `
|
||||
-ContentType 'application/json' -Body $body
|
||||
}
|
||||
catch {
|
||||
# Release for this tag may already exist; fetch it.
|
||||
$release = Invoke-RestMethod -Method Get -Uri "$apiBase/releases/tags/$tag" -Headers $headers
|
||||
}
|
||||
|
||||
$artifacts = Join-Path $repoRoot 'artifacts'
|
||||
$assets = Get-ChildItem $artifacts -File | Where-Object { $_.Name -like "Agent-$Version*" }
|
||||
if (-not $assets) {
|
||||
throw "No artifacts matching Agent-$Version* under $artifacts."
|
||||
}
|
||||
|
||||
foreach ($asset in $assets) {
|
||||
Write-Host "Uploading $($asset.Name)"
|
||||
$uri = "$apiBase/releases/$($release.id)/assets?name=$([uri]::EscapeDataString($asset.Name))"
|
||||
Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -InFile $asset.FullName -ContentType 'application/octet-stream' | Out-Null
|
||||
}
|
||||
|
||||
Write-Host "Release $tag published with $($assets.Count) asset(s)."
|
||||
@@ -0,0 +1,53 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Runs unit tests (and optionally the Svelte check + integration tests).
|
||||
|
||||
.EXAMPLE
|
||||
./scripts/Test.ps1
|
||||
./scripts/Test.ps1 -IncludeIntegration -IncludeWebUI
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[ValidateSet('Debug', 'Release')]
|
||||
[string]$Configuration = 'Release',
|
||||
[string]$Version,
|
||||
[switch]$IncludeIntegration,
|
||||
[switch]$IncludeWebUI
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$Version = & (Join-Path $PSScriptRoot 'Get-UnifiedVersion.ps1') -Version $Version
|
||||
|
||||
$unitProjects = @(
|
||||
'tests/Shared.Tests',
|
||||
'tests/Agent.Tests',
|
||||
'tests/Backend.Tests'
|
||||
)
|
||||
|
||||
foreach ($project in $unitProjects) {
|
||||
dotnet test (Join-Path $repoRoot $project) -c $Configuration --nologo "-p:UnifiedVersion=$Version"
|
||||
if ($LASTEXITCODE -ne 0) { throw "Tests failed in $project ($LASTEXITCODE)." }
|
||||
}
|
||||
|
||||
if ($IncludeIntegration) {
|
||||
dotnet test (Join-Path $repoRoot 'tests/Integration.Tests') -c $Configuration --nologo "-p:UnifiedVersion=$Version"
|
||||
if ($LASTEXITCODE -ne 0) { throw "Integration tests failed ($LASTEXITCODE)." }
|
||||
}
|
||||
|
||||
if ($IncludeWebUI) {
|
||||
Push-Location (Join-Path $repoRoot 'src/WebUI')
|
||||
try {
|
||||
if (-not (Test-Path 'node_modules')) {
|
||||
npm ci
|
||||
if ($LASTEXITCODE -ne 0) { throw "npm ci failed ($LASTEXITCODE)." }
|
||||
}
|
||||
npm run check
|
||||
if ($LASTEXITCODE -ne 0) { throw "svelte-check failed ($LASTEXITCODE)." }
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host 'All requested test suites passed.'
|
||||
@@ -0,0 +1,242 @@
|
||||
#!/usr/bin/env bash
|
||||
#=============================================================================
|
||||
# ExecuteR - server stack deployment
|
||||
#=============================================================================
|
||||
#
|
||||
# Bootstrap straight from the repository (no clone required):
|
||||
#
|
||||
# curl -fsSL https://git.example.com/owner/ExecuteR/raw/branch/main/scripts/deploy.sh | bash
|
||||
# curl -fsSL https://.../deploy.sh | bash -s -- --with-proxy --host control.example.com
|
||||
#
|
||||
# Or from a checkout:
|
||||
#
|
||||
# ./scripts/deploy.sh
|
||||
# ./scripts/deploy.sh --with-proxy --host control.example.com
|
||||
#
|
||||
# Pulls the published images from the Gitea container registry and falls back
|
||||
# to building from source when a pull is not possible. The in-stack reverse
|
||||
# proxy is OPT-IN (--with-proxy); by default the stack assumes you already run
|
||||
# an edge proxy.
|
||||
#=============================================================================
|
||||
set -Eeuo pipefail
|
||||
|
||||
# ── Defaults (override with flags or environment) ───────────────────────────
|
||||
REPO_RAW_URL="${REPO_RAW_URL:-https://git.example.com/owner/ExecuteR/raw/branch/main}"
|
||||
INSTALL_DIR="${INSTALL_DIR:-/opt/executer}"
|
||||
WITH_PROXY=0
|
||||
PUBLIC_HOSTNAME="${PROXY_PUBLIC_HOSTNAME:-}"
|
||||
FORCE_BUILD=0
|
||||
NO_PULL=0
|
||||
NO_START=0
|
||||
|
||||
log() { printf '\033[1;34m==>\033[0m %s\n' "$*"; }
|
||||
warn() { printf '\033[1;33mwarn:\033[0m %s\n' "$*" >&2; }
|
||||
die() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; }
|
||||
|
||||
usage() {
|
||||
# Print the leading comment banner, stopping at the first code line.
|
||||
awk 'NR>1 { if (/^#/) { sub(/^# ?/, ""); print } else { exit } }' "$0"
|
||||
cat <<'USAGE'
|
||||
|
||||
Options:
|
||||
--with-proxy Also run the in-stack nginx reverse proxy (opt-in)
|
||||
--host <hostname> Public hostname for the proxy site config
|
||||
--dir <path> Install directory (default /opt/executer)
|
||||
--repo-url <url> Raw file base URL used when bootstrapping via curl
|
||||
--build Always build from source, never pull
|
||||
--no-pull Do not pull; use local images or build
|
||||
--no-start Prepare files and images but do not start the stack
|
||||
-h, --help Show this help
|
||||
USAGE
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--with-proxy) WITH_PROXY=1; shift ;;
|
||||
--host) PUBLIC_HOSTNAME="${2:?--host needs a value}"; shift 2 ;;
|
||||
--dir) INSTALL_DIR="${2:?--dir needs a value}"; shift 2 ;;
|
||||
--repo-url) REPO_RAW_URL="${2:?--repo-url needs a value}"; shift 2 ;;
|
||||
--build) FORCE_BUILD=1; shift ;;
|
||||
--no-pull) NO_PULL=1; shift ;;
|
||||
--no-start) NO_START=1; shift ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) die "unknown option: $1 (try --help)" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# ── Prerequisites ───────────────────────────────────────────────────────────
|
||||
command -v docker >/dev/null 2>&1 || die "docker is required"
|
||||
docker compose version >/dev/null 2>&1 || die "docker compose v2 is required"
|
||||
command -v curl >/dev/null 2>&1 || die "curl is required"
|
||||
docker info >/dev/null 2>&1 || die "cannot talk to the Docker daemon (need root or docker group?)"
|
||||
|
||||
# ── Locate or fetch the stack files ─────────────────────────────────────────
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd || echo '')"
|
||||
REPO_ROOT=""
|
||||
if [[ -n "$SCRIPT_DIR" && -f "$SCRIPT_DIR/../docker-compose.yml" ]]; then
|
||||
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
fi
|
||||
|
||||
if [[ -n "$REPO_ROOT" ]]; then
|
||||
log "Deploying from checkout: $REPO_ROOT"
|
||||
STACK_DIR="$REPO_ROOT"
|
||||
else
|
||||
log "Bootstrapping into $INSTALL_DIR from $REPO_RAW_URL"
|
||||
mkdir -p "$INSTALL_DIR"
|
||||
STACK_DIR="$INSTALL_DIR"
|
||||
|
||||
fetch() {
|
||||
local rel="$1" dest="$STACK_DIR/$1"
|
||||
mkdir -p "$(dirname "$dest")"
|
||||
if ! curl -fsSL "$REPO_RAW_URL/$rel" -o "$dest"; then
|
||||
warn "could not fetch $rel"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
fetch docker-compose.yml || die "docker-compose.yml is required"
|
||||
fetch .env.example || die ".env.example is required"
|
||||
fetch src/Infra/nats/nats.conf || die "nats.conf is required"
|
||||
[[ $WITH_PROXY -eq 1 ]] && { fetch docker-compose.proxy.yml; fetch src/Infra/nginx/executer.conf; }
|
||||
# Optional; only needed when building from source.
|
||||
fetch docker-compose.dev.yml || true
|
||||
fi
|
||||
|
||||
cd "$STACK_DIR"
|
||||
|
||||
# ── .env ────────────────────────────────────────────────────────────────────
|
||||
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"
|
||||
fi
|
||||
|
||||
# shellcheck disable=SC1091
|
||||
set -a; source .env; set +a
|
||||
STACK_NAME="${STACK_NAME:-stk-executer-00001}"
|
||||
STACK_BINDMOUNTROOT="${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}"
|
||||
|
||||
# ── Bind-mount directories ──────────────────────────────────────────────────
|
||||
log "Preparing data directories under $STACK_BINDMOUNTROOT/$STACK_NAME"
|
||||
mkdir -p \
|
||||
"$STACK_BINDMOUNTROOT/$STACK_NAME/NATS/JetStream" \
|
||||
"$STACK_BINDMOUNTROOT/$STACK_NAME/NATS/Resolver" \
|
||||
"$STACK_BINDMOUNTROOT/$STACK_NAME/API/Data/logs" \
|
||||
"$STACK_BINDMOUNTROOT/$STACK_NAME/API/Data/agent"
|
||||
[[ $WITH_PROXY -eq 1 ]] && mkdir -p \
|
||||
"$STACK_BINDMOUNTROOT/$STACK_NAME/Proxy/Config" \
|
||||
"$STACK_BINDMOUNTROOT/$STACK_NAME/Proxy/Certs" \
|
||||
"$STACK_BINDMOUNTROOT/$STACK_NAME/Proxy/Logs" \
|
||||
"$STACK_BINDMOUNTROOT/$STACK_NAME/Proxy/Acme"
|
||||
|
||||
# ── Compose file selection ──────────────────────────────────────────────────
|
||||
COMPOSE_FILES=(-f docker-compose.yml)
|
||||
if [[ $WITH_PROXY -eq 1 ]]; then
|
||||
[[ -f docker-compose.proxy.yml ]] || die "--with-proxy needs docker-compose.proxy.yml"
|
||||
COMPOSE_FILES+=(-f docker-compose.proxy.yml)
|
||||
fi
|
||||
compose() { docker compose "${COMPOSE_FILES[@]}" "$@"; }
|
||||
|
||||
# ── Images: pull published, fall back to building ───────────────────────────
|
||||
BUILD_NEEDED=$FORCE_BUILD
|
||||
if [[ $FORCE_BUILD -eq 0 && $NO_PULL -eq 0 ]]; then
|
||||
# Packages published by a private repo need authentication. For Gitea's
|
||||
# built-in registry any account token works as the password.
|
||||
if [[ -n "${REGISTRY_USERNAME:-}" && -n "${REGISTRY_TOKEN:-}" && -n "${REGISTRY:-}" ]]; then
|
||||
REGISTRY_LOGIN_HOST="${REGISTRY%%/*}"
|
||||
log "Logging in to $REGISTRY_LOGIN_HOST as $REGISTRY_USERNAME"
|
||||
if ! printf '%s' "$REGISTRY_TOKEN" \
|
||||
| docker login "$REGISTRY_LOGIN_HOST" -u "$REGISTRY_USERNAME" --password-stdin >/dev/null 2>&1; then
|
||||
warn "registry login failed — continuing (public images may still pull)"
|
||||
fi
|
||||
fi
|
||||
|
||||
log "Pulling images from ${REGISTRY:-<registry unset>}"
|
||||
if ! compose pull --quiet 2>/dev/null; then
|
||||
warn "pull failed or images unavailable — falling back to building from source"
|
||||
BUILD_NEEDED=1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ $BUILD_NEEDED -eq 1 ]]; then
|
||||
[[ -f src/Infra/backend/Dockerfile ]] \
|
||||
|| die "cannot build: source not present. Clone the repo, or make the registry reachable."
|
||||
log "Building images from source"
|
||||
UNIFIED_VERSION="${UNIFIED_VERSION:-$(date -u +%Y.%m.%d.%H%M)}" compose build
|
||||
fi
|
||||
|
||||
# ── NATS operator/account keys (generated by the backend image itself) ──────
|
||||
if [[ ! -f secrets/nats/resolver.conf ]]; then
|
||||
log "Generating NATS operator/account keys"
|
||||
mkdir -p secrets/nats
|
||||
BACKEND_IMAGE_REF="$(compose config --images 2>/dev/null | grep -E 'backend|executer-backend' | head -1 || true)"
|
||||
[[ -n "$BACKEND_IMAGE_REF" ]] || die "could not resolve the backend image reference"
|
||||
|
||||
docker run --rm -v "$PWD/secrets/nats:/out" "$BACKEND_IMAGE_REF" \
|
||||
nats-auth init --output /out \
|
||||
|| die "NATS key generation failed"
|
||||
|
||||
SIGNING_SEED="$(tr -d '\r\n' < secrets/nats/account-signing.nk)"
|
||||
ACCOUNT_PUB="$(tr -d '\r\n' < secrets/nats/account.pub)"
|
||||
OPERATOR_PUB="$(tr -d '\r\n' < secrets/nats/operator.pub)"
|
||||
sed -i "s|^NATS_ACCOUNT_SIGNING_SEED=.*|NATS_ACCOUNT_SIGNING_SEED=$SIGNING_SEED|" .env
|
||||
sed -i "s|^NATS_ACCOUNT_PUBLIC_KEY=.*|NATS_ACCOUNT_PUBLIC_KEY=$ACCOUNT_PUB|" .env
|
||||
sed -i "s|^NATS_OPERATOR_PUBLIC_KEY=.*|NATS_OPERATOR_PUBLIC_KEY=$OPERATOR_PUB|" .env
|
||||
chmod 600 secrets/nats/*.nk 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# ── Proxy site config ───────────────────────────────────────────────────────
|
||||
if [[ $WITH_PROXY -eq 1 ]]; then
|
||||
PROXY_CONF="$STACK_BINDMOUNTROOT/$STACK_NAME/Proxy/Config/executer.conf"
|
||||
if [[ ! -f "$PROXY_CONF" ]]; then
|
||||
[[ -f src/Infra/nginx/executer.conf ]] || die "src/Infra/nginx/executer.conf not found"
|
||||
[[ -n "$PUBLIC_HOSTNAME" ]] || die "--host is required with --with-proxy"
|
||||
log "Writing proxy site config for $PUBLIC_HOSTNAME"
|
||||
|
||||
# In-stack proxy reaches services by compose service name, not host IP.
|
||||
sed -e "s|control\.example\.com|$PUBLIC_HOSTNAME|g" \
|
||||
-e "s|server 10\.0\.0\.10:13080;|server webui:3000;|" \
|
||||
-e "s|server 10\.0\.0\.10:19080;|server backend:8080;|" \
|
||||
-e "s|server 10\.0\.0\.10:19222;|server nats:9222;|" \
|
||||
-e "s|/etc/nginx/ssl/$PUBLIC_HOSTNAME/fullchain.cer|/etc/nginx/ssl/fullchain.pem|" \
|
||||
-e "s|/etc/nginx/ssl/$PUBLIC_HOSTNAME/private.key|/etc/nginx/ssl/private.key|" \
|
||||
src/Infra/nginx/executer.conf > "$PROXY_CONF"
|
||||
|
||||
warn "Place TLS files at $STACK_BINDMOUNTROOT/$STACK_NAME/Proxy/Certs/{fullchain.pem,private.key}"
|
||||
fi
|
||||
fi
|
||||
|
||||
# ── Start ───────────────────────────────────────────────────────────────────
|
||||
if [[ $NO_START -eq 1 ]]; then
|
||||
log "Prepared (not started, --no-start)."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
log "Starting the stack"
|
||||
compose up -d --remove-orphans
|
||||
|
||||
log "Waiting for the backend to report healthy"
|
||||
for _ in $(seq 1 60); do
|
||||
if curl -fsS "http://127.0.0.1:${BACKEND_PORT:-19080}/api/health" >/dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
|
||||
echo
|
||||
compose ps
|
||||
echo
|
||||
log "ExecuteR is up."
|
||||
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
|
||||
echo
|
||||
echo " Initial admin: ${INITIAL_ADMIN_USERNAME:-admin} / ${GENERATED_ADMIN_PASSWORD}"
|
||||
echo " (also stored in .env — change it after first sign-in)"
|
||||
fi
|
||||
@@ -0,0 +1,43 @@
|
||||
# secrets/
|
||||
|
||||
Generated secret material lives here and is **git-ignored** (only this
|
||||
README is committed).
|
||||
|
||||
Generate development secrets:
|
||||
|
||||
```powershell
|
||||
./scripts/New-LocalSecrets.ps1
|
||||
```
|
||||
|
||||
This produces:
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `../.env` | Compose environment (initial admin password, NATS signing seed, …) |
|
||||
| `nats/operator.nk` | NATS operator seed — SECRET |
|
||||
| `nats/account.nk` | NATS application account seed — SECRET |
|
||||
| `nats/account-signing.nk` | Account signing seed used by the backend to issue user JWTs — SECRET |
|
||||
| `nats/sys-account.nk` / `nats/sys-user.nk` | System account/user seeds — SECRET |
|
||||
| `nats/resolver.conf` | Operator JWT + account preload mounted into the NATS container |
|
||||
|
||||
## How the NATS keys are generated
|
||||
|
||||
Keys are real Ed25519 NKeys generated via the backend's `nats-auth` CLI
|
||||
(`dotnet run --project src/Backend -- nats-auth init`), which uses the
|
||||
official NATS.NKeys/NATS.Jwt libraries — the same code path the backend
|
||||
uses at runtime to issue agent and browser user JWTs. If you prefer
|
||||
`nsc`, an equivalent manual flow is documented in the root README.
|
||||
|
||||
## Required secrets (production)
|
||||
|
||||
- `INITIAL_ADMIN_PASSWORD` — first-boot local admin password
|
||||
- `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
|
||||
- `OIDC_CLIENT_SECRET` — only when OIDC is enabled
|
||||
- `GITEA_TOKEN` — CI release/push automation
|
||||
- `CONTAINER_REGISTRY_PASSWORD` — if different from the Gitea token
|
||||
- `CODE_SIGNING_CERT_PASSWORD` — optional release signing
|
||||
|
||||
Never log or commit any of these. Rotate by re-running generation and
|
||||
restarting the affected services.
|
||||
@@ -0,0 +1,59 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<RootNamespace>Agent</RootNamespace>
|
||||
<AssemblyName>Agent</AssemblyName>
|
||||
<RuntimeIdentifiers>win-x64</RuntimeIdentifiers>
|
||||
<!-- Required by the LibraryImport interop source generator. -->
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<!-- Ship only English resources (drops PowerShell's ~15 localization satellites). -->
|
||||
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
|
||||
<!-- The full PowerShell SDK reference-assembly manifest is host-only bloat. -->
|
||||
<PreserveCompilationContext>false</PreserveCompilationContext>
|
||||
<!-- Generated by scripts/Generate-Icons.ps1; absent for plain dev builds. -->
|
||||
<ApplicationIcon Condition="Exists('$(MSBuildThisFileDirectory)..\..\artifacts\icons\app.ico')">$(MSBuildThisFileDirectory)..\..\artifacts\icons\app.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" />
|
||||
<PackageReference Include="Microsoft.PowerShell.SDK" />
|
||||
<PackageReference Include="System.ServiceProcess.ServiceController" />
|
||||
<PackageReference Include="System.Management" />
|
||||
<PackageReference Include="System.Security.Cryptography.ProtectedData" />
|
||||
<PackageReference Include="NATS.Net" />
|
||||
<PackageReference Include="NATS.NKeys" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Shared.Contracts\Shared.Contracts.csproj" />
|
||||
<ProjectReference Include="..\Shared.Infrastructure\Shared.Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
Trim the agent payload before single-file bundling. The PowerShell SDK
|
||||
pulls in interactive/gallery modules and cross-platform native runtimes
|
||||
that a headless Windows service never uses. Core automation modules
|
||||
(Management, Utility, Security, Host, Diagnostics, CimCmdlets, Archive)
|
||||
are retained so ordinary admin scripts keep their normal cmdlet surface.
|
||||
-->
|
||||
<Target Name="TrimAgentPayload" BeforeTargets="GenerateSingleFileBundle;ComputeResolvedFilesToPublishList">
|
||||
<ItemGroup>
|
||||
<ResolvedFileToPublish Remove="@(ResolvedFileToPublish)"
|
||||
Condition="
|
||||
$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Replace('\','/').Contains('Modules/PSReadLine/')) OR
|
||||
$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Replace('\','/').Contains('Modules/PackageManagement/')) OR
|
||||
$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Replace('\','/').Contains('Modules/PowerShellGet/')) OR
|
||||
$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Replace('\','/').Contains('runtimes/unix/')) OR
|
||||
$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Replace('\','/').Contains('runtimes/linux')) OR
|
||||
$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Replace('\','/').Contains('runtimes/osx')) OR
|
||||
$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Replace('\','/').Contains('runtimes/browser')) OR
|
||||
$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Replace('\','/').Contains('/alpine'))
|
||||
" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,108 @@
|
||||
using Agent.Service;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Hosting.WindowsServices;
|
||||
using Shared.Infrastructure.Constants;
|
||||
using Shared.Infrastructure.Versioning;
|
||||
|
||||
namespace Agent.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Entry-point command dispatcher. One binary supports foreground operation,
|
||||
/// Windows service operation (no argument, launched by SCM), and idempotent
|
||||
/// service lifecycle commands.
|
||||
/// </summary>
|
||||
public static class AgentCli
|
||||
{
|
||||
public static async Task<int> RunAsync(string[] args)
|
||||
{
|
||||
var command = args.Length > 0 ? args[0].Trim().ToLowerInvariant() : null;
|
||||
|
||||
try
|
||||
{
|
||||
switch (command)
|
||||
{
|
||||
case null when WindowsServiceHelpers.IsWindowsService():
|
||||
await AgentHost.Build(runAsService: true).RunAsync();
|
||||
return 0;
|
||||
|
||||
case null:
|
||||
PrintUsage();
|
||||
return 1;
|
||||
|
||||
case "foreground":
|
||||
await AgentHost.Build(runAsService: false).RunAsync();
|
||||
return 0;
|
||||
|
||||
case "version":
|
||||
Console.WriteLine(BuildVersion.Resolve(typeof(AgentCli).Assembly));
|
||||
return 0;
|
||||
|
||||
case "install":
|
||||
return ServiceLifecycle.Install();
|
||||
|
||||
case "remove":
|
||||
return ServiceLifecycle.Remove();
|
||||
|
||||
case "start":
|
||||
return ServiceLifecycle.Start();
|
||||
|
||||
case "stop":
|
||||
return ServiceLifecycle.Stop();
|
||||
|
||||
case "initialize":
|
||||
var installResult = ServiceLifecycle.Install();
|
||||
return installResult != 0 ? installResult : ServiceLifecycle.Start();
|
||||
|
||||
case "status":
|
||||
return ServiceLifecycle.Status();
|
||||
|
||||
// Hidden: invoked by the MSI during explicit full uninstall
|
||||
// (never during upgrade) to remove credentials and runtime state.
|
||||
case "purge-credentials":
|
||||
return PurgeCredentials();
|
||||
|
||||
default:
|
||||
Console.Error.WriteLine($"Unknown command '{command}'.");
|
||||
PrintUsage();
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"error: {ex.Message}");
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
private static int PurgeCredentials()
|
||||
{
|
||||
var runtimeState = new Storage.RuntimeStateStore(new Configuration.WindowsRegistryStore());
|
||||
runtimeState.Purge();
|
||||
|
||||
var dataDirectory = Branding.AgentProgramDataDirectory;
|
||||
if (Directory.Exists(dataDirectory))
|
||||
{
|
||||
Directory.Delete(dataDirectory, recursive: true);
|
||||
}
|
||||
|
||||
Console.WriteLine("Runtime credentials and state removed.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static void PrintUsage()
|
||||
{
|
||||
Console.WriteLine($"{Branding.AgentServiceDisplayName} {BuildVersion.Resolve(typeof(AgentCli).Assembly)}");
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Usage: Agent.exe <command>");
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Commands:");
|
||||
Console.WriteLine(" foreground Run interactively with console logging");
|
||||
Console.WriteLine(" install Create/update the Windows service registration");
|
||||
Console.WriteLine(" remove Stop and remove the Windows service");
|
||||
Console.WriteLine(" start Start the installed service");
|
||||
Console.WriteLine(" stop Stop the service");
|
||||
Console.WriteLine(" initialize install + start");
|
||||
Console.WriteLine(" status Show service and enrollment state");
|
||||
Console.WriteLine(" version Print the build version");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
using Agent.Configuration;
|
||||
using Agent.Files;
|
||||
using Agent.Inventory;
|
||||
using Agent.Messaging;
|
||||
using Agent.PowerShell;
|
||||
using Agent.Storage;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NATS.Client.Core;
|
||||
using NATS.Client.JetStream;
|
||||
using Shared.Contracts.Messages;
|
||||
using Shared.Contracts.Models;
|
||||
using Shared.Infrastructure.Nats;
|
||||
|
||||
namespace Agent.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Consumes the agent's durable JetStream command feed with explicit acks.
|
||||
/// A script command is acknowledged only after the job id has been durably
|
||||
/// recorded, and duplicates are acknowledged without re-execution.
|
||||
/// </summary>
|
||||
public sealed class CommandProcessor(
|
||||
NatsConnection connection,
|
||||
AgentPublisher publisher,
|
||||
InventoryPublisher inventory,
|
||||
PowerShellJobHandler jobHandler,
|
||||
FileDownloadHandler fileHandler,
|
||||
JobHistoryStore jobHistory,
|
||||
AgentConfiguration configuration,
|
||||
ILogger logger)
|
||||
{
|
||||
public async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var js = new NatsJSContext(connection);
|
||||
var consumerName = JetStreamDefaults.AgentCommandConsumerName(publisher.ClientId);
|
||||
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var consumer = await js.GetConsumerAsync(
|
||||
JetStreamDefaults.CommandStreamName, consumerName, cancellationToken);
|
||||
|
||||
logger.LogInformation("Command consumer {Consumer} bound", consumerName);
|
||||
|
||||
// The agent is now genuinely ready for jobs (connected AND
|
||||
// consuming commands) — announce it so the backend can fire
|
||||
// on-agent-ready triggers.
|
||||
await publisher.PublishAsync(
|
||||
NatsSubjects.AgentEvent(publisher.ClientId),
|
||||
MessageTypes.AgentEvent,
|
||||
new AgentEventPayload(
|
||||
publisher.ClientId, AgentEventKinds.Ready, "command consumer bound", DateTimeOffset.UtcNow),
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
await foreach (var message in consumer.ConsumeAsync<byte[]>(cancellationToken: cancellationToken))
|
||||
{
|
||||
await HandleMessageAsync(message, cancellationToken);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex,
|
||||
"Command consumer unavailable ({Message}); retrying in 15s", ex.Message);
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(15), cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleMessageAsync(INatsJSMsg<byte[]> message, CancellationToken cancellationToken)
|
||||
{
|
||||
MessageEnvelope? envelope = null;
|
||||
try
|
||||
{
|
||||
envelope = message.Data is { Length: > 0 } ? MessageEnvelope.FromUtf8Bytes(message.Data) : null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Malformed command envelope on {Subject}", message.Subject);
|
||||
}
|
||||
|
||||
if (envelope is null)
|
||||
{
|
||||
await message.AckTerminateAsync(cancellationToken: cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (envelope.MessageType)
|
||||
{
|
||||
case MessageTypes.CommandInventory:
|
||||
await message.AckAsync(cancellationToken: cancellationToken);
|
||||
await inventory.TriggerAsync("command", cancellationToken);
|
||||
break;
|
||||
|
||||
case MessageTypes.CommandScript:
|
||||
await HandleScriptCommandAsync(envelope, message, cancellationToken);
|
||||
break;
|
||||
|
||||
case MessageTypes.CommandFileDownload:
|
||||
await HandleFileCommandAsync(envelope, message, cancellationToken);
|
||||
break;
|
||||
|
||||
default:
|
||||
logger.LogWarning("Unknown command type {MessageType}; terminating delivery", envelope.MessageType);
|
||||
await message.AckTerminateAsync(cancellationToken: cancellationToken);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleScriptCommandAsync(
|
||||
MessageEnvelope envelope, INatsJSMsg<byte[]> message, CancellationToken cancellationToken)
|
||||
{
|
||||
var command = envelope.GetPayload<ScriptCommandPayload>();
|
||||
if (command is null || command.JobId == Guid.Empty)
|
||||
{
|
||||
await message.AckTerminateAsync(cancellationToken: cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!configuration.AllowScriptExecution.Value)
|
||||
{
|
||||
logger.LogWarning("Script command {JobId} rejected: script execution disabled by policy", command.JobId);
|
||||
await message.AckAsync(cancellationToken: cancellationToken);
|
||||
await publisher.PublishAsync(
|
||||
NatsSubjects.JobState(command.JobId),
|
||||
MessageTypes.JobState,
|
||||
new JobStatePayload(
|
||||
command.JobId, publisher.ClientId, JobState.Failed, ExitCode: null,
|
||||
DateTimeOffset.UtcNow, "Script execution is disabled by policy on this device."),
|
||||
new EndpointRef(EndpointKinds.Job, command.JobId.ToString("D")),
|
||||
envelope.CorrelationId,
|
||||
envelope.MessageId,
|
||||
cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
// Idempotency: record durably BEFORE ack; duplicates ack and skip.
|
||||
if (!jobHistory.TryRecordAccepted(command.JobId))
|
||||
{
|
||||
logger.LogInformation("Duplicate delivery of job {JobId}; acknowledged without re-execution", command.JobId);
|
||||
await message.AckAsync(cancellationToken: cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
await message.AckAsync(cancellationToken: cancellationToken);
|
||||
logger.LogInformation("Job {JobId} accepted ({ScriptName})", command.JobId, command.ScriptName);
|
||||
|
||||
// Execute in the background so the consumer loop keeps flowing.
|
||||
_ = Task.Run(
|
||||
() => jobHandler.RunJobAsync(command, envelope.CorrelationId, envelope.MessageId, cancellationToken),
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
private async Task HandleFileCommandAsync(
|
||||
MessageEnvelope envelope, INatsJSMsg<byte[]> message, CancellationToken cancellationToken)
|
||||
{
|
||||
var command = envelope.GetPayload<FileDownloadCommandPayload>();
|
||||
if (command is null || command.JobId == Guid.Empty || string.IsNullOrWhiteSpace(command.Url))
|
||||
{
|
||||
await message.AckTerminateAsync(cancellationToken: cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!jobHistory.TryRecordAccepted(command.JobId))
|
||||
{
|
||||
await message.AckAsync(cancellationToken: cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
await message.AckAsync(cancellationToken: cancellationToken);
|
||||
logger.LogInformation("File download job {JobId} accepted", command.JobId);
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await fileHandler.RunAsync(command, envelope.CorrelationId, envelope.MessageId, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
jobHistory.MarkCompleted(command.JobId, "FileDownload");
|
||||
}
|
||||
}, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
using Shared.Infrastructure.Configuration;
|
||||
using Shared.Infrastructure.Constants;
|
||||
using Shared.Infrastructure.Routing;
|
||||
|
||||
namespace Agent.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Effective agent configuration with per-value provenance
|
||||
/// (GPO policy > normal registry > dev-only environment > compiled default).
|
||||
/// </summary>
|
||||
public sealed class AgentConfiguration
|
||||
{
|
||||
public required ConfigurationValue<string?> ServerUrlText { get; init; }
|
||||
public required ConfigurationValue<string?> BootstrapToken { get; init; }
|
||||
public required ConfigurationValue<string> LogLevel { get; init; }
|
||||
public required ConfigurationValue<TimeSpan> InventoryInterval { get; init; }
|
||||
public required ConfigurationValue<TimeSpan> ReconnectMinDelay { get; init; }
|
||||
public required ConfigurationValue<TimeSpan> ReconnectMaxDelay { get; init; }
|
||||
public required ConfigurationValue<bool> AllowRemoteShell { get; init; }
|
||||
public required ConfigurationValue<bool> AllowScriptExecution { get; init; }
|
||||
|
||||
/// <summary>Parsed ServerURL; null when unset or invalid.</summary>
|
||||
public ServerUrl? ServerUrl =>
|
||||
Shared.Infrastructure.Routing.ServerUrl.TryParse(ServerUrlText.Value, out var parsed, out _) ? parsed : null;
|
||||
|
||||
public bool HasBootstrapToken => !string.IsNullOrWhiteSpace(BootstrapToken.Value);
|
||||
}
|
||||
|
||||
/// <summary>Loads effective configuration using deterministic precedence.</summary>
|
||||
public sealed class AgentConfigurationLoader(IRegistryStore registry, bool allowEnvironment)
|
||||
{
|
||||
/// <summary>
|
||||
/// <paramref name="allowEnvironment"/> must only be true for foreground /
|
||||
/// development runs — environment values never apply in service mode and
|
||||
/// never override GPO in any mode.
|
||||
/// </summary>
|
||||
public AgentConfiguration Load()
|
||||
{
|
||||
return new AgentConfiguration
|
||||
{
|
||||
ServerUrlText = ResolveString(AgentConfigurationKeys.ServerUrl, AgentConfigurationKeys.EnvironmentNames.ServerUrl, null),
|
||||
BootstrapToken = ResolveString(AgentConfigurationKeys.BootstrapToken, AgentConfigurationKeys.EnvironmentNames.BootstrapToken, null),
|
||||
LogLevel = ResolveString(AgentConfigurationKeys.LogLevel, AgentConfigurationKeys.EnvironmentNames.LogLevel, "Information")!,
|
||||
InventoryInterval = ResolveTimeSpan(AgentConfigurationKeys.InventoryInterval, ProtocolDefaults.DefaultInventoryInterval),
|
||||
ReconnectMinDelay = ResolveTimeSpan(AgentConfigurationKeys.ReconnectMinDelay, ProtocolDefaults.ReconnectMinDelay),
|
||||
ReconnectMaxDelay = ResolveTimeSpan(AgentConfigurationKeys.ReconnectMaxDelay, ProtocolDefaults.ReconnectMaxDelay),
|
||||
AllowRemoteShell = ResolveBool(AgentConfigurationKeys.AllowRemoteShell, defaultValue: false),
|
||||
AllowScriptExecution = ResolveBool(AgentConfigurationKeys.AllowScriptExecution, defaultValue: true),
|
||||
};
|
||||
}
|
||||
|
||||
private ConfigurationValue<string?> ResolveString(string valueName, string? environmentName, string? defaultValue)
|
||||
{
|
||||
var policy = Normalize(registry.ReadString(Branding.AgentPolicyRegistryKey, valueName));
|
||||
if (policy is not null)
|
||||
{
|
||||
return new ConfigurationValue<string?>(policy, ConfigurationSource.GroupPolicy);
|
||||
}
|
||||
|
||||
var normal = Normalize(registry.ReadString(Branding.AgentRegistryKey, valueName));
|
||||
if (normal is not null)
|
||||
{
|
||||
return new ConfigurationValue<string?>(normal, ConfigurationSource.Registry);
|
||||
}
|
||||
|
||||
if (allowEnvironment && environmentName is not null)
|
||||
{
|
||||
var env = Normalize(Environment.GetEnvironmentVariable(environmentName));
|
||||
if (env is not null)
|
||||
{
|
||||
return new ConfigurationValue<string?>(env, ConfigurationSource.EnvironmentDevelopmentOnly);
|
||||
}
|
||||
}
|
||||
|
||||
return new ConfigurationValue<string?>(defaultValue, ConfigurationSource.Default);
|
||||
}
|
||||
|
||||
private ConfigurationValue<TimeSpan> ResolveTimeSpan(string valueName, TimeSpan defaultValue)
|
||||
{
|
||||
var raw = ResolveString(valueName, environmentName: null, defaultValue: null);
|
||||
if (raw.Value is not null)
|
||||
{
|
||||
// Accept plain seconds ("90") or a TimeSpan literal ("00:01:30").
|
||||
if (int.TryParse(raw.Value, out var seconds) && seconds > 0)
|
||||
{
|
||||
return new ConfigurationValue<TimeSpan>(TimeSpan.FromSeconds(seconds), raw.Source);
|
||||
}
|
||||
|
||||
if (TimeSpan.TryParse(raw.Value, out var span) && span > TimeSpan.Zero)
|
||||
{
|
||||
return new ConfigurationValue<TimeSpan>(span, raw.Source);
|
||||
}
|
||||
}
|
||||
|
||||
return new ConfigurationValue<TimeSpan>(defaultValue, ConfigurationSource.Default);
|
||||
}
|
||||
|
||||
private ConfigurationValue<bool> ResolveBool(string valueName, bool defaultValue)
|
||||
{
|
||||
var policy = registry.ReadDword(Branding.AgentPolicyRegistryKey, valueName);
|
||||
if (policy is not null)
|
||||
{
|
||||
return new ConfigurationValue<bool>(policy != 0, ConfigurationSource.GroupPolicy);
|
||||
}
|
||||
|
||||
var normal = registry.ReadDword(Branding.AgentRegistryKey, valueName);
|
||||
if (normal is not null)
|
||||
{
|
||||
return new ConfigurationValue<bool>(normal != 0, ConfigurationSource.Registry);
|
||||
}
|
||||
|
||||
return new ConfigurationValue<bool>(defaultValue, ConfigurationSource.Default);
|
||||
}
|
||||
|
||||
private static string? Normalize(string? value)
|
||||
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
namespace Agent.Configuration;
|
||||
|
||||
/// <summary>Registry value names for administrator configuration.</summary>
|
||||
public static class AgentConfigurationKeys
|
||||
{
|
||||
public const string ServerUrl = "ServerURL";
|
||||
public const string BootstrapToken = "BootstrapToken";
|
||||
public const string LogLevel = "LogLevel";
|
||||
public const string InventoryInterval = "InventoryInterval";
|
||||
public const string ReconnectMinDelay = "ReconnectMinDelay";
|
||||
public const string ReconnectMaxDelay = "ReconnectMaxDelay";
|
||||
public const string AllowRemoteShell = "AllowRemoteShell";
|
||||
public const string AllowScriptExecution = "AllowScriptExecution";
|
||||
|
||||
/// <summary>Development-only environment variable names (never override GPO).</summary>
|
||||
public static class EnvironmentNames
|
||||
{
|
||||
public const string ServerUrl = "AGENT_SERVER_URL";
|
||||
public const string BootstrapToken = "AGENT_BOOTSTRAP_TOKEN";
|
||||
public const string LogLevel = "AGENT_LOG_LEVEL";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Registry value names for runtime-managed state.</summary>
|
||||
public static class AgentRuntimeKeys
|
||||
{
|
||||
public const string ClientId = "ClientId";
|
||||
public const string EnrollmentId = "EnrollmentId";
|
||||
public const string LastEnrollmentUtc = "LastEnrollmentUtc";
|
||||
public const string LastConnectedUtc = "LastConnectedUtc";
|
||||
public const string CredentialExpiresUtc = "CredentialExpiresUtc";
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace Agent.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Thin registry read/write seam so configuration precedence is unit-testable.
|
||||
/// Paths are relative to HKLM.
|
||||
/// </summary>
|
||||
public interface IRegistryStore
|
||||
{
|
||||
string? ReadString(string keyPath, string valueName);
|
||||
int? ReadDword(string keyPath, string valueName);
|
||||
void WriteString(string keyPath, string valueName, string value);
|
||||
void DeleteValue(string keyPath, string valueName);
|
||||
void DeleteKeyTree(string keyPath);
|
||||
}
|
||||
|
||||
/// <summary>HKLM-backed registry store used in production.</summary>
|
||||
public sealed class WindowsRegistryStore : IRegistryStore
|
||||
{
|
||||
public string? ReadString(string keyPath, string valueName)
|
||||
{
|
||||
using var key = Registry.LocalMachine.OpenSubKey(keyPath);
|
||||
return key?.GetValue(valueName) as string;
|
||||
}
|
||||
|
||||
public int? ReadDword(string keyPath, string valueName)
|
||||
{
|
||||
using var key = Registry.LocalMachine.OpenSubKey(keyPath);
|
||||
return key?.GetValue(valueName) is int value ? value : null;
|
||||
}
|
||||
|
||||
public void WriteString(string keyPath, string valueName, string value)
|
||||
{
|
||||
using var key = Registry.LocalMachine.CreateSubKey(keyPath);
|
||||
key.SetValue(valueName, value, RegistryValueKind.String);
|
||||
}
|
||||
|
||||
public void DeleteValue(string keyPath, string valueName)
|
||||
{
|
||||
using var key = Registry.LocalMachine.OpenSubKey(keyPath, writable: true);
|
||||
key?.DeleteValue(valueName, throwOnMissingValue: false);
|
||||
}
|
||||
|
||||
public void DeleteKeyTree(string keyPath)
|
||||
{
|
||||
Registry.LocalMachine.DeleteSubKeyTree(keyPath, throwOnMissingSubKey: false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Principal;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shared.Infrastructure.Constants;
|
||||
|
||||
namespace Agent.Enrollment;
|
||||
|
||||
/// <summary>Persisted agent credential material. The NKey seed never leaves this machine.</summary>
|
||||
public sealed record AgentCredentials(
|
||||
int Version,
|
||||
string ClientId,
|
||||
Guid EnrollmentId,
|
||||
string UserJwt,
|
||||
string NkeySeed,
|
||||
DateTimeOffset? ExpiresUtc)
|
||||
{
|
||||
public const int CurrentVersion = 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DPAPI(LocalMachine)-protected credential persistence in
|
||||
/// %ProgramData%\<Company>\<Product>\credentials.dat. The file and its
|
||||
/// directory are ACL'd to SYSTEM + Administrators only. Content is a
|
||||
/// versioned encrypted JSON blob — never a plaintext .creds file.
|
||||
/// </summary>
|
||||
public sealed class CredentialStore(ILogger<CredentialStore> logger)
|
||||
{
|
||||
private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
private static string FilePath =>
|
||||
Path.Combine(Branding.AgentProgramDataDirectory, Branding.CredentialFileName);
|
||||
|
||||
public AgentCredentials? Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var encrypted = File.ReadAllBytes(FilePath);
|
||||
var plain = ProtectedData.Unprotect(encrypted, optionalEntropy: null, DataProtectionScope.LocalMachine);
|
||||
var credentials = JsonSerializer.Deserialize<AgentCredentials>(plain, SerializerOptions);
|
||||
|
||||
if (credentials is null || credentials.Version != AgentCredentials.CurrentVersion)
|
||||
{
|
||||
logger.LogWarning("Credential file has unsupported version; ignoring");
|
||||
return null;
|
||||
}
|
||||
|
||||
return credentials;
|
||||
}
|
||||
catch (Exception ex) when (ex is CryptographicException or JsonException or IOException)
|
||||
{
|
||||
logger.LogWarning(ex, "Credential file unreadable; treating agent as unenrolled");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void Save(AgentCredentials credentials)
|
||||
{
|
||||
var directory = EnsureProtectedDirectory();
|
||||
|
||||
var plain = JsonSerializer.SerializeToUtf8Bytes(credentials, SerializerOptions);
|
||||
var encrypted = ProtectedData.Protect(plain, optionalEntropy: null, DataProtectionScope.LocalMachine);
|
||||
|
||||
var path = Path.Combine(directory, Branding.CredentialFileName);
|
||||
File.WriteAllBytes(path, encrypted);
|
||||
ApplyRestrictedAcl(new FileInfo(path));
|
||||
|
||||
logger.LogInformation("Credentials persisted for client {ClientId}", credentials.ClientId);
|
||||
}
|
||||
|
||||
public void Delete()
|
||||
{
|
||||
if (File.Exists(FilePath))
|
||||
{
|
||||
File.Delete(FilePath);
|
||||
}
|
||||
}
|
||||
|
||||
private static string EnsureProtectedDirectory()
|
||||
{
|
||||
var directory = new DirectoryInfo(Branding.AgentProgramDataDirectory);
|
||||
if (!directory.Exists)
|
||||
{
|
||||
directory.Create();
|
||||
}
|
||||
|
||||
var security = new DirectorySecurity();
|
||||
security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
|
||||
security.AddAccessRule(new FileSystemAccessRule(
|
||||
new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
|
||||
FileSystemRights.FullControl,
|
||||
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
|
||||
PropagationFlags.None,
|
||||
AccessControlType.Allow));
|
||||
security.AddAccessRule(new FileSystemAccessRule(
|
||||
new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),
|
||||
FileSystemRights.FullControl,
|
||||
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
|
||||
PropagationFlags.None,
|
||||
AccessControlType.Allow));
|
||||
directory.SetAccessControl(security);
|
||||
|
||||
return directory.FullName;
|
||||
}
|
||||
|
||||
private static void ApplyRestrictedAcl(FileInfo file)
|
||||
{
|
||||
var security = new FileSecurity();
|
||||
security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
|
||||
security.AddAccessRule(new FileSystemAccessRule(
|
||||
new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
|
||||
FileSystemRights.FullControl,
|
||||
AccessControlType.Allow));
|
||||
security.AddAccessRule(new FileSystemAccessRule(
|
||||
new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),
|
||||
FileSystemRights.FullControl,
|
||||
AccessControlType.Allow));
|
||||
file.SetAccessControl(security);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using System.Net.Http.Json;
|
||||
using Agent.Configuration;
|
||||
using Agent.Identity;
|
||||
using Agent.Storage;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NATS.NKeys;
|
||||
using Shared.Contracts.Api;
|
||||
using Shared.Contracts.Serialization;
|
||||
using Shared.Infrastructure.Versioning;
|
||||
|
||||
namespace Agent.Enrollment;
|
||||
|
||||
/// <summary>
|
||||
/// Secure one-time bootstrap: generates the local user NKey pair (the private
|
||||
/// seed never leaves the endpoint), sends the public key + bootstrap token
|
||||
/// over HTTPS, persists the returned scoped user JWT with DPAPI, and erases
|
||||
/// the bootstrap token from the registry.
|
||||
/// </summary>
|
||||
public sealed class EnrollmentService(
|
||||
CredentialStore credentialStore,
|
||||
RuntimeStateStore runtimeState,
|
||||
IHardwareIdentitySource hardwareIdentity,
|
||||
ILogger<EnrollmentService> logger)
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns valid credentials, either loaded from the protected store or
|
||||
/// obtained by bootstrapping. Null when enrollment is currently impossible
|
||||
/// (no bootstrap token / server rejection) — callers retry with backoff.
|
||||
/// </summary>
|
||||
public async Task<AgentCredentials?> EnsureEnrolledAsync(AgentConfiguration configuration, CancellationToken cancellationToken)
|
||||
{
|
||||
var clientId = ResolveClientId();
|
||||
|
||||
var stored = credentialStore.Load();
|
||||
if (stored is not null)
|
||||
{
|
||||
if (stored.ClientId != clientId)
|
||||
{
|
||||
// Hardware materially changed: treat as a new device (MVP rule).
|
||||
logger.LogWarning(
|
||||
"Stored credentials belong to client {StoredClientId} but recomputed identity is {ClientId}; re-enrolling as new device",
|
||||
stored.ClientId, clientId);
|
||||
credentialStore.Delete();
|
||||
}
|
||||
else if (configuration.HasBootstrapToken)
|
||||
{
|
||||
// A token is only present because an administrator just placed
|
||||
// one (it is erased after every successful enrollment), so it
|
||||
// is an explicit instruction to re-enroll — this is how an
|
||||
// orphaned device is brought back.
|
||||
logger.LogInformation(
|
||||
"Bootstrap token present for already-enrolled client {ClientId}; re-enrolling", clientId);
|
||||
credentialStore.Delete();
|
||||
}
|
||||
else
|
||||
{
|
||||
return stored;
|
||||
}
|
||||
}
|
||||
|
||||
if (!configuration.HasBootstrapToken)
|
||||
{
|
||||
logger.LogError("Agent is not enrolled and no bootstrap token is configured");
|
||||
return null;
|
||||
}
|
||||
|
||||
var serverUrl = configuration.ServerUrl;
|
||||
if (serverUrl is null)
|
||||
{
|
||||
logger.LogError("Agent cannot enroll: ServerURL is missing or invalid");
|
||||
return null;
|
||||
}
|
||||
|
||||
using var userKey = KeyPair.CreatePair(PrefixByte.User);
|
||||
|
||||
var request = new BootstrapRequest(
|
||||
BootstrapToken: configuration.BootstrapToken.Value!,
|
||||
ClientId: clientId,
|
||||
NkeyPublic: userKey.GetPublicKey(),
|
||||
AgentVersion: BuildVersion.Resolve(typeof(EnrollmentService).Assembly),
|
||||
Device: ReadDeviceInfo());
|
||||
|
||||
using var http = new HttpClient();
|
||||
var endpoint = serverUrl.ApiEndpoint(ApiRoutes.Bootstrap);
|
||||
logger.LogInformation("Bootstrapping client {ClientId} against {Endpoint}", clientId, endpoint);
|
||||
|
||||
using var response = await http.PostAsJsonAsync(endpoint, request, JsonDefaults.Options, cancellationToken);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
logger.LogError("Bootstrap rejected with HTTP {StatusCode}", (int)response.StatusCode);
|
||||
return null;
|
||||
}
|
||||
|
||||
var result = await response.Content.ReadFromJsonAsync<BootstrapResponse>(JsonDefaults.Options, cancellationToken);
|
||||
if (result is null || string.IsNullOrWhiteSpace(result.UserJwt))
|
||||
{
|
||||
logger.LogError("Bootstrap response was empty or invalid");
|
||||
return null;
|
||||
}
|
||||
|
||||
var credentials = new AgentCredentials(
|
||||
Version: AgentCredentials.CurrentVersion,
|
||||
ClientId: clientId,
|
||||
EnrollmentId: result.EnrollmentId,
|
||||
UserJwt: result.UserJwt,
|
||||
NkeySeed: userKey.GetSeed(),
|
||||
ExpiresUtc: result.CredentialExpiresUtc);
|
||||
|
||||
credentialStore.Save(credentials);
|
||||
|
||||
runtimeState.EnrollmentId = result.EnrollmentId.ToString("D");
|
||||
runtimeState.LastEnrollmentUtc = DateTimeOffset.UtcNow;
|
||||
runtimeState.CredentialExpiresUtc = result.CredentialExpiresUtc;
|
||||
runtimeState.ClearBootstrapToken();
|
||||
|
||||
logger.LogInformation("Enrollment {EnrollmentId} complete; bootstrap token cleared", result.EnrollmentId);
|
||||
return credentials;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the deterministic client id, verifies it against the cached
|
||||
/// runtime value and refreshes the cache.
|
||||
/// </summary>
|
||||
public string ResolveClientId()
|
||||
{
|
||||
var clientId = ClientIdentityFactory.ComputeClientId(hardwareIdentity.Read());
|
||||
|
||||
var cached = runtimeState.ClientId;
|
||||
if (cached is not null && cached != clientId)
|
||||
{
|
||||
logger.LogWarning("Recomputed client id differs from cached value; hardware may have changed");
|
||||
}
|
||||
|
||||
runtimeState.ClientId = clientId;
|
||||
return clientId;
|
||||
}
|
||||
|
||||
private EnrollDeviceInfo ReadDeviceInfo()
|
||||
{
|
||||
var identity = hardwareIdentity.Read();
|
||||
string? osCaption = null;
|
||||
string? osVersion = null;
|
||||
try
|
||||
{
|
||||
osCaption = Environment.OSVersion.VersionString;
|
||||
osVersion = Environment.OSVersion.Version.ToString();
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Non-fatal; inventory supplies full OS details later.
|
||||
}
|
||||
|
||||
return new EnrollDeviceInfo(
|
||||
Hostname: Environment.MachineName,
|
||||
Manufacturer: identity.Manufacturer,
|
||||
Model: identity.Model,
|
||||
OsCaption: osCaption,
|
||||
OsVersion: osVersion);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
using System.Security.Cryptography;
|
||||
using Agent.Messaging;
|
||||
using Agent.Storage;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shared.Contracts.Messages;
|
||||
using Shared.Contracts.Models;
|
||||
using Shared.Infrastructure.Nats;
|
||||
|
||||
namespace Agent.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Downloads a file from a backend-presigned URL to a path on the device,
|
||||
/// reporting Running/progress/output/state on the job subjects so it appears in
|
||||
/// the live Jobs pipeline. S3 credentials never reach the agent — only the
|
||||
/// short-lived presigned URL does.
|
||||
/// </summary>
|
||||
public sealed class FileDownloadHandler(AgentPublisher publisher, JobHistoryStore cache, ILogger logger)
|
||||
{
|
||||
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(30) };
|
||||
|
||||
public async Task RunAsync(
|
||||
FileDownloadCommandPayload command, Guid correlationId, Guid? causationId, CancellationToken cancellationToken)
|
||||
{
|
||||
var jobId = command.JobId;
|
||||
var jobTarget = new EndpointRef(EndpointKinds.Job, jobId.ToString("D"));
|
||||
var sequence = 0L;
|
||||
|
||||
async Task OutputAsync(OutputStreamKind stream, string text) => await publisher.PublishAsync(
|
||||
NatsSubjects.JobOutput(jobId), MessageTypes.JobOutput,
|
||||
new JobOutputPayload(jobId, publisher.ClientId, Interlocked.Increment(ref sequence), stream, DateTimeOffset.UtcNow, text),
|
||||
jobTarget, correlationId, causationId);
|
||||
|
||||
async Task StateAsync(JobState state, int? exitCode, string? message) => await publisher.PublishAsync(
|
||||
NatsSubjects.JobState(jobId), MessageTypes.JobState,
|
||||
new JobStatePayload(jobId, publisher.ClientId, state, exitCode, DateTimeOffset.UtcNow, message),
|
||||
jobTarget, correlationId, causationId);
|
||||
|
||||
async Task ProgressAsync(int percent, long done, long? total) => await publisher.PublishAsync(
|
||||
NatsSubjects.JobProgress(jobId), MessageTypes.JobProgress,
|
||||
new JobProgressPayload(jobId, publisher.ClientId, "Downloading file",
|
||||
total is > 0 ? $"{done / 1024} / {total / 1024} KB" : $"{done / 1024} KB", percent, null, DateTimeOffset.UtcNow),
|
||||
jobTarget, correlationId, causationId);
|
||||
|
||||
try
|
||||
{
|
||||
await StateAsync(JobState.Running, null, null);
|
||||
await OutputAsync(OutputStreamKind.Information, $"Downloading {command.SourceDescription ?? "file"} -> {command.DestinationPath}");
|
||||
|
||||
var directory = Path.GetDirectoryName(command.DestinationPath);
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
var cached = cache.GetDownloadCache(command.DestinationPath);
|
||||
var fileExists = File.Exists(command.DestinationPath);
|
||||
|
||||
// 1. Strongest check: the caller told us the expected hash and the
|
||||
// file on disk already matches it. No request at all.
|
||||
if (fileExists && !string.IsNullOrWhiteSpace(command.Sha256))
|
||||
{
|
||||
await using var existing = File.OpenRead(command.DestinationPath);
|
||||
var actualHash = Convert.ToHexStringLower(await SHA256.HashDataAsync(existing, cancellationToken));
|
||||
if (string.Equals(actualHash, command.Sha256.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await OutputAsync(OutputStreamKind.Output,
|
||||
$"Already present with matching SHA-256; skipped download of {command.DestinationPath}");
|
||||
await StateAsync(JobState.Succeeded, 0, "Already up to date.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, command.Url);
|
||||
|
||||
// 2. Otherwise let S3 decide: send the stored ETag so an unchanged
|
||||
// object comes back as 304 and costs no transfer.
|
||||
if (fileExists && !string.IsNullOrWhiteSpace(cached?.ETag))
|
||||
{
|
||||
request.Headers.TryAddWithoutValidation("If-None-Match", cached.ETag);
|
||||
}
|
||||
|
||||
using var response = await Http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
|
||||
if (response.StatusCode == System.Net.HttpStatusCode.NotModified)
|
||||
{
|
||||
await OutputAsync(OutputStreamKind.Output,
|
||||
$"Object unchanged (ETag {cached?.ETag}); skipped download of {command.DestinationPath}");
|
||||
await StateAsync(JobState.Succeeded, 0, "Already up to date.");
|
||||
return;
|
||||
}
|
||||
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var total = command.SizeBytes ?? response.Content.Headers.ContentLength;
|
||||
var tempPath = command.DestinationPath + ".executer-partial";
|
||||
|
||||
using (var source = await response.Content.ReadAsStreamAsync(cancellationToken))
|
||||
await using (var target = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
{
|
||||
var buffer = new byte[81920];
|
||||
long done = 0;
|
||||
var lastPercent = -1;
|
||||
int read;
|
||||
while ((read = await source.ReadAsync(buffer, cancellationToken)) > 0)
|
||||
{
|
||||
await target.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
|
||||
done += read;
|
||||
if (total is > 0)
|
||||
{
|
||||
var percent = (int)Math.Min(100, done * 100 / total.Value);
|
||||
if (percent != lastPercent && percent % 5 == 0)
|
||||
{
|
||||
lastPercent = percent;
|
||||
await ProgressAsync(percent, done, total);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await ProgressAsync(100, done, total);
|
||||
}
|
||||
|
||||
// Always hash what we fetched: it verifies the transfer when an
|
||||
// expected hash was supplied, and seeds the cache either way.
|
||||
string downloadedHash;
|
||||
await using (var verifyStream = File.OpenRead(tempPath))
|
||||
{
|
||||
downloadedHash = Convert.ToHexStringLower(await SHA256.HashDataAsync(verifyStream, cancellationToken));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(command.Sha256)
|
||||
&& !string.Equals(downloadedHash, command.Sha256.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
File.Delete(tempPath);
|
||||
await OutputAsync(OutputStreamKind.Error, $"Hash mismatch (expected {command.Sha256}, got {downloadedHash})");
|
||||
await StateAsync(JobState.Failed, 1, "SHA-256 verification failed.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(command.Sha256))
|
||||
{
|
||||
await OutputAsync(OutputStreamKind.Information, "SHA-256 verified.");
|
||||
}
|
||||
|
||||
File.Move(tempPath, command.DestinationPath, overwrite: true);
|
||||
|
||||
var etag = response.Headers.ETag?.Tag;
|
||||
cache.RecordDownload(
|
||||
command.DestinationPath,
|
||||
command.SourceDescription,
|
||||
etag,
|
||||
downloadedHash,
|
||||
new FileInfo(command.DestinationPath).Length);
|
||||
|
||||
await OutputAsync(OutputStreamKind.Output, $"Saved to {command.DestinationPath}");
|
||||
await StateAsync(JobState.Succeeded, 0, null);
|
||||
logger.LogInformation("File download job {JobId} succeeded (etag {ETag})", jobId, etag ?? "none");
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
await StateAsync(JobState.Cancelled, -1, "Cancelled.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "File download job {JobId} failed", jobId);
|
||||
await OutputAsync(OutputStreamKind.Error, ex.Message);
|
||||
await StateAsync(JobState.Failed, 1, ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.Management;
|
||||
|
||||
namespace Agent.Identity;
|
||||
|
||||
/// <summary>Reads stable hardware identifiers from CIM/WMI via managed APIs.</summary>
|
||||
public sealed class CimHardwareIdentitySource : IHardwareIdentitySource
|
||||
{
|
||||
public HardwareIdentity Read()
|
||||
{
|
||||
string? uuid = null;
|
||||
string? identifyingNumber = null;
|
||||
Query("SELECT UUID, IdentifyingNumber FROM Win32_ComputerSystemProduct", obj =>
|
||||
{
|
||||
uuid = obj["UUID"] as string;
|
||||
identifyingNumber = obj["IdentifyingNumber"] as string;
|
||||
});
|
||||
|
||||
string? biosSerial = null;
|
||||
Query("SELECT SerialNumber FROM Win32_BIOS", obj => biosSerial = obj["SerialNumber"] as string);
|
||||
|
||||
string? boardSerial = null;
|
||||
Query("SELECT SerialNumber FROM Win32_BaseBoard", obj => boardSerial = obj["SerialNumber"] as string);
|
||||
|
||||
string? manufacturer = null;
|
||||
string? model = null;
|
||||
Query("SELECT Manufacturer, Model FROM Win32_ComputerSystem", obj =>
|
||||
{
|
||||
manufacturer = obj["Manufacturer"] as string;
|
||||
model = obj["Model"] as string;
|
||||
});
|
||||
|
||||
return new HardwareIdentity(uuid, biosSerial, boardSerial, identifyingNumber, manufacturer, model);
|
||||
}
|
||||
|
||||
private static void Query(string wql, Action<ManagementBaseObject> onFirst)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var searcher = new ManagementObjectSearcher(wql);
|
||||
using var results = searcher.Get();
|
||||
foreach (var obj in results)
|
||||
{
|
||||
using (obj)
|
||||
{
|
||||
onFirst(obj);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (ManagementException)
|
||||
{
|
||||
// Missing WMI class/values — treated as absent identifiers.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Agent.Identity;
|
||||
|
||||
/// <summary>
|
||||
/// Builds the deterministic client id: normalized labeled canonical string
|
||||
/// over stable hardware identifiers, hashed with SHA-256, exposed as
|
||||
/// lowercase hex. Requires at least one strong identifier.
|
||||
/// </summary>
|
||||
public static class ClientIdentityFactory
|
||||
{
|
||||
private static readonly string[] JunkValues =
|
||||
[
|
||||
"TO BE FILLED BY O.E.M.",
|
||||
"DEFAULT STRING",
|
||||
"SYSTEM SERIAL NUMBER",
|
||||
"SYSTEM PRODUCT NAME",
|
||||
"SYSTEM MANUFACTURER",
|
||||
"NONE",
|
||||
"N/A",
|
||||
"NA",
|
||||
"UNKNOWN",
|
||||
"NOT SPECIFIED",
|
||||
"NOT APPLICABLE",
|
||||
"NO ENCLOSURE",
|
||||
"CHASSIS SERIAL NUMBER",
|
||||
"0",
|
||||
"00000000-0000-0000-0000-000000000000",
|
||||
"FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF",
|
||||
"03000200-0400-0500-0006-000700080009", // widely-cloned AMI placeholder UUID
|
||||
"12345678-1234-5678-90AB-CDDEEFAABBCC",
|
||||
];
|
||||
|
||||
/// <summary>Normalizes one raw identifier; null when placeholder/junk.</summary>
|
||||
public static string? Normalize(string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var normalized = value.Trim().ToUpperInvariant();
|
||||
|
||||
if (JunkValues.Contains(normalized))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// Reject strings that are entirely zeros/punctuation (e.g. "0000000").
|
||||
if (normalized.All(c => c is '0' or '-' or '.' or ' ' or '_'))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/// <summary>Builds the labeled canonical identity string, e.g. <c>UUID=…|BIOS=…|…</c>.</summary>
|
||||
public static string BuildCanonicalIdentity(HardwareIdentity identity)
|
||||
{
|
||||
var uuid = Normalize(identity.SystemProductUuid);
|
||||
var bios = Normalize(identity.BiosSerialNumber);
|
||||
var board = Normalize(identity.BaseboardSerialNumber);
|
||||
var ident = Normalize(identity.IdentifyingNumber);
|
||||
var manufacturer = Normalize(identity.Manufacturer);
|
||||
var model = Normalize(identity.Model);
|
||||
|
||||
var hasStrongIdentifier = uuid is not null || bios is not null || board is not null || ident is not null;
|
||||
if (!hasStrongIdentifier)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"No strong hardware identifier available (UUID/BIOS/baseboard/identifying number all missing or placeholders).");
|
||||
}
|
||||
|
||||
return $"UUID={uuid}|BIOS={bios}|BOARD={board}|IDENT={ident}|MFR={manufacturer}|MODEL={model}";
|
||||
}
|
||||
|
||||
/// <summary>Lowercase-hex SHA-256 of the canonical identity string.</summary>
|
||||
public static string ComputeClientId(HardwareIdentity identity)
|
||||
{
|
||||
var canonical = BuildCanonicalIdentity(identity);
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(canonical)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace Agent.Identity;
|
||||
|
||||
/// <summary>Raw hardware identity values read from CIM/WMI.</summary>
|
||||
public sealed record HardwareIdentity(
|
||||
string? SystemProductUuid,
|
||||
string? BiosSerialNumber,
|
||||
string? BaseboardSerialNumber,
|
||||
string? IdentifyingNumber,
|
||||
string? Manufacturer,
|
||||
string? Model);
|
||||
|
||||
/// <summary>Seam for reading hardware identity (CIM in production, fixed values in tests).</summary>
|
||||
public interface IHardwareIdentitySource
|
||||
{
|
||||
HardwareIdentity Read();
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
using System.Management;
|
||||
using Agent.Identity;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Agent.Inventory;
|
||||
|
||||
/// <summary>Collects the MVP inventory snapshot from CIM/WMI and managed APIs.</summary>
|
||||
public sealed class InventoryCollector(IHardwareIdentitySource identitySource)
|
||||
{
|
||||
public InventoryReport Collect(string clientId)
|
||||
{
|
||||
var hardware = identitySource.Read();
|
||||
|
||||
string? domain = null;
|
||||
var partOfDomain = false;
|
||||
string? systemType = null;
|
||||
long totalMemory = 0;
|
||||
QueryFirst("SELECT Domain, PartOfDomain, SystemType, TotalPhysicalMemory FROM Win32_ComputerSystem", obj =>
|
||||
{
|
||||
domain = obj["Domain"] as string;
|
||||
partOfDomain = obj["PartOfDomain"] as bool? ?? false;
|
||||
systemType = obj["SystemType"] as string;
|
||||
totalMemory = (long?)(obj["TotalPhysicalMemory"] as ulong?) ?? 0;
|
||||
});
|
||||
|
||||
string? biosVersion = null;
|
||||
QueryFirst("SELECT SMBIOSBIOSVersion FROM Win32_BIOS", obj => biosVersion = obj["SMBIOSBIOSVersion"] as string);
|
||||
|
||||
var identity = new InventoryIdentity(
|
||||
ClientId: clientId,
|
||||
Hostname: Environment.MachineName,
|
||||
Manufacturer: hardware.Manufacturer?.Trim(),
|
||||
Model: hardware.Model?.Trim(),
|
||||
SerialNumber: hardware.BiosSerialNumber?.Trim(),
|
||||
BiosVersion: biosVersion?.Trim(),
|
||||
BaseboardSerial: hardware.BaseboardSerialNumber?.Trim(),
|
||||
DomainOrWorkgroup: domain,
|
||||
PartOfDomain: partOfDomain,
|
||||
SystemType: systemType);
|
||||
|
||||
var os = CollectOs();
|
||||
var cpu = CollectCpu();
|
||||
var memory = CollectMemory();
|
||||
var disks = CollectDisks();
|
||||
var volumes = CollectVolumes();
|
||||
var network = CollectNetwork();
|
||||
|
||||
return new InventoryReport(
|
||||
Identity: identity,
|
||||
Os: os,
|
||||
Cpu: cpu,
|
||||
Memory: memory,
|
||||
TotalPhysicalMemoryBytes: totalMemory,
|
||||
Disks: disks,
|
||||
Volumes: volumes,
|
||||
Network: network,
|
||||
CollectedUtc: DateTimeOffset.UtcNow);
|
||||
}
|
||||
|
||||
private static InventoryOs CollectOs()
|
||||
{
|
||||
string? caption = null;
|
||||
string? version = null;
|
||||
string? build = null;
|
||||
string? architecture = null;
|
||||
DateTimeOffset? installDate = null;
|
||||
DateTimeOffset? lastBoot = null;
|
||||
string? edition = null;
|
||||
|
||||
QueryFirst(
|
||||
"SELECT Caption, Version, BuildNumber, OSArchitecture, InstallDate, LastBootUpTime, OperatingSystemSKU FROM Win32_OperatingSystem",
|
||||
obj =>
|
||||
{
|
||||
caption = (obj["Caption"] as string)?.Trim();
|
||||
version = obj["Version"] as string;
|
||||
build = obj["BuildNumber"] as string;
|
||||
architecture = obj["OSArchitecture"] as string;
|
||||
installDate = ConvertCimDate(obj["InstallDate"] as string);
|
||||
lastBoot = ConvertCimDate(obj["LastBootUpTime"] as string);
|
||||
edition = obj["OperatingSystemSKU"]?.ToString();
|
||||
});
|
||||
|
||||
return new InventoryOs(caption, version, build, architecture, installDate, lastBoot, edition);
|
||||
}
|
||||
|
||||
private static InventoryCpu CollectCpu()
|
||||
{
|
||||
string? name = null;
|
||||
var logical = 0;
|
||||
var cores = 0;
|
||||
Query("SELECT Name, NumberOfLogicalProcessors, NumberOfCores FROM Win32_Processor", obj =>
|
||||
{
|
||||
name ??= (obj["Name"] as string)?.Trim();
|
||||
logical += (int?)(obj["NumberOfLogicalProcessors"] as uint?) ?? 0;
|
||||
cores += (int?)(obj["NumberOfCores"] as uint?) ?? 0;
|
||||
});
|
||||
|
||||
return new InventoryCpu(name, logical, cores);
|
||||
}
|
||||
|
||||
private static List<InventoryMemoryModule> CollectMemory()
|
||||
{
|
||||
var modules = new List<InventoryMemoryModule>();
|
||||
Query("SELECT DeviceLocator, Capacity, Manufacturer, Speed FROM Win32_PhysicalMemory", obj =>
|
||||
{
|
||||
modules.Add(new InventoryMemoryModule(
|
||||
DeviceLocator: obj["DeviceLocator"] as string,
|
||||
CapacityBytes: (long?)(obj["Capacity"] as ulong?) ?? 0,
|
||||
Manufacturer: (obj["Manufacturer"] as string)?.Trim(),
|
||||
SpeedMhz: (int?)(obj["Speed"] as uint?)));
|
||||
});
|
||||
return modules;
|
||||
}
|
||||
|
||||
private static List<InventoryDisk> CollectDisks()
|
||||
{
|
||||
var disks = new List<InventoryDisk>();
|
||||
Query("SELECT Model, SerialNumber, Size, InterfaceType FROM Win32_DiskDrive", obj =>
|
||||
{
|
||||
disks.Add(new InventoryDisk(
|
||||
Model: (obj["Model"] as string)?.Trim(),
|
||||
SerialNumber: (obj["SerialNumber"] as string)?.Trim(),
|
||||
SizeBytes: (long?)(obj["Size"] as ulong?) ?? 0,
|
||||
BusType: obj["InterfaceType"] as string));
|
||||
});
|
||||
return disks;
|
||||
}
|
||||
|
||||
private static List<InventoryVolume> CollectVolumes()
|
||||
{
|
||||
var volumes = new List<InventoryVolume>();
|
||||
Query("SELECT DeviceID, FileSystem, Size, FreeSpace FROM Win32_LogicalDisk WHERE DriveType = 3", obj =>
|
||||
{
|
||||
volumes.Add(new InventoryVolume(
|
||||
DriveLetter: obj["DeviceID"] as string ?? string.Empty,
|
||||
FileSystem: obj["FileSystem"] as string,
|
||||
TotalSizeBytes: (long?)(obj["Size"] as ulong?) ?? 0,
|
||||
FreeSpaceBytes: (long?)(obj["FreeSpace"] as ulong?) ?? 0));
|
||||
});
|
||||
return volumes;
|
||||
}
|
||||
|
||||
private static List<InventoryNetworkAdapter> CollectNetwork()
|
||||
{
|
||||
var adapters = new List<InventoryNetworkAdapter>();
|
||||
Query(
|
||||
"SELECT Description, MACAddress, IPAddress, DefaultIPGateway, DNSServerSearchOrder FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE",
|
||||
obj =>
|
||||
{
|
||||
var addresses = obj["IPAddress"] as string[] ?? [];
|
||||
adapters.Add(new InventoryNetworkAdapter(
|
||||
Description: obj["Description"] as string,
|
||||
MacAddress: obj["MACAddress"] as string,
|
||||
Ipv4Addresses: [.. addresses.Where(a => !a.Contains(':'))],
|
||||
Ipv6Addresses: [.. addresses.Where(a => a.Contains(':'))],
|
||||
Gateways: [.. obj["DefaultIPGateway"] as string[] ?? []],
|
||||
DnsServers: [.. obj["DNSServerSearchOrder"] as string[] ?? []]));
|
||||
});
|
||||
return adapters;
|
||||
}
|
||||
|
||||
private static DateTimeOffset? ConvertCimDate(string? cimDate)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(cimDate))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return new DateTimeOffset(ManagementDateTimeConverter.ToDateTime(cimDate).ToUniversalTime(), TimeSpan.Zero);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Query(string wql, Action<ManagementBaseObject> onEach)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var searcher = new ManagementObjectSearcher(wql);
|
||||
using var results = searcher.Get();
|
||||
foreach (var obj in results)
|
||||
{
|
||||
using (obj)
|
||||
{
|
||||
onEach(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (ManagementException)
|
||||
{
|
||||
// Missing class/namespace — section stays empty.
|
||||
}
|
||||
}
|
||||
|
||||
private static void QueryFirst(string wql, Action<ManagementBaseObject> onFirst)
|
||||
{
|
||||
var seen = false;
|
||||
Query(wql, obj =>
|
||||
{
|
||||
if (!seen)
|
||||
{
|
||||
seen = true;
|
||||
onFirst(obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using Agent.Messaging;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shared.Contracts.Messages;
|
||||
using Shared.Infrastructure.Nats;
|
||||
|
||||
namespace Agent.Inventory;
|
||||
|
||||
/// <summary>
|
||||
/// Publishes the full inventory snapshot: immediately at session start
|
||||
/// (covers enrollment and reconnect), on the configured interval, and on
|
||||
/// demand when the backend sends an inventory command.
|
||||
/// </summary>
|
||||
public sealed class InventoryPublisher(
|
||||
InventoryCollector collector,
|
||||
AgentPublisher publisher,
|
||||
TimeSpan interval,
|
||||
ILogger logger)
|
||||
{
|
||||
private readonly SemaphoreSlim publishLock = new(1, 1);
|
||||
|
||||
public async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
await TriggerAsync("interval", cancellationToken);
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(interval, cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task TriggerAsync(string reason, CancellationToken cancellationToken)
|
||||
{
|
||||
await publishLock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
var report = collector.Collect(publisher.ClientId);
|
||||
await publisher.PublishAsync(
|
||||
NatsSubjects.AgentInventory(publisher.ClientId),
|
||||
MessageTypes.AgentInventory,
|
||||
new InventoryPayload(report),
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
logger.LogInformation("Inventory published ({Reason})", reason);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Inventory collection/publish failed ({Reason})", reason);
|
||||
}
|
||||
finally
|
||||
{
|
||||
publishLock.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using Agent.Configuration;
|
||||
using Agent.Enrollment;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NATS.Client.Core;
|
||||
using Shared.Infrastructure.Routing;
|
||||
|
||||
namespace Agent.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// Builds the NATS client options for the WSS connection derived from
|
||||
/// ServerURL. Credentials are supplied from protected in-memory state —
|
||||
/// no .creds file is ever written.
|
||||
/// </summary>
|
||||
public static class AgentNatsOptionsFactory
|
||||
{
|
||||
public static NatsOpts Build(
|
||||
ServerUrl serverUrl,
|
||||
AgentCredentials credentials,
|
||||
AgentConfiguration configuration,
|
||||
ILoggerFactory loggerFactory)
|
||||
{
|
||||
return NatsOpts.Default with
|
||||
{
|
||||
Url = serverUrl.AgentWebSocketEndpoint.ToString(),
|
||||
Name = $"agent-{credentials.ClientId}",
|
||||
AuthOpts = NatsAuthOpts.Default with
|
||||
{
|
||||
Jwt = credentials.UserJwt,
|
||||
Seed = credentials.NkeySeed,
|
||||
},
|
||||
ReconnectWaitMin = configuration.ReconnectMinDelay.Value,
|
||||
ReconnectWaitMax = configuration.ReconnectMaxDelay.Value,
|
||||
ReconnectJitter = TimeSpan.FromMilliseconds(500),
|
||||
MaxReconnectRetry = -1,
|
||||
RetryOnInitialConnect = true,
|
||||
DrainSubscriptionsOnDispose = true,
|
||||
LoggerFactory = loggerFactory,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using NATS.Client.Core;
|
||||
using Shared.Contracts.Messages;
|
||||
|
||||
namespace Agent.Messaging;
|
||||
|
||||
/// <summary>Publishes enveloped messages from this agent.</summary>
|
||||
public sealed class AgentPublisher(NatsConnection connection, string clientId)
|
||||
{
|
||||
public EndpointRef Source { get; } = new(EndpointKinds.Agent, clientId);
|
||||
|
||||
public string ClientId => clientId;
|
||||
|
||||
public async ValueTask PublishAsync<TPayload>(
|
||||
string subject,
|
||||
string messageType,
|
||||
TPayload payload,
|
||||
EndpointRef? target = null,
|
||||
Guid? correlationId = null,
|
||||
Guid? causationId = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var envelope = MessageEnvelope.Create(messageType, Source, payload, target, correlationId, causationId);
|
||||
await connection.PublishAsync(subject, envelope.ToUtf8Bytes(), cancellationToken: cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using System.Management.Automation;
|
||||
using System.Management.Automation.Runspaces;
|
||||
|
||||
namespace Agent.PowerShell;
|
||||
|
||||
/// <summary>Result of one in-process PowerShell execution.</summary>
|
||||
public sealed record PowerShellExecutionResult(bool HadErrors, bool WasCancelled, string? FailureMessage);
|
||||
|
||||
/// <summary>
|
||||
/// Executes scripts in-process through System.Management.Automation:
|
||||
/// runspace + AddScript/AddParameter, async invocation, live subscription to
|
||||
/// every stream, cooperative cancellation, clean disposal.
|
||||
/// </summary>
|
||||
public sealed class PowerShellExecutionService
|
||||
{
|
||||
public Task<PowerShellExecutionResult> ExecuteAsync(
|
||||
string scriptContent,
|
||||
IReadOnlyDictionary<string, object?>? parameters,
|
||||
Action<NormalizedOutputRecord> onRecord,
|
||||
Action<NormalizedProgressRecord> onProgress,
|
||||
CancellationToken cancellationToken)
|
||||
=> ExecuteAsync(scriptContent, parameters, prelude: null, onRecord, onProgress, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="prelude"/> (reusable function definitions), if any,
|
||||
/// then the main <paramref name="scriptContent"/> in the same runspace, so
|
||||
/// the main script keeps its <c>param()</c> block first while still calling
|
||||
/// shared functions.
|
||||
/// </summary>
|
||||
public async Task<PowerShellExecutionResult> ExecuteAsync(
|
||||
string scriptContent,
|
||||
IReadOnlyDictionary<string, object?>? parameters,
|
||||
string? prelude,
|
||||
Action<NormalizedOutputRecord> onRecord,
|
||||
Action<NormalizedProgressRecord> onProgress,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
using var runspace = PowerShellRunspaceFactory.Create();
|
||||
using var powerShell = System.Management.Automation.PowerShell.Create();
|
||||
powerShell.Runspace = runspace;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(prelude))
|
||||
{
|
||||
powerShell.AddScript(prelude);
|
||||
powerShell.AddStatement();
|
||||
}
|
||||
|
||||
powerShell.AddScript(scriptContent);
|
||||
if (parameters is not null)
|
||||
{
|
||||
foreach (var (name, value) in parameters)
|
||||
{
|
||||
powerShell.AddParameter(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
var output = new PSDataCollection<PSObject>();
|
||||
output.DataAdded += (_, e) => onRecord(PowerShellOutputNormalizer.FromOutput(output[e.Index]));
|
||||
|
||||
powerShell.Streams.Error.DataAdded += (_, e) =>
|
||||
onRecord(PowerShellOutputNormalizer.FromError(powerShell.Streams.Error[e.Index]));
|
||||
powerShell.Streams.Warning.DataAdded += (_, e) =>
|
||||
onRecord(PowerShellOutputNormalizer.FromWarning(powerShell.Streams.Warning[e.Index]));
|
||||
powerShell.Streams.Verbose.DataAdded += (_, e) =>
|
||||
onRecord(PowerShellOutputNormalizer.FromVerbose(powerShell.Streams.Verbose[e.Index]));
|
||||
powerShell.Streams.Debug.DataAdded += (_, e) =>
|
||||
onRecord(PowerShellOutputNormalizer.FromDebug(powerShell.Streams.Debug[e.Index]));
|
||||
powerShell.Streams.Information.DataAdded += (_, e) =>
|
||||
onRecord(PowerShellOutputNormalizer.FromInformation(powerShell.Streams.Information[e.Index]));
|
||||
powerShell.Streams.Progress.DataAdded += (_, e) =>
|
||||
onProgress(PowerShellOutputNormalizer.FromProgress(powerShell.Streams.Progress[e.Index]));
|
||||
|
||||
var wasCancelled = false;
|
||||
await using var registration = cancellationToken.Register(() =>
|
||||
{
|
||||
wasCancelled = true;
|
||||
try
|
||||
{
|
||||
powerShell.BeginStop(null, null);
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// Execution already completed.
|
||||
}
|
||||
});
|
||||
|
||||
string? failureMessage = null;
|
||||
try
|
||||
{
|
||||
await powerShell.InvokeAsync<PSObject, PSObject>(input: null, output: output).ConfigureAwait(false);
|
||||
}
|
||||
catch (PipelineStoppedException)
|
||||
{
|
||||
wasCancelled = true;
|
||||
}
|
||||
catch (RuntimeException ex)
|
||||
{
|
||||
// Terminating error: surface as an error record + failed result.
|
||||
failureMessage = ex.Message;
|
||||
onRecord(new NormalizedOutputRecord(Shared.Contracts.Models.OutputStreamKind.Error, ex.Message));
|
||||
}
|
||||
|
||||
return new PowerShellExecutionResult(
|
||||
HadErrors: powerShell.HadErrors || failureMessage is not null,
|
||||
WasCancelled: wasCancelled,
|
||||
FailureMessage: failureMessage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
using Agent.Messaging;
|
||||
using Agent.Storage;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shared.Contracts.Messages;
|
||||
using Shared.Contracts.Models;
|
||||
using Shared.Infrastructure.Constants;
|
||||
using Shared.Infrastructure.Nats;
|
||||
|
||||
namespace Agent.PowerShell;
|
||||
|
||||
/// <summary>
|
||||
/// Runs one script job: streams normalized output/progress records to Core
|
||||
/// NATS with a per-job monotonic sequence and publishes job state transitions.
|
||||
/// </summary>
|
||||
public sealed class PowerShellJobHandler(
|
||||
PowerShellExecutionService executionService,
|
||||
AgentPublisher publisher,
|
||||
JobHistoryStore jobHistory,
|
||||
ILogger logger)
|
||||
{
|
||||
private int activeJobs;
|
||||
|
||||
public int ActiveJobs => Volatile.Read(ref activeJobs);
|
||||
|
||||
public async Task RunJobAsync(ScriptCommandPayload command, Guid correlationId, Guid? causationId, CancellationToken cancellationToken)
|
||||
{
|
||||
var jobId = command.JobId;
|
||||
var jobTarget = new EndpointRef(EndpointKinds.Job, jobId.ToString("D"));
|
||||
var sequence = 0L;
|
||||
|
||||
Interlocked.Increment(ref activeJobs);
|
||||
try
|
||||
{
|
||||
await PublishStateAsync(JobState.Running, exitCode: null, message: null);
|
||||
|
||||
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
var timeout = TimeSpan.FromSeconds(command.TimeoutSeconds is > 0
|
||||
? command.TimeoutSeconds.Value
|
||||
: ProtocolDefaults.DefaultScriptTimeoutSeconds);
|
||||
timeoutCts.CancelAfter(timeout);
|
||||
|
||||
var pending = new List<Task>();
|
||||
|
||||
var boundParameters = ScriptArgumentBinder.Bind(command.Parameters, command.Arguments);
|
||||
|
||||
var result = await executionService.ExecuteAsync(
|
||||
command.Content,
|
||||
boundParameters,
|
||||
command.Prelude,
|
||||
onRecord: record => pending.Add(PublishOutputAsync(record, Interlocked.Increment(ref sequence))),
|
||||
onProgress: progress => pending.Add(PublishProgressAsync(progress)),
|
||||
cancellationToken: timeoutCts.Token);
|
||||
|
||||
await Task.WhenAll(pending);
|
||||
|
||||
JobState finalState;
|
||||
int exitCode;
|
||||
string? message = null;
|
||||
|
||||
if (result.WasCancelled && cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
finalState = JobState.Cancelled;
|
||||
exitCode = -1;
|
||||
message = "Execution cancelled.";
|
||||
}
|
||||
else if (result.WasCancelled)
|
||||
{
|
||||
finalState = JobState.TimedOut;
|
||||
exitCode = -1;
|
||||
message = $"Execution exceeded the {timeout.TotalSeconds:F0}s timeout.";
|
||||
}
|
||||
else if (result.HadErrors)
|
||||
{
|
||||
finalState = JobState.Failed;
|
||||
exitCode = 1;
|
||||
message = result.FailureMessage;
|
||||
}
|
||||
else
|
||||
{
|
||||
finalState = JobState.Succeeded;
|
||||
exitCode = 0;
|
||||
}
|
||||
|
||||
jobHistory.MarkCompleted(jobId, finalState.ToString());
|
||||
await PublishStateAsync(finalState, exitCode, message);
|
||||
|
||||
logger.LogInformation("Job {JobId} finished: {State}", jobId, finalState);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Job {JobId} crashed", jobId);
|
||||
jobHistory.MarkCompleted(jobId, JobState.Failed.ToString());
|
||||
await PublishStateAsync(JobState.Failed, exitCode: 1, message: ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Decrement(ref activeJobs);
|
||||
}
|
||||
|
||||
async Task PublishOutputAsync(NormalizedOutputRecord record, long seq)
|
||||
{
|
||||
try
|
||||
{
|
||||
await publisher.PublishAsync(
|
||||
NatsSubjects.JobOutput(jobId),
|
||||
MessageTypes.JobOutput,
|
||||
new JobOutputPayload(jobId, publisher.ClientId, seq, record.Stream, DateTimeOffset.UtcNow, record.Text),
|
||||
jobTarget,
|
||||
correlationId,
|
||||
causationId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to publish output record for job {JobId}", jobId);
|
||||
}
|
||||
}
|
||||
|
||||
async Task PublishProgressAsync(NormalizedProgressRecord progress)
|
||||
{
|
||||
try
|
||||
{
|
||||
await publisher.PublishAsync(
|
||||
NatsSubjects.JobProgress(jobId),
|
||||
MessageTypes.JobProgress,
|
||||
new JobProgressPayload(
|
||||
jobId,
|
||||
publisher.ClientId,
|
||||
progress.Activity,
|
||||
progress.StatusDescription,
|
||||
progress.PercentComplete,
|
||||
progress.SecondsRemaining,
|
||||
DateTimeOffset.UtcNow),
|
||||
jobTarget,
|
||||
correlationId,
|
||||
causationId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to publish progress for job {JobId}", jobId);
|
||||
}
|
||||
}
|
||||
|
||||
async Task PublishStateAsync(JobState state, int? exitCode, string? message)
|
||||
{
|
||||
await publisher.PublishAsync(
|
||||
NatsSubjects.JobState(jobId),
|
||||
MessageTypes.JobState,
|
||||
new JobStatePayload(jobId, publisher.ClientId, state, exitCode, DateTimeOffset.UtcNow, message),
|
||||
jobTarget,
|
||||
correlationId,
|
||||
causationId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using System.Management.Automation;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Agent.PowerShell;
|
||||
|
||||
/// <summary>One normalized record from any PowerShell stream.</summary>
|
||||
public sealed record NormalizedOutputRecord(OutputStreamKind Stream, string Text);
|
||||
|
||||
/// <summary>Normalized PowerShell progress record.</summary>
|
||||
public sealed record NormalizedProgressRecord(
|
||||
string Activity,
|
||||
string? StatusDescription,
|
||||
int? PercentComplete,
|
||||
int? SecondsRemaining);
|
||||
|
||||
/// <summary>Converts PowerShell stream objects into wire-friendly records.</summary>
|
||||
public static class PowerShellOutputNormalizer
|
||||
{
|
||||
public static NormalizedOutputRecord FromOutput(PSObject? value)
|
||||
=> new(OutputStreamKind.Output, ToText(value));
|
||||
|
||||
public static NormalizedOutputRecord FromError(ErrorRecord record)
|
||||
{
|
||||
var text = record.Exception?.Message ?? record.ToString();
|
||||
if (record.InvocationInfo?.PositionMessage is { Length: > 0 } position)
|
||||
{
|
||||
text = $"{text}{Environment.NewLine}{position}";
|
||||
}
|
||||
|
||||
return new NormalizedOutputRecord(OutputStreamKind.Error, text);
|
||||
}
|
||||
|
||||
public static NormalizedOutputRecord FromWarning(WarningRecord record)
|
||||
=> new(OutputStreamKind.Warning, record.Message);
|
||||
|
||||
public static NormalizedOutputRecord FromVerbose(VerboseRecord record)
|
||||
=> new(OutputStreamKind.Verbose, record.Message);
|
||||
|
||||
public static NormalizedOutputRecord FromDebug(DebugRecord record)
|
||||
=> new(OutputStreamKind.Debug, record.Message);
|
||||
|
||||
public static NormalizedOutputRecord FromInformation(InformationRecord record)
|
||||
=> new(OutputStreamKind.Information, record.MessageData?.ToString() ?? string.Empty);
|
||||
|
||||
public static NormalizedProgressRecord FromProgress(ProgressRecord record)
|
||||
=> new(
|
||||
Activity: record.Activity,
|
||||
StatusDescription: string.IsNullOrEmpty(record.StatusDescription) ? null : record.StatusDescription,
|
||||
PercentComplete: record.PercentComplete >= 0 ? record.PercentComplete : null,
|
||||
SecondsRemaining: record.SecondsRemaining >= 0 ? record.SecondsRemaining : null);
|
||||
|
||||
private static string ToText(PSObject? value)
|
||||
{
|
||||
if (value?.BaseObject is null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return value.ToString() ?? string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.Management.Automation.Runspaces;
|
||||
|
||||
namespace Agent.PowerShell;
|
||||
|
||||
/// <summary>Creates runspaces for in-process PowerShell execution (SDK-hosted, never powershell.exe).</summary>
|
||||
public static class PowerShellRunspaceFactory
|
||||
{
|
||||
public static Runspace Create()
|
||||
{
|
||||
var initialSessionState = InitialSessionState.CreateDefault();
|
||||
initialSessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass;
|
||||
|
||||
var runspace = RunspaceFactory.CreateRunspace(initialSessionState);
|
||||
runspace.Open();
|
||||
return runspace;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using System.Collections;
|
||||
using System.Text.Json;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Agent.PowerShell;
|
||||
|
||||
/// <summary>
|
||||
/// Coerces JSON argument values into CLR types matching each declared
|
||||
/// <see cref="ScriptParameter"/>, so PowerShell binds strongly typed values
|
||||
/// (string/number/bool/array/hashtable, with typed hashtable keys).
|
||||
/// </summary>
|
||||
public static class ScriptArgumentBinder
|
||||
{
|
||||
public static Dictionary<string, object?> Bind(
|
||||
IReadOnlyList<ScriptParameter>? parameters,
|
||||
IReadOnlyDictionary<string, JsonElement>? arguments)
|
||||
{
|
||||
var result = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
|
||||
if (parameters is null)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
foreach (var parameter in parameters)
|
||||
{
|
||||
JsonElement value;
|
||||
var hasValue = arguments is not null && arguments.TryGetValue(parameter.Name, out value);
|
||||
if (!hasValue)
|
||||
{
|
||||
if (parameter.DefaultValue is { } def && def.ValueKind is not JsonValueKind.Undefined)
|
||||
{
|
||||
value = def;
|
||||
}
|
||||
else
|
||||
{
|
||||
continue; // Let PowerShell apply its own default / prompt suppression.
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
value = arguments![parameter.Name];
|
||||
}
|
||||
|
||||
result[parameter.Name] = Convert(parameter, value);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static object? Convert(ScriptParameter parameter, JsonElement value)
|
||||
=> parameter.Type switch
|
||||
{
|
||||
ScriptParameterType.String => value.ValueKind == JsonValueKind.Null ? null : value.ToString(),
|
||||
ScriptParameterType.Number => ConvertNumber(value),
|
||||
ScriptParameterType.Boolean => ConvertBoolean(value),
|
||||
ScriptParameterType.Array => ConvertArray(parameter.ElementType ?? PrimitiveType.String, value),
|
||||
ScriptParameterType.Hashtable => ConvertHashtable(
|
||||
parameter.KeyType ?? PrimitiveType.String, parameter.ValueType ?? PrimitiveType.String, value),
|
||||
_ => value.ToString(),
|
||||
};
|
||||
|
||||
private static object? ConvertPrimitive(PrimitiveType type, JsonElement value) => type switch
|
||||
{
|
||||
PrimitiveType.Number => ConvertNumber(value),
|
||||
PrimitiveType.Boolean => ConvertBoolean(value),
|
||||
_ => value.ValueKind == JsonValueKind.Null ? null : value.ToString(),
|
||||
};
|
||||
|
||||
private static object? ConvertNumber(JsonElement value)
|
||||
{
|
||||
if (value.ValueKind == JsonValueKind.Number)
|
||||
{
|
||||
if (value.TryGetInt64(out var l))
|
||||
{
|
||||
return l is >= int.MinValue and <= int.MaxValue ? (int)l : l;
|
||||
}
|
||||
|
||||
return value.GetDouble();
|
||||
}
|
||||
|
||||
if (value.ValueKind == JsonValueKind.String && double.TryParse(value.GetString(), out var parsed))
|
||||
{
|
||||
return parsed == Math.Floor(parsed) && !double.IsInfinity(parsed) ? (long)parsed : parsed;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static bool ConvertBoolean(JsonElement value) => value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.True => true,
|
||||
JsonValueKind.False => false,
|
||||
JsonValueKind.String => bool.TryParse(value.GetString(), out var b) && b,
|
||||
JsonValueKind.Number => value.TryGetInt64(out var n) && n != 0,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static object?[] ConvertArray(PrimitiveType elementType, JsonElement value)
|
||||
{
|
||||
if (value.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var items = new List<object?>();
|
||||
foreach (var element in value.EnumerateArray())
|
||||
{
|
||||
items.Add(ConvertPrimitive(elementType, element));
|
||||
}
|
||||
|
||||
return items.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Accepts either a JSON object (string keys) or an array of
|
||||
/// <c>{ "key": ..., "value": ... }</c> pairs (typed keys) and returns a
|
||||
/// PowerShell <see cref="Hashtable"/> with coerced keys and values.
|
||||
/// </summary>
|
||||
private static Hashtable ConvertHashtable(PrimitiveType keyType, PrimitiveType valueType, JsonElement value)
|
||||
{
|
||||
var table = new Hashtable();
|
||||
|
||||
if (value.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (var property in value.EnumerateObject())
|
||||
{
|
||||
var key = ConvertPrimitiveKey(keyType, property.Name);
|
||||
if (key is not null)
|
||||
{
|
||||
table[key] = ConvertPrimitive(valueType, property.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (value.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var entry in value.EnumerateArray())
|
||||
{
|
||||
if (entry.ValueKind != JsonValueKind.Object
|
||||
|| !entry.TryGetProperty("key", out var keyElement)
|
||||
|| !entry.TryGetProperty("value", out var valueElement))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var key = ConvertPrimitive(keyType, keyElement);
|
||||
if (key is not null)
|
||||
{
|
||||
table[key] = ConvertPrimitive(valueType, valueElement);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
private static object? ConvertPrimitiveKey(PrimitiveType keyType, string rawKey)
|
||||
=> keyType switch
|
||||
{
|
||||
PrimitiveType.Number => long.TryParse(rawKey, out var l) ? l : rawKey,
|
||||
PrimitiveType.Boolean => bool.TryParse(rawKey, out var b) && b,
|
||||
_ => rawKey,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
using Agent.Commands;
|
||||
|
||||
return await AgentCli.RunAsync(args);
|
||||
@@ -0,0 +1,56 @@
|
||||
using Agent.Messaging;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shared.Contracts.Messages;
|
||||
using Shared.Infrastructure.Constants;
|
||||
using Shared.Infrastructure.Nats;
|
||||
using Shared.Infrastructure.Versioning;
|
||||
|
||||
namespace Agent.Progress;
|
||||
|
||||
/// <summary>Publishes the periodic presence heartbeat over Core NATS.</summary>
|
||||
public sealed class PresencePublisher(
|
||||
AgentPublisher publisher,
|
||||
Func<int> activeJobCounter,
|
||||
ILogger logger)
|
||||
{
|
||||
private static readonly string AgentVersion = BuildVersion.Resolve(typeof(PresencePublisher).Assembly);
|
||||
|
||||
public async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var subject = NatsSubjects.AgentPresence(publisher.ClientId);
|
||||
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var payload = new PresencePayload(
|
||||
ClientId: publisher.ClientId,
|
||||
Hostname: Environment.MachineName,
|
||||
AgentVersion: AgentVersion,
|
||||
Status: "online",
|
||||
TimestampUtc: DateTimeOffset.UtcNow,
|
||||
UptimeSeconds: Environment.TickCount64 / 1000,
|
||||
ActiveJobs: activeJobCounter());
|
||||
|
||||
await publisher.PublishAsync(subject, MessageTypes.AgentPresence, payload, cancellationToken: cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Presence publish failed; retrying on next interval");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(ProtocolDefaults.PresenceInterval, cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Agent.Configuration;
|
||||
using Agent.Enrollment;
|
||||
using Agent.Identity;
|
||||
using Agent.Storage;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using Shared.Infrastructure.Constants;
|
||||
using Shared.Infrastructure.Logging;
|
||||
|
||||
namespace Agent.Service;
|
||||
|
||||
/// <summary>Builds the Generic Host used for both foreground and service operation.</summary>
|
||||
public static class AgentHost
|
||||
{
|
||||
public static IHost Build(bool runAsService)
|
||||
{
|
||||
var settings = new HostApplicationBuilderSettings
|
||||
{
|
||||
// The SCM starts services with an arbitrary current directory.
|
||||
ContentRootPath = AppContext.BaseDirectory,
|
||||
};
|
||||
|
||||
var builder = Host.CreateApplicationBuilder(settings);
|
||||
|
||||
// Centralized Serilog: console + daily rolling file with retention.
|
||||
// Log level honors the agent's own configuration precedence
|
||||
// (GPO > registry > default) rather than only environment variables.
|
||||
var registry = new WindowsRegistryStore();
|
||||
var agentConfiguration = new AgentConfigurationLoader(registry, allowEnvironment: !runAsService).Load();
|
||||
|
||||
var logSettings = LogSettings.FromConfiguration(
|
||||
builder.Configuration,
|
||||
LogDefaults.Agent,
|
||||
defaultDirectory: Path.Combine(Branding.AgentProgramDataDirectory, "logs")) with
|
||||
{
|
||||
// The agent's level comes from its own precedence chain
|
||||
// (GPO > registry > default), not from the environment.
|
||||
Level = agentConfiguration.LogLevel.Value,
|
||||
};
|
||||
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Services.AddSerilog(LoggingSetup.CreateLogger(logSettings, "agent"), dispose: true);
|
||||
|
||||
if (runAsService)
|
||||
{
|
||||
builder.Services.AddWindowsService(options => options.ServiceName = Branding.AgentServiceName);
|
||||
}
|
||||
|
||||
builder.Services.AddSingleton<IRegistryStore, WindowsRegistryStore>();
|
||||
builder.Services.AddSingleton<RuntimeStateStore>();
|
||||
builder.Services.AddSingleton<CredentialStore>();
|
||||
builder.Services.AddSingleton<IHardwareIdentitySource, CimHardwareIdentitySource>();
|
||||
builder.Services.AddSingleton<EnrollmentService>();
|
||||
builder.Services.AddSingleton<Storage.JobHistoryStore>();
|
||||
builder.Services.AddSingleton<IAgentSessionFactory, AgentSessionFactory>();
|
||||
|
||||
// Environment variables are development-only and never apply in
|
||||
// service mode (and never override GPO in any mode).
|
||||
builder.Services.AddSingleton(new AgentConfigurationLoader(registry, allowEnvironment: !runAsService));
|
||||
|
||||
builder.Services.AddHostedService<AgentWorker>();
|
||||
|
||||
return builder.Build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using Agent.Commands;
|
||||
using Agent.Configuration;
|
||||
using Agent.Enrollment;
|
||||
using Agent.Files;
|
||||
using Agent.Identity;
|
||||
using Agent.Inventory;
|
||||
using Agent.Messaging;
|
||||
using Agent.PowerShell;
|
||||
using Agent.Progress;
|
||||
using Agent.Shell;
|
||||
using Agent.Storage;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NATS.Client.Core;
|
||||
|
||||
namespace Agent.Service;
|
||||
|
||||
/// <summary>Creates the per-connection agent session.</summary>
|
||||
public interface IAgentSessionFactory
|
||||
{
|
||||
IAgentSession Create(NatsConnection connection, AgentCredentials credentials, AgentConfiguration configuration);
|
||||
}
|
||||
|
||||
/// <summary>One logical session bound to a connected NATS client.</summary>
|
||||
public interface IAgentSession
|
||||
{
|
||||
Task RunAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class AgentSessionFactory(
|
||||
IHardwareIdentitySource hardwareIdentity,
|
||||
JobHistoryStore jobHistory,
|
||||
ILoggerFactory loggerFactory) : IAgentSessionFactory
|
||||
{
|
||||
public IAgentSession Create(NatsConnection connection, AgentCredentials credentials, AgentConfiguration configuration)
|
||||
=> new AgentSession(connection, credentials, configuration, hardwareIdentity, jobHistory, loggerFactory);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the concurrent per-connection components: presence heartbeat,
|
||||
/// inventory publishing and durable command processing.
|
||||
/// </summary>
|
||||
public sealed class AgentSession : IAgentSession
|
||||
{
|
||||
private readonly PresencePublisher presence;
|
||||
private readonly InventoryPublisher inventory;
|
||||
private readonly CommandProcessor commands;
|
||||
private readonly ShellCommandListener shell;
|
||||
private readonly ILogger<AgentSession> logger;
|
||||
private readonly AgentCredentials credentials;
|
||||
private readonly AgentConfiguration configuration;
|
||||
|
||||
public AgentSession(
|
||||
NatsConnection connection,
|
||||
AgentCredentials credentials,
|
||||
AgentConfiguration configuration,
|
||||
IHardwareIdentitySource hardwareIdentity,
|
||||
JobHistoryStore jobHistory,
|
||||
ILoggerFactory loggerFactory)
|
||||
{
|
||||
this.credentials = credentials;
|
||||
this.configuration = configuration;
|
||||
logger = loggerFactory.CreateLogger<AgentSession>();
|
||||
|
||||
var publisher = new AgentPublisher(connection, credentials.ClientId);
|
||||
var collector = new InventoryCollector(hardwareIdentity);
|
||||
var executionService = new PowerShellExecutionService();
|
||||
var jobHandler = new PowerShellJobHandler(
|
||||
executionService, publisher, jobHistory, loggerFactory.CreateLogger<PowerShellJobHandler>());
|
||||
var fileHandler = new FileDownloadHandler(publisher, jobHistory, loggerFactory.CreateLogger<FileDownloadHandler>());
|
||||
|
||||
presence = new PresencePublisher(
|
||||
publisher, () => jobHandler.ActiveJobs, loggerFactory.CreateLogger<PresencePublisher>());
|
||||
inventory = new InventoryPublisher(
|
||||
collector, publisher, configuration.InventoryInterval.Value, loggerFactory.CreateLogger<InventoryPublisher>());
|
||||
commands = new CommandProcessor(
|
||||
connection, publisher, inventory, jobHandler, fileHandler, jobHistory, configuration,
|
||||
loggerFactory.CreateLogger<CommandProcessor>());
|
||||
shell = new ShellCommandListener(
|
||||
connection, publisher, configuration, loggerFactory.CreateLogger<ShellCommandListener>());
|
||||
}
|
||||
|
||||
public async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Session started for client {ClientId} (remote shell {RemoteShell}, script execution {ScriptExecution})",
|
||||
credentials.ClientId,
|
||||
configuration.AllowRemoteShell.Value ? "enabled" : "disabled",
|
||||
configuration.AllowScriptExecution.Value ? "enabled" : "disabled");
|
||||
|
||||
// Inventory publishes immediately (enrollment/reconnect), then on interval.
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(
|
||||
presence.RunAsync(cancellationToken),
|
||||
inventory.RunAsync(cancellationToken),
|
||||
commands.RunAsync(cancellationToken),
|
||||
shell.RunAsync(cancellationToken));
|
||||
}
|
||||
finally
|
||||
{
|
||||
shell.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using Agent.Configuration;
|
||||
using Agent.Enrollment;
|
||||
using Agent.Messaging;
|
||||
using Agent.Storage;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NATS.Client.Core;
|
||||
using Shared.Infrastructure.Versioning;
|
||||
|
||||
namespace Agent.Service;
|
||||
|
||||
/// <summary>
|
||||
/// Root background worker: loads configuration, ensures enrollment, keeps a
|
||||
/// resilient NATS-over-WebSocket connection and runs the agent session
|
||||
/// (presence, inventory, command handling) on top of it.
|
||||
/// </summary>
|
||||
public sealed class AgentWorker(
|
||||
AgentConfigurationLoader configurationLoader,
|
||||
EnrollmentService enrollment,
|
||||
RuntimeStateStore runtimeState,
|
||||
IAgentSessionFactory sessionFactory,
|
||||
ILoggerFactory loggerFactory,
|
||||
ILogger<AgentWorker> logger) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
logger.LogInformation("Agent {Version} starting", BuildVersion.Resolve(typeof(AgentWorker).Assembly));
|
||||
|
||||
var retryDelay = TimeSpan.FromSeconds(10);
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Reload configuration every cycle so registry/GPO changes
|
||||
// (e.g. a newly written bootstrap token) are picked up.
|
||||
var configuration = configurationLoader.Load();
|
||||
|
||||
var credentials = await enrollment.EnsureEnrolledAsync(configuration, stoppingToken);
|
||||
if (credentials is null || configuration.ServerUrl is null)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
|
||||
continue;
|
||||
}
|
||||
|
||||
var opts = AgentNatsOptionsFactory.Build(configuration.ServerUrl, credentials, configuration, loggerFactory);
|
||||
|
||||
await using var nats = new NatsConnection(opts);
|
||||
|
||||
nats.ConnectionOpened += (_, _) =>
|
||||
{
|
||||
logger.LogInformation("NATS connected to {Url}", opts.Url);
|
||||
runtimeState.LastConnectedUtc = DateTimeOffset.UtcNow;
|
||||
return default;
|
||||
};
|
||||
nats.ConnectionDisconnected += (_, _) =>
|
||||
{
|
||||
logger.LogWarning("NATS disconnected; automatic reconnect in progress");
|
||||
return default;
|
||||
};
|
||||
nats.ReconnectFailed += (_, _) =>
|
||||
{
|
||||
logger.LogWarning("NATS reconnect attempt failed; will retry with backoff");
|
||||
return default;
|
||||
};
|
||||
|
||||
await nats.ConnectAsync();
|
||||
|
||||
var session = sessionFactory.Create(nats, credentials, configuration);
|
||||
await session.RunAsync(stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Agent session failed; restarting in {Delay}", retryDelay);
|
||||
try
|
||||
{
|
||||
await Task.Delay(retryDelay, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogInformation("Agent stopping");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Agent.Service;
|
||||
|
||||
/// <summary>
|
||||
/// Minimal advapi32 service-control interop for install/update/remove.
|
||||
/// Start/stop/query use <see cref="System.ServiceProcess.ServiceController"/>.
|
||||
/// </summary>
|
||||
internal static partial class ServiceControlApi
|
||||
{
|
||||
internal const uint SC_MANAGER_ALL_ACCESS = 0xF003F;
|
||||
internal const uint SERVICE_ALL_ACCESS = 0xF01FF;
|
||||
internal const uint SERVICE_WIN32_OWN_PROCESS = 0x10;
|
||||
internal const uint SERVICE_AUTO_START = 0x2;
|
||||
internal const uint SERVICE_ERROR_NORMAL = 0x1;
|
||||
internal const uint SERVICE_NO_CHANGE = 0xFFFFFFFF;
|
||||
|
||||
internal const int SERVICE_CONFIG_DESCRIPTION = 1;
|
||||
internal const int SERVICE_CONFIG_FAILURE_ACTIONS = 2;
|
||||
internal const int SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 3;
|
||||
|
||||
internal const int SC_ACTION_RESTART = 1;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
internal struct SERVICE_DESCRIPTION
|
||||
{
|
||||
public string lpDescription;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct SERVICE_DELAYED_AUTO_START_INFO
|
||||
{
|
||||
public bool fDelayedAutostart;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct SC_ACTION
|
||||
{
|
||||
public int Type;
|
||||
public uint Delay;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
internal struct SERVICE_FAILURE_ACTIONS
|
||||
{
|
||||
public uint dwResetPeriod;
|
||||
public string? lpRebootMsg;
|
||||
public string? lpCommand;
|
||||
public uint cActions;
|
||||
public IntPtr lpsaActions;
|
||||
}
|
||||
|
||||
[LibraryImport("advapi32.dll", EntryPoint = "OpenSCManagerW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)]
|
||||
internal static partial IntPtr OpenSCManager(string? machineName, string? databaseName, uint access);
|
||||
|
||||
[LibraryImport("advapi32.dll", EntryPoint = "OpenServiceW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)]
|
||||
internal static partial IntPtr OpenService(IntPtr scManager, string serviceName, uint access);
|
||||
|
||||
[LibraryImport("advapi32.dll", EntryPoint = "CreateServiceW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)]
|
||||
internal static partial IntPtr CreateService(
|
||||
IntPtr scManager,
|
||||
string serviceName,
|
||||
string displayName,
|
||||
uint desiredAccess,
|
||||
uint serviceType,
|
||||
uint startType,
|
||||
uint errorControl,
|
||||
string binaryPathName,
|
||||
string? loadOrderGroup,
|
||||
IntPtr tagId,
|
||||
string? dependencies,
|
||||
string? serviceStartName,
|
||||
string? password);
|
||||
|
||||
[LibraryImport("advapi32.dll", EntryPoint = "ChangeServiceConfigW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool ChangeServiceConfig(
|
||||
IntPtr service,
|
||||
uint serviceType,
|
||||
uint startType,
|
||||
uint errorControl,
|
||||
string? binaryPathName,
|
||||
string? loadOrderGroup,
|
||||
IntPtr tagId,
|
||||
string? dependencies,
|
||||
string? serviceStartName,
|
||||
string? password,
|
||||
string? displayName);
|
||||
|
||||
[DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2W", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static extern bool ChangeServiceConfig2(IntPtr service, int infoLevel, ref SERVICE_DESCRIPTION info);
|
||||
|
||||
[DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2W", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static extern bool ChangeServiceConfig2(IntPtr service, int infoLevel, ref SERVICE_DELAYED_AUTO_START_INFO info);
|
||||
|
||||
[DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2W", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static extern bool ChangeServiceConfig2(IntPtr service, int infoLevel, ref SERVICE_FAILURE_ACTIONS info);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool DeleteService(IntPtr service);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool CloseServiceHandle(IntPtr handle);
|
||||
|
||||
internal static Win32Exception LastError(string operation)
|
||||
=> new(Marshal.GetLastPInvokeError(), $"{operation} failed");
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.ServiceProcess;
|
||||
using Shared.Infrastructure.Constants;
|
||||
using static Agent.Service.ServiceControlApi;
|
||||
|
||||
namespace Agent.Service;
|
||||
|
||||
/// <summary>
|
||||
/// Idempotent Windows service lifecycle operations using Windows APIs
|
||||
/// (never sc.exe). Install creates or updates the registration, sets
|
||||
/// Automatic (Delayed Start), description, and a restart recovery policy.
|
||||
/// </summary>
|
||||
public static class ServiceLifecycle
|
||||
{
|
||||
private static readonly TimeSpan StateChangeTimeout = TimeSpan.FromSeconds(60);
|
||||
private static readonly TimeSpan RecoveryRestartDelay = TimeSpan.FromSeconds(30);
|
||||
|
||||
public static int Install()
|
||||
{
|
||||
var binaryPath = $"\"{Environment.ProcessPath ?? throw new InvalidOperationException("Cannot determine executable path.")}\"";
|
||||
|
||||
var scm = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);
|
||||
if (scm == IntPtr.Zero)
|
||||
{
|
||||
throw LastError("OpenSCManager (administrator rights required)");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var service = OpenService(scm, Branding.AgentServiceName, SERVICE_ALL_ACCESS);
|
||||
if (service == IntPtr.Zero)
|
||||
{
|
||||
service = CreateService(
|
||||
scm,
|
||||
Branding.AgentServiceName,
|
||||
Branding.AgentServiceDisplayName,
|
||||
SERVICE_ALL_ACCESS,
|
||||
SERVICE_WIN32_OWN_PROCESS,
|
||||
SERVICE_AUTO_START,
|
||||
SERVICE_ERROR_NORMAL,
|
||||
binaryPath,
|
||||
loadOrderGroup: null,
|
||||
tagId: IntPtr.Zero,
|
||||
dependencies: null,
|
||||
serviceStartName: null, // LocalSystem
|
||||
password: null);
|
||||
|
||||
if (service == IntPtr.Zero)
|
||||
{
|
||||
throw LastError("CreateService");
|
||||
}
|
||||
|
||||
Console.WriteLine($"Service '{Branding.AgentServiceName}' created.");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Update binary path/display name in case the binary moved.
|
||||
if (!ChangeServiceConfig(
|
||||
service,
|
||||
SERVICE_WIN32_OWN_PROCESS,
|
||||
SERVICE_AUTO_START,
|
||||
SERVICE_ERROR_NORMAL,
|
||||
binaryPath,
|
||||
loadOrderGroup: null,
|
||||
tagId: IntPtr.Zero,
|
||||
dependencies: null,
|
||||
serviceStartName: null,
|
||||
password: null,
|
||||
Branding.AgentServiceDisplayName))
|
||||
{
|
||||
throw LastError("ChangeServiceConfig");
|
||||
}
|
||||
|
||||
Console.WriteLine($"Service '{Branding.AgentServiceName}' updated.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
ApplyMetadata(service);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseServiceHandle(service);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseServiceHandle(scm);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ApplyMetadata(IntPtr service)
|
||||
{
|
||||
var description = new SERVICE_DESCRIPTION { lpDescription = Branding.AgentServiceDescription };
|
||||
if (!ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, ref description))
|
||||
{
|
||||
throw LastError("ChangeServiceConfig2(description)");
|
||||
}
|
||||
|
||||
var delayed = new SERVICE_DELAYED_AUTO_START_INFO { fDelayedAutostart = true };
|
||||
if (!ChangeServiceConfig2(service, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, ref delayed))
|
||||
{
|
||||
throw LastError("ChangeServiceConfig2(delayed auto start)");
|
||||
}
|
||||
|
||||
// Recovery: restart on first, second and subsequent failures.
|
||||
var actions = new SC_ACTION[]
|
||||
{
|
||||
new() { Type = SC_ACTION_RESTART, Delay = (uint)RecoveryRestartDelay.TotalMilliseconds },
|
||||
new() { Type = SC_ACTION_RESTART, Delay = (uint)RecoveryRestartDelay.TotalMilliseconds },
|
||||
new() { Type = SC_ACTION_RESTART, Delay = (uint)RecoveryRestartDelay.TotalMilliseconds },
|
||||
};
|
||||
|
||||
var actionsPtr = Marshal.AllocHGlobal(Marshal.SizeOf<SC_ACTION>() * actions.Length);
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < actions.Length; i++)
|
||||
{
|
||||
Marshal.StructureToPtr(actions[i], actionsPtr + i * Marshal.SizeOf<SC_ACTION>(), false);
|
||||
}
|
||||
|
||||
var failureActions = new SERVICE_FAILURE_ACTIONS
|
||||
{
|
||||
dwResetPeriod = (uint)TimeSpan.FromDays(1).TotalSeconds,
|
||||
lpRebootMsg = null,
|
||||
lpCommand = null,
|
||||
cActions = (uint)actions.Length,
|
||||
lpsaActions = actionsPtr,
|
||||
};
|
||||
|
||||
if (!ChangeServiceConfig2(service, SERVICE_CONFIG_FAILURE_ACTIONS, ref failureActions))
|
||||
{
|
||||
throw LastError("ChangeServiceConfig2(failure actions)");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(actionsPtr);
|
||||
}
|
||||
}
|
||||
|
||||
public static int Remove()
|
||||
{
|
||||
if (!Exists())
|
||||
{
|
||||
Console.WriteLine($"Service '{Branding.AgentServiceName}' is not installed.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
Stop();
|
||||
|
||||
var scm = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);
|
||||
if (scm == IntPtr.Zero)
|
||||
{
|
||||
throw LastError("OpenSCManager (administrator rights required)");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var service = OpenService(scm, Branding.AgentServiceName, SERVICE_ALL_ACCESS);
|
||||
if (service == IntPtr.Zero)
|
||||
{
|
||||
Console.WriteLine($"Service '{Branding.AgentServiceName}' is not installed.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (!DeleteService(service))
|
||||
{
|
||||
throw LastError("DeleteService");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseServiceHandle(service);
|
||||
}
|
||||
|
||||
Console.WriteLine($"Service '{Branding.AgentServiceName}' removed.");
|
||||
return 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseServiceHandle(scm);
|
||||
}
|
||||
}
|
||||
|
||||
public static int Start()
|
||||
{
|
||||
if (!Exists())
|
||||
{
|
||||
Console.Error.WriteLine($"Service '{Branding.AgentServiceName}' is not installed.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
using var controller = new ServiceController(Branding.AgentServiceName);
|
||||
if (controller.Status is ServiceControllerStatus.Running)
|
||||
{
|
||||
Console.WriteLine("Service is already running.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (controller.Status is not ServiceControllerStatus.StartPending)
|
||||
{
|
||||
controller.Start();
|
||||
}
|
||||
|
||||
controller.WaitForStatus(ServiceControllerStatus.Running, StateChangeTimeout);
|
||||
Console.WriteLine("Service started.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int Stop()
|
||||
{
|
||||
if (!Exists())
|
||||
{
|
||||
Console.WriteLine($"Service '{Branding.AgentServiceName}' is not installed.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
using var controller = new ServiceController(Branding.AgentServiceName);
|
||||
if (controller.Status is ServiceControllerStatus.Stopped)
|
||||
{
|
||||
Console.WriteLine("Service is already stopped.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (controller.CanStop)
|
||||
{
|
||||
controller.Stop();
|
||||
}
|
||||
|
||||
controller.WaitForStatus(ServiceControllerStatus.Stopped, StateChangeTimeout);
|
||||
Console.WriteLine("Service stopped.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int Status()
|
||||
{
|
||||
string state;
|
||||
var installed = Exists();
|
||||
if (installed)
|
||||
{
|
||||
using var controller = new ServiceController(Branding.AgentServiceName);
|
||||
state = controller.Status.ToString();
|
||||
}
|
||||
else
|
||||
{
|
||||
state = "NotInstalled";
|
||||
}
|
||||
|
||||
// Machine-readable line first, human-readable after.
|
||||
Console.WriteLine($"{{\"service\":\"{Branding.AgentServiceName}\",\"installed\":{(installed ? "true" : "false")},\"state\":\"{state}\"}}");
|
||||
Console.WriteLine($"Service '{Branding.AgentServiceDisplayName}': {state}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static bool Exists()
|
||||
=> ServiceController.GetServices().Any(s =>
|
||||
string.Equals(s.ServiceName, Branding.AgentServiceName, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Agent.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// Win32 Pseudoconsole (ConPTY) + process-creation interop. ConPTY ships in
|
||||
/// all supported modern Windows versions, so no WinPTY fallback is bundled.
|
||||
/// </summary>
|
||||
internal static partial class ConPtyInterop
|
||||
{
|
||||
internal const int STARTF_USESTDHANDLES = 0x00000100;
|
||||
internal const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
|
||||
internal const int PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE = 0x00020016;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct COORD
|
||||
{
|
||||
public short X;
|
||||
public short Y;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct STARTUPINFOEX
|
||||
{
|
||||
public STARTUPINFO StartupInfo;
|
||||
public IntPtr lpAttributeList;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
internal struct STARTUPINFO
|
||||
{
|
||||
public int cb;
|
||||
public string? lpReserved;
|
||||
public string? lpDesktop;
|
||||
public string? lpTitle;
|
||||
public int dwX;
|
||||
public int dwY;
|
||||
public int dwXSize;
|
||||
public int dwYSize;
|
||||
public int dwXCountChars;
|
||||
public int dwYCountChars;
|
||||
public int dwFillAttribute;
|
||||
public int dwFlags;
|
||||
public short wShowWindow;
|
||||
public short cbReserved2;
|
||||
public IntPtr lpReserved2;
|
||||
public IntPtr hStdInput;
|
||||
public IntPtr hStdOutput;
|
||||
public IntPtr hStdError;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct PROCESS_INFORMATION
|
||||
{
|
||||
public IntPtr hProcess;
|
||||
public IntPtr hThread;
|
||||
public int dwProcessId;
|
||||
public int dwThreadId;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct SECURITY_ATTRIBUTES
|
||||
{
|
||||
public int nLength;
|
||||
public IntPtr lpSecurityDescriptor;
|
||||
public int bInheritHandle;
|
||||
}
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
internal static partial int CreatePseudoConsole(COORD size, IntPtr hInput, IntPtr hOutput, uint dwFlags, out IntPtr phPC);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
internal static partial int ResizePseudoConsole(IntPtr hPC, COORD size);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
internal static partial void ClosePseudoConsole(IntPtr hPC);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool CreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, IntPtr lpPipeAttributes, int nSize);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool CloseHandle(IntPtr hObject);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||
internal static extern bool CreateProcessW(
|
||||
string? lpApplicationName,
|
||||
string lpCommandLine,
|
||||
IntPtr lpProcessAttributes,
|
||||
IntPtr lpThreadAttributes,
|
||||
[MarshalAs(UnmanagedType.Bool)] bool bInheritHandles,
|
||||
uint dwCreationFlags,
|
||||
IntPtr lpEnvironment,
|
||||
string? lpCurrentDirectory,
|
||||
ref STARTUPINFOEX lpStartupInfo,
|
||||
out PROCESS_INFORMATION lpProcessInformation);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool InitializeProcThreadAttributeList(
|
||||
IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
internal static extern bool UpdateProcThreadAttribute(
|
||||
IntPtr lpAttributeList, uint dwFlags, IntPtr attribute, IntPtr lpValue,
|
||||
IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool DeleteProcThreadAttributeList(IntPtr lpAttributeList);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
internal static partial uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool TerminateProcess(IntPtr hProcess, uint uExitCode);
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using static Agent.Shell.ConPtyInterop;
|
||||
|
||||
namespace Agent.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// A live ConPTY-backed shell process. Terminal output is delivered via
|
||||
/// <see cref="OutputReceived"/>; input is written with <see cref="Write"/>.
|
||||
/// </summary>
|
||||
public sealed class ConPtySession : IDisposable
|
||||
{
|
||||
private IntPtr pseudoConsole = IntPtr.Zero;
|
||||
private IntPtr attributeList = IntPtr.Zero;
|
||||
private PROCESS_INFORMATION processInfo;
|
||||
|
||||
private SafeFileHandle? inputWriteHandle;
|
||||
private FileStream? inputStream;
|
||||
private FileStream? outputStream;
|
||||
|
||||
private readonly CancellationTokenSource lifetime = new();
|
||||
private bool disposed;
|
||||
|
||||
/// <summary>Raised with raw terminal output bytes as they arrive.</summary>
|
||||
public event Action<ReadOnlyMemory<byte>>? OutputReceived;
|
||||
|
||||
/// <summary>Raised when the shell process exits.</summary>
|
||||
public event Action? Exited;
|
||||
|
||||
public void Start(string commandLine, int cols, int rows)
|
||||
{
|
||||
// Two pipes: one the PTY reads input from, one it writes output to.
|
||||
if (!CreatePipe(out var inputRead, out var inputWrite, IntPtr.Zero, 0))
|
||||
{
|
||||
throw new InvalidOperationException("CreatePipe(input) failed.");
|
||||
}
|
||||
|
||||
if (!CreatePipe(out var outputRead, out var outputWrite, IntPtr.Zero, 0))
|
||||
{
|
||||
throw new InvalidOperationException("CreatePipe(output) failed.");
|
||||
}
|
||||
|
||||
var size = new COORD { X = (short)Math.Clamp(cols, 1, short.MaxValue), Y = (short)Math.Clamp(rows, 1, short.MaxValue) };
|
||||
var hr = CreatePseudoConsole(size, inputRead, outputWrite, 0, out pseudoConsole);
|
||||
if (hr != 0)
|
||||
{
|
||||
throw new InvalidOperationException($"CreatePseudoConsole failed (HRESULT 0x{hr:X8}).");
|
||||
}
|
||||
|
||||
// The PTY owns these ends now.
|
||||
CloseHandle(inputRead);
|
||||
CloseHandle(outputWrite);
|
||||
|
||||
inputWriteHandle = new SafeFileHandle(inputWrite, ownsHandle: true);
|
||||
inputStream = new FileStream(inputWriteHandle, FileAccess.Write);
|
||||
outputStream = new FileStream(new SafeFileHandle(outputRead, ownsHandle: true), FileAccess.Read);
|
||||
|
||||
StartProcess(commandLine);
|
||||
|
||||
_ = Task.Run(PumpOutputAsync);
|
||||
_ = Task.Run(WatchProcessAsync);
|
||||
}
|
||||
|
||||
private void StartProcess(string commandLine)
|
||||
{
|
||||
var startupInfo = new STARTUPINFOEX();
|
||||
startupInfo.StartupInfo.cb = Marshal.SizeOf<STARTUPINFOEX>();
|
||||
|
||||
var size = IntPtr.Zero;
|
||||
InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref size);
|
||||
attributeList = Marshal.AllocHGlobal(size);
|
||||
startupInfo.lpAttributeList = attributeList;
|
||||
|
||||
if (!InitializeProcThreadAttributeList(attributeList, 1, 0, ref size))
|
||||
{
|
||||
throw new InvalidOperationException("InitializeProcThreadAttributeList failed.");
|
||||
}
|
||||
|
||||
if (!UpdateProcThreadAttribute(
|
||||
attributeList, 0, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
|
||||
pseudoConsole, IntPtr.Size, IntPtr.Zero, IntPtr.Zero))
|
||||
{
|
||||
throw new InvalidOperationException("UpdateProcThreadAttribute failed.");
|
||||
}
|
||||
|
||||
if (!CreateProcessW(
|
||||
lpApplicationName: null,
|
||||
lpCommandLine: commandLine,
|
||||
lpProcessAttributes: IntPtr.Zero,
|
||||
lpThreadAttributes: IntPtr.Zero,
|
||||
bInheritHandles: false,
|
||||
dwCreationFlags: EXTENDED_STARTUPINFO_PRESENT,
|
||||
lpEnvironment: IntPtr.Zero,
|
||||
lpCurrentDirectory: null,
|
||||
lpStartupInfo: ref startupInfo,
|
||||
lpProcessInformation: out processInfo))
|
||||
{
|
||||
throw new InvalidOperationException($"CreateProcess failed (Win32 {Marshal.GetLastWin32Error()}).");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PumpOutputAsync()
|
||||
{
|
||||
var buffer = new byte[4096];
|
||||
try
|
||||
{
|
||||
while (!lifetime.IsCancellationRequested)
|
||||
{
|
||||
var read = await outputStream!.ReadAsync(buffer, lifetime.Token);
|
||||
if (read == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
OutputReceived?.Invoke(buffer.AsMemory(0, read).ToArray());
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Pipe closed on shutdown.
|
||||
}
|
||||
}
|
||||
|
||||
private async Task WatchProcessAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!lifetime.IsCancellationRequested)
|
||||
{
|
||||
if (WaitForSingleObject(processInfo.hProcess, 250) == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
await Task.Delay(50, lifetime.Token);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Exited?.Invoke();
|
||||
}
|
||||
|
||||
public async Task WriteAsync(ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
|
||||
{
|
||||
if (inputStream is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await inputStream.WriteAsync(data, cancellationToken);
|
||||
await inputStream.FlushAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public void Resize(int cols, int rows)
|
||||
{
|
||||
if (pseudoConsole != IntPtr.Zero)
|
||||
{
|
||||
ResizePseudoConsole(pseudoConsole, new COORD
|
||||
{
|
||||
X = (short)Math.Clamp(cols, 1, short.MaxValue),
|
||||
Y = (short)Math.Clamp(rows, 1, short.MaxValue),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
disposed = true;
|
||||
lifetime.Cancel();
|
||||
|
||||
if (pseudoConsole != IntPtr.Zero)
|
||||
{
|
||||
ClosePseudoConsole(pseudoConsole);
|
||||
pseudoConsole = IntPtr.Zero;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
inputStream?.Dispose();
|
||||
outputStream?.Dispose();
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// Pipe already closed.
|
||||
}
|
||||
|
||||
if (processInfo.hProcess != IntPtr.Zero)
|
||||
{
|
||||
if (WaitForSingleObject(processInfo.hProcess, 0) != 0)
|
||||
{
|
||||
TerminateProcess(processInfo.hProcess, 0);
|
||||
}
|
||||
|
||||
CloseHandle(processInfo.hThread);
|
||||
CloseHandle(processInfo.hProcess);
|
||||
}
|
||||
|
||||
if (attributeList != IntPtr.Zero)
|
||||
{
|
||||
DeleteProcThreadAttributeList(attributeList);
|
||||
Marshal.FreeHGlobal(attributeList);
|
||||
attributeList = IntPtr.Zero;
|
||||
}
|
||||
|
||||
lifetime.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using Agent.Configuration;
|
||||
using Agent.Messaging;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NATS.Client.Core;
|
||||
using Shared.Contracts.Messages;
|
||||
using Shared.Infrastructure.Nats;
|
||||
|
||||
namespace Agent.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes to Core NATS shell commands (open/input/resize/close) and drives
|
||||
/// the <see cref="ShellManager"/>. Shell traffic stays on Core NATS — never
|
||||
/// JetStream. Honors the AllowRemoteShell policy.
|
||||
/// </summary>
|
||||
public sealed class ShellCommandListener(
|
||||
NatsConnection connection,
|
||||
AgentPublisher publisher,
|
||||
AgentConfiguration configuration,
|
||||
ILogger logger) : IDisposable
|
||||
{
|
||||
private readonly ShellManager manager = new(publisher, logger);
|
||||
|
||||
public async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!configuration.AllowRemoteShell.Value)
|
||||
{
|
||||
logger.LogInformation("Remote shell disabled by policy; not listening for shell commands");
|
||||
return;
|
||||
}
|
||||
|
||||
// command.shell.open | command.shell.input | command.shell.resize | command.shell.close
|
||||
var subject = $"agent.{publisher.ClientId}.command.shell.*";
|
||||
|
||||
await foreach (var msg in connection.SubscribeAsync<byte[]>(subject, cancellationToken: cancellationToken))
|
||||
{
|
||||
if (msg.Data is null || msg.Data.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await HandleAsync(MessageEnvelope.FromUtf8Bytes(msg.Data), cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to handle shell command on {Subject}", msg.Subject);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleAsync(MessageEnvelope? envelope, CancellationToken cancellationToken)
|
||||
{
|
||||
if (envelope is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
switch (envelope.MessageType)
|
||||
{
|
||||
case MessageTypes.CommandShellOpen:
|
||||
var open = envelope.GetPayload<ShellOpenCommandPayload>();
|
||||
if (open is not null)
|
||||
{
|
||||
manager.Open(open, cancellationToken);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case MessageTypes.CommandShellInput:
|
||||
var input = envelope.GetPayload<ShellInputPayload>();
|
||||
if (input is not null)
|
||||
{
|
||||
await manager.WriteAsync(input, cancellationToken);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case MessageTypes.CommandShellResize:
|
||||
var resize = envelope.GetPayload<ShellResizePayload>();
|
||||
if (resize is not null)
|
||||
{
|
||||
manager.Resize(resize);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case MessageTypes.CommandShellClose:
|
||||
var close = envelope.GetPayload<ShellClosePayload>();
|
||||
if (close is not null)
|
||||
{
|
||||
manager.Close(close.SessionId, close.Reason ?? "closed by backend");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => manager.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
using Agent.Messaging;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shared.Contracts.Messages;
|
||||
using Shared.Contracts.Models;
|
||||
using Shared.Infrastructure.Constants;
|
||||
using Shared.Infrastructure.Nats;
|
||||
|
||||
namespace Agent.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// Manages interactive ConPTY shell sessions for one agent. MVP allows a
|
||||
/// single active session per device; opening a new one closes the previous.
|
||||
/// Output is published as base64 over Core NATS with a monotonic sequence.
|
||||
/// </summary>
|
||||
public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDisposable
|
||||
{
|
||||
private readonly Lock gate = new();
|
||||
private ActiveShell? current;
|
||||
|
||||
private sealed class ActiveShell
|
||||
{
|
||||
public required Guid SessionId { get; init; }
|
||||
public required ConPtySession Pty { get; init; }
|
||||
public required Timer IdleTimer { get; init; }
|
||||
public required Timer MaxLifetimeTimer { get; init; }
|
||||
public long Sequence;
|
||||
public DateTimeOffset LastActivityUtc = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
public void Open(ShellOpenCommandPayload command, CancellationToken cancellationToken)
|
||||
{
|
||||
CloseCurrent("superseded by new session");
|
||||
|
||||
var shell = ResolveShellCommand();
|
||||
var pty = new ConPtySession();
|
||||
Guid sessionId = command.SessionId;
|
||||
|
||||
var active = new ActiveShell
|
||||
{
|
||||
SessionId = sessionId,
|
||||
Pty = pty,
|
||||
IdleTimer = new Timer(_ => OnIdleTimeout(sessionId), null, ProtocolDefaults.ShellIdleTimeout, Timeout.InfiniteTimeSpan),
|
||||
MaxLifetimeTimer = new Timer(_ => OnMaxLifetime(sessionId), null, ProtocolDefaults.ShellMaxLifetime, Timeout.InfiniteTimeSpan),
|
||||
};
|
||||
|
||||
pty.OutputReceived += data => PublishOutput(active, data);
|
||||
pty.Exited += () => Close(sessionId, "shell process exited");
|
||||
|
||||
lock (gate)
|
||||
{
|
||||
current = active;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
pty.Start(shell, Math.Max(command.Cols, 1), Math.Max(command.Rows, 1));
|
||||
PublishState(sessionId, ShellSessionState.Open, null);
|
||||
logger.LogInformation("Shell session {SessionId} opened ({Shell})", sessionId, shell);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to open shell session {SessionId}", sessionId);
|
||||
PublishState(sessionId, ShellSessionState.Failed, ex.Message);
|
||||
Close(sessionId, "open failed");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task WriteAsync(ShellInputPayload input, CancellationToken cancellationToken)
|
||||
{
|
||||
ActiveShell? active;
|
||||
lock (gate)
|
||||
{
|
||||
active = current?.SessionId == input.SessionId ? current : null;
|
||||
}
|
||||
|
||||
if (active is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
active.LastActivityUtc = DateTimeOffset.UtcNow;
|
||||
active.IdleTimer.Change(ProtocolDefaults.ShellIdleTimeout, Timeout.InfiniteTimeSpan);
|
||||
|
||||
try
|
||||
{
|
||||
var bytes = Convert.FromBase64String(input.DataBase64);
|
||||
await active.Pty.WriteAsync(bytes, cancellationToken);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
logger.LogWarning("Discarded malformed shell input for {SessionId}", input.SessionId);
|
||||
}
|
||||
}
|
||||
|
||||
public void Resize(ShellResizePayload resize)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
if (current?.SessionId == resize.SessionId)
|
||||
{
|
||||
current.Pty.Resize(resize.Cols, resize.Rows);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Close(Guid sessionId, string reason)
|
||||
{
|
||||
ActiveShell? active;
|
||||
lock (gate)
|
||||
{
|
||||
if (current?.SessionId != sessionId)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
active = current;
|
||||
current = null;
|
||||
}
|
||||
|
||||
DisposeShell(active, reason);
|
||||
PublishState(sessionId, ShellSessionState.Closed, reason);
|
||||
logger.LogInformation("Shell session {SessionId} closed: {Reason}", sessionId, reason);
|
||||
}
|
||||
|
||||
private void CloseCurrent(string reason)
|
||||
{
|
||||
Guid? sessionId;
|
||||
lock (gate)
|
||||
{
|
||||
sessionId = current?.SessionId;
|
||||
}
|
||||
|
||||
if (sessionId is not null)
|
||||
{
|
||||
Close(sessionId.Value, reason);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnIdleTimeout(Guid sessionId) => Close(sessionId, "idle timeout");
|
||||
|
||||
private void OnMaxLifetime(Guid sessionId) => Close(sessionId, "maximum session lifetime reached");
|
||||
|
||||
private void PublishOutput(ActiveShell active, ReadOnlyMemory<byte> data)
|
||||
{
|
||||
var sequence = Interlocked.Increment(ref active.Sequence);
|
||||
var payload = new ShellOutputPayload(active.SessionId, sequence, Convert.ToBase64String(data.Span));
|
||||
|
||||
_ = publisher.PublishAsync(
|
||||
NatsSubjects.AgentShellOutput(publisher.ClientId, active.SessionId),
|
||||
MessageTypes.ShellOutput,
|
||||
payload);
|
||||
}
|
||||
|
||||
private void PublishState(Guid sessionId, ShellSessionState state, string? message)
|
||||
{
|
||||
_ = publisher.PublishAsync(
|
||||
NatsSubjects.AgentShellState(publisher.ClientId, sessionId),
|
||||
MessageTypes.ShellState,
|
||||
new ShellStatePayload(sessionId, state, message));
|
||||
}
|
||||
|
||||
private static void DisposeShell(ActiveShell? active, string reason)
|
||||
{
|
||||
if (active is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
active.IdleTimer.Dispose();
|
||||
active.MaxLifetimeTimer.Dispose();
|
||||
active.Pty.Dispose();
|
||||
_ = reason;
|
||||
}
|
||||
|
||||
/// <summary>Prefers PowerShell 7 (pwsh) when present, else Windows PowerShell.</summary>
|
||||
private static string ResolveShellCommand()
|
||||
{
|
||||
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
|
||||
var pwsh = Path.Combine(programFiles, "PowerShell", "7", "pwsh.exe");
|
||||
if (File.Exists(pwsh))
|
||||
{
|
||||
return $"\"{pwsh}\" -NoLogo";
|
||||
}
|
||||
|
||||
var windowsPowerShell = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.System),
|
||||
"WindowsPowerShell", "v1.0", "powershell.exe");
|
||||
return $"\"{windowsPowerShell}\" -NoLogo";
|
||||
}
|
||||
|
||||
public void Dispose() => CloseCurrent("agent shutting down");
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Shared.Infrastructure.Constants;
|
||||
|
||||
namespace Agent.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Durable local record of handled job ids so JetStream redelivery or agent
|
||||
/// restart never executes the same script twice. Retains the most recent
|
||||
/// completed entries (bounded) in a lightweight SQLite database.
|
||||
/// </summary>
|
||||
public sealed class JobHistoryStore : IDisposable
|
||||
{
|
||||
private readonly SqliteConnection connection;
|
||||
private readonly Lock writeLock = new();
|
||||
|
||||
public JobHistoryStore()
|
||||
: this(Path.Combine(Branding.AgentProgramDataDirectory, Branding.JobHistoryFileName))
|
||||
{
|
||||
}
|
||||
|
||||
public JobHistoryStore(string databasePath)
|
||||
{
|
||||
var directory = Path.GetDirectoryName(databasePath);
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
connection = new SqliteConnection($"Data Source={databasePath}");
|
||||
connection.Open();
|
||||
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = """
|
||||
CREATE TABLE IF NOT EXISTS HandledJobs (
|
||||
JobId TEXT PRIMARY KEY,
|
||||
AcceptedUtc TEXT NOT NULL,
|
||||
CompletedUtc TEXT NULL,
|
||||
State TEXT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DownloadCache (
|
||||
DestinationPath TEXT PRIMARY KEY,
|
||||
ObjectKey TEXT NULL,
|
||||
ETag TEXT NULL,
|
||||
Sha256 TEXT NULL,
|
||||
SizeBytes INTEGER NULL,
|
||||
DownloadedUtc TEXT NOT NULL
|
||||
);
|
||||
""";
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
/// <summary>What the agent knows about a previously downloaded file.</summary>
|
||||
public sealed record DownloadCacheEntry(string? ETag, string? Sha256, long? SizeBytes);
|
||||
|
||||
public DownloadCacheEntry? GetDownloadCache(string destinationPath)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText =
|
||||
"SELECT ETag, Sha256, SizeBytes FROM DownloadCache WHERE DestinationPath = $path;";
|
||||
command.Parameters.AddWithValue("$path", destinationPath);
|
||||
|
||||
using var reader = command.ExecuteReader();
|
||||
if (!reader.Read())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new DownloadCacheEntry(
|
||||
reader.IsDBNull(0) ? null : reader.GetString(0),
|
||||
reader.IsDBNull(1) ? null : reader.GetString(1),
|
||||
reader.IsDBNull(2) ? null : reader.GetInt64(2));
|
||||
}
|
||||
|
||||
public void RecordDownload(string destinationPath, string? objectKey, string? etag, string? sha256, long sizeBytes)
|
||||
{
|
||||
lock (writeLock)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = """
|
||||
INSERT INTO DownloadCache (DestinationPath, ObjectKey, ETag, Sha256, SizeBytes, DownloadedUtc)
|
||||
VALUES ($path, $key, $etag, $sha, $size, $utc)
|
||||
ON CONFLICT(DestinationPath) DO UPDATE SET
|
||||
ObjectKey = excluded.ObjectKey,
|
||||
ETag = excluded.ETag,
|
||||
Sha256 = excluded.Sha256,
|
||||
SizeBytes = excluded.SizeBytes,
|
||||
DownloadedUtc = excluded.DownloadedUtc;
|
||||
""";
|
||||
command.Parameters.AddWithValue("$path", destinationPath);
|
||||
command.Parameters.AddWithValue("$key", (object?)objectKey ?? DBNull.Value);
|
||||
command.Parameters.AddWithValue("$etag", (object?)etag ?? DBNull.Value);
|
||||
command.Parameters.AddWithValue("$sha", (object?)sha256 ?? DBNull.Value);
|
||||
command.Parameters.AddWithValue("$size", sizeBytes);
|
||||
command.Parameters.AddWithValue("$utc", DateTimeOffset.UtcNow.ToString("O"));
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Durably records a job as accepted. Returns false when the job was
|
||||
/// already recorded (duplicate delivery) — the caller must not execute it.
|
||||
/// </summary>
|
||||
public bool TryRecordAccepted(Guid jobId)
|
||||
{
|
||||
lock (writeLock)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "INSERT OR IGNORE INTO HandledJobs (JobId, AcceptedUtc) VALUES ($id, $utc);";
|
||||
command.Parameters.AddWithValue("$id", jobId.ToString("D"));
|
||||
command.Parameters.AddWithValue("$utc", DateTimeOffset.UtcNow.ToString("O"));
|
||||
return command.ExecuteNonQuery() == 1;
|
||||
}
|
||||
}
|
||||
|
||||
public void MarkCompleted(Guid jobId, string state)
|
||||
{
|
||||
lock (writeLock)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "UPDATE HandledJobs SET CompletedUtc = $utc, State = $state WHERE JobId = $id;";
|
||||
command.Parameters.AddWithValue("$utc", DateTimeOffset.UtcNow.ToString("O"));
|
||||
command.Parameters.AddWithValue("$state", state);
|
||||
command.Parameters.AddWithValue("$id", jobId.ToString("D"));
|
||||
command.ExecuteNonQuery();
|
||||
|
||||
Prune();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsHandled(Guid jobId)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT 1 FROM HandledJobs WHERE JobId = $id;";
|
||||
command.Parameters.AddWithValue("$id", jobId.ToString("D"));
|
||||
return command.ExecuteScalar() is not null;
|
||||
}
|
||||
|
||||
private void Prune()
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = """
|
||||
DELETE FROM HandledJobs WHERE JobId NOT IN (
|
||||
SELECT JobId FROM HandledJobs ORDER BY AcceptedUtc DESC LIMIT $keep
|
||||
);
|
||||
""";
|
||||
command.Parameters.AddWithValue("$keep", Shared.Infrastructure.Constants.ProtocolDefaults.JobIdempotencyRetention);
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
public void Dispose() => connection.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using Agent.Configuration;
|
||||
using Shared.Infrastructure.Constants;
|
||||
|
||||
namespace Agent.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Runtime-managed registry state below the Runtime subkey, plus secure
|
||||
/// deletion of the bootstrap token after successful enrollment.
|
||||
/// </summary>
|
||||
public sealed class RuntimeStateStore(IRegistryStore registry)
|
||||
{
|
||||
public string? ClientId
|
||||
{
|
||||
get => registry.ReadString(Branding.AgentRuntimeRegistryKey, AgentRuntimeKeys.ClientId);
|
||||
set => WriteOrDelete(AgentRuntimeKeys.ClientId, value);
|
||||
}
|
||||
|
||||
public string? EnrollmentId
|
||||
{
|
||||
get => registry.ReadString(Branding.AgentRuntimeRegistryKey, AgentRuntimeKeys.EnrollmentId);
|
||||
set => WriteOrDelete(AgentRuntimeKeys.EnrollmentId, value);
|
||||
}
|
||||
|
||||
public DateTimeOffset? LastEnrollmentUtc
|
||||
{
|
||||
get => ReadTimestamp(AgentRuntimeKeys.LastEnrollmentUtc);
|
||||
set => WriteTimestamp(AgentRuntimeKeys.LastEnrollmentUtc, value);
|
||||
}
|
||||
|
||||
public DateTimeOffset? LastConnectedUtc
|
||||
{
|
||||
get => ReadTimestamp(AgentRuntimeKeys.LastConnectedUtc);
|
||||
set => WriteTimestamp(AgentRuntimeKeys.LastConnectedUtc, value);
|
||||
}
|
||||
|
||||
public DateTimeOffset? CredentialExpiresUtc
|
||||
{
|
||||
get => ReadTimestamp(AgentRuntimeKeys.CredentialExpiresUtc);
|
||||
set => WriteTimestamp(AgentRuntimeKeys.CredentialExpiresUtc, value);
|
||||
}
|
||||
|
||||
/// <summary>Removes the one-time bootstrap token from the normal registry key.</summary>
|
||||
public void ClearBootstrapToken()
|
||||
=> registry.DeleteValue(Branding.AgentRegistryKey, AgentConfigurationKeys.BootstrapToken);
|
||||
|
||||
/// <summary>Removes all runtime state (explicit full uninstall only).</summary>
|
||||
public void Purge()
|
||||
=> registry.DeleteKeyTree(Branding.AgentRuntimeRegistryKey);
|
||||
|
||||
private DateTimeOffset? ReadTimestamp(string name)
|
||||
=> DateTimeOffset.TryParse(
|
||||
registry.ReadString(Branding.AgentRuntimeRegistryKey, name),
|
||||
null,
|
||||
System.Globalization.DateTimeStyles.RoundtripKind,
|
||||
out var value)
|
||||
? value
|
||||
: null;
|
||||
|
||||
private void WriteTimestamp(string name, DateTimeOffset? value)
|
||||
=> WriteOrDelete(name, value?.ToUniversalTime().ToString("O"));
|
||||
|
||||
private void WriteOrDelete(string name, string? value)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
registry.DeleteValue(Branding.AgentRuntimeRegistryKey, name);
|
||||
}
|
||||
else
|
||||
{
|
||||
registry.WriteString(Branding.AgentRuntimeRegistryKey, name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using Backend.Auth;
|
||||
using Backend.Data;
|
||||
using Backend.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shared.Contracts.Api;
|
||||
using Shared.Infrastructure.Constants;
|
||||
using Shared.Infrastructure.Security;
|
||||
|
||||
namespace Backend.Api;
|
||||
|
||||
public static class BootstrapTokenEndpoints
|
||||
{
|
||||
public static void Map(WebApplication app)
|
||||
{
|
||||
app.MapPost(ApiRoutes.AdminBootstrapTokens, CreateAsync).RequireAuthorization(AuthConstants.PolicyAdmin);
|
||||
app.MapGet(ApiRoutes.AdminBootstrapTokens, ListAsync).RequireAuthorization(AuthConstants.PolicyAdmin);
|
||||
app.MapDelete(ApiRoutes.AdminBootstrapToken, RevokeAsync).RequireAuthorization(AuthConstants.PolicyAdmin);
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateAsync(
|
||||
CreateBootstrapTokenRequest? request,
|
||||
AppDbContext db,
|
||||
AuditService audit,
|
||||
HttpContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var lifetime = request?.ValidMinutes is > 0
|
||||
? TimeSpan.FromMinutes(request.ValidMinutes.Value)
|
||||
: ProtocolDefaults.BootstrapTokenDefaultLifetime;
|
||||
var maxUses = request?.MaxUses is > 0 ? request.MaxUses.Value : ProtocolDefaults.BootstrapTokenDefaultMaxUses;
|
||||
|
||||
// Plaintext exists exactly once: in this response. Only the hash is stored.
|
||||
var token = TokenGenerator.CreateUrlSafeToken(ProtocolDefaults.BootstrapTokenEntropyBytes);
|
||||
var actor = context.User.Identity?.Name;
|
||||
|
||||
var entity = new BootstrapTokenEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
TokenHash = TokenHashing.Sha256Hex(token),
|
||||
CreatedUtc = DateTimeOffset.UtcNow,
|
||||
ExpiresUtc = DateTimeOffset.UtcNow + lifetime,
|
||||
MaxUses = maxUses,
|
||||
Note = request?.Note,
|
||||
CreatedBy = actor,
|
||||
};
|
||||
db.BootstrapTokens.Add(entity);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
await audit.LogAsync(AuditCategories.Admin, "bootstrap-token-created", actor,
|
||||
detail: $"id={entity.Id} maxUses={maxUses}", cancellationToken: cancellationToken);
|
||||
|
||||
return Results.Ok(ToDto(entity, token));
|
||||
}
|
||||
|
||||
private static async Task<IResult> ListAsync(AppDbContext db, CancellationToken cancellationToken)
|
||||
{
|
||||
var tokens = await db.BootstrapTokens.AsNoTracking()
|
||||
.OrderByDescending(t => t.CreatedUtc)
|
||||
.Take(100)
|
||||
.ToListAsync(cancellationToken);
|
||||
return Results.Ok(tokens.Select(t => ToDto(t, token: null)).ToList());
|
||||
}
|
||||
|
||||
private static async Task<IResult> RevokeAsync(
|
||||
Guid id, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await db.BootstrapTokens.SingleOrDefaultAsync(t => t.Id == id, cancellationToken);
|
||||
if (entity is null)
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
|
||||
entity.Revoked = true;
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
await audit.LogAsync(AuditCategories.Admin, "bootstrap-token-revoked", context.User.Identity?.Name,
|
||||
detail: $"id={id}", cancellationToken: cancellationToken);
|
||||
|
||||
return Results.NoContent();
|
||||
}
|
||||
|
||||
private static BootstrapTokenDto ToDto(BootstrapTokenEntity entity, string? token) => new(
|
||||
entity.Id, token, entity.CreatedUtc, entity.ExpiresUtc,
|
||||
entity.MaxUses, entity.Uses, entity.Revoked, entity.Note, entity.CreatedBy);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using System.Text.Json;
|
||||
using Backend.Auth;
|
||||
using Backend.Data;
|
||||
using Backend.Jobs;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shared.Contracts.Api;
|
||||
using Shared.Contracts.Models;
|
||||
using Shared.Contracts.Serialization;
|
||||
using Shared.Infrastructure.Constants;
|
||||
using Shared.Infrastructure.Nats;
|
||||
|
||||
namespace Backend.Api;
|
||||
|
||||
public static class DeviceEndpoints
|
||||
{
|
||||
public static void Map(WebApplication app)
|
||||
{
|
||||
app.MapGet(ApiRoutes.Devices, ListAsync).RequireAuthorization(AuthConstants.PolicyViewer);
|
||||
app.MapGet(ApiRoutes.Device, GetAsync).RequireAuthorization(AuthConstants.PolicyViewer);
|
||||
app.MapPost(ApiRoutes.DeviceInventory, RefreshInventoryAsync).RequireAuthorization(AuthConstants.PolicyOperator);
|
||||
}
|
||||
|
||||
private static async Task<IResult> ListAsync(AppDbContext db, CancellationToken cancellationToken)
|
||||
{
|
||||
var devices = await db.Devices.AsNoTracking()
|
||||
.OrderBy(d => d.Hostname)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
return Results.Ok(devices.Select(d => ToDto(d, now)).ToList());
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetAsync(
|
||||
string clientId, AppDbContext db, Groups.DeviceGroupService groups, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!SubjectIdentifier.IsValid(clientId))
|
||||
{
|
||||
return Results.BadRequest();
|
||||
}
|
||||
|
||||
var device = await db.Devices.AsNoTracking()
|
||||
.Include(d => d.Inventory)
|
||||
.SingleOrDefaultAsync(d => d.ClientId == clientId, cancellationToken);
|
||||
if (device is null)
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
|
||||
InventoryReport? report = null;
|
||||
if (device.Inventory is not null)
|
||||
{
|
||||
report = JsonDefaults.Deserialize<InventoryReport>(device.Inventory.ReportJson);
|
||||
}
|
||||
|
||||
return Results.Ok(new DeviceDetailDto(
|
||||
ToDto(device, DateTimeOffset.UtcNow),
|
||||
report,
|
||||
device.Inventory?.UpdatedUtc,
|
||||
await groups.GetGroupsForDeviceAsync(clientId, cancellationToken)));
|
||||
}
|
||||
|
||||
private static async Task<IResult> RefreshInventoryAsync(
|
||||
string clientId,
|
||||
AppDbContext db,
|
||||
CommandDispatcher dispatcher,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!SubjectIdentifier.IsValid(clientId))
|
||||
{
|
||||
return Results.BadRequest();
|
||||
}
|
||||
|
||||
var exists = await db.Devices.AnyAsync(d => d.ClientId == clientId, cancellationToken);
|
||||
if (!exists)
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
|
||||
var dispatched = await dispatcher.DispatchInventoryRefreshAsync(clientId, "manual refresh", cancellationToken);
|
||||
return dispatched
|
||||
? Results.Accepted()
|
||||
: Results.Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Messaging unavailable.");
|
||||
}
|
||||
|
||||
internal static DeviceDto ToDto(DeviceEntity device, DateTimeOffset now)
|
||||
{
|
||||
IReadOnlyList<string> addresses = [];
|
||||
if (!string.IsNullOrEmpty(device.IpAddressesJson))
|
||||
{
|
||||
addresses = JsonDefaults.Deserialize<List<string>>(device.IpAddressesJson) ?? [];
|
||||
}
|
||||
|
||||
return new DeviceDto(
|
||||
ClientId: device.ClientId,
|
||||
Hostname: device.Hostname,
|
||||
Manufacturer: device.Manufacturer,
|
||||
Model: device.Model,
|
||||
OsCaption: device.OsCaption,
|
||||
OsVersion: device.OsVersion,
|
||||
AgentVersion: device.AgentVersion,
|
||||
IpAddresses: addresses,
|
||||
Status: ProtocolDefaults.CalculateStatus(device.LastSeenUtc, now),
|
||||
LastSeenUtc: device.LastSeenUtc,
|
||||
EnrolledUtc: device.EnrolledUtc,
|
||||
Tags: Groups.DeviceGroupService.ParseTags(device.TagsJson),
|
||||
IsOrphaned: device.IsOrphaned);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using Shared.Infrastructure.Constants;
|
||||
|
||||
namespace Backend.Api;
|
||||
|
||||
/// <summary>
|
||||
/// What happens to devices that stop checking in.
|
||||
///
|
||||
/// A device silent for longer than the window is <b>orphaned</b>: its
|
||||
/// credential refresh is refused and no work is dispatched to it, even if it
|
||||
/// reappears. Recovery is deliberate — push a fresh bootstrap token to the
|
||||
/// endpoint and the agent re-enrolls, which clears the flag and reuses the
|
||||
/// same device record.
|
||||
///
|
||||
/// The window is centrally defaulted by
|
||||
/// <see cref="ProtocolDefaults.DefaultOrphanAfterDays"/> (30 days) and
|
||||
/// overridden with <c>DEVICE_ORPHAN_AFTER_DAYS</c>. Set that to <c>0</c> to
|
||||
/// disable orphaning entirely, so silent devices simply go Stale then Offline
|
||||
/// and reconnect on their own.
|
||||
/// </summary>
|
||||
public sealed class DeviceLifecycleOptions
|
||||
{
|
||||
public int OrphanAfterDays { get; init; } = ProtocolDefaults.DefaultOrphanAfterDays;
|
||||
|
||||
public bool OrphaningEnabled => OrphanAfterDays > 0;
|
||||
|
||||
public TimeSpan OrphanAfter => TimeSpan.FromDays(OrphanAfterDays);
|
||||
|
||||
public static DeviceLifecycleOptions FromConfiguration(IConfiguration configuration)
|
||||
{
|
||||
var raw = configuration["DEVICE_ORPHAN_AFTER_DAYS"];
|
||||
|
||||
// Unset falls back to the central default; 0 explicitly disables.
|
||||
var days = string.IsNullOrWhiteSpace(raw)
|
||||
? ProtocolDefaults.DefaultOrphanAfterDays
|
||||
: int.TryParse(raw, out var parsed) && parsed >= 0
|
||||
? parsed
|
||||
: ProtocolDefaults.DefaultOrphanAfterDays;
|
||||
|
||||
return new DeviceLifecycleOptions { OrphanAfterDays = days };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Backend.Auth;
|
||||
|
||||
/// <summary>Auth scheme names, claim types and authorization policy names.</summary>
|
||||
public static class AuthConstants
|
||||
{
|
||||
public const string CookieScheme = "ExecuteRCookie";
|
||||
public const string OidcScheme = "oidc";
|
||||
|
||||
public const string RoleClaim = "role";
|
||||
public const string ProviderClaim = "auth_provider";
|
||||
|
||||
public const string ProviderLocal = "local";
|
||||
public const string ProviderOidc = "oidc";
|
||||
|
||||
// Policy names (generic — no product branding).
|
||||
public const string PolicyViewer = "viewer";
|
||||
public const string PolicyOperator = "operator";
|
||||
public const string PolicyAdmin = "admin";
|
||||
|
||||
public static string RoleName(UserRole role) => role.ToString();
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using System.Security.Claims;
|
||||
using Backend.Proxy;
|
||||
using Backend.Security;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Shared.Contracts.Api;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Backend.Auth;
|
||||
|
||||
public static class AuthEndpoints
|
||||
{
|
||||
public static void Map(WebApplication app, OidcOptions oidc)
|
||||
{
|
||||
app.MapPost(ApiRoutes.AuthLogin, LoginAsync)
|
||||
.RequireRateLimiting(RateLimitPolicies.Auth)
|
||||
.AllowAnonymous();
|
||||
|
||||
app.MapPost(ApiRoutes.AuthLogout, (Delegate)LogoutAsync);
|
||||
|
||||
app.MapGet(ApiRoutes.AuthSession, GetSession).AllowAnonymous();
|
||||
|
||||
app.MapGet(ApiRoutes.AuthOidcLogin, (HttpContext context) =>
|
||||
oidc.IsUsable
|
||||
? Results.Challenge(new AuthenticationProperties { RedirectUri = "/" }, [AuthConstants.OidcScheme])
|
||||
: Results.NotFound(new { error = "OIDC is not configured." }))
|
||||
.AllowAnonymous();
|
||||
|
||||
// OIDC completes at CallbackPath (handler-owned); this route lets the
|
||||
// SPA finalize the app cookie mapping if needed.
|
||||
app.MapGet(ApiRoutes.AuthOidcCallback, () => Results.Redirect("/")).AllowAnonymous();
|
||||
}
|
||||
|
||||
private static async Task<IResult> LoginAsync(
|
||||
LoginRequest request,
|
||||
UserService users,
|
||||
AuditService audit,
|
||||
HttpContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var remoteIp = ClientIp.EffectiveText(context);
|
||||
|
||||
var user = await users.ValidateCredentialsAsync(request.Username, request.Password, cancellationToken);
|
||||
if (user is null)
|
||||
{
|
||||
await audit.LogAsync(AuditCategories.Auth, "login-failed",
|
||||
actor: request.Username, remoteIp: remoteIp, cancellationToken: cancellationToken);
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
var principal = AuthExtensions.BuildPrincipal(
|
||||
user.Username, user.DisplayName, user.Role, AuthConstants.ProviderLocal);
|
||||
await context.SignInAsync(AuthConstants.CookieScheme, principal);
|
||||
CsrfProtection.IssueToken(context);
|
||||
|
||||
await audit.LogAsync(AuditCategories.Auth, "login-succeeded",
|
||||
actor: user.Username, remoteIp: remoteIp, cancellationToken: cancellationToken);
|
||||
|
||||
return Results.Ok(new SessionResponse(
|
||||
true, user.Username, user.DisplayName, user.Role, AuthConstants.ProviderLocal));
|
||||
}
|
||||
|
||||
private static async Task<IResult> LogoutAsync(HttpContext context)
|
||||
{
|
||||
await context.SignOutAsync(AuthConstants.CookieScheme);
|
||||
context.Response.Cookies.Delete(CsrfProtection.CookieName);
|
||||
return Results.Ok();
|
||||
}
|
||||
|
||||
private static IResult GetSession(HttpContext context)
|
||||
{
|
||||
var user = context.User;
|
||||
if (user.Identity?.IsAuthenticated != true)
|
||||
{
|
||||
return Results.Ok(new SessionResponse(false, null, null, null, null));
|
||||
}
|
||||
|
||||
// Ensure a CSRF token exists for this authenticated session.
|
||||
if (!context.Request.Cookies.ContainsKey(CsrfProtection.CookieName))
|
||||
{
|
||||
CsrfProtection.IssueToken(context);
|
||||
}
|
||||
|
||||
var roleName = user.FindFirstValue(ClaimTypes.Role);
|
||||
_ = Enum.TryParse<UserRole>(roleName, out var role);
|
||||
|
||||
return Results.Ok(new SessionResponse(
|
||||
true,
|
||||
user.Identity.Name,
|
||||
user.FindFirstValue("display_name") ?? user.Identity.Name,
|
||||
role,
|
||||
user.FindFirstValue(AuthConstants.ProviderClaim) ?? AuthConstants.ProviderLocal));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Backend.Auth;
|
||||
|
||||
/// <summary>Wires cookie + optional OIDC authentication and role-based authorization.</summary>
|
||||
public static class AuthExtensions
|
||||
{
|
||||
public static void AddControlPlaneAuth(this WebApplicationBuilder builder, OidcOptions oidc)
|
||||
{
|
||||
var authBuilder = builder.Services
|
||||
.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultScheme = AuthConstants.CookieScheme;
|
||||
options.DefaultChallengeScheme = oidc.IsUsable ? AuthConstants.OidcScheme : AuthConstants.CookieScheme;
|
||||
})
|
||||
.AddCookie(AuthConstants.CookieScheme, options =>
|
||||
{
|
||||
options.Cookie.Name = "executer_session";
|
||||
options.Cookie.HttpOnly = true;
|
||||
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
|
||||
// Lax so the OIDC redirect back to the app carries the cookie.
|
||||
options.Cookie.SameSite = SameSiteMode.Lax;
|
||||
options.SlidingExpiration = true;
|
||||
options.ExpireTimeSpan = TimeSpan.FromHours(12);
|
||||
|
||||
// APIs must return 401/403, never redirect to a login page.
|
||||
options.Events.OnRedirectToLogin = context =>
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
options.Events.OnRedirectToAccessDenied = context =>
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
});
|
||||
|
||||
if (oidc.IsUsable)
|
||||
{
|
||||
authBuilder.AddOpenIdConnect(AuthConstants.OidcScheme, options =>
|
||||
{
|
||||
options.Authority = oidc.Authority;
|
||||
options.ClientId = oidc.ClientId;
|
||||
options.ClientSecret = oidc.ClientSecret;
|
||||
options.ResponseType = OpenIdConnectResponseType.Code;
|
||||
options.CallbackPath = oidc.CallbackPath;
|
||||
options.SaveTokens = false;
|
||||
options.GetClaimsFromUserInfoEndpoint = true;
|
||||
options.SignInScheme = AuthConstants.CookieScheme;
|
||||
options.UsePkce = true;
|
||||
|
||||
options.Scope.Clear();
|
||||
foreach (var scope in oidc.Scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
options.Scope.Add(scope);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(oidc.NameClaim))
|
||||
{
|
||||
options.TokenValidationParameters.NameClaimType = oidc.NameClaim;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(oidc.RoleClaim))
|
||||
{
|
||||
options.TokenValidationParameters.RoleClaimType = oidc.RoleClaim;
|
||||
}
|
||||
|
||||
// Upsert the user and stamp the app role claim onto the cookie identity.
|
||||
options.Events.OnTokenValidated = async context =>
|
||||
{
|
||||
var principal = context.Principal;
|
||||
if (principal?.Identity is not ClaimsIdentity identity)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var subject = principal.FindFirstValue(ClaimTypes.NameIdentifier)
|
||||
?? principal.FindFirstValue("sub");
|
||||
if (string.IsNullOrEmpty(subject))
|
||||
{
|
||||
context.Fail("OIDC token has no subject claim.");
|
||||
return;
|
||||
}
|
||||
|
||||
var username = (oidc.NameClaim is not null ? principal.FindFirstValue(oidc.NameClaim) : null)
|
||||
?? principal.FindFirstValue(ClaimTypes.Name)
|
||||
?? principal.FindFirstValue("preferred_username")
|
||||
?? principal.FindFirstValue(ClaimTypes.Email)
|
||||
?? subject;
|
||||
var displayName = principal.FindFirstValue("name") ?? username;
|
||||
|
||||
// MVP role mapping: matching admin role claim → Admin, else Operator.
|
||||
var role = UserRole.Operator;
|
||||
if (!string.IsNullOrWhiteSpace(oidc.AdminRole) && !string.IsNullOrWhiteSpace(oidc.RoleClaim))
|
||||
{
|
||||
var hasAdminRole = principal.FindAll(oidc.RoleClaim)
|
||||
.Any(c => string.Equals(c.Value, oidc.AdminRole, StringComparison.OrdinalIgnoreCase));
|
||||
if (hasAdminRole)
|
||||
{
|
||||
role = UserRole.Admin;
|
||||
}
|
||||
}
|
||||
|
||||
var users = context.HttpContext.RequestServices.GetRequiredService<UserService>();
|
||||
await users.UpsertOidcUserAsync(subject, username, displayName, role, context.HttpContext.RequestAborted);
|
||||
|
||||
// Normalize the identity so cookie claims match local users.
|
||||
identity.AddClaim(new Claim(ClaimTypes.Role, role.ToString()));
|
||||
identity.AddClaim(new Claim(AuthConstants.ProviderClaim, AuthConstants.ProviderOidc));
|
||||
identity.AddClaim(new Claim("display_name", displayName));
|
||||
if (identity.FindFirst(ClaimTypes.Name) is null)
|
||||
{
|
||||
identity.AddClaim(new Claim(ClaimTypes.Name, username));
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
builder.Services.AddAuthorization(options =>
|
||||
{
|
||||
options.AddPolicy(AuthConstants.PolicyViewer, policy =>
|
||||
policy.RequireRole(nameof(UserRole.Viewer), nameof(UserRole.Operator), nameof(UserRole.Admin)));
|
||||
options.AddPolicy(AuthConstants.PolicyOperator, policy =>
|
||||
policy.RequireRole(nameof(UserRole.Operator), nameof(UserRole.Admin)));
|
||||
options.AddPolicy(AuthConstants.PolicyAdmin, policy =>
|
||||
policy.RequireRole(nameof(UserRole.Admin)));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Builds the cookie principal for an authenticated user.</summary>
|
||||
public static ClaimsPrincipal BuildPrincipal(string username, string? displayName, UserRole role, string provider)
|
||||
{
|
||||
var identity = new ClaimsIdentity(AuthConstants.CookieScheme, ClaimTypes.Name, ClaimTypes.Role);
|
||||
identity.AddClaim(new Claim(ClaimTypes.Name, username));
|
||||
identity.AddClaim(new Claim(ClaimTypes.Role, role.ToString()));
|
||||
identity.AddClaim(new Claim(AuthConstants.ProviderClaim, provider));
|
||||
if (!string.IsNullOrWhiteSpace(displayName))
|
||||
{
|
||||
identity.AddClaim(new Claim("display_name", displayName));
|
||||
}
|
||||
|
||||
return new ClaimsPrincipal(identity);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Backend.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Double-submit-cookie CSRF protection for cookie-authenticated,
|
||||
/// state-changing REST calls. The browser reads the non-HttpOnly
|
||||
/// <c>csrf_token</c> cookie and echoes it in the <c>X-CSRF-Token</c> header;
|
||||
/// the middleware requires the two to match. Bearer/enrollment endpoints and
|
||||
/// safe methods are exempt.
|
||||
/// </summary>
|
||||
public static class CsrfProtection
|
||||
{
|
||||
public const string CookieName = "csrf_token";
|
||||
public const string HeaderName = "X-CSRF-Token";
|
||||
|
||||
public static string IssueToken(HttpContext context)
|
||||
{
|
||||
var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
|
||||
context.Response.Cookies.Append(CookieName, token, new CookieOptions
|
||||
{
|
||||
HttpOnly = false, // Must be readable by the SPA.
|
||||
SameSite = SameSiteMode.Lax,
|
||||
Secure = context.Request.IsHttps,
|
||||
Path = "/",
|
||||
});
|
||||
return token;
|
||||
}
|
||||
|
||||
public static RequestDelegate Middleware(RequestDelegate next) => async context =>
|
||||
{
|
||||
if (RequiresValidation(context))
|
||||
{
|
||||
var cookie = context.Request.Cookies[CookieName];
|
||||
var header = context.Request.Headers[HeaderName].ToString();
|
||||
|
||||
if (string.IsNullOrEmpty(cookie)
|
||||
|| string.IsNullOrEmpty(header)
|
||||
|| !CryptographicOperations.FixedTimeEquals(
|
||||
System.Text.Encoding.UTF8.GetBytes(cookie),
|
||||
System.Text.Encoding.UTF8.GetBytes(header)))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
await context.Response.WriteAsJsonAsync(new { error = "CSRF validation failed." });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await next(context);
|
||||
};
|
||||
|
||||
private static bool RequiresValidation(HttpContext context)
|
||||
{
|
||||
var method = context.Request.Method;
|
||||
if (HttpMethods.IsGet(method) || HttpMethods.IsHead(method) || HttpMethods.IsOptions(method))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var path = context.Request.Path;
|
||||
|
||||
// Enrollment endpoints are agent-to-server (no cookie); exempt.
|
||||
if (path.StartsWithSegments("/api/enrollment"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Login establishes the session; protected by rate limiting + credentials.
|
||||
if (path.StartsWithSegments("/api/auth/login"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Only guard cookie-authenticated API calls.
|
||||
return path.StartsWithSegments("/api")
|
||||
&& context.Request.Cookies.ContainsKey("executer_session");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
namespace Backend.Auth;
|
||||
|
||||
/// <summary>Generic OIDC configuration (works with any compliant provider).</summary>
|
||||
public sealed class OidcOptions
|
||||
{
|
||||
public bool Enabled { get; init; }
|
||||
public string? Authority { get; init; }
|
||||
public string? ClientId { get; init; }
|
||||
public string? ClientSecret { get; init; }
|
||||
public string CallbackPath { get; init; } = "/signin-oidc";
|
||||
public string Scopes { get; init; } = "openid profile email";
|
||||
public string? NameClaim { get; init; }
|
||||
public string? RoleClaim { get; init; }
|
||||
public string? AdminRole { get; init; }
|
||||
|
||||
public bool IsUsable => Enabled
|
||||
&& !string.IsNullOrWhiteSpace(Authority)
|
||||
&& !string.IsNullOrWhiteSpace(ClientId);
|
||||
|
||||
public static OidcOptions FromConfiguration(IConfiguration configuration) => new()
|
||||
{
|
||||
Enabled = configuration["OIDC_ENABLED"] == "1",
|
||||
Authority = configuration["OIDC_AUTHORITY"],
|
||||
ClientId = configuration["OIDC_CLIENT_ID"],
|
||||
ClientSecret = configuration["OIDC_CLIENT_SECRET"],
|
||||
CallbackPath = string.IsNullOrWhiteSpace(configuration["OIDC_CALLBACK_PATH"])
|
||||
? "/signin-oidc"
|
||||
: configuration["OIDC_CALLBACK_PATH"]!,
|
||||
Scopes = string.IsNullOrWhiteSpace(configuration["OIDC_SCOPES"])
|
||||
? "openid profile email"
|
||||
: configuration["OIDC_SCOPES"]!,
|
||||
NameClaim = configuration["OIDC_NAME_CLAIM"],
|
||||
RoleClaim = configuration["OIDC_ROLE_CLAIM"],
|
||||
AdminRole = configuration["OIDC_ADMIN_ROLE"],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using Backend.Data;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Backend.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Local user lifecycle and password verification. Passwords are hashed with
|
||||
/// ASP.NET Core's <see cref="PasswordHasher{T}"/>; there is no compiled default
|
||||
/// password. Rehashes transparently when the hasher recommends it.
|
||||
/// </summary>
|
||||
public sealed class UserService(AppDbContext db, ILogger<UserService> logger)
|
||||
{
|
||||
private readonly PasswordHasher<UserEntity> hasher = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates the initial admin from environment secrets on first startup only.
|
||||
/// Never overwrites an existing admin's password.
|
||||
/// </summary>
|
||||
public async Task EnsureInitialAdminAsync(string? username, string? password, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await db.Users.AnyAsync(cancellationToken))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
|
||||
{
|
||||
logger.LogWarning(
|
||||
"No users exist and INITIAL_ADMIN_USERNAME/PASSWORD are not set; create an admin to enable sign-in");
|
||||
return;
|
||||
}
|
||||
|
||||
var admin = new UserEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = username.Trim(),
|
||||
DisplayName = username.Trim(),
|
||||
Role = UserRole.Admin,
|
||||
AuthProvider = AuthConstants.ProviderLocal,
|
||||
CreatedUtc = DateTimeOffset.UtcNow,
|
||||
};
|
||||
admin.PasswordHash = hasher.HashPassword(admin, password);
|
||||
db.Users.Add(admin);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Initial admin '{Username}' created", admin.Username);
|
||||
}
|
||||
|
||||
public async Task<UserEntity?> ValidateCredentialsAsync(string username, string password, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = await db.Users.SingleOrDefaultAsync(
|
||||
u => u.Username == username && u.AuthProvider == AuthConstants.ProviderLocal, cancellationToken);
|
||||
if (user?.PasswordHash is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var result = hasher.VerifyHashedPassword(user, user.PasswordHash, password);
|
||||
if (result == PasswordVerificationResult.Failed)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (result == PasswordVerificationResult.SuccessRehashNeeded)
|
||||
{
|
||||
user.PasswordHash = hasher.HashPassword(user, password);
|
||||
}
|
||||
|
||||
user.LastLoginUtc = DateTimeOffset.UtcNow;
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>Upserts an OIDC-authenticated user, assigning role from claims.</summary>
|
||||
public async Task<UserEntity> UpsertOidcUserAsync(
|
||||
string externalId, string username, string? displayName, UserRole role, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = await db.Users.SingleOrDefaultAsync(
|
||||
u => u.ExternalId == externalId && u.AuthProvider == AuthConstants.ProviderOidc, cancellationToken);
|
||||
|
||||
if (user is null)
|
||||
{
|
||||
user = new UserEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = username,
|
||||
DisplayName = displayName ?? username,
|
||||
Role = role,
|
||||
AuthProvider = AuthConstants.ProviderOidc,
|
||||
ExternalId = externalId,
|
||||
CreatedUtc = DateTimeOffset.UtcNow,
|
||||
};
|
||||
db.Users.Add(user);
|
||||
}
|
||||
else
|
||||
{
|
||||
user.Username = username;
|
||||
user.DisplayName = displayName ?? username;
|
||||
user.Role = role;
|
||||
}
|
||||
|
||||
user.LastLoginUtc = DateTimeOffset.UtcNow;
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>Backend</RootNamespace>
|
||||
<UserSecretsId>backend-dev-secrets</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AWSSDK.S3" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="NATS.Net" />
|
||||
<PackageReference Include="NATS.Jwt" />
|
||||
<PackageReference Include="NATS.NKeys" />
|
||||
<PackageReference Include="Serilog.AspNetCore" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Shared.Contracts\Shared.Contracts.csproj" />
|
||||
<ProjectReference Include="..\Shared.Infrastructure\Shared.Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,160 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Backend.Data;
|
||||
|
||||
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<UserEntity> Users => Set<UserEntity>();
|
||||
public DbSet<OidcProviderEntity> OidcProviders => Set<OidcProviderEntity>();
|
||||
public DbSet<DeviceEntity> Devices => Set<DeviceEntity>();
|
||||
public DbSet<DeviceInventoryEntity> DeviceInventory => Set<DeviceInventoryEntity>();
|
||||
public DbSet<ScriptEntity> Scripts => Set<ScriptEntity>();
|
||||
public DbSet<FunctionModuleEntity> FunctionModules => Set<FunctionModuleEntity>();
|
||||
public DbSet<JobEntity> Jobs => Set<JobEntity>();
|
||||
public DbSet<JobOutputEntity> JobOutput => Set<JobOutputEntity>();
|
||||
public DbSet<BootstrapTokenEntity> BootstrapTokens => Set<BootstrapTokenEntity>();
|
||||
public DbSet<AuditEventEntity> AuditEvents => Set<AuditEventEntity>();
|
||||
public DbSet<ShellSessionEntity> ShellSessions => Set<ShellSessionEntity>();
|
||||
public DbSet<DeviceGroupEntity> DeviceGroups => Set<DeviceGroupEntity>();
|
||||
public DbSet<DeviceGroupMemberEntity> DeviceGroupMembers => Set<DeviceGroupMemberEntity>();
|
||||
public DbSet<ScriptTriggerEntity> ScriptTriggers => Set<ScriptTriggerEntity>();
|
||||
public DbSet<ScriptTriggerRunEntity> ScriptTriggerRuns => Set<ScriptTriggerRunEntity>();
|
||||
|
||||
/// <summary>
|
||||
/// SQLite cannot ORDER BY / compare DateTimeOffset natively, so it stores
|
||||
/// timestamps as UTC ticks. Postgres and SQL Server use native timestamp
|
||||
/// columns. All application timestamps are UTC either way.
|
||||
/// </summary>
|
||||
protected virtual bool StoreTimestampsAsTicks => false;
|
||||
|
||||
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
|
||||
{
|
||||
if (StoreTimestampsAsTicks)
|
||||
{
|
||||
configurationBuilder.Properties<DateTimeOffset>().HaveConversion<UtcTicksConverter>();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class UtcTicksConverter() : ValueConverter<DateTimeOffset, long>(
|
||||
value => value.UtcTicks,
|
||||
ticks => new DateTimeOffset(ticks, TimeSpan.Zero));
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<UserEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("Users");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.HasIndex(e => e.Username).IsUnique();
|
||||
entity.Property(e => e.Role).HasConversion<string>();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<OidcProviderEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("OidcProviders");
|
||||
entity.HasKey(e => e.Id);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<DeviceEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("Devices");
|
||||
entity.HasKey(e => e.ClientId);
|
||||
entity.HasIndex(e => e.Hostname);
|
||||
entity.HasOne(e => e.Inventory)
|
||||
.WithOne()
|
||||
.HasForeignKey<DeviceInventoryEntity>(e => e.ClientId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<DeviceInventoryEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("DeviceInventory");
|
||||
entity.HasKey(e => e.ClientId);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<ScriptEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("Scripts");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.HasIndex(e => e.Name);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<FunctionModuleEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("FunctionModules");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.HasIndex(e => e.Name);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<JobEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("Jobs");
|
||||
entity.HasKey(e => e.JobId);
|
||||
entity.HasIndex(e => e.ClientId);
|
||||
entity.HasIndex(e => e.CreatedUtc);
|
||||
entity.Property(e => e.State).HasConversion<string>();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<JobOutputEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("JobOutput");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.HasIndex(e => new { e.JobId, e.Sequence }).IsUnique();
|
||||
entity.Property(e => e.Stream).HasConversion<string>();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<BootstrapTokenEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("BootstrapTokens");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.HasIndex(e => e.TokenHash).IsUnique();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<AuditEventEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("AuditEvents");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.HasIndex(e => e.TimestampUtc);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<ShellSessionEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("ShellSessions");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.HasIndex(e => e.ClientId);
|
||||
entity.Property(e => e.State).HasConversion<string>();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<DeviceGroupEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("DeviceGroups");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.HasIndex(e => e.Name).IsUnique();
|
||||
entity.Property(e => e.Kind).HasConversion<string>();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<DeviceGroupMemberEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("DeviceGroupMembers");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.HasIndex(e => new { e.GroupId, e.ClientId }).IsUnique();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<ScriptTriggerEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("ScriptTriggers");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.HasIndex(e => e.TriggerType);
|
||||
entity.Property(e => e.TriggerType).HasConversion<string>();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<ScriptTriggerRunEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("ScriptTriggerRuns");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.HasIndex(e => new { e.TriggerId, e.ClientId }).IsUnique();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
namespace Backend.Data;
|
||||
|
||||
/// <summary>Supported relational providers. SQLite is the default.</summary>
|
||||
public enum DatabaseProvider
|
||||
{
|
||||
Sqlite,
|
||||
Postgres,
|
||||
SqlServer,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Database selection. SQLite uses <c>DATABASE_PATH</c>; the server providers
|
||||
/// use <c>DATABASE_CONNECTION_STRING</c>.
|
||||
/// </summary>
|
||||
public sealed class DatabaseOptions
|
||||
{
|
||||
public DatabaseProvider Provider { get; init; } = DatabaseProvider.Sqlite;
|
||||
public required string ConnectionString { get; init; }
|
||||
|
||||
public static DatabaseOptions FromConfiguration(IConfiguration configuration)
|
||||
{
|
||||
var provider = (configuration["DATABASE_PROVIDER"] ?? "sqlite").Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"postgres" or "postgresql" or "npgsql" => DatabaseProvider.Postgres,
|
||||
"sqlserver" or "mssql" => DatabaseProvider.SqlServer,
|
||||
_ => DatabaseProvider.Sqlite,
|
||||
};
|
||||
|
||||
var connectionString = configuration["DATABASE_CONNECTION_STRING"];
|
||||
|
||||
if (provider == DatabaseProvider.Sqlite)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(connectionString))
|
||||
{
|
||||
var path = configuration["DATABASE_PATH"];
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
path = Path.Combine("data", "app.db");
|
||||
}
|
||||
|
||||
var directory = Path.GetDirectoryName(Path.GetFullPath(path));
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
connectionString = $"Data Source={path}";
|
||||
}
|
||||
}
|
||||
else if (string.IsNullOrWhiteSpace(connectionString))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"DATABASE_PROVIDER={provider} requires DATABASE_CONNECTION_STRING.");
|
||||
}
|
||||
|
||||
return new DatabaseOptions { Provider = provider, ConnectionString = connectionString! };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
using System.Text.Json;
|
||||
using Shared.Contracts.Models;
|
||||
using Shared.Contracts.Serialization;
|
||||
|
||||
namespace Backend.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Development-only sample data (DEV_SEED=1) so the UI has devices, inventory
|
||||
/// and jobs to render without a live agent. Never runs outside Development.
|
||||
/// </summary>
|
||||
public static class DevSeeder
|
||||
{
|
||||
public static async Task SeedAsync(AppDbContext db, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (db.Devices.Any())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
var samples = new[]
|
||||
{
|
||||
("PC-ENG-014", "Dell Inc.", "OptiPlex 7090", "Windows 11 Pro", TimeSpan.FromSeconds(12), new[] { "10.20.4.14" }, new[] { "engineering", "workstation" }),
|
||||
("PC-FIN-003", "LENOVO", "ThinkCentre M90q", "Windows 11 Enterprise", TimeSpan.FromMinutes(3), new[] { "10.20.6.3" }, new[] { "finance", "workstation" }),
|
||||
("LAB-VM-27", "Microsoft Corporation", "Virtual Machine", "Windows Server 2022", TimeSpan.FromMinutes(20), new[] { "10.30.9.27" }, new[] { "lab", "server" }),
|
||||
};
|
||||
|
||||
var i = 0;
|
||||
foreach (var (hostname, mfr, model, os, seenAgo, ips, tags) in samples)
|
||||
{
|
||||
var clientId = (Guid.NewGuid().ToString("N") + Guid.NewGuid().ToString("N"))[..64];
|
||||
var device = new DeviceEntity
|
||||
{
|
||||
ClientId = clientId,
|
||||
Hostname = hostname,
|
||||
Manufacturer = mfr,
|
||||
Model = model,
|
||||
OsCaption = os,
|
||||
OsVersion = "10.0.26100",
|
||||
AgentVersion = "2026.08.06.2151",
|
||||
NkeyPublic = "UADEVSEED" + i,
|
||||
EnrollmentId = Guid.NewGuid(),
|
||||
EnrolledUtc = now.AddDays(-i - 1),
|
||||
LastSeenUtc = now - seenAgo,
|
||||
IpAddressesJson = JsonSerializer.Serialize(ips, JsonDefaults.Options),
|
||||
TagsJson = JsonSerializer.Serialize(tags, JsonDefaults.Options),
|
||||
};
|
||||
db.Devices.Add(device);
|
||||
|
||||
var report = new InventoryReport(
|
||||
new InventoryIdentity(clientId, hostname, mfr, model, $"SN{1000 + i}", "1.14.3", $"BB{2000 + i}", "GRACE", true, "x64-based PC"),
|
||||
new InventoryOs(os, "10.0.26100", "26100", "64-bit", now.AddMonths(-6), now - seenAgo - TimeSpan.FromHours(9), "Professional"),
|
||||
new InventoryCpu("Intel(R) Core(TM) i7-11700 @ 2.50GHz", 16, 8),
|
||||
[new InventoryMemoryModule("DIMM A", 17_179_869_184, "Samsung", 3200), new InventoryMemoryModule("DIMM B", 17_179_869_184, "Samsung", 3200)],
|
||||
34_359_738_368,
|
||||
[new InventoryDisk("Samsung SSD 980 1TB", $"S{i}XYZ", 1_000_204_886_016, "NVMe")],
|
||||
[new InventoryVolume("C:", "NTFS", 1_000_204_886_016, 512_204_886_016)],
|
||||
[new InventoryNetworkAdapter("Intel Ethernet I219-LM", "00:1A:2B:3C:4D:0" + i, ips, ["fe80::1"], ["10.20.0.1"], ["10.20.0.10", "10.20.0.11"])],
|
||||
now - seenAgo);
|
||||
|
||||
db.DeviceInventory.Add(new DeviceInventoryEntity
|
||||
{
|
||||
ClientId = clientId,
|
||||
ReportJson = JsonDefaults.Serialize(report),
|
||||
UpdatedUtc = now - seenAgo,
|
||||
});
|
||||
i++;
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// Sample groups: one dynamic (rules) and one static.
|
||||
var dynamicRules = new GroupRuleSet(RuleCombine.And, [
|
||||
new RuleGroup(RuleCombine.Or, [
|
||||
new RuleCondition("manufacturer", RuleOperator.Equals, "Dell Inc."),
|
||||
new RuleCondition("manufacturer", RuleOperator.Equals, "LENOVO"),
|
||||
]),
|
||||
new RuleGroup(RuleCombine.And, [
|
||||
new RuleCondition("memory.totalGb", RuleOperator.GreaterOrEqual, "16"),
|
||||
new RuleCondition("tags", RuleOperator.Contains, "workstation"),
|
||||
]),
|
||||
]);
|
||||
|
||||
db.DeviceGroups.Add(new DeviceGroupEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Physical workstations (16 GB+)",
|
||||
Description = "Dell or Lenovo workstations with at least 16 GB of memory.",
|
||||
Kind = GroupKind.Dynamic,
|
||||
RulesJson = JsonDefaults.Serialize(dynamicRules),
|
||||
CreatedUtc = now,
|
||||
UpdatedUtc = now,
|
||||
UpdatedBy = "seed",
|
||||
});
|
||||
|
||||
var labGroup = new DeviceGroupEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Lab machines",
|
||||
Description = "Hand-picked lab devices.",
|
||||
Kind = GroupKind.Static,
|
||||
CreatedUtc = now,
|
||||
UpdatedUtc = now,
|
||||
UpdatedBy = "seed",
|
||||
};
|
||||
db.DeviceGroups.Add(labGroup);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
|
||||
var labDevice = db.Devices.FirstOrDefault(d => d.Hostname == "LAB-VM-27");
|
||||
if (labDevice is not null)
|
||||
{
|
||||
db.DeviceGroupMembers.Add(new DeviceGroupMemberEntity
|
||||
{
|
||||
GroupId = labGroup.Id,
|
||||
ClientId = labDevice.ClientId,
|
||||
AddedUtc = now,
|
||||
});
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
var firstDevice = db.Devices.First();
|
||||
var script = db.Scripts.FirstOrDefault();
|
||||
if (script is not null)
|
||||
{
|
||||
var jobs = new[]
|
||||
{
|
||||
(JobState.Succeeded, now.AddMinutes(-8), now.AddMinutes(-7), 0),
|
||||
(JobState.Running, now.AddMinutes(-1), (DateTimeOffset?)null, (int?)null),
|
||||
(JobState.Failed, now.AddHours(-2), now.AddHours(-2).AddSeconds(4), 1),
|
||||
};
|
||||
|
||||
foreach (var (state, started, completed, exit) in jobs)
|
||||
{
|
||||
var job = new JobEntity
|
||||
{
|
||||
JobId = Guid.NewGuid(),
|
||||
ClientId = firstDevice.ClientId,
|
||||
ScriptId = script.Id,
|
||||
ScriptName = script.Name,
|
||||
State = state,
|
||||
CreatedUtc = started.AddSeconds(-1),
|
||||
StartedUtc = started,
|
||||
CompletedUtc = completed,
|
||||
ExitCode = exit,
|
||||
RequestedBy = "admin",
|
||||
OutputSummary = state == JobState.Failed ? "Access to the path is denied." : null,
|
||||
};
|
||||
db.Jobs.Add(job);
|
||||
|
||||
for (var s = 1; s <= 5; s++)
|
||||
{
|
||||
db.JobOutput.Add(new JobOutputEntity
|
||||
{
|
||||
JobId = job.JobId,
|
||||
Sequence = s,
|
||||
Stream = OutputStreamKind.Output,
|
||||
TimestampUtc = started.AddSeconds(s),
|
||||
Text = $"Completed step {s}",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
using Shared.Contracts.Models;
|
||||
|
||||
namespace Backend.Data;
|
||||
|
||||
public sealed class UserEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public required string Username { get; set; }
|
||||
public string? DisplayName { get; set; }
|
||||
public string? PasswordHash { get; set; }
|
||||
public UserRole Role { get; set; }
|
||||
/// <summary>"local" or "oidc".</summary>
|
||||
public required string AuthProvider { get; set; }
|
||||
/// <summary>OIDC subject claim for external users.</summary>
|
||||
public string? ExternalId { get; set; }
|
||||
public DateTimeOffset CreatedUtc { get; set; }
|
||||
public DateTimeOffset? LastLoginUtc { get; set; }
|
||||
}
|
||||
|
||||
public sealed class OidcProviderEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public required string Authority { get; set; }
|
||||
public required string ClientId { get; set; }
|
||||
public bool Enabled { get; set; }
|
||||
}
|
||||
|
||||
public sealed class DeviceEntity
|
||||
{
|
||||
public required string ClientId { get; set; }
|
||||
public required string Hostname { get; set; }
|
||||
public string? Manufacturer { get; set; }
|
||||
public string? Model { get; set; }
|
||||
public string? OsCaption { get; set; }
|
||||
public string? OsVersion { get; set; }
|
||||
public string? AgentVersion { get; set; }
|
||||
/// <summary>Enrolled NATS user public key bound to this device.</summary>
|
||||
public required string NkeyPublic { get; set; }
|
||||
public Guid EnrollmentId { get; set; }
|
||||
public DateTimeOffset EnrolledUtc { get; set; }
|
||||
public DateTimeOffset? LastSeenUtc { get; set; }
|
||||
/// <summary>JSON array of current IP addresses (from presence/inventory).</summary>
|
||||
public string? IpAddressesJson { get; set; }
|
||||
/// <summary>JSON array of operator-assigned tags (usable in group rules).</summary>
|
||||
public string? TagsJson { get; set; }
|
||||
/// <summary>Set once the agent has reported it is connected and consuming commands.</summary>
|
||||
public DateTimeOffset? ReadyUtc { get; set; }
|
||||
/// <summary>
|
||||
/// Silent past the configured orphan window: credential refresh and job
|
||||
/// dispatch are refused until the device re-enrolls with a fresh token.
|
||||
/// </summary>
|
||||
public bool IsOrphaned { get; set; }
|
||||
public DateTimeOffset? OrphanedUtc { get; set; }
|
||||
|
||||
public DeviceInventoryEntity? Inventory { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A static or rule-based dynamic device group.</summary>
|
||||
public sealed class DeviceGroupEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public GroupKind Kind { get; set; }
|
||||
/// <summary>Serialized GroupRuleSet; only meaningful for dynamic groups.</summary>
|
||||
public string? RulesJson { get; set; }
|
||||
public DateTimeOffset CreatedUtc { get; set; }
|
||||
public DateTimeOffset UpdatedUtc { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Explicit membership row for static groups.</summary>
|
||||
public sealed class DeviceGroupMemberEntity
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public Guid GroupId { get; set; }
|
||||
public required string ClientId { get; set; }
|
||||
public DateTimeOffset AddedUtc { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs a script automatically when a lifecycle event occurs for a device in
|
||||
/// the target group (or every device when GroupId is null).
|
||||
/// </summary>
|
||||
public sealed class ScriptTriggerEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid ScriptId { get; set; }
|
||||
public Guid? GroupId { get; set; }
|
||||
public ScriptTriggerType TriggerType { get; set; }
|
||||
public bool Enabled { get; set; } = true;
|
||||
/// <summary>Run at most once per device (default) or every time the event fires.</summary>
|
||||
public bool OncePerDevice { get; set; } = true;
|
||||
public DateTimeOffset CreatedUtc { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Records that a trigger already fired for a device (OncePerDevice).</summary>
|
||||
public sealed class ScriptTriggerRunEntity
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public Guid TriggerId { get; set; }
|
||||
public required string ClientId { get; set; }
|
||||
public Guid JobId { get; set; }
|
||||
public DateTimeOffset FiredUtc { get; set; }
|
||||
}
|
||||
|
||||
public sealed class DeviceInventoryEntity
|
||||
{
|
||||
public required string ClientId { get; set; }
|
||||
/// <summary>Latest full InventoryReport snapshot as JSON (MVP keeps latest only).</summary>
|
||||
public required string ReportJson { get; set; }
|
||||
public DateTimeOffset UpdatedUtc { get; set; }
|
||||
}
|
||||
|
||||
public sealed class ScriptEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public required string Language { get; set; }
|
||||
public required string Content { get; set; }
|
||||
/// <summary>JSON array of ScriptParameter definitions.</summary>
|
||||
public string? ParametersJson { get; set; }
|
||||
/// <summary>JSON array of attached FunctionModule ids (prepended at run time).</summary>
|
||||
public string? FunctionModuleIdsJson { get; set; }
|
||||
public DateTimeOffset CreatedUtc { get; set; }
|
||||
public DateTimeOffset UpdatedUtc { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Reusable PowerShell function library prepended to referencing scripts.</summary>
|
||||
public sealed class FunctionModuleEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public required string Content { get; set; }
|
||||
public DateTimeOffset CreatedUtc { get; set; }
|
||||
public DateTimeOffset UpdatedUtc { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
|
||||
public sealed class JobEntity
|
||||
{
|
||||
public Guid JobId { get; set; }
|
||||
public required string ClientId { get; set; }
|
||||
public Guid ScriptId { get; set; }
|
||||
public required string ScriptName { get; set; }
|
||||
public JobState State { get; set; }
|
||||
public DateTimeOffset CreatedUtc { get; set; }
|
||||
public DateTimeOffset? StartedUtc { get; set; }
|
||||
public DateTimeOffset? CompletedUtc { get; set; }
|
||||
public int? ExitCode { get; set; }
|
||||
public string? RequestedBy { get; set; }
|
||||
public string? OutputSummary { get; set; }
|
||||
}
|
||||
|
||||
public sealed class JobOutputEntity
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public Guid JobId { get; set; }
|
||||
public long Sequence { get; set; }
|
||||
public OutputStreamKind Stream { get; set; }
|
||||
public DateTimeOffset TimestampUtc { get; set; }
|
||||
public required string Text { get; set; }
|
||||
}
|
||||
|
||||
public sealed class BootstrapTokenEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
/// <summary>SHA-256 hex of the token; plaintext is never stored.</summary>
|
||||
public required string TokenHash { get; set; }
|
||||
public DateTimeOffset CreatedUtc { get; set; }
|
||||
public DateTimeOffset ExpiresUtc { get; set; }
|
||||
public int MaxUses { get; set; }
|
||||
public int Uses { get; set; }
|
||||
public bool Revoked { get; set; }
|
||||
public string? Note { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
}
|
||||
|
||||
public sealed class AuditEventEntity
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public DateTimeOffset TimestampUtc { get; set; }
|
||||
public required string Category { get; set; }
|
||||
public required string Action { get; set; }
|
||||
public string? Actor { get; set; }
|
||||
public string? ClientId { get; set; }
|
||||
public string? Detail { get; set; }
|
||||
public string? RemoteIp { get; set; }
|
||||
}
|
||||
|
||||
public sealed class ShellSessionEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public required string ClientId { get; set; }
|
||||
public string? RequestedBy { get; set; }
|
||||
public ShellSessionState State { get; set; }
|
||||
public DateTimeOffset CreatedUtc { get; set; }
|
||||
public DateTimeOffset? ClosedUtc { get; set; }
|
||||
/// <summary>Metadata only — shell transcripts are not persisted in the MVP.</summary>
|
||||
public string? CloseReason { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Backend.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Backend.Data.Migrations.Postgres
|
||||
{
|
||||
[DbContext(typeof(PostgresAppDbContext))]
|
||||
[Migration("20260807013241_InitialCreate")]
|
||||
partial class InitialCreate
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.10")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("Backend.Data.AuditEventEntity", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||
|
||||
b.Property<string>("Action")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Actor")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Category")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ClientId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Detail")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("RemoteIp")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("TimestampUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TimestampUtc");
|
||||
|
||||
b.ToTable("AuditEvents", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", 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<DateTimeOffset>("ExpiresUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int>("MaxUses")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("Note")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("Revoked")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Uses")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("BootstrapTokens", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
|
||||
{
|
||||
b.Property<string>("ClientId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("AgentVersion")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("EnrolledUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid>("EnrollmentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Hostname")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("IpAddressesJson")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastSeenUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Manufacturer")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Model")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("NkeyPublic")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("OsCaption")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("OsVersion")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("ClientId");
|
||||
|
||||
b.HasIndex("Hostname");
|
||||
|
||||
b.ToTable("Devices", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
|
||||
{
|
||||
b.Property<string>("ClientId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ReportJson")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("ClientId");
|
||||
|
||||
b.ToTable("DeviceInventory", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Content")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("UpdatedBy")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name");
|
||||
|
||||
b.ToTable("FunctionModules", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.JobEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("JobId")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("ClientId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset?>("CompletedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int?>("ExitCode")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("OutputSummary")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("RequestedBy")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("ScriptId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("ScriptName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset?>("StartedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("State")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("JobId");
|
||||
|
||||
b.HasIndex("ClientId");
|
||||
|
||||
b.HasIndex("CreatedUtc");
|
||||
|
||||
b.ToTable("Jobs", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.JobOutputEntity", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||
|
||||
b.Property<Guid>("JobId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<long>("Sequence")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<string>("Stream")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Text")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("TimestampUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("JobId", "Sequence")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("JobOutput", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.OidcProviderEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Authority")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ClientId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("Enabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("OidcProviders", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.ScriptEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Content")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("CreatedBy")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("FunctionModuleIdsJson")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Language")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ParametersJson")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("UpdatedBy")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name");
|
||||
|
||||
b.ToTable("Scripts", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.ShellSessionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("ClientId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("CloseReason")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset?>("ClosedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("RequestedBy")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("State")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ClientId");
|
||||
|
||||
b.ToTable("ShellSessions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.UserEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("AuthProvider")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ExternalId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastLoginUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Username")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
|
||||
{
|
||||
b.HasOne("Backend.Data.DeviceEntity", null)
|
||||
.WithOne("Inventory")
|
||||
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
|
||||
{
|
||||
b.Navigation("Inventory");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Backend.Data.Migrations.Postgres
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitialCreate : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "AuditEvents",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false)
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
TimestampUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
Category = table.Column<string>(type: "text", nullable: false),
|
||||
Action = table.Column<string>(type: "text", nullable: false),
|
||||
Actor = table.Column<string>(type: "text", nullable: true),
|
||||
ClientId = table.Column<string>(type: "text", nullable: true),
|
||||
Detail = table.Column<string>(type: "text", nullable: true),
|
||||
RemoteIp = table.Column<string>(type: "text", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_AuditEvents", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "BootstrapTokens",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
TokenHash = table.Column<string>(type: "text", nullable: false),
|
||||
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
ExpiresUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
MaxUses = table.Column<int>(type: "integer", nullable: false),
|
||||
Uses = table.Column<int>(type: "integer", nullable: false),
|
||||
Revoked = table.Column<bool>(type: "boolean", nullable: false),
|
||||
Note = table.Column<string>(type: "text", nullable: true),
|
||||
CreatedBy = table.Column<string>(type: "text", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_BootstrapTokens", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Devices",
|
||||
columns: table => new
|
||||
{
|
||||
ClientId = table.Column<string>(type: "text", nullable: false),
|
||||
Hostname = table.Column<string>(type: "text", nullable: false),
|
||||
Manufacturer = table.Column<string>(type: "text", nullable: true),
|
||||
Model = table.Column<string>(type: "text", nullable: true),
|
||||
OsCaption = table.Column<string>(type: "text", nullable: true),
|
||||
OsVersion = table.Column<string>(type: "text", nullable: true),
|
||||
AgentVersion = table.Column<string>(type: "text", nullable: true),
|
||||
NkeyPublic = table.Column<string>(type: "text", nullable: false),
|
||||
EnrollmentId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
EnrolledUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
LastSeenUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
IpAddressesJson = table.Column<string>(type: "text", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Devices", x => x.ClientId);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "FunctionModules",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Name = table.Column<string>(type: "text", nullable: false),
|
||||
Description = table.Column<string>(type: "text", nullable: true),
|
||||
Content = table.Column<string>(type: "text", nullable: false),
|
||||
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
UpdatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
UpdatedBy = table.Column<string>(type: "text", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_FunctionModules", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "JobOutput",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false)
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
JobId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Sequence = table.Column<long>(type: "bigint", nullable: false),
|
||||
Stream = table.Column<string>(type: "text", nullable: false),
|
||||
TimestampUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
Text = table.Column<string>(type: "text", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_JobOutput", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Jobs",
|
||||
columns: table => new
|
||||
{
|
||||
JobId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
ClientId = table.Column<string>(type: "text", nullable: false),
|
||||
ScriptId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
ScriptName = table.Column<string>(type: "text", nullable: false),
|
||||
State = table.Column<string>(type: "text", nullable: false),
|
||||
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
StartedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
CompletedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
ExitCode = table.Column<int>(type: "integer", nullable: true),
|
||||
RequestedBy = table.Column<string>(type: "text", nullable: true),
|
||||
OutputSummary = table.Column<string>(type: "text", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Jobs", x => x.JobId);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "OidcProviders",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Name = table.Column<string>(type: "text", nullable: false),
|
||||
Authority = table.Column<string>(type: "text", nullable: false),
|
||||
ClientId = table.Column<string>(type: "text", nullable: false),
|
||||
Enabled = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_OidcProviders", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Scripts",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Name = table.Column<string>(type: "text", nullable: false),
|
||||
Description = table.Column<string>(type: "text", nullable: true),
|
||||
Language = table.Column<string>(type: "text", nullable: false),
|
||||
Content = table.Column<string>(type: "text", nullable: false),
|
||||
ParametersJson = table.Column<string>(type: "text", nullable: true),
|
||||
FunctionModuleIdsJson = table.Column<string>(type: "text", nullable: true),
|
||||
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
UpdatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
CreatedBy = table.Column<string>(type: "text", nullable: true),
|
||||
UpdatedBy = table.Column<string>(type: "text", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Scripts", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ShellSessions",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
ClientId = table.Column<string>(type: "text", nullable: false),
|
||||
RequestedBy = table.Column<string>(type: "text", nullable: true),
|
||||
State = table.Column<string>(type: "text", nullable: false),
|
||||
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
ClosedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
CloseReason = table.Column<string>(type: "text", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_ShellSessions", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Users",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Username = table.Column<string>(type: "text", nullable: false),
|
||||
DisplayName = table.Column<string>(type: "text", nullable: true),
|
||||
PasswordHash = table.Column<string>(type: "text", nullable: true),
|
||||
Role = table.Column<string>(type: "text", nullable: false),
|
||||
AuthProvider = table.Column<string>(type: "text", nullable: false),
|
||||
ExternalId = table.Column<string>(type: "text", nullable: true),
|
||||
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
LastLoginUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Users", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "DeviceInventory",
|
||||
columns: table => new
|
||||
{
|
||||
ClientId = table.Column<string>(type: "text", nullable: false),
|
||||
ReportJson = table.Column<string>(type: "text", nullable: false),
|
||||
UpdatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_DeviceInventory", x => x.ClientId);
|
||||
table.ForeignKey(
|
||||
name: "FK_DeviceInventory_Devices_ClientId",
|
||||
column: x => x.ClientId,
|
||||
principalTable: "Devices",
|
||||
principalColumn: "ClientId",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_AuditEvents_TimestampUtc",
|
||||
table: "AuditEvents",
|
||||
column: "TimestampUtc");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_BootstrapTokens_TokenHash",
|
||||
table: "BootstrapTokens",
|
||||
column: "TokenHash",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Devices_Hostname",
|
||||
table: "Devices",
|
||||
column: "Hostname");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_FunctionModules_Name",
|
||||
table: "FunctionModules",
|
||||
column: "Name");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_JobOutput_JobId_Sequence",
|
||||
table: "JobOutput",
|
||||
columns: new[] { "JobId", "Sequence" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Jobs_ClientId",
|
||||
table: "Jobs",
|
||||
column: "ClientId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Jobs_CreatedUtc",
|
||||
table: "Jobs",
|
||||
column: "CreatedUtc");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Scripts_Name",
|
||||
table: "Scripts",
|
||||
column: "Name");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ShellSessions_ClientId",
|
||||
table: "ShellSessions",
|
||||
column: "ClientId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Users_Username",
|
||||
table: "Users",
|
||||
column: "Username",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "AuditEvents");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "BootstrapTokens");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "DeviceInventory");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "FunctionModules");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "JobOutput");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Jobs");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "OidcProviders");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Scripts");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "ShellSessions");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Users");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Devices");
|
||||
}
|
||||
}
|
||||
}
|
||||