diff --git a/.env.example b/.env.example index 740c269..6797b11 100644 --- a/.env.example +++ b/.env.example @@ -75,16 +75,27 @@ INITIAL_ADMIN_USERNAME=admin # Generate: openssl rand -base64 24 INITIAL_ADMIN_PASSWORD= -# ── OIDC (optional) ──────────────────────────────────────────────────────── +# ── OIDC (optional; also configurable from Settings → Authentication) ────── +# Register the redirect URI /api/auth/oidc/callback at your provider. +# The path is fixed by design — the Settings page shows the exact value. OIDC_ENABLED=0 OIDC_AUTHORITY= OIDC_CLIENT_ID= OIDC_CLIENT_SECRET= -OIDC_CALLBACK_PATH=/signin-oidc +# Friendly name shown on the sign-in button (Authentik, Entra ID, Keycloak…) +OIDC_PROVIDER_NAME= OIDC_SCOPES=openid profile email OIDC_NAME_CLAIM= OIDC_ROLE_CLAIM= OIDC_ADMIN_ROLE= +OIDC_OPERATOR_ROLE= +OIDC_VIEWER_ROLE= +OIDC_DEFAULT_ROLE=Operator +OIDC_REQUIRE_MAPPED_ROLE=0 +# LocalOnly | Both | OidcOnly | OidcAutoRedirect +AUTH_LOGIN_MODE=Both +# Break-glass: 1 bypasses OIDC entirely regardless of saved settings. +AUTH_FORCE_LOCAL=0 # ── NATS decentralized auth (generated — do NOT hand-edit) ───────────────── # These MUST be real Ed25519 NKeys from scripts/New-LocalSecrets.ps1 diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index ded0182..422893a 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -9,10 +9,25 @@ on: jobs: build-test: # Windows is required to build/test the agent (CIM, ConPTY, DPAPI, service). - runs-on: windows + # Label must match a registered runner: windows-host. + runs-on: windows-host steps: + # This repository uses the SHA-256 object format. actions/checkout + # cannot clone it (it inits a SHA-1 repo then fetches: "mismatched + # algorithms"), so check out with plain git clone, which negotiates + # the object format correctly. - name: Checkout - uses: actions/checkout@v4 + shell: pwsh + env: + CHECKOUT_TOKEN: ${{ github.token }} + run: | + $ErrorActionPreference = 'Stop' + Get-ChildItem -Force | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue + $ref = '${{ github.head_ref }}' + if (-not $ref) { $ref = '${{ github.ref_name }}' } + $url = '${{ github.server_url }}/${{ github.repository }}.git' -replace '^https://', "https://x-access-token:$env:CHECKOUT_TOKEN@" + git clone --depth 1 --branch $ref $url . + git log -1 --format='%H %s' - name: Setup .NET 10 uses: actions/setup-dotnet@v4 @@ -22,7 +37,8 @@ jobs: - name: Setup Node uses: actions/setup-node@v4 with: - node-version: '20' + # @nats-io/* packages require Node >= 22. + node-version: '22' - name: Compute unified version id: ver @@ -61,6 +77,30 @@ jobs: run: npm run build working-directory: src/WebUI + # Package the agent here (only Windows can build it) so the Linux image + # job can bake it into the backend image — no manual seeding at deploy. + - name: Package agent + if: ${{ github.event_name == 'push' }} + shell: pwsh + run: | + ./scripts/Package-Agent.ps1 -Version ${{ steps.ver.outputs.version }} + $stage = 'artifacts/agent-package' + New-Item -ItemType Directory -Force $stage | Out-Null + $msi = "artifacts/Agent-${{ steps.ver.outputs.version }}.msi" + $zip = "artifacts/Agent-${{ steps.ver.outputs.version }}-win-x64.zip" + if (Test-Path $msi) { Copy-Item $msi "$stage/Agent.msi" } + if (Test-Path $zip) { Copy-Item $zip "$stage/Agent.zip" } + '${{ steps.ver.outputs.version }}' | Set-Content "$stage/VERSION" -NoNewline + Get-ChildItem $stage | Select-Object Name, Length + + - name: Upload agent package + if: ${{ github.event_name == 'push' }} + uses: actions/upload-artifact@v3 + with: + name: agent-package + path: artifacts/agent-package/ + retention-days: 7 + images: # Build the backend + webui images and publish them to the Gitea container # registry. Image names match what docker-compose.yml pulls: @@ -68,7 +108,8 @@ jobs: # //executer-webui: needs: build-test if: ${{ github.event_name == 'push' }} - runs-on: ubuntu-latest + # Needs Docker; label must match a registered Linux runner. + runs-on: ubuntu-host 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 @@ -82,8 +123,19 @@ jobs: BUILTIN_TOKEN: ${{ secrets.GITEA_TOKEN }} OWNER: ${{ github.repository_owner }} steps: + # SHA-256 repo: plain git clone (see build-test). - name: Checkout - uses: actions/checkout@v4 + shell: bash + env: + CHECKOUT_TOKEN: ${{ github.token }} + run: | + set -e + find . -mindepth 1 -maxdepth 1 -exec rm -rf {} + 2>/dev/null || true + REF='${{ github.head_ref }}' + [ -z "$REF" ] && REF='${{ github.ref_name }}' + URL="$(echo '${{ github.server_url }}/${{ github.repository }}.git' | sed "s#^https://#https://x-access-token:${CHECKOUT_TOKEN}@#")" + git clone --depth 1 --branch "$REF" "$URL" . + git log -1 --format='%H %s' - name: Resolve version and registry target id: ver @@ -117,6 +169,24 @@ jobs: - name: Registry login run: echo "$REGISTRY_LOGIN_PASSWORD" | docker login "${{ steps.ver.outputs.host }}" -u "${{ steps.ver.outputs.user }}" --password-stdin + # Bake the Windows-built agent into the backend image so the URL install + # flow serves it with no manual seeding. + - name: Download agent package + uses: actions/download-artifact@v3 + continue-on-error: true + with: + name: agent-package + path: src/Infra/backend/agent-package + + - name: Confirm agent package staged + run: | + if ls src/Infra/backend/agent-package/Agent.* >/dev/null 2>&1; then + echo "Agent package will be baked into the backend image:" + ls -la src/Infra/backend/agent-package/ + else + echo "::warning::No agent package staged - the backend image will ship without an installer and /api/enrollment/agent-package will 404 until one is mounted or offloaded to S3." + fi + - name: Build images env: VERSION: ${{ steps.ver.outputs.version }} diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 1e3cbf8..f17b284 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -7,11 +7,22 @@ on: 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 + # to a Gitea release for the unified version. + # Label must match a registered runner: windows-host. + runs-on: windows-host steps: + # SHA-256 repo: plain git clone (actions/checkout inits SHA-1 and + # cannot fetch from a SHA-256 server). - name: Checkout - uses: actions/checkout@v4 + shell: pwsh + env: + CHECKOUT_TOKEN: ${{ github.token }} + run: | + $ErrorActionPreference = 'Stop' + Get-ChildItem -Force | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue + $url = '${{ github.server_url }}/${{ github.repository }}.git' -replace '^https://', "https://x-access-token:$env:CHECKOUT_TOKEN@" + git clone --depth 1 --branch '${{ github.ref_name }}' $url . + git log -1 --format='%H %s' - name: Setup .NET 10 uses: actions/setup-dotnet@v4 diff --git a/.gitignore b/.gitignore index 08c1dfb..b2fdd05 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,7 @@ assets/*.ico # OS noise Thumbs.db .DS_Store + +# CI stages the built agent installer here before the backend image build +src/Infra/backend/agent-package/* +!src/Infra/backend/agent-package/.gitkeep diff --git a/Directory.Packages.props b/Directory.Packages.props index d094619..d6087ed 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -32,6 +32,7 @@ + @@ -47,6 +48,7 @@ + diff --git a/README.md b/README.md index 67f3eb8..d00b441 100644 --- a/README.md +++ b/README.md @@ -39,15 +39,17 @@ with **no SignalR, SSE, or polling**. 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) +16. [Secrets providers and $Secrets](#secrets-providers-and-secrets) +17. [Device groups and script triggers](#device-groups-and-script-triggers) +18. [Group runs and schedules](#group-runs-and-schedules) +19. [Database providers](#database-providers) +20. [Logging](#logging) +21. [Device lifecycle: reconnect or orphan](#device-lifecycle-reconnect-or-orphan) +22. [S3 file delivery](#s3-file-delivery) +23. [CI/CD and GITEA_* variables](#cicd-and-gitea_-variables) +24. [Versioning](#versioning) +25. [MVP demo sequence](#mvp-demo-sequence) +26. [Troubleshooting](#troubleshooting) --- @@ -333,9 +335,10 @@ 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). +A ready-to-adapt single-file nginx site (nginx-ui style, edge rate limiting, +long-lived WebSocket timeouts and commented IP allow-lists) is in +[src/Infra/nginx](src/Infra/nginx). The OIDC callback (`/api/auth/oidc/callback`) +rides the `/api/*` location — no extra route is needed. --- @@ -427,7 +430,9 @@ 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): +Generic OIDC (any compliant provider — Authentik, Keycloak, Entra ID, Okta) is +configurable from **Settings → Authentication** (saved values override the +environment and apply without a restart) or bootstrapped via environment: ```text OIDC_ENABLED=1 @@ -437,11 +442,28 @@ OIDC_CLIENT_SECRET= OIDC_SCOPES=openid profile email OIDC_ROLE_CLAIM=groups OIDC_ADMIN_ROLE=executer-admins +OIDC_OPERATOR_ROLE=executer-operators +OIDC_VIEWER_ROLE=executer-viewers +AUTH_LOGIN_MODE=Both # LocalOnly | Both | OidcOnly | OidcAutoRedirect ``` +Register the redirect URI `/api/auth/oidc/callback` at the +provider — the path is fixed by design and shown (copyable) in the Settings UI. +Displayed URLs and generated install commands use `PUBLIC_SERVER_URL` when +set; otherwise they derive from **trusted forwarded headers**, so they are +correct behind the reverse proxy without any configuration. + 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. +file delivery), **Viewer** (read-only). Group→role mapping checks Admin → +Operator → Viewer (most privileged wins); unmatched users get the configured +default role, or are refused when *Require mapped role* is on. + +**Lockout recovery** (an IdP outage is never terminal): + +- `/login?local=1` always reveals the local sign-in form, even in SSO-only modes. +- `docker exec EXECUTER-API-00001 dotnet Backend.dll auth-reset --admin admin --password ''` + disables OIDC in the database and restores/creates a local admin. +- `AUTH_FORCE_LOCAL=1` (environment only) bypasses stored OIDC settings at startup. ![Login](docs/screenshots/login.png) @@ -450,10 +472,22 @@ 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. +string, number, boolean, array (with element type), and hashtable. Hashtable +entries are **typed per entry** — every key and value picks its own primitive +(string/number/boolean) as you add it, carried as native JSON and rebuilt by +the agent, so `@{ Name = 'x'; 42 = $true; Retries = 3 }` arrives exactly +typed. Values bind with `AddParameter`, so PowerShell receives real `[int]`, +`[bool]`, `[string[]]`, and `[hashtable]` values. The builder sits in a +full-width strip above the editor (toggle **Define**); run-time values stay in +the side panel next to the target. + +String values **expand on the target device automatically** — `%TEMP%`, +`$env:COMPUTERNAME` and `$(…)` resolve with the *device's* environment +(`ExpandEnvironmentVariables`, then `ExpandString` in the job's runspace) +before the script runs. Mark a parameter **Literal** in the builder to opt out +and pass the raw text through exactly as typed (regex patterns, literal `$`). +Expansion applies to string scalars, string array elements and hashtable +values — hashtable keys stay literal. Reusable **function modules** (managed under **Functions**) can be attached to a script; the backend prepends them as a prelude executed first in the same @@ -463,6 +497,42 @@ runspace, so individual scripts stay small and duplication is avoided. --- +## Secrets providers and $Secrets + +Configure external vaults under **Settings → Secrets providers** (Infisical +first; the driver interface is pluggable). Connection details are stored as a +**Data Protection-encrypted blob**, secret config fields never return to the +browser, and a **Test connection** validates authentication and listing before +you rely on it. + +In the script editor's define strip, bind entries of a secrets dictionary to +provider secrets. At dispatch time the **server** resolves every binding and +sends only the values with the job — **devices and browsers never contact the +vault and never hold vault credentials**. The agent injects them as a +**case-insensitive ordered dictionary** session variable (name configurable per +script, default `Secrets`): + +```powershell +# Bindings: ApiKey ← Infisical API_KEY, DbPassword ← Infisical DB_PASSWORD +Invoke-RestMethod -Uri $Url -Headers @{ Authorization = "Bearer $($Secrets.ApiKey)" } +$cred = ConvertTo-SecureString $Secrets.dbpassword -AsPlainText -Force # case-insensitive +``` + +The secret picker **browses the vault**: folders starting from the provider's +default path, then a dropdown of secret names at the chosen path (names only — +values never reach the browser), with manual entry as the fallback when the +vault is unreachable. Saved providers have a per-row **⚡ Test** that validates +the stored credentials without re-entering them. A failed fetch at dispatch +(vault down, secret missing) fails the job with a value-free error naming the +binding and provider. Triggered and scheduled runs resolve secrets the same +way as manual runs. + +![Secrets providers](docs/screenshots/settings-secrets.png) + +![Script parameters and secrets](docs/screenshots/script-parameters.png) + +--- + ## Device groups and script triggers Groups are either **static** (an explicit member list) or **dynamic** (rules @@ -511,6 +581,48 @@ and typed parameters and appear alongside manual runs. --- +## Group runs and schedules + +The script editor's target selector offers **devices and groups**. A group run +creates one job per non-orphaned member — offline members receive theirs +durably when they reconnect — and the side panel tracks every job live, with +click-to-focus output per device. Orphaned members are reported as skipped. + +**Schedules are reusable cadence objects** — a schedule defines *when* +(one-shot or recurring), nothing else. Scripts honor a schedule through +**assignments**: script + schedule + target (device or group, members resolved +at fire time) + stored run values. One "Nightly at 1am" cadence can drive any +number of scripts, and pausing the cadence pauses everything attached to it. + +The cadence builder leads with friendly selectors — *every N minutes/hours*, +*daily/weekly/monthly at a time* with weekday chips — and compiles them to +cron internally; a raw cron field exists only under **Advanced**. Whatever is +chosen is auto-described in plain English and grounded by a server-computed +preview of the next occurrences. + +![Schedule builder](docs/screenshots/script-schedule.png) + +The **Schedules** nav page manages the cadence objects and shows what uses +each one; the script editor's Schedules panel attaches/detaches them: + +![Schedules overview](docs/screenshots/schedules.png) + +Semantics worth knowing: + +- Expressions evaluate in the schedule's **time zone** (default UTC), so + "daily at 01:00" tracks DST; storage and comparison are UTC. +- The worker sweeps every 30 s; recurrence advances from *now* after each + firing, so server downtime causes **at most one late firing**, never a storm. +- One-shot cadences disable themselves after firing every assignment once. +- Each assignment records its own **last result** (jobs queued, or the error — + e.g. a vault failure) without stalling the cadence, and jobs show + `schedule:` as their requester. +- Deleting a script or a schedule removes its assignments with it. +- Run values captured when a schedule is attached are used for every firing; + secret bindings resolve fresh server-side at each fire time. + +--- + ## Database providers SQLite is the default and needs no configuration. Postgres and SQL Server are @@ -617,11 +729,62 @@ the device keeps its history, groups and tags. --- +## Agent installer delivery + +**The installer ships inside the backend image — no manual seeding.** The CI +Windows job runs `Package-Agent.ps1`, uploads the result as an artifact, and +the Linux image job stages it into the backend image at `/opt/executer/agent` +before `docker build`. A stock deployment can therefore serve +`/api/enrollment/install` immediately. + +The backend resolves the package in this order: + +1. `AGENT_PACKAGE_PATH`, when explicitly set +2. `/opt/executer/agent` — baked in by CI +3. `/data/agent` — a manually mounted volume (local builds, air-gapped) + +If S3 offload is enabled, `/api/enrollment/agent-package` returns a **302 to a +presigned URL** instead of streaming the file, keeping multi-megabyte +downloads off the control plane. If presigning fails for any reason it falls +back to local delivery rather than breaking installs. + +Settings → **Agent installer delivery** shows which source is live, the file +size, version and SHA-256, and offers a one-click upload to S3. Re-uploading an +unchanged build is skipped (the object key is content-addressed by hash). + +For a local build without CI: + +```powershell +./scripts/Package-Agent.ps1 # writes artifacts/Agent-.msi +# then mount that directory at /data/agent, or set AGENT_PACKAGE_PATH +``` + +--- + ## 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. +Configure an S3-compatible store (AWS S3, MinIO, Backblaze B2) from +**Settings → Object storage**, then push files from +**Device → Actions → Send file**. Credentials stay on the server — the endpoint +only ever sees a short-lived URL. + +**Configured and tested from the UI.** Settings saved in the browser are stored +in the database (the secret key encrypted at rest with Data Protection) and +override the `S3_*` environment variables, which remain the bootstrap defaults. +The **Test connection** button runs a real round-trip and reports each step +separately, so a partial failure is obvious: + +| Step | What it proves | +|------|----------------| +| bucket | Credentials valid and the bucket reachable | +| write | The key has `PutObject` | +| read | Content round-trips intact | +| presigned download | The signed URL is fetchable — this is the mechanism agents use, and the step that catches an endpoint reachable from the backend but not from devices | +| delete | The key can clean up after itself | + +A probe object is written under `executer-connectivity-check/` and deleted +again. Only a fully passing test records `lastTestUtc`, and agent offload +cannot be enabled until one has passed. ```mermaid sequenceDiagram diff --git a/docker-compose.yml b/docker-compose.yml index 79071c7..d461c2f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -115,15 +115,22 @@ services: PUBLIC_SERVER_URL: '${PUBLIC_SERVER_URL:-}' INITIAL_ADMIN_USERNAME: '${INITIAL_ADMIN_USERNAME:-}' INITIAL_ADMIN_PASSWORD: '${INITIAL_ADMIN_PASSWORD:-}' + # The OIDC callback path is fixed at /api/auth/oidc/callback (shown in the UI). 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_PROVIDER_NAME: '${OIDC_PROVIDER_NAME:-}' 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:-}' + OIDC_OPERATOR_ROLE: '${OIDC_OPERATOR_ROLE:-}' + OIDC_VIEWER_ROLE: '${OIDC_VIEWER_ROLE:-}' + OIDC_DEFAULT_ROLE: '${OIDC_DEFAULT_ROLE:-Operator}' + OIDC_REQUIRE_MAPPED_ROLE: '${OIDC_REQUIRE_MAPPED_ROLE:-0}' + AUTH_LOGIN_MODE: '${AUTH_LOGIN_MODE:-Both}' + AUTH_FORCE_LOCAL: '${AUTH_FORCE_LOCAL:-0}' NATS_ACCOUNT_SIGNING_SEED: '${NATS_ACCOUNT_SIGNING_SEED:-}' NATS_ACCOUNT_PUBLIC_KEY: '${NATS_ACCOUNT_PUBLIC_KEY:-}' AGENT_PACKAGE_PATH: '${AGENT_PACKAGE_PATH:-/data/agent}' diff --git a/docs/screenshots/dashboard-light.png b/docs/screenshots/dashboard-light.png index e7400ee..bba0f09 100644 Binary files a/docs/screenshots/dashboard-light.png and b/docs/screenshots/dashboard-light.png differ diff --git a/docs/screenshots/dashboard.png b/docs/screenshots/dashboard.png index 732bb2b..03cf18f 100644 Binary files a/docs/screenshots/dashboard.png and b/docs/screenshots/dashboard.png differ diff --git a/docs/screenshots/device-actions.png b/docs/screenshots/device-actions.png index 629f5ea..a26fe7c 100644 Binary files a/docs/screenshots/device-actions.png and b/docs/screenshots/device-actions.png differ diff --git a/docs/screenshots/device-detail.png b/docs/screenshots/device-detail.png index 788f724..b488dcc 100644 Binary files a/docs/screenshots/device-detail.png and b/docs/screenshots/device-detail.png differ diff --git a/docs/screenshots/device-hardware.png b/docs/screenshots/device-hardware.png index 4b7eecb..49d1d49 100644 Binary files a/docs/screenshots/device-hardware.png and b/docs/screenshots/device-hardware.png differ diff --git a/docs/screenshots/device-network.png b/docs/screenshots/device-network.png index b4c0cc6..7d8d25e 100644 Binary files a/docs/screenshots/device-network.png and b/docs/screenshots/device-network.png differ diff --git a/docs/screenshots/device-public-ip.png b/docs/screenshots/device-public-ip.png new file mode 100644 index 0000000..d88918c Binary files /dev/null and b/docs/screenshots/device-public-ip.png differ diff --git a/docs/screenshots/devices.png b/docs/screenshots/devices.png index 519caf3..01aacae 100644 Binary files a/docs/screenshots/devices.png and b/docs/screenshots/devices.png differ diff --git a/docs/screenshots/functions.png b/docs/screenshots/functions.png index 17d1fc5..98a18f5 100644 Binary files a/docs/screenshots/functions.png and b/docs/screenshots/functions.png differ diff --git a/docs/screenshots/groups-light.png b/docs/screenshots/groups-light.png index 2742bc1..ac7253a 100644 Binary files a/docs/screenshots/groups-light.png and b/docs/screenshots/groups-light.png differ diff --git a/docs/screenshots/groups-rule-builder.png b/docs/screenshots/groups-rule-builder.png index 374b054..15502c7 100644 Binary files a/docs/screenshots/groups-rule-builder.png and b/docs/screenshots/groups-rule-builder.png differ diff --git a/docs/screenshots/groups-static-members.png b/docs/screenshots/groups-static-members.png index c20fd2a..ea9e674 100644 Binary files a/docs/screenshots/groups-static-members.png and b/docs/screenshots/groups-static-members.png differ diff --git a/docs/screenshots/groups.png b/docs/screenshots/groups.png index 9be6c7c..ddda35e 100644 Binary files a/docs/screenshots/groups.png and b/docs/screenshots/groups.png differ diff --git a/docs/screenshots/jobs.png b/docs/screenshots/jobs.png index 2d9f40d..1f95702 100644 Binary files a/docs/screenshots/jobs.png and b/docs/screenshots/jobs.png differ diff --git a/docs/screenshots/login.png b/docs/screenshots/login.png index 992f625..075784e 100644 Binary files a/docs/screenshots/login.png and b/docs/screenshots/login.png differ diff --git a/docs/screenshots/schedules.png b/docs/screenshots/schedules.png new file mode 100644 index 0000000..236442c Binary files /dev/null and b/docs/screenshots/schedules.png differ diff --git a/docs/screenshots/script-editor.png b/docs/screenshots/script-editor.png index 6fc6935..d60ca42 100644 Binary files a/docs/screenshots/script-editor.png and b/docs/screenshots/script-editor.png differ diff --git a/docs/screenshots/script-parameters.png b/docs/screenshots/script-parameters.png index 0a96b63..7f558b7 100644 Binary files a/docs/screenshots/script-parameters.png and b/docs/screenshots/script-parameters.png differ diff --git a/docs/screenshots/script-schedule.png b/docs/screenshots/script-schedule.png new file mode 100644 index 0000000..5058090 Binary files /dev/null and b/docs/screenshots/script-schedule.png differ diff --git a/docs/screenshots/script-schedules-card.png b/docs/screenshots/script-schedules-card.png new file mode 100644 index 0000000..2ce7fc5 Binary files /dev/null and b/docs/screenshots/script-schedules-card.png differ diff --git a/docs/screenshots/scripts.png b/docs/screenshots/scripts.png index 528a015..63b5ebe 100644 Binary files a/docs/screenshots/scripts.png and b/docs/screenshots/scripts.png differ diff --git a/docs/screenshots/settings-install-command.png b/docs/screenshots/settings-install-command.png index 9088a07..b356dbe 100644 Binary files a/docs/screenshots/settings-install-command.png and b/docs/screenshots/settings-install-command.png differ diff --git a/docs/screenshots/settings-secrets.png b/docs/screenshots/settings-secrets.png new file mode 100644 index 0000000..86d00da Binary files /dev/null and b/docs/screenshots/settings-secrets.png differ diff --git a/docs/screenshots/settings.png b/docs/screenshots/settings.png index eca4480..0068ced 100644 Binary files a/docs/screenshots/settings.png and b/docs/screenshots/settings.png differ diff --git a/scripts/Generate-Icons.ps1 b/scripts/Generate-Icons.ps1 index 7e78933..829a737 100644 --- a/scripts/Generate-Icons.ps1 +++ b/scripts/Generate-Icons.ps1 @@ -27,6 +27,15 @@ if (-not $Force -and (Test-Path $output) -and $magick = Get-Command magick -ErrorAction SilentlyContinue if (-not $magick) { + # winget only exists in interactive user contexts — CI service accounts + # (LocalSystem) do not have it. The icon is cosmetic (the MSI compiles + # without it via ?ifdef AppIconPath), so degrade to a warning. + $winget = Get-Command winget -ErrorAction SilentlyContinue + if (-not $winget) { + Write-Warning 'ImageMagick and winget are both unavailable — skipping icon generation (MSI builds without an icon).' + return + } + 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)." } diff --git a/src/Agent/Enrollment/CredentialStore.cs b/src/Agent/Enrollment/CredentialStore.cs index 0449ac8..3eb7c04 100644 --- a/src/Agent/Enrollment/CredentialStore.cs +++ b/src/Agent/Enrollment/CredentialStore.cs @@ -21,7 +21,7 @@ public sealed record AgentCredentials( /// /// DPAPI(LocalMachine)-protected credential persistence in -/// %ProgramData%\<Company>\<Product>\credentials.dat. The file and its +/// %ProgramData%\ExecuteR\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. /// diff --git a/src/Agent/Inventory/InventoryCollector.cs b/src/Agent/Inventory/InventoryCollector.cs index 75a626b..f3390af 100644 --- a/src/Agent/Inventory/InventoryCollector.cs +++ b/src/Agent/Inventory/InventoryCollector.cs @@ -115,31 +115,87 @@ public sealed class InventoryCollector(IHardwareIdentitySource identitySource) private static List CollectDisks() { var disks = new List(); - Query("SELECT Model, SerialNumber, Size, InterfaceType FROM Win32_DiskDrive", obj => + Query("SELECT Index, 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)); + BusType: obj["InterfaceType"] as string, + Index: (int?)(obj["Index"] as uint?))); }); return disks; } private static List CollectVolumes() { + var letterToDisk = MapDriveLettersToDisks(); + var volumes = new List(); Query("SELECT DeviceID, FileSystem, Size, FreeSpace FROM Win32_LogicalDisk WHERE DriveType = 3", obj => { + var letter = obj["DeviceID"] as string ?? string.Empty; volumes.Add(new InventoryVolume( - DriveLetter: obj["DeviceID"] as string ?? string.Empty, + DriveLetter: letter, FileSystem: obj["FileSystem"] as string, TotalSizeBytes: (long?)(obj["Size"] as ulong?) ?? 0, - FreeSpaceBytes: (long?)(obj["FreeSpace"] as ulong?) ?? 0)); + FreeSpaceBytes: (long?)(obj["FreeSpace"] as ulong?) ?? 0, + DiskIndex: letterToDisk.TryGetValue(letter, out var index) ? index : null)); }); return volumes; } + /// + /// Walks Win32_DiskDriveToDiskPartition and Win32_LogicalDiskToPartition + /// so each drive letter maps back to its physical disk index. The + /// association rows expose object-reference strings; the identifiers are + /// parsed out of them. + /// + private static Dictionary MapDriveLettersToDisks() + { + // Win32_DiskPartition.DeviceID ("Disk #0, Partition #1") → disk index. + var partitionToDisk = new Dictionary(StringComparer.OrdinalIgnoreCase); + Query("SELECT Antecedent, Dependent FROM Win32_DiskDriveToDiskPartition", obj => + { + var driveRef = obj["Antecedent"] as string; // …PHYSICALDRIVE0" + var partitionRef = obj["Dependent"] as string; // …DeviceID="Disk #0, Partition #1" + var indexMatch = System.Text.RegularExpressions.Regex.Match( + driveRef ?? string.Empty, @"PHYSICALDRIVE(\d+)"); + var partition = ExtractDeviceId(partitionRef); + if (indexMatch.Success && partition is not null) + { + partitionToDisk[partition] = int.Parse(indexMatch.Groups[1].Value); + } + }); + + var letterToDisk = new Dictionary(StringComparer.OrdinalIgnoreCase); + Query("SELECT Antecedent, Dependent FROM Win32_LogicalDiskToPartition", obj => + { + var partition = ExtractDeviceId(obj["Antecedent"] as string); + var letter = ExtractDeviceId(obj["Dependent"] as string); + if (partition is not null && letter is not null + && partitionToDisk.TryGetValue(partition, out var index)) + { + letterToDisk[letter] = index; + } + }); + + return letterToDisk; + } + + /// Pulls the DeviceID value out of a WMI object-reference string. + private static string? ExtractDeviceId(string? objectReference) + { + if (objectReference is null) + { + return null; + } + + var match = System.Text.RegularExpressions.Regex.Match( + objectReference, "DeviceID=\"([^\"]+)\""); + return match.Success ? match.Groups[1].Value.Replace("\\\\", "\\") : null; + } + private static List CollectNetwork() { var adapters = new List(); diff --git a/src/Agent/PowerShell/PowerShellExecutionService.cs b/src/Agent/PowerShell/PowerShellExecutionService.cs index 4b4c7e6..3af8add 100644 --- a/src/Agent/PowerShell/PowerShellExecutionService.cs +++ b/src/Agent/PowerShell/PowerShellExecutionService.cs @@ -25,7 +25,10 @@ public sealed class PowerShellExecutionService /// Runs (reusable function definitions), if any, /// then the main in the same runspace, so /// the main script keeps its param() block first while still calling - /// shared functions. + /// shared functions. rewrites string argument + /// values with the device's environment before binding, and + /// are set on the runspace before + /// anything runs (used for the injected secrets dictionary). /// public async Task ExecuteAsync( string scriptContent, @@ -33,12 +36,27 @@ public sealed class PowerShellExecutionService string? prelude, Action onRecord, Action onProgress, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + IReadOnlyDictionary? expansions = null, + IReadOnlyDictionary? sessionVariables = null) { using var runspace = PowerShellRunspaceFactory.Create(); using var powerShell = System.Management.Automation.PowerShell.Create(); powerShell.Runspace = runspace; + if (sessionVariables is not null) + { + foreach (var (name, value) in sessionVariables) + { + runspace.SessionStateProxy.SetVariable(name, value); + } + } + + if (parameters is not null && expansions is { Count: > 0 }) + { + parameters = ValueExpander.Expand(parameters, expansions, runspace); + } + if (!string.IsNullOrWhiteSpace(prelude)) { powerShell.AddScript(prelude); diff --git a/src/Agent/PowerShell/PowerShellJobHandler.cs b/src/Agent/PowerShell/PowerShellJobHandler.cs index f68c4d5..485e60e 100644 --- a/src/Agent/PowerShell/PowerShellJobHandler.cs +++ b/src/Agent/PowerShell/PowerShellJobHandler.cs @@ -42,6 +42,28 @@ public sealed class PowerShellJobHandler( var pending = new List(); var boundParameters = ScriptArgumentBinder.Bind(command.Parameters, command.Arguments); + // Expansion is the background default; only Literal opts out. + var expansions = command.Parameters? + .Where(p => p.Expansion != ValueExpansion.Literal) + .ToDictionary(p => p.Name, p => p.Expansion, StringComparer.OrdinalIgnoreCase); + + // Server-resolved secrets become a case-insensitive ordered + // dictionary session variable ($Secrets.Name by default). Values + // are never logged or published by the agent. + Dictionary? sessionVariables = null; + if (command.Secrets is { Count: > 0 }) + { + var secrets = new System.Collections.Specialized.OrderedDictionary(StringComparer.OrdinalIgnoreCase); + foreach (var secret in command.Secrets) + { + secrets[secret.Name] = secret.Value; + } + + var variableName = string.IsNullOrWhiteSpace(command.SecretsVariableName) + ? "Secrets" + : command.SecretsVariableName; + sessionVariables = new Dictionary { [variableName] = secrets }; + } var result = await executionService.ExecuteAsync( command.Content, @@ -49,7 +71,9 @@ public sealed class PowerShellJobHandler( command.Prelude, onRecord: record => pending.Add(PublishOutputAsync(record, Interlocked.Increment(ref sequence))), onProgress: progress => pending.Add(PublishProgressAsync(progress)), - cancellationToken: timeoutCts.Token); + cancellationToken: timeoutCts.Token, + expansions: expansions, + sessionVariables: sessionVariables); await Task.WhenAll(pending); diff --git a/src/Agent/PowerShell/ScriptArgumentBinder.cs b/src/Agent/PowerShell/ScriptArgumentBinder.cs index dc12a40..b076a8f 100644 --- a/src/Agent/PowerShell/ScriptArgumentBinder.cs +++ b/src/Agent/PowerShell/ScriptArgumentBinder.cs @@ -54,8 +54,7 @@ public static class ScriptArgumentBinder 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), + ScriptParameterType.Hashtable => ConvertHashtable(value), _ => value.ToString(), }; @@ -72,7 +71,15 @@ public static class ScriptArgumentBinder { if (value.TryGetInt64(out var l)) { - return l is >= int.MinValue and <= int.MaxValue ? (int)l : l; + // Explicit branches: a conditional expression would widen the + // int back to long before boxing, breaking hashtable key + // equality (boxed long 42 never equals a literal int 42). + if (l is >= int.MinValue and <= int.MaxValue) + { + return (int)l; + } + + return l; } return value.GetDouble(); @@ -113,10 +120,11 @@ public static class ScriptArgumentBinder /// /// Accepts either a JSON object (string keys) or an array of - /// { "key": ..., "value": ... } pairs (typed keys) and returns a - /// PowerShell with coerced keys and values. + /// { "key": ..., "value": ... } pairs and returns a PowerShell + /// . Entries are typed per entry: the native JSON + /// kind of each key and value (string/number/boolean) is preserved. /// - private static Hashtable ConvertHashtable(PrimitiveType keyType, PrimitiveType valueType, JsonElement value) + private static Hashtable ConvertHashtable(JsonElement value) { var table = new Hashtable(); @@ -124,11 +132,7 @@ public static class ScriptArgumentBinder { foreach (var property in value.EnumerateObject()) { - var key = ConvertPrimitiveKey(keyType, property.Name); - if (key is not null) - { - table[key] = ConvertPrimitive(valueType, property.Value); - } + table[property.Name] = FromJson(property.Value); } } else if (value.ValueKind == JsonValueKind.Array) @@ -142,10 +146,10 @@ public static class ScriptArgumentBinder continue; } - var key = ConvertPrimitive(keyType, keyElement); + var key = FromJson(keyElement); if (key is not null) { - table[key] = ConvertPrimitive(valueType, valueElement); + table[key] = FromJson(valueElement); } } } @@ -153,11 +157,13 @@ public static class ScriptArgumentBinder 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, - }; + /// CLR value matching a JSON element's own kind. + private static object? FromJson(JsonElement element) => element.ValueKind switch + { + JsonValueKind.Number => ConvertNumber(element), + JsonValueKind.True => true, + JsonValueKind.False => false, + JsonValueKind.Null or JsonValueKind.Undefined => null, + _ => element.ToString(), + }; } diff --git a/src/Agent/PowerShell/ValueExpander.cs b/src/Agent/PowerShell/ValueExpander.cs new file mode 100644 index 0000000..f24b7c5 --- /dev/null +++ b/src/Agent/PowerShell/ValueExpander.cs @@ -0,0 +1,78 @@ +using System.Collections; +using System.Management.Automation.Runspaces; +using Shared.Contracts.Models; + +namespace Agent.PowerShell; + +/// +/// Expands string argument values on the target device in the background: +/// %VAR% via ExpandEnvironmentVariables, then $env:VAR and $(…) via +/// ExpandString in the job's runspace. Parameters marked +/// pass through untouched. +/// +public static class ValueExpander +{ + public static IReadOnlyDictionary Expand( + IReadOnlyDictionary values, + IReadOnlyDictionary expansions, + Runspace runspace) + { + var result = new Dictionary(values, StringComparer.OrdinalIgnoreCase); + + foreach (var (name, mode) in expansions) + { + if (mode == ValueExpansion.Literal || !result.TryGetValue(name, out var value)) + { + continue; + } + + result[name] = ExpandValue(value, runspace); + } + + return result; + } + + private static object? ExpandValue(object? value, Runspace runspace) => value switch + { + string s => ExpandString(s, runspace), + object?[] array => array.Select(item => ExpandValue(item, runspace)).ToArray(), + Hashtable table => ExpandHashtableValues(table, runspace), + _ => value, + }; + + private static Hashtable ExpandHashtableValues(Hashtable table, Runspace runspace) + { + // Keys stay literal — only values are subject to expansion. + var expanded = new Hashtable(); + foreach (DictionaryEntry entry in table) + { + expanded[entry.Key] = entry.Value is string s ? ExpandString(s, runspace) : entry.Value; + } + + return expanded; + } + + private static string ExpandString(string value, Runspace runspace) + { + // %VAR% first (pure .NET), then PowerShell string interpolation. + var expanded = System.Environment.ExpandEnvironmentVariables(value); + + // Nothing PowerShell would touch — skip the pipeline round-trip. + if (!expanded.Contains('$') && !expanded.Contains('`')) + { + return expanded; + } + + // ExpandString treats the input as double-quoted string content, so + // $env:VAR, $(…) and backtick escapes resolve; passing the raw value + // as an argument keeps embedded quotes from being re-parsed. + using var powerShell = System.Management.Automation.PowerShell.Create(); + powerShell.Runspace = runspace; + powerShell + .AddScript("param($s) $ExecutionContext.InvokeCommand.ExpandString($s)") + .AddArgument(expanded); + + var results = powerShell.Invoke(); + return results.Count > 0 && results[0] is not null ? results[0].ToString() : expanded; + } +} diff --git a/src/Backend/Api/DeviceEndpoints.cs b/src/Backend/Api/DeviceEndpoints.cs index f62c11e..008030c 100644 --- a/src/Backend/Api/DeviceEndpoints.cs +++ b/src/Backend/Api/DeviceEndpoints.cs @@ -103,6 +103,7 @@ public static class DeviceEndpoints LastSeenUtc: device.LastSeenUtc, EnrolledUtc: device.EnrolledUtc, Tags: Groups.DeviceGroupService.ParseTags(device.TagsJson), - IsOrphaned: device.IsOrphaned); + IsOrphaned: device.IsOrphaned, + PublicIp: device.PublicIp); } } diff --git a/src/Backend/Auth/AuthBootstrap.cs b/src/Backend/Auth/AuthBootstrap.cs new file mode 100644 index 0000000..ebed666 --- /dev/null +++ b/src/Backend/Auth/AuthBootstrap.cs @@ -0,0 +1,40 @@ +using Shared.Contracts.Models; + +namespace Backend.Auth; + +/// +/// Reads the environment bootstrap defaults for authentication. Anything saved +/// from the Settings UI layers on top of these. +/// +public static class AuthBootstrap +{ + public static AuthSettings FromConfiguration(IConfiguration configuration) + { + var mode = configuration["AUTH_LOGIN_MODE"]; + + return new AuthSettings + { + OidcEnabled = configuration["OIDC_ENABLED"] == "1", + Authority = configuration["OIDC_AUTHORITY"], + ClientId = configuration["OIDC_CLIENT_ID"], + ClientSecret = configuration["OIDC_CLIENT_SECRET"], + ProviderName = configuration["OIDC_PROVIDER_NAME"], + 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"], + OperatorRole = configuration["OIDC_OPERATOR_ROLE"], + ViewerRole = configuration["OIDC_VIEWER_ROLE"], + DefaultRole = Enum.TryParse(configuration["OIDC_DEFAULT_ROLE"], true, out var role) + ? role + : UserRole.Operator, + RequireMappedRole = configuration["OIDC_REQUIRE_MAPPED_ROLE"] == "1", + LoginMode = Enum.TryParse(mode, true, out var parsed) ? parsed : LoginMode.Both, + + // Break-glass: ignores stored OIDC settings entirely. + ForceLocal = configuration["AUTH_FORCE_LOCAL"] == "1", + }; + } +} diff --git a/src/Backend/Auth/AuthEndpoints.cs b/src/Backend/Auth/AuthEndpoints.cs index 3bfe2f4..5e67564 100644 --- a/src/Backend/Auth/AuthEndpoints.cs +++ b/src/Backend/Auth/AuthEndpoints.cs @@ -9,7 +9,7 @@ namespace Backend.Auth; public static class AuthEndpoints { - public static void Map(WebApplication app, OidcOptions oidc) + public static void Map(WebApplication app) { app.MapPost(ApiRoutes.AuthLogin, LoginAsync) .RequireRateLimiting(RateLimitPolicies.Auth) @@ -19,10 +19,16 @@ public static class AuthEndpoints 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." })) + // Challenge only when OIDC is actually usable, so a half-configured or + // disabled provider returns a clear error instead of a broken redirect. + app.MapGet(ApiRoutes.AuthOidcLogin, async ( + HttpContext context, AuthSettingsService settings, CancellationToken cancellationToken) => + { + var effective = await settings.GetEffectiveAsync(cancellationToken); + return effective.IsOidcUsable + ? Results.Challenge(new AuthenticationProperties { RedirectUri = "/" }, [AuthConstants.OidcScheme]) + : Results.NotFound(new { error = "Single sign-on is not configured." }); + }) .AllowAnonymous(); // OIDC completes at CallbackPath (handler-owned); this route lets the diff --git a/src/Backend/Auth/AuthExtensions.cs b/src/Backend/Auth/AuthExtensions.cs index a67dd49..5978f1a 100644 --- a/src/Backend/Auth/AuthExtensions.cs +++ b/src/Backend/Auth/AuthExtensions.cs @@ -1,32 +1,44 @@ using System.Security.Claims; using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using Microsoft.Extensions.Options; +using Microsoft.Extensions.Primitives; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Shared.Contracts.Models; namespace Backend.Auth; -/// Wires cookie + optional OIDC authentication and role-based authorization. +/// Wires cookie + OIDC authentication and role-based authorization. public static class AuthExtensions { - public static void AddControlPlaneAuth(this WebApplicationBuilder builder, OidcOptions oidc) + public static void AddControlPlaneAuth(this WebApplicationBuilder builder, AuthSettings bootstrap) { - var authBuilder = builder.Services + builder.Services.AddSingleton(bootstrap); + builder.Services.AddSingleton(new AuthSettingsCache(bootstrap)); + builder.Services.AddScoped(); + + // OpenIdConnectOptions are rebuilt from the settings cache whenever the + // UI saves, so enabling or repointing OIDC needs no restart. + builder.Services.AddSingleton, ConfigureOidc>(); + builder.Services.AddSingleton, OidcChangeTokenSource>(); + + builder.Services .AddAuthentication(options => { options.DefaultScheme = AuthConstants.CookieScheme; - options.DefaultChallengeScheme = oidc.IsUsable ? AuthConstants.OidcScheme : AuthConstants.CookieScheme; + // Challenges are issued explicitly by the login endpoints, so the + // default stays local; that keeps API 401s from bouncing to an IdP. + options.DefaultChallengeScheme = 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; @@ -37,88 +49,10 @@ public static class AuthExtensions 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(); - 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)); - } - }; - }); - } + }) + // Registered unconditionally; ConfigureOidc fills it from current + // settings and the login endpoint refuses to challenge when unusable. + .AddOpenIdConnect(AuthConstants.OidcScheme, _ => { }); builder.Services.AddAuthorization(options => { @@ -131,7 +65,6 @@ public static class AuthExtensions }); } - /// Builds the cookie principal for an authenticated user. public static ClaimsPrincipal BuildPrincipal(string username, string? displayName, UserRole role, string provider) { var identity = new ClaimsIdentity(AuthConstants.CookieScheme, ClaimTypes.Name, ClaimTypes.Role); @@ -146,3 +79,130 @@ public static class AuthExtensions return new ClaimsPrincipal(identity); } } + +/// Builds OpenIdConnectOptions from the live settings cache. +internal sealed class ConfigureOidc(AuthSettingsCache cache, IServiceScopeFactory scopeFactory) + : IConfigureNamedOptions +{ + public void Configure(OpenIdConnectOptions options) => Configure(Options.DefaultName, options); + + public void Configure(string? name, OpenIdConnectOptions options) + { + if (name != AuthConstants.OidcScheme) + { + return; + } + + var settings = cache.Current; + + // The OIDC handler is an IAuthenticationRequestHandler, so the + // authentication middleware initializes it on every request — and + // RemoteAuthenticationOptions.Validate() throws on a null Authority or + // ClientId. Placeholders keep validation happy while OIDC is off; the + // login endpoint refuses to challenge unless the real settings are + // usable, so these are never contacted. + options.Authority = string.IsNullOrWhiteSpace(settings.Authority) + ? "https://oidc.invalid/not-configured" + : settings.Authority; + options.ClientId = string.IsNullOrWhiteSpace(settings.ClientId) + ? "oidc-not-configured" + : settings.ClientId; + options.ClientSecret = settings.ClientSecret; + options.ResponseType = OpenIdConnectResponseType.Code; + // Fixed by design — must match the IdP registration exactly. + options.CallbackPath = AuthSettingsService.CallbackPath; + options.SaveTokens = false; + options.GetClaimsFromUserInfoEndpoint = true; + options.SignInScheme = AuthConstants.CookieScheme; + options.UsePkce = true; + + options.Scope.Clear(); + foreach (var scope in settings.Scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + options.Scope.Add(scope); + } + + if (!string.IsNullOrWhiteSpace(settings.NameClaim)) + { + options.TokenValidationParameters.NameClaimType = settings.NameClaim; + } + + if (!string.IsNullOrWhiteSpace(settings.RoleClaim)) + { + options.TokenValidationParameters.RoleClaimType = settings.RoleClaim; + } + + options.Events.OnTokenValidated = async context => + { + var current = cache.Current; + if (context.Principal?.Identity is not ClaimsIdentity identity) + { + return; + } + + var principal = context.Principal; + var subject = principal.FindFirstValue(ClaimTypes.NameIdentifier) ?? principal.FindFirstValue("sub"); + if (string.IsNullOrEmpty(subject)) + { + context.Fail("OIDC token has no subject claim."); + return; + } + + var username = (current.NameClaim is not null ? principal.FindFirstValue(current.NameClaim) : null) + ?? principal.FindFirstValue(ClaimTypes.Name) + ?? principal.FindFirstValue("preferred_username") + ?? principal.FindFirstValue(ClaimTypes.Email) + ?? subject; + var displayName = principal.FindFirstValue("name") ?? username; + + // Map identity-provider groups/roles onto an application role. + var claimValues = string.IsNullOrWhiteSpace(current.RoleClaim) + ? [] + : principal.FindAll(current.RoleClaim).Select(c => c.Value).ToList(); + + var role = current.MapRole(claimValues); + if (role is null) + { + context.Fail( + "Your account is not a member of any group mapped to an ExecuteR role."); + return; + } + + using var scope = scopeFactory.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService(); + await users.UpsertOidcUserAsync( + subject, username, displayName, role.Value, context.HttpContext.RequestAborted); + + identity.AddClaim(new Claim(ClaimTypes.Role, role.Value.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)); + } + }; + + // Never strand the operator on an IdP error page. + options.Events.OnRemoteFailure = context => + { + context.Response.Redirect( + "/login?error=" + Uri.EscapeDataString(context.Failure?.Message ?? "Single sign-on failed.")); + context.HandleResponse(); + return Task.CompletedTask; + }; + + options.Events.OnAccessDenied = context => + { + context.Response.Redirect("/login?error=" + Uri.EscapeDataString("Access denied by the identity provider.")); + context.HandleResponse(); + return Task.CompletedTask; + }; + } +} + +internal sealed class OidcChangeTokenSource(AuthSettingsCache cache) : IOptionsChangeTokenSource +{ + public string Name => AuthConstants.OidcScheme; + + public IChangeToken GetChangeToken() => cache.GetChangeToken(); +} diff --git a/src/Backend/Auth/AuthResetCli.cs b/src/Backend/Auth/AuthResetCli.cs new file mode 100644 index 0000000..4bfd894 --- /dev/null +++ b/src/Backend/Auth/AuthResetCli.cs @@ -0,0 +1,128 @@ +using Backend.Data; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Models; + +namespace Backend.Auth; + +/// +/// Lockout recovery, runnable inside the container: +/// +/// docker exec EXECUTER-API-00001 dotnet Backend.dll auth-reset +/// docker exec EXECUTER-API-00001 dotnet Backend.dll auth-reset --admin admin --password '<new>' +/// +/// Disables OIDC and restores local sign-in, so an identity provider that is +/// down, misconfigured or has revoked the client can never permanently lock an +/// operator out. Optionally resets (or creates) a local admin. +/// +/// Setting AUTH_FORCE_LOCAL=1 achieves the same at startup without a database +/// write, which is the faster option if the container will not stay up. +/// +public static class AuthResetCli +{ + public static async Task RunAsync(string[] args, IConfiguration configuration) + { + var username = ArgValue(args, "--admin"); + var password = ArgValue(args, "--password"); + + var databaseOptions = DatabaseOptions.FromConfiguration(configuration); + + var services = new ServiceCollection(); + services.AddLogging(b => b.AddSimpleConsole()); + services.AddDataProtection().PersistKeysToFileSystem( + new DirectoryInfo(DataProtectionPath(configuration))); + services.AddApplicationDatabase(databaseOptions); + services.AddScoped(); + + await using var provider = services.BuildServiceProvider(); + using var scope = provider.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + // Clear the OIDC flags directly: this must work even when the rest of + // the application cannot start. + foreach (var (key, value) in new[] + { + (AuthSettingsService.Keys.OidcEnabled, "0"), + (AuthSettingsService.Keys.LoginMode, nameof(LoginMode.LocalOnly)), + }) + { + var row = await db.AppSettings.SingleOrDefaultAsync(s => s.Key == key); + if (row is null) + { + db.AppSettings.Add(new AppSettingEntity + { + Key = key, + Value = value, + IsSecret = false, + UpdatedUtc = DateTimeOffset.UtcNow, + UpdatedBy = "auth-reset", + }); + } + else + { + row.Value = value; + row.UpdatedUtc = DateTimeOffset.UtcNow; + row.UpdatedBy = "auth-reset"; + } + } + + await db.SaveChangesAsync(); + Console.WriteLine("OIDC disabled; local sign-in restored."); + + if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password)) + { + var hasher = new PasswordHasher(); + var user = await db.Users.SingleOrDefaultAsync( + u => u.Username == username && u.AuthProvider == AuthConstants.ProviderLocal); + + if (user is null) + { + user = new UserEntity + { + Id = Guid.NewGuid(), + Username = username!, + DisplayName = username, + Role = UserRole.Admin, + AuthProvider = AuthConstants.ProviderLocal, + CreatedUtc = DateTimeOffset.UtcNow, + }; + db.Users.Add(user); + Console.WriteLine($"Local admin '{username}' created."); + } + else + { + user.Role = UserRole.Admin; + Console.WriteLine($"Local admin '{username}' password reset and role set to Admin."); + } + + user.PasswordHash = hasher.HashPassword(user, password!); + await db.SaveChangesAsync(); + } + else + { + Console.WriteLine("Tip: pass --admin --password to also reset a local admin."); + } + + Console.WriteLine("Restart is not required; sign in at /login."); + return 0; + } + + private static string DataProtectionPath(IConfiguration configuration) + { + var configured = configuration["DATAPROTECTION_PATH"]; + if (!string.IsNullOrWhiteSpace(configured)) + { + return configured; + } + + var databasePath = configuration["DATABASE_PATH"] ?? "data/app.db"; + return Path.Combine(Path.GetDirectoryName(Path.GetFullPath(databasePath)) ?? "data", "keys"); + } + + private static string? ArgValue(string[] args, string name) + { + var index = Array.IndexOf(args, name); + return index >= 0 && index + 1 < args.Length ? args[index + 1] : null; + } +} diff --git a/src/Backend/Auth/AuthSettings.cs b/src/Backend/Auth/AuthSettings.cs new file mode 100644 index 0000000..20e6f14 --- /dev/null +++ b/src/Backend/Auth/AuthSettings.cs @@ -0,0 +1,95 @@ +using Shared.Contracts.Models; + +namespace Backend.Auth; + +/// How the sign-in page behaves. +public enum LoginMode +{ + /// Local username/password only. + LocalOnly, + + /// Both local fields and an SSO button. + Both, + + /// SSO button only — local fields hidden (still reachable, see below). + OidcOnly, + + /// Redirect straight to the identity provider, no sign-in page. + OidcAutoRedirect, +} + +/// +/// Effective authentication configuration: values saved from the UI layered +/// over the environment bootstrap defaults. +/// +/// The OIDC redirect path is deliberately NOT operator-tunable at runtime — see +/// . +/// +public sealed record AuthSettings +{ + public bool OidcEnabled { get; init; } + public string? Authority { get; init; } + public string? ClientId { get; init; } + public string? ClientSecret { get; init; } + /// Friendly IdP name shown on the sign-in button (e.g. "Authentik", "Entra ID"). + public string? ProviderName { get; init; } + public string Scopes { get; init; } = "openid profile email"; + public string? NameClaim { get; init; } + public string? RoleClaim { get; init; } + + /// Claim values mapped to each application role. + public string? AdminRole { get; init; } + public string? OperatorRole { get; init; } + public string? ViewerRole { get; init; } + + /// Role granted to an authenticated user matching no mapping. + public UserRole DefaultRole { get; init; } = UserRole.Operator; + + /// Refuse sign-in entirely when no mapping matches. + public bool RequireMappedRole { get; init; } + + public LoginMode LoginMode { get; init; } = LoginMode.LocalOnly; + + /// + /// Emergency switch (env only, never settable from the UI): forces local + /// sign-in regardless of what is stored. See the auth-reset CLI. + /// + public bool ForceLocal { get; init; } + + public bool IsOidcUsable => OidcEnabled + && !ForceLocal + && !string.IsNullOrWhiteSpace(Authority) + && !string.IsNullOrWhiteSpace(ClientId); + + /// Local sign-in is never truly switched off — see the lockout note. + public bool ShowLocalFields => !IsOidcUsable || LoginMode is LoginMode.LocalOnly or LoginMode.Both; + + public bool AutoRedirect => IsOidcUsable && LoginMode == LoginMode.OidcAutoRedirect; + + /// Maps identity-provider claim values to an application role. + public UserRole? MapRole(IEnumerable claimValues) + { + var values = claimValues.ToList(); + + bool Matches(string? configured) => + !string.IsNullOrWhiteSpace(configured) + && values.Any(v => string.Equals(v, configured, StringComparison.OrdinalIgnoreCase)); + + if (Matches(AdminRole)) + { + return UserRole.Admin; + } + + if (Matches(OperatorRole)) + { + return UserRole.Operator; + } + + if (Matches(ViewerRole)) + { + return UserRole.Viewer; + } + + return RequireMappedRole ? null : DefaultRole; + } +} diff --git a/src/Backend/Auth/AuthSettingsEndpoints.cs b/src/Backend/Auth/AuthSettingsEndpoints.cs new file mode 100644 index 0000000..4837d8e --- /dev/null +++ b/src/Backend/Auth/AuthSettingsEndpoints.cs @@ -0,0 +1,186 @@ +using Backend.Security; +using Shared.Contracts.Api; + +namespace Backend.Auth; + +/// +/// Identity-provider configuration from the UI, plus the anonymous config the +/// sign-in page needs to decide what to render. +/// +public static class AuthSettingsEndpoints +{ + public static void Map(WebApplication app) + { + app.MapGet(ApiRoutes.AuthConfig, GetPublicConfigAsync).AllowAnonymous(); + app.MapGet(ApiRoutes.AuthSettings, GetAsync).RequireAuthorization(AuthConstants.PolicyAdmin); + app.MapPut(ApiRoutes.AuthSettings, SaveAsync).RequireAuthorization(AuthConstants.PolicyAdmin); + app.MapPost(ApiRoutes.AuthSettingsTest, TestAsync).RequireAuthorization(AuthConstants.PolicyAdmin); + } + + /// Anonymous: only what the sign-in page needs to render itself. + private static async Task GetPublicConfigAsync( + AuthSettingsService settings, CancellationToken cancellationToken) + { + var effective = await settings.GetEffectiveAsync(cancellationToken); + return Results.Ok(new AuthConfigDto( + OidcAvailable: effective.IsOidcUsable, + ShowLocalFields: effective.ShowLocalFields, + AutoRedirect: effective.AutoRedirect, + // Friendly name (Authentik, Entra ID, …) when set; authority host + // is only the fallback. + ProviderName: effective.IsOidcUsable + ? (string.IsNullOrWhiteSpace(effective.ProviderName) + ? DescribeAuthority(effective.Authority) + : effective.ProviderName) + : null)); + } + + private static string? DescribeAuthority(string? authority) + => Uri.TryCreate(authority, UriKind.Absolute, out var uri) ? uri.Host : authority; + + private static async Task GetAsync( + AuthSettingsService settings, + HttpContext context, + IConfiguration configuration, + CancellationToken cancellationToken) + { + var effective = await settings.GetEffectiveAsync(cancellationToken); + return Results.Ok(ToDto(effective, context, configuration)); + } + + private static async Task SaveAsync( + AuthSettingsDto request, + AuthSettingsService settings, + AuditService audit, + HttpContext context, + IConfiguration configuration, + CancellationToken cancellationToken) + { + var current = await settings.GetEffectiveAsync(cancellationToken); + + if (!Enum.TryParse(request.LoginMode, true, out var mode)) + { + mode = LoginMode.LocalOnly; + } + + // Refuse to hide local sign-in behind an IdP that is not usable — + // that is exactly how an instance locks itself out. + var wouldBeUsable = request.OidcEnabled + && !string.IsNullOrWhiteSpace(request.Authority) + && !string.IsNullOrWhiteSpace(request.ClientId); + + if (!wouldBeUsable && mode is LoginMode.OidcOnly or LoginMode.OidcAutoRedirect) + { + return Results.BadRequest(new + { + error = "Configure and enable OIDC before choosing an SSO-only sign-in mode.", + }); + } + + var updated = current with + { + OidcEnabled = request.OidcEnabled, + Authority = request.Authority, + ClientId = request.ClientId, + ClientSecret = request.ClientSecret, + ProviderName = request.ProviderName, + Scopes = string.IsNullOrWhiteSpace(request.Scopes) ? "openid profile email" : request.Scopes, + NameClaim = request.NameClaim, + RoleClaim = request.RoleClaim, + AdminRole = request.AdminRole, + OperatorRole = request.OperatorRole, + ViewerRole = request.ViewerRole, + DefaultRole = request.DefaultRole, + RequireMappedRole = request.RequireMappedRole, + LoginMode = mode, + }; + + await settings.SaveAsync(updated, context.User.Identity?.Name, cancellationToken); + + await audit.LogAsync(AuditCategories.Auth, "oidc-settings-updated", context.User.Identity?.Name, + detail: $"enabled={request.OidcEnabled} mode={mode} authority={request.Authority}", + cancellationToken: cancellationToken); + + return Results.Ok(ToDto(await settings.GetEffectiveAsync(cancellationToken), context, configuration)); + } + + /// Fetches the discovery document so a bad authority is caught before saving. + private static async Task TestAsync( + AuthSettingsDto request, AuthSettingsService settings, CancellationToken cancellationToken) + { + var steps = new List(); + var authority = string.IsNullOrWhiteSpace(request.Authority) + ? (await settings.GetEffectiveAsync(cancellationToken)).Authority + : request.Authority; + + if (string.IsNullOrWhiteSpace(authority)) + { + steps.Add(new S3TestStepDto("authority", false, "Authority is required.")); + return Results.Ok(new AuthTestResultDto(false, steps)); + } + + var discovery = $"{authority.TrimEnd('/')}/.well-known/openid-configuration"; + try + { + using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; + using var response = await http.GetAsync(discovery, cancellationToken); + + if (!response.IsSuccessStatusCode) + { + steps.Add(new S3TestStepDto("discovery", false, + $"HTTP {(int)response.StatusCode} from {discovery}")); + return Results.Ok(new AuthTestResultDto(false, steps)); + } + + steps.Add(new S3TestStepDto("discovery", true, $"{discovery} reachable")); + + using var document = System.Text.Json.JsonDocument.Parse( + await response.Content.ReadAsStringAsync(cancellationToken)); + var root = document.RootElement; + + foreach (var required in new[] { "authorization_endpoint", "token_endpoint", "jwks_uri" }) + { + var present = root.TryGetProperty(required, out _); + steps.Add(new S3TestStepDto(required, present, present ? "present" : "missing from discovery")); + } + + var pkce = root.TryGetProperty("code_challenge_methods_supported", out var methods) + && methods.EnumerateArray().Any(m => m.GetString() == "S256"); + steps.Add(new S3TestStepDto("PKCE (S256)", pkce, + pkce ? "supported" : "not advertised — sign-in may fail")); + } + catch (Exception ex) + { + steps.Add(new S3TestStepDto("discovery", false, ex.Message)); + } + + return Results.Ok(new AuthTestResultDto(steps.All(s => s.Ok), steps)); + } + + private static AuthSettingsDto ToDto(AuthSettings s, HttpContext context, IConfiguration configuration) + { + // PUBLIC_SERVER_URL wins so the IdP registration matches what agents + // and browsers actually use, even when an admin browses via an + // internal hostname; trusted forwarded headers are the fallback. + var origin = Backend.Proxy.PublicUrl.Resolve(context, configuration); + return new AuthSettingsDto( + OidcEnabled: s.OidcEnabled, + Authority: s.Authority, + ClientId: s.ClientId, + ClientSecret: null, + ProviderName: s.ProviderName, + Scopes: s.Scopes, + NameClaim: s.NameClaim, + RoleClaim: s.RoleClaim, + AdminRole: s.AdminRole, + OperatorRole: s.OperatorRole, + ViewerRole: s.ViewerRole, + DefaultRole: s.DefaultRole, + RequireMappedRole: s.RequireMappedRole, + LoginMode: s.LoginMode.ToString(), + ClientSecretIsSet: !string.IsNullOrWhiteSpace(s.ClientSecret), + ForcedLocalByEnvironment: s.ForceLocal, + CallbackPath: AuthSettingsService.CallbackPath, + RedirectUri: origin + AuthSettingsService.CallbackPath); + } +} diff --git a/src/Backend/Auth/AuthSettingsService.cs b/src/Backend/Auth/AuthSettingsService.cs new file mode 100644 index 0000000..fee2204 --- /dev/null +++ b/src/Backend/Auth/AuthSettingsService.cs @@ -0,0 +1,144 @@ +using Backend.Settings; +using Microsoft.Extensions.Primitives; +using Shared.Contracts.Models; + +namespace Backend.Auth; + +/// +/// Resolves effective auth settings (database over environment) and caches +/// them for the OIDC handler, which cannot take a scoped dependency. +/// +/// Saving triggers a change token so the handler is rebuilt without a restart. +/// +public sealed class AuthSettingsService(SettingsStore store, AuthSettings environmentDefaults, AuthSettingsCache cache) +{ + public const string Prefix = "auth."; + + /// + /// The OIDC redirect path is fixed. It must match what is registered at the + /// identity provider exactly, and letting it drift at runtime is a reliable + /// way to break sign-in with no obvious cause. It lives under /api/ so the + /// reverse proxy's existing API location covers it, and it is shown in the + /// UI so it can be copied into the IdP verbatim. + /// + public const string CallbackPath = Shared.Contracts.Api.ApiRoutes.AuthOidcCallback; + + public static class Keys + { + public const string OidcEnabled = Prefix + "oidcEnabled"; + public const string Authority = Prefix + "authority"; + public const string ClientId = Prefix + "clientId"; + public const string ClientSecret = Prefix + "clientSecret"; + public const string ProviderName = Prefix + "providerName"; + public const string Scopes = Prefix + "scopes"; + public const string NameClaim = Prefix + "nameClaim"; + public const string RoleClaim = Prefix + "roleClaim"; + public const string AdminRole = Prefix + "adminRole"; + public const string OperatorRole = Prefix + "operatorRole"; + public const string ViewerRole = Prefix + "viewerRole"; + public const string DefaultRole = Prefix + "defaultRole"; + public const string RequireMappedRole = Prefix + "requireMappedRole"; + public const string LoginMode = Prefix + "loginMode"; + } + + public async Task GetEffectiveAsync(CancellationToken cancellationToken) + { + var saved = await store.GetAllAsync(Prefix, cancellationToken); + var effective = Merge(saved, environmentDefaults); + cache.Set(effective); + return effective; + } + + internal static AuthSettings Merge(IReadOnlyDictionary saved, AuthSettings defaults) => new() + { + OidcEnabled = Bool(saved, Keys.OidcEnabled, defaults.OidcEnabled), + Authority = Str(saved, Keys.Authority, defaults.Authority), + ClientId = Str(saved, Keys.ClientId, defaults.ClientId), + ClientSecret = Str(saved, Keys.ClientSecret, defaults.ClientSecret), + ProviderName = Str(saved, Keys.ProviderName, defaults.ProviderName), + Scopes = Str(saved, Keys.Scopes, defaults.Scopes) ?? "openid profile email", + NameClaim = Str(saved, Keys.NameClaim, defaults.NameClaim), + RoleClaim = Str(saved, Keys.RoleClaim, defaults.RoleClaim), + AdminRole = Str(saved, Keys.AdminRole, defaults.AdminRole), + OperatorRole = Str(saved, Keys.OperatorRole, defaults.OperatorRole), + ViewerRole = Str(saved, Keys.ViewerRole, defaults.ViewerRole), + DefaultRole = Enum.TryParse(Str(saved, Keys.DefaultRole, null), true, out var role) + ? role + : defaults.DefaultRole, + RequireMappedRole = Bool(saved, Keys.RequireMappedRole, defaults.RequireMappedRole), + LoginMode = Enum.TryParse(Str(saved, Keys.LoginMode, null), true, out var mode) + ? mode + : defaults.LoginMode, + // Never persisted: environment-only escape hatch. + ForceLocal = defaults.ForceLocal, + }; + + public async Task SaveAsync(AuthSettings settings, string? actor, CancellationToken cancellationToken) + { + await store.SetAsync(Keys.OidcEnabled, settings.OidcEnabled ? "1" : "0", false, actor, cancellationToken); + await store.SetAsync(Keys.Authority, settings.Authority, false, actor, cancellationToken); + await store.SetAsync(Keys.ClientId, settings.ClientId, false, actor, cancellationToken); + await store.SetAsync(Keys.ProviderName, settings.ProviderName, false, actor, cancellationToken); + await store.SetAsync(Keys.Scopes, settings.Scopes, false, actor, cancellationToken); + await store.SetAsync(Keys.NameClaim, settings.NameClaim, false, actor, cancellationToken); + await store.SetAsync(Keys.RoleClaim, settings.RoleClaim, false, actor, cancellationToken); + await store.SetAsync(Keys.AdminRole, settings.AdminRole, false, actor, cancellationToken); + await store.SetAsync(Keys.OperatorRole, settings.OperatorRole, false, actor, cancellationToken); + await store.SetAsync(Keys.ViewerRole, settings.ViewerRole, false, actor, cancellationToken); + await store.SetAsync(Keys.DefaultRole, settings.DefaultRole.ToString(), false, actor, cancellationToken); + await store.SetAsync( + Keys.RequireMappedRole, settings.RequireMappedRole ? "1" : "0", false, actor, cancellationToken); + await store.SetAsync(Keys.LoginMode, settings.LoginMode.ToString(), false, actor, cancellationToken); + + // Null secret means "keep the stored one". + if (!string.IsNullOrWhiteSpace(settings.ClientSecret)) + { + await store.SetAsync(Keys.ClientSecret, settings.ClientSecret, true, actor, cancellationToken); + } + + // Rebuild the OIDC handler with the new values. + cache.Set(await GetEffectiveAsync(cancellationToken)); + cache.Reload(); + } + + /// Disables OIDC and restores local sign-in. Used by the auth-reset CLI. + public async Task ResetToLocalAsync(string? actor, CancellationToken cancellationToken) + { + await store.SetAsync(Keys.OidcEnabled, "0", false, actor, cancellationToken); + await store.SetAsync(Keys.LoginMode, nameof(LoginMode.LocalOnly), false, actor, cancellationToken); + cache.Set(await GetEffectiveAsync(cancellationToken)); + cache.Reload(); + } + + public AuthSettings EnvironmentDefaults => environmentDefaults; + + private static string? Str(IReadOnlyDictionary saved, string key, string? fallback) + => saved.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value) ? value : fallback; + + private static bool Bool(IReadOnlyDictionary saved, string key, bool fallback) + => saved.TryGetValue(key, out var value) ? value is "1" or "true" or "True" : fallback; +} + +/// +/// Holds the current effective auth settings for the OIDC handler (a singleton +/// that cannot resolve scoped services), and signals options reload on change. +/// +public sealed class AuthSettingsCache(AuthSettings initial) +{ + private AuthSettings current = initial; + private CancellationTokenSource changeSource = new(); + + public AuthSettings Current => Volatile.Read(ref current); + + public void Set(AuthSettings settings) => Volatile.Write(ref current, settings); + + public IChangeToken GetChangeToken() => new CancellationChangeToken(changeSource.Token); + + /// Invalidates cached OpenIdConnectOptions so they are rebuilt. + public void Reload() + { + var previous = Interlocked.Exchange(ref changeSource, new CancellationTokenSource()); + previous.Cancel(); + previous.Dispose(); + } +} diff --git a/src/Backend/Auth/OidcOptions.cs b/src/Backend/Auth/OidcOptions.cs deleted file mode 100644 index b8075e0..0000000 --- a/src/Backend/Auth/OidcOptions.cs +++ /dev/null @@ -1,36 +0,0 @@ -namespace Backend.Auth; - -/// Generic OIDC configuration (works with any compliant provider). -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"], - }; -} diff --git a/src/Backend/Backend.csproj b/src/Backend/Backend.csproj index 9df7a52..06e0d29 100644 --- a/src/Backend/Backend.csproj +++ b/src/Backend/Backend.csproj @@ -6,8 +6,13 @@ backend-dev-secrets + + + + + diff --git a/src/Backend/Data/AppDbContext.cs b/src/Backend/Data/AppDbContext.cs index 33f0232..f8ca777 100644 --- a/src/Backend/Data/AppDbContext.cs +++ b/src/Backend/Data/AppDbContext.cs @@ -21,6 +21,10 @@ public class AppDbContext(DbContextOptions options) : DbContext(op public DbSet DeviceGroupMembers => Set(); public DbSet ScriptTriggers => Set(); public DbSet ScriptTriggerRuns => Set(); + public DbSet AppSettings => Set(); + public DbSet SecretsProviders => Set(); + public DbSet Schedules => Set(); + public DbSet ScriptSchedules => Set(); /// /// SQLite cannot ORDER BY / compare DateTimeOffset natively, so it stores @@ -156,5 +160,38 @@ public class AppDbContext(DbContextOptions options) : DbContext(op entity.HasKey(e => e.Id); entity.HasIndex(e => new { e.TriggerId, e.ClientId }).IsUnique(); }); + + modelBuilder.Entity(entity => + { + entity.ToTable("AppSettings"); + entity.HasKey(e => e.Key); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("SecretsProviders"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.Name).IsUnique(); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("Schedules"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.Name).IsUnique(); + entity.HasIndex(e => e.NextRunUtc); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("ScriptSchedules"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.ScheduleId); + entity.HasIndex(e => e.ScriptId); + entity.HasOne().WithMany() + .HasForeignKey(e => e.ScheduleId).OnDelete(DeleteBehavior.Cascade); + entity.HasOne().WithMany() + .HasForeignKey(e => e.ScriptId).OnDelete(DeleteBehavior.Cascade); + }); } } diff --git a/src/Backend/Data/DevSeeder.cs b/src/Backend/Data/DevSeeder.cs index 813efa0..65f21d8 100644 --- a/src/Backend/Data/DevSeeder.cs +++ b/src/Backend/Data/DevSeeder.cs @@ -43,6 +43,7 @@ public static class DevSeeder EnrollmentId = Guid.NewGuid(), EnrolledUtc = now.AddDays(-i - 1), LastSeenUtc = now - seenAgo, + PublicIp = $"203.0.113.{40 + i}", IpAddressesJson = JsonSerializer.Serialize(ips, JsonDefaults.Options), TagsJson = JsonSerializer.Serialize(tags, JsonDefaults.Options), }; @@ -54,8 +55,15 @@ public static class DevSeeder 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 InventoryDisk("Samsung SSD 980 1TB", $"S{i}XYZ", 1_000_204_886_016, "NVMe", Index: 0), + new InventoryDisk("WDC WD40EZRZ 4TB", $"WD{i}ABC", 4_000_787_030_016, "SATA", Index: 1), + ], + [ + new InventoryVolume("C:", "NTFS", 511_000_000_000, 198_500_000_000, DiskIndex: 0), + new InventoryVolume("D:", "NTFS", 488_000_000_000, 402_100_000_000, DiskIndex: 0), + new InventoryVolume("E:", "NTFS", 4_000_000_000_000, 1_250_000_000_000, DiskIndex: 1), + ], [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); diff --git a/src/Backend/Data/Entities.cs b/src/Backend/Data/Entities.cs index e0af7c5..6055994 100644 --- a/src/Backend/Data/Entities.cs +++ b/src/Backend/Data/Entities.cs @@ -53,6 +53,12 @@ public sealed class DeviceEntity public bool IsOrphaned { get; set; } public DateTimeOffset? OrphanedUtc { get; set; } + /// + /// Public IP the agent was last seen from, resolved through trusted + /// forwarded headers at enrollment and credential refresh. + /// + public string? PublicIp { get; set; } + public DeviceInventoryEntity? Inventory { get; set; } } @@ -125,12 +131,94 @@ public sealed class ScriptEntity public string? ParametersJson { get; set; } /// JSON array of attached FunctionModule ids (prepended at run time). public string? FunctionModuleIdsJson { get; set; } + /// JSON array of SecretBinding definitions (resolved server-side at dispatch). + public string? SecretBindingsJson { get; set; } + /// Session variable the resolved secrets dictionary binds to (default "Secrets"). + public string? SecretsVariableName { get; set; } public DateTimeOffset CreatedUtc { get; set; } public DateTimeOffset UpdatedUtc { get; set; } public string? CreatedBy { get; set; } public string? UpdatedBy { get; set; } } +/// +/// A reusable cadence object: one-shot () or recurring +/// (, evaluated in ). +/// Schedules carry no script or target — objects (scripts) honor a schedule +/// through associations. +/// +public sealed class ScheduleEntity +{ + public Guid Id { get; set; } + public required string Name { get; set; } + /// 5-field cron for recurring schedules; null for one-shot. + public string? CronExpression { get; set; } + /// Fire time for one-shot schedules; null for recurring. + public DateTimeOffset? RunOnceUtc { get; set; } + public string TimeZoneId { get; set; } = "UTC"; + public bool Enabled { get; set; } = true; + public DateTimeOffset? NextRunUtc { get; set; } + public DateTimeOffset? LastRunUtc { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public DateTimeOffset UpdatedUtc { get; set; } + public string? CreatedBy { get; set; } + public string? UpdatedBy { get; set; } +} + +/// +/// A script honoring a schedule: when the schedule fires, this script runs +/// against exactly one of / +/// (group members resolved at fire time) with the stored argument values. +/// +public sealed class ScriptScheduleEntity +{ + public Guid Id { get; set; } + public required Guid ScheduleId { get; set; } + public required Guid ScriptId { get; set; } + public string? ClientId { get; set; } + public Guid? GroupId { get; set; } + /// Argument values captured when the association was saved. + public string? ArgumentsJson { get; set; } + public bool Enabled { get; set; } = true; + public DateTimeOffset? LastRunUtc { get; set; } + /// Human-readable outcome of the last firing (job counts or the error). + public string? LastResult { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public string? CreatedBy { get; set; } +} + +/// +/// A configured external secrets store (e.g. Infisical). Connection settings +/// are a Data Protection-encrypted JSON blob; only the backend ever decrypts +/// them, and secret values are fetched server-side at job dispatch. +/// +public sealed class SecretsProviderEntity +{ + public Guid Id { get; set; } + public required string Name { get; set; } + /// Driver kind, e.g. "infisical". + public required string Kind { get; set; } + /// Encrypted driver-specific config JSON. + public required string ConfigProtected { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public DateTimeOffset UpdatedUtc { get; set; } + public string? UpdatedBy { get; set; } +} + +/// +/// Operator-editable application settings that override environment defaults. +/// Values marked secret are encrypted at rest with ASP.NET Data Protection and +/// are never returned to the browser. +/// +public sealed class AppSettingEntity +{ + public required string Key { get; set; } + public string? Value { get; set; } + public bool IsSecret { get; set; } + public DateTimeOffset UpdatedUtc { get; set; } + public string? UpdatedBy { get; set; } +} + /// Reusable PowerShell function library prepended to referencing scripts. public sealed class FunctionModuleEntity { diff --git a/src/Backend/Data/Migrations/Postgres/20260807135644_AddAppSettings.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260807135644_AddAppSettings.Designer.cs new file mode 100644 index 0000000..9a5449e --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807135644_AddAppSettings.Designer.cs @@ -0,0 +1,606 @@ +// +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("20260807135644_AddAppSettings")] + partial class AddAppSettings + { + /// + 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.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("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("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("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 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807135644_AddAppSettings.cs b/src/Backend/Data/Migrations/Postgres/20260807135644_AddAppSettings.cs new file mode 100644 index 0000000..f700513 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807135644_AddAppSettings.cs @@ -0,0 +1,37 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddAppSettings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AppSettings", + columns: table => new + { + Key = table.Column(type: "text", nullable: false), + Value = table.Column(type: "text", nullable: true), + IsSecret = table.Column(type: "boolean", nullable: false), + UpdatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedBy = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AppSettings", x => x.Key); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AppSettings"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807150650_AddSecretsProviders.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260807150650_AddSecretsProviders.Designer.cs new file mode 100644 index 0000000..77610e3 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807150650_AddSecretsProviders.Designer.cs @@ -0,0 +1,647 @@ +// +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("20260807150650_AddSecretsProviders")] + partial class AddSecretsProviders + { + /// + 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.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("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("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("SecretBindingsJson") + .HasColumnType("text"); + + b.Property("SecretsVariableName") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("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 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807150650_AddSecretsProviders.cs b/src/Backend/Data/Migrations/Postgres/20260807150650_AddSecretsProviders.cs new file mode 100644 index 0000000..274f927 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807150650_AddSecretsProviders.cs @@ -0,0 +1,65 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddSecretsProviders : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "SecretBindingsJson", + table: "Scripts", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "SecretsVariableName", + table: "Scripts", + type: "text", + nullable: true); + + migrationBuilder.CreateTable( + name: "SecretsProviders", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "text", nullable: false), + Kind = table.Column(type: "text", nullable: false), + ConfigProtected = table.Column(type: "text", nullable: false), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedBy = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_SecretsProviders", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_SecretsProviders_Name", + table: "SecretsProviders", + column: "Name", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "SecretsProviders"); + + migrationBuilder.DropColumn( + name: "SecretBindingsJson", + table: "Scripts"); + + migrationBuilder.DropColumn( + name: "SecretsVariableName", + table: "Scripts"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807153218_AddScheduledRuns.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260807153218_AddScheduledRuns.Designer.cs new file mode 100644 index 0000000..335e6b2 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807153218_AddScheduledRuns.Designer.cs @@ -0,0 +1,711 @@ +// +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("20260807153218_AddScheduledRuns")] + partial class AddScheduledRuns + { + /// + 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.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("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("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScheduledRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ArgumentsJson") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CronExpression") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("LastResult") + .HasColumnType("text"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RunOnceUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScheduledRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("SecretBindingsJson") + .HasColumnType("text"); + + b.Property("SecretsVariableName") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("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 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807153218_AddScheduledRuns.cs b/src/Backend/Data/Migrations/Postgres/20260807153218_AddScheduledRuns.cs new file mode 100644 index 0000000..a17e853 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807153218_AddScheduledRuns.cs @@ -0,0 +1,59 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddScheduledRuns : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ScheduledRuns", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + ScriptId = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "text", nullable: true), + ClientId = table.Column(type: "text", nullable: true), + GroupId = table.Column(type: "uuid", nullable: true), + CronExpression = table.Column(type: "text", nullable: true), + RunOnceUtc = table.Column(type: "timestamp with time zone", nullable: true), + TimeZoneId = table.Column(type: "text", nullable: false), + Enabled = table.Column(type: "boolean", nullable: false), + ArgumentsJson = table.Column(type: "text", nullable: true), + NextRunUtc = table.Column(type: "timestamp with time zone", nullable: true), + LastRunUtc = table.Column(type: "timestamp with time zone", nullable: true), + LastResult = table.Column(type: "text", nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + CreatedBy = table.Column(type: "text", nullable: true), + UpdatedBy = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScheduledRuns", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledRuns_NextRunUtc", + table: "ScheduledRuns", + column: "NextRunUtc"); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledRuns_ScriptId", + table: "ScheduledRuns", + column: "ScriptId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScheduledRuns"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807165542_ScheduleObjects.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260807165542_ScheduleObjects.Designer.cs new file mode 100644 index 0000000..1ebe964 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807165542_ScheduleObjects.Designer.cs @@ -0,0 +1,758 @@ +// +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("20260807165542_ScheduleObjects")] + partial class ScheduleObjects + { + /// + 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.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("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("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CronExpression") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RunOnceUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("NextRunUtc"); + + b.ToTable("Schedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("SecretBindingsJson") + .HasColumnType("text"); + + b.Property("SecretsVariableName") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ArgumentsJson") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("LastResult") + .HasColumnType("text"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScheduleId") + .HasColumnType("uuid"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScriptSchedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("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.ScriptScheduleEntity", b => + { + b.HasOne("Backend.Data.ScheduleEntity", null) + .WithMany() + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.ScriptEntity", null) + .WithMany() + .HasForeignKey("ScriptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807165542_ScheduleObjects.cs b/src/Backend/Data/Migrations/Postgres/20260807165542_ScheduleObjects.cs new file mode 100644 index 0000000..47e49c6 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807165542_ScheduleObjects.cs @@ -0,0 +1,141 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class ScheduleObjects : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScheduledRuns"); + + migrationBuilder.CreateTable( + name: "Schedules", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "text", nullable: false), + CronExpression = table.Column(type: "text", nullable: true), + RunOnceUtc = table.Column(type: "timestamp with time zone", nullable: true), + TimeZoneId = table.Column(type: "text", nullable: false), + Enabled = table.Column(type: "boolean", nullable: false), + NextRunUtc = table.Column(type: "timestamp with time zone", nullable: true), + LastRunUtc = table.Column(type: "timestamp with time zone", nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + CreatedBy = table.Column(type: "text", nullable: true), + UpdatedBy = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Schedules", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ScriptSchedules", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + ScheduleId = table.Column(type: "uuid", nullable: false), + ScriptId = table.Column(type: "uuid", nullable: false), + ClientId = table.Column(type: "text", nullable: true), + GroupId = table.Column(type: "uuid", nullable: true), + ArgumentsJson = table.Column(type: "text", nullable: true), + Enabled = table.Column(type: "boolean", nullable: false), + LastRunUtc = table.Column(type: "timestamp with time zone", nullable: true), + LastResult = table.Column(type: "text", nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + CreatedBy = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScriptSchedules", x => x.Id); + table.ForeignKey( + name: "FK_ScriptSchedules_Schedules_ScheduleId", + column: x => x.ScheduleId, + principalTable: "Schedules", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ScriptSchedules_Scripts_ScriptId", + column: x => x.ScriptId, + principalTable: "Scripts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Schedules_Name", + table: "Schedules", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Schedules_NextRunUtc", + table: "Schedules", + column: "NextRunUtc"); + + migrationBuilder.CreateIndex( + name: "IX_ScriptSchedules_ScheduleId", + table: "ScriptSchedules", + column: "ScheduleId"); + + migrationBuilder.CreateIndex( + name: "IX_ScriptSchedules_ScriptId", + table: "ScriptSchedules", + column: "ScriptId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScriptSchedules"); + + migrationBuilder.DropTable( + name: "Schedules"); + + migrationBuilder.CreateTable( + name: "ScheduledRuns", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + ArgumentsJson = table.Column(type: "text", nullable: true), + ClientId = table.Column(type: "text", nullable: true), + CreatedBy = table.Column(type: "text", nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + CronExpression = table.Column(type: "text", nullable: true), + Enabled = table.Column(type: "boolean", nullable: false), + GroupId = table.Column(type: "uuid", nullable: true), + LastResult = table.Column(type: "text", nullable: true), + LastRunUtc = table.Column(type: "timestamp with time zone", nullable: true), + Name = table.Column(type: "text", nullable: true), + NextRunUtc = table.Column(type: "timestamp with time zone", nullable: true), + RunOnceUtc = table.Column(type: "timestamp with time zone", nullable: true), + ScriptId = table.Column(type: "uuid", nullable: false), + TimeZoneId = table.Column(type: "text", nullable: false), + UpdatedBy = table.Column(type: "text", nullable: true), + UpdatedUtc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ScheduledRuns", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledRuns_NextRunUtc", + table: "ScheduledRuns", + column: "NextRunUtc"); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledRuns_ScriptId", + table: "ScheduledRuns", + column: "ScriptId"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807185828_AddDevicePublicIp.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260807185828_AddDevicePublicIp.Designer.cs new file mode 100644 index 0000000..27b5483 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807185828_AddDevicePublicIp.Designer.cs @@ -0,0 +1,761 @@ +// +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("20260807185828_AddDevicePublicIp")] + partial class AddDevicePublicIp + { + /// + 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.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("PublicIp") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("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("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CronExpression") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RunOnceUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("NextRunUtc"); + + b.ToTable("Schedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("SecretBindingsJson") + .HasColumnType("text"); + + b.Property("SecretsVariableName") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ArgumentsJson") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("LastResult") + .HasColumnType("text"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScheduleId") + .HasColumnType("uuid"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScriptSchedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("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.ScriptScheduleEntity", b => + { + b.HasOne("Backend.Data.ScheduleEntity", null) + .WithMany() + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.ScriptEntity", null) + .WithMany() + .HasForeignKey("ScriptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807185828_AddDevicePublicIp.cs b/src/Backend/Data/Migrations/Postgres/20260807185828_AddDevicePublicIp.cs new file mode 100644 index 0000000..de27c3e --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807185828_AddDevicePublicIp.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddDevicePublicIp : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "PublicIp", + table: "Devices", + type: "text", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "PublicIp", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs index 486fd78..14331a5 100644 --- a/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs @@ -22,6 +22,28 @@ namespace Backend.Data.Migrations.Postgres NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => { b.Property("Id") @@ -145,6 +167,9 @@ namespace Backend.Data.Migrations.Postgres b.Property("OsVersion") .HasColumnType("text"); + b.Property("PublicIp") + .HasColumnType("text"); + b.Property("ReadyUtc") .HasColumnType("timestamp with time zone"); @@ -378,6 +403,57 @@ namespace Backend.Data.Migrations.Postgres b.ToTable("OidcProviders", (string)null); }); + modelBuilder.Entity("Backend.Data.ScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CronExpression") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RunOnceUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("NextRunUtc"); + + b.ToTable("Schedules", (string)null); + }); + modelBuilder.Entity("Backend.Data.ScriptEntity", b => { b.Property("Id") @@ -411,6 +487,12 @@ namespace Backend.Data.Migrations.Postgres b.Property("ParametersJson") .HasColumnType("text"); + b.Property("SecretBindingsJson") + .HasColumnType("text"); + + b.Property("SecretsVariableName") + .HasColumnType("text"); + b.Property("UpdatedBy") .HasColumnType("text"); @@ -424,6 +506,51 @@ namespace Backend.Data.Migrations.Postgres b.ToTable("Scripts", (string)null); }); + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ArgumentsJson") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("LastResult") + .HasColumnType("text"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScheduleId") + .HasColumnType("uuid"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScriptSchedules", (string)null); + }); + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => { b.Property("Id") @@ -488,6 +615,41 @@ namespace Backend.Data.Migrations.Postgres b.ToTable("ScriptTriggerRuns", (string)null); }); + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => { b.Property("Id") @@ -571,6 +733,21 @@ namespace Backend.Data.Migrations.Postgres .IsRequired(); }); + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.HasOne("Backend.Data.ScheduleEntity", null) + .WithMany() + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.ScriptEntity", null) + .WithMany() + .HasForeignKey("ScriptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Backend.Data.DeviceEntity", b => { b.Navigation("Inventory"); diff --git a/src/Backend/Data/Migrations/SqlServer/20260807135650_AddAppSettings.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260807135650_AddAppSettings.Designer.cs new file mode 100644 index 0000000..5c404b8 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807135650_AddAppSettings.Designer.cs @@ -0,0 +1,606 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20260807135650_AddAppSettings")] + partial class AddAppSettings + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + 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 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807135650_AddAppSettings.cs b/src/Backend/Data/Migrations/SqlServer/20260807135650_AddAppSettings.cs new file mode 100644 index 0000000..2f0de4d --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807135650_AddAppSettings.cs @@ -0,0 +1,37 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddAppSettings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AppSettings", + columns: table => new + { + Key = table.Column(type: "nvarchar(450)", nullable: false), + Value = table.Column(type: "nvarchar(max)", nullable: true), + IsSecret = table.Column(type: "bit", nullable: false), + UpdatedUtc = table.Column(type: "datetimeoffset", nullable: false), + UpdatedBy = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AppSettings", x => x.Key); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AppSettings"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807150654_AddSecretsProviders.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260807150654_AddSecretsProviders.Designer.cs new file mode 100644 index 0000000..10f9708 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807150654_AddSecretsProviders.Designer.cs @@ -0,0 +1,647 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20260807150654_AddSecretsProviders")] + partial class AddSecretsProviders + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + 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 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807150654_AddSecretsProviders.cs b/src/Backend/Data/Migrations/SqlServer/20260807150654_AddSecretsProviders.cs new file mode 100644 index 0000000..799b8b7 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807150654_AddSecretsProviders.cs @@ -0,0 +1,65 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddSecretsProviders : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "SecretBindingsJson", + table: "Scripts", + type: "nvarchar(max)", + nullable: true); + + migrationBuilder.AddColumn( + name: "SecretsVariableName", + table: "Scripts", + type: "nvarchar(max)", + nullable: true); + + migrationBuilder.CreateTable( + name: "SecretsProviders", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + Name = table.Column(type: "nvarchar(450)", nullable: false), + Kind = table.Column(type: "nvarchar(max)", nullable: false), + ConfigProtected = table.Column(type: "nvarchar(max)", nullable: false), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + UpdatedUtc = table.Column(type: "datetimeoffset", nullable: false), + UpdatedBy = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_SecretsProviders", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_SecretsProviders_Name", + table: "SecretsProviders", + column: "Name", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "SecretsProviders"); + + migrationBuilder.DropColumn( + name: "SecretBindingsJson", + table: "Scripts"); + + migrationBuilder.DropColumn( + name: "SecretsVariableName", + table: "Scripts"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807153221_AddScheduledRuns.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260807153221_AddScheduledRuns.Designer.cs new file mode 100644 index 0000000..9a9cd76 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807153221_AddScheduledRuns.Designer.cs @@ -0,0 +1,711 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20260807153221_AddScheduledRuns")] + partial class AddScheduledRuns + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScheduledRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .HasColumnType("nvarchar(max)"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScheduledRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + 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 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807153221_AddScheduledRuns.cs b/src/Backend/Data/Migrations/SqlServer/20260807153221_AddScheduledRuns.cs new file mode 100644 index 0000000..3a791c7 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807153221_AddScheduledRuns.cs @@ -0,0 +1,59 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddScheduledRuns : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ScheduledRuns", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + ScriptId = table.Column(type: "uniqueidentifier", nullable: false), + Name = table.Column(type: "nvarchar(max)", nullable: true), + ClientId = table.Column(type: "nvarchar(max)", nullable: true), + GroupId = table.Column(type: "uniqueidentifier", nullable: true), + CronExpression = table.Column(type: "nvarchar(max)", nullable: true), + RunOnceUtc = table.Column(type: "datetimeoffset", nullable: true), + TimeZoneId = table.Column(type: "nvarchar(max)", nullable: false), + Enabled = table.Column(type: "bit", nullable: false), + ArgumentsJson = table.Column(type: "nvarchar(max)", nullable: true), + NextRunUtc = table.Column(type: "datetimeoffset", nullable: true), + LastRunUtc = table.Column(type: "datetimeoffset", nullable: true), + LastResult = table.Column(type: "nvarchar(max)", nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + UpdatedUtc = table.Column(type: "datetimeoffset", nullable: false), + CreatedBy = table.Column(type: "nvarchar(max)", nullable: true), + UpdatedBy = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScheduledRuns", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledRuns_NextRunUtc", + table: "ScheduledRuns", + column: "NextRunUtc"); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledRuns_ScriptId", + table: "ScheduledRuns", + column: "ScriptId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScheduledRuns"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807165546_ScheduleObjects.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260807165546_ScheduleObjects.Designer.cs new file mode 100644 index 0000000..2223636 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807165546_ScheduleObjects.Designer.cs @@ -0,0 +1,758 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20260807165546_ScheduleObjects")] + partial class ScheduleObjects + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("NextRunUtc"); + + b.ToTable("Schedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScheduleId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScriptSchedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + 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.ScriptScheduleEntity", b => + { + b.HasOne("Backend.Data.ScheduleEntity", null) + .WithMany() + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.ScriptEntity", null) + .WithMany() + .HasForeignKey("ScriptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807165546_ScheduleObjects.cs b/src/Backend/Data/Migrations/SqlServer/20260807165546_ScheduleObjects.cs new file mode 100644 index 0000000..4b18d1e --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807165546_ScheduleObjects.cs @@ -0,0 +1,141 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class ScheduleObjects : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScheduledRuns"); + + migrationBuilder.CreateTable( + name: "Schedules", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + Name = table.Column(type: "nvarchar(450)", nullable: false), + CronExpression = table.Column(type: "nvarchar(max)", nullable: true), + RunOnceUtc = table.Column(type: "datetimeoffset", nullable: true), + TimeZoneId = table.Column(type: "nvarchar(max)", nullable: false), + Enabled = table.Column(type: "bit", nullable: false), + NextRunUtc = table.Column(type: "datetimeoffset", nullable: true), + LastRunUtc = table.Column(type: "datetimeoffset", nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + UpdatedUtc = table.Column(type: "datetimeoffset", nullable: false), + CreatedBy = table.Column(type: "nvarchar(max)", nullable: true), + UpdatedBy = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Schedules", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ScriptSchedules", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + ScheduleId = table.Column(type: "uniqueidentifier", nullable: false), + ScriptId = table.Column(type: "uniqueidentifier", nullable: false), + ClientId = table.Column(type: "nvarchar(max)", nullable: true), + GroupId = table.Column(type: "uniqueidentifier", nullable: true), + ArgumentsJson = table.Column(type: "nvarchar(max)", nullable: true), + Enabled = table.Column(type: "bit", nullable: false), + LastRunUtc = table.Column(type: "datetimeoffset", nullable: true), + LastResult = table.Column(type: "nvarchar(max)", nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + CreatedBy = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScriptSchedules", x => x.Id); + table.ForeignKey( + name: "FK_ScriptSchedules_Schedules_ScheduleId", + column: x => x.ScheduleId, + principalTable: "Schedules", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ScriptSchedules_Scripts_ScriptId", + column: x => x.ScriptId, + principalTable: "Scripts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Schedules_Name", + table: "Schedules", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Schedules_NextRunUtc", + table: "Schedules", + column: "NextRunUtc"); + + migrationBuilder.CreateIndex( + name: "IX_ScriptSchedules_ScheduleId", + table: "ScriptSchedules", + column: "ScheduleId"); + + migrationBuilder.CreateIndex( + name: "IX_ScriptSchedules_ScriptId", + table: "ScriptSchedules", + column: "ScriptId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScriptSchedules"); + + migrationBuilder.DropTable( + name: "Schedules"); + + migrationBuilder.CreateTable( + name: "ScheduledRuns", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + ArgumentsJson = table.Column(type: "nvarchar(max)", nullable: true), + ClientId = table.Column(type: "nvarchar(max)", nullable: true), + CreatedBy = table.Column(type: "nvarchar(max)", nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + CronExpression = table.Column(type: "nvarchar(max)", nullable: true), + Enabled = table.Column(type: "bit", nullable: false), + GroupId = table.Column(type: "uniqueidentifier", nullable: true), + LastResult = table.Column(type: "nvarchar(max)", nullable: true), + LastRunUtc = table.Column(type: "datetimeoffset", nullable: true), + Name = table.Column(type: "nvarchar(max)", nullable: true), + NextRunUtc = table.Column(type: "datetimeoffset", nullable: true), + RunOnceUtc = table.Column(type: "datetimeoffset", nullable: true), + ScriptId = table.Column(type: "uniqueidentifier", nullable: false), + TimeZoneId = table.Column(type: "nvarchar(max)", nullable: false), + UpdatedBy = table.Column(type: "nvarchar(max)", nullable: true), + UpdatedUtc = table.Column(type: "datetimeoffset", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ScheduledRuns", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledRuns_NextRunUtc", + table: "ScheduledRuns", + column: "NextRunUtc"); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledRuns_ScriptId", + table: "ScheduledRuns", + column: "ScriptId"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807185831_AddDevicePublicIp.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260807185831_AddDevicePublicIp.Designer.cs new file mode 100644 index 0000000..0e5944a --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807185831_AddDevicePublicIp.Designer.cs @@ -0,0 +1,761 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20260807185831_AddDevicePublicIp")] + partial class AddDevicePublicIp + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("PublicIp") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("NextRunUtc"); + + b.ToTable("Schedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScheduleId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScriptSchedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + 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.ScriptScheduleEntity", b => + { + b.HasOne("Backend.Data.ScheduleEntity", null) + .WithMany() + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.ScriptEntity", null) + .WithMany() + .HasForeignKey("ScriptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807185831_AddDevicePublicIp.cs b/src/Backend/Data/Migrations/SqlServer/20260807185831_AddDevicePublicIp.cs new file mode 100644 index 0000000..cdbb007 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807185831_AddDevicePublicIp.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddDevicePublicIp : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "PublicIp", + table: "Devices", + type: "nvarchar(max)", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "PublicIp", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs index 03e23f5..17f381e 100644 --- a/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs @@ -22,6 +22,28 @@ namespace Backend.Data.Migrations.SqlServer SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => { b.Property("Id") @@ -145,6 +167,9 @@ namespace Backend.Data.Migrations.SqlServer b.Property("OsVersion") .HasColumnType("nvarchar(max)"); + b.Property("PublicIp") + .HasColumnType("nvarchar(max)"); + b.Property("ReadyUtc") .HasColumnType("datetimeoffset"); @@ -378,6 +403,57 @@ namespace Backend.Data.Migrations.SqlServer b.ToTable("OidcProviders", (string)null); }); + modelBuilder.Entity("Backend.Data.ScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("NextRunUtc"); + + b.ToTable("Schedules", (string)null); + }); + modelBuilder.Entity("Backend.Data.ScriptEntity", b => { b.Property("Id") @@ -411,6 +487,12 @@ namespace Backend.Data.Migrations.SqlServer b.Property("ParametersJson") .HasColumnType("nvarchar(max)"); + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + b.Property("UpdatedBy") .HasColumnType("nvarchar(max)"); @@ -424,6 +506,51 @@ namespace Backend.Data.Migrations.SqlServer b.ToTable("Scripts", (string)null); }); + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScheduleId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScriptSchedules", (string)null); + }); + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => { b.Property("Id") @@ -488,6 +615,41 @@ namespace Backend.Data.Migrations.SqlServer b.ToTable("ScriptTriggerRuns", (string)null); }); + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => { b.Property("Id") @@ -571,6 +733,21 @@ namespace Backend.Data.Migrations.SqlServer .IsRequired(); }); + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.HasOne("Backend.Data.ScheduleEntity", null) + .WithMany() + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.ScriptEntity", null) + .WithMany() + .HasForeignKey("ScriptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Backend.Data.DeviceEntity", b => { b.Navigation("Inventory"); diff --git a/src/Backend/Data/Migrations/Sqlite/20260807135638_AddAppSettings.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20260807135638_AddAppSettings.Designer.cs new file mode 100644 index 0000000..db3c705 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807135638_AddAppSettings.Designer.cs @@ -0,0 +1,593 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + [Migration("20260807135638_AddAppSettings")] + partial class AddAppSettings + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("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 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807135638_AddAppSettings.cs b/src/Backend/Data/Migrations/Sqlite/20260807135638_AddAppSettings.cs new file mode 100644 index 0000000..b297c66 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807135638_AddAppSettings.cs @@ -0,0 +1,36 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddAppSettings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AppSettings", + columns: table => new + { + Key = table.Column(type: "TEXT", nullable: false), + Value = table.Column(type: "TEXT", nullable: true), + IsSecret = table.Column(type: "INTEGER", nullable: false), + UpdatedUtc = table.Column(type: "INTEGER", nullable: false), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AppSettings", x => x.Key); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AppSettings"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807150646_AddSecretsProviders.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20260807150646_AddSecretsProviders.Designer.cs new file mode 100644 index 0000000..4cb8d9a --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807150646_AddSecretsProviders.Designer.cs @@ -0,0 +1,634 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + [Migration("20260807150646_AddSecretsProviders")] + partial class AddSecretsProviders + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("SecretBindingsJson") + .HasColumnType("TEXT"); + + b.Property("SecretsVariableName") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("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 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807150646_AddSecretsProviders.cs b/src/Backend/Data/Migrations/Sqlite/20260807150646_AddSecretsProviders.cs new file mode 100644 index 0000000..28f66b7 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807150646_AddSecretsProviders.cs @@ -0,0 +1,65 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddSecretsProviders : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "SecretBindingsJson", + table: "Scripts", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "SecretsVariableName", + table: "Scripts", + type: "TEXT", + nullable: true); + + migrationBuilder.CreateTable( + name: "SecretsProviders", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", nullable: false), + Kind = table.Column(type: "TEXT", nullable: false), + ConfigProtected = table.Column(type: "TEXT", nullable: false), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + UpdatedUtc = table.Column(type: "INTEGER", nullable: false), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_SecretsProviders", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_SecretsProviders_Name", + table: "SecretsProviders", + column: "Name", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "SecretsProviders"); + + migrationBuilder.DropColumn( + name: "SecretBindingsJson", + table: "Scripts"); + + migrationBuilder.DropColumn( + name: "SecretsVariableName", + table: "Scripts"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807153214_AddScheduledRuns.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20260807153214_AddScheduledRuns.Designer.cs new file mode 100644 index 0000000..25ccbe1 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807153214_AddScheduledRuns.Designer.cs @@ -0,0 +1,698 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + [Migration("20260807153214_AddScheduledRuns")] + partial class AddScheduledRuns + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScheduledRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScheduledRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("SecretBindingsJson") + .HasColumnType("TEXT"); + + b.Property("SecretsVariableName") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("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 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807153214_AddScheduledRuns.cs b/src/Backend/Data/Migrations/Sqlite/20260807153214_AddScheduledRuns.cs new file mode 100644 index 0000000..74ecfb0 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807153214_AddScheduledRuns.cs @@ -0,0 +1,59 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddScheduledRuns : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ScheduledRuns", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ScriptId = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", nullable: true), + ClientId = table.Column(type: "TEXT", nullable: true), + GroupId = table.Column(type: "TEXT", nullable: true), + CronExpression = table.Column(type: "TEXT", nullable: true), + RunOnceUtc = table.Column(type: "INTEGER", nullable: true), + TimeZoneId = table.Column(type: "TEXT", nullable: false), + Enabled = table.Column(type: "INTEGER", nullable: false), + ArgumentsJson = table.Column(type: "TEXT", nullable: true), + NextRunUtc = table.Column(type: "INTEGER", nullable: true), + LastRunUtc = table.Column(type: "INTEGER", nullable: true), + LastResult = table.Column(type: "TEXT", nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + UpdatedUtc = table.Column(type: "INTEGER", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScheduledRuns", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledRuns_NextRunUtc", + table: "ScheduledRuns", + column: "NextRunUtc"); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledRuns_ScriptId", + table: "ScheduledRuns", + column: "ScriptId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScheduledRuns"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807165537_ScheduleObjects.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20260807165537_ScheduleObjects.Designer.cs new file mode 100644 index 0000000..45cd362 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807165537_ScheduleObjects.Designer.cs @@ -0,0 +1,745 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + [Migration("20260807165537_ScheduleObjects")] + partial class ScheduleObjects + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("NextRunUtc"); + + b.ToTable("Schedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("SecretBindingsJson") + .HasColumnType("TEXT"); + + b.Property("SecretsVariableName") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("ScheduleId") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScriptSchedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("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.ScriptScheduleEntity", b => + { + b.HasOne("Backend.Data.ScheduleEntity", null) + .WithMany() + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.ScriptEntity", null) + .WithMany() + .HasForeignKey("ScriptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807165537_ScheduleObjects.cs b/src/Backend/Data/Migrations/Sqlite/20260807165537_ScheduleObjects.cs new file mode 100644 index 0000000..1d54676 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807165537_ScheduleObjects.cs @@ -0,0 +1,141 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class ScheduleObjects : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScheduledRuns"); + + migrationBuilder.CreateTable( + name: "Schedules", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", nullable: false), + CronExpression = table.Column(type: "TEXT", nullable: true), + RunOnceUtc = table.Column(type: "INTEGER", nullable: true), + TimeZoneId = table.Column(type: "TEXT", nullable: false), + Enabled = table.Column(type: "INTEGER", nullable: false), + NextRunUtc = table.Column(type: "INTEGER", nullable: true), + LastRunUtc = table.Column(type: "INTEGER", nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + UpdatedUtc = table.Column(type: "INTEGER", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Schedules", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ScriptSchedules", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ScheduleId = table.Column(type: "TEXT", nullable: false), + ScriptId = table.Column(type: "TEXT", nullable: false), + ClientId = table.Column(type: "TEXT", nullable: true), + GroupId = table.Column(type: "TEXT", nullable: true), + ArgumentsJson = table.Column(type: "TEXT", nullable: true), + Enabled = table.Column(type: "INTEGER", nullable: false), + LastRunUtc = table.Column(type: "INTEGER", nullable: true), + LastResult = table.Column(type: "TEXT", nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScriptSchedules", x => x.Id); + table.ForeignKey( + name: "FK_ScriptSchedules_Schedules_ScheduleId", + column: x => x.ScheduleId, + principalTable: "Schedules", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ScriptSchedules_Scripts_ScriptId", + column: x => x.ScriptId, + principalTable: "Scripts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Schedules_Name", + table: "Schedules", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Schedules_NextRunUtc", + table: "Schedules", + column: "NextRunUtc"); + + migrationBuilder.CreateIndex( + name: "IX_ScriptSchedules_ScheduleId", + table: "ScriptSchedules", + column: "ScheduleId"); + + migrationBuilder.CreateIndex( + name: "IX_ScriptSchedules_ScriptId", + table: "ScriptSchedules", + column: "ScriptId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScriptSchedules"); + + migrationBuilder.DropTable( + name: "Schedules"); + + migrationBuilder.CreateTable( + name: "ScheduledRuns", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ArgumentsJson = table.Column(type: "TEXT", nullable: true), + ClientId = table.Column(type: "TEXT", nullable: true), + CreatedBy = table.Column(type: "TEXT", nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + CronExpression = table.Column(type: "TEXT", nullable: true), + Enabled = table.Column(type: "INTEGER", nullable: false), + GroupId = table.Column(type: "TEXT", nullable: true), + LastResult = table.Column(type: "TEXT", nullable: true), + LastRunUtc = table.Column(type: "INTEGER", nullable: true), + Name = table.Column(type: "TEXT", nullable: true), + NextRunUtc = table.Column(type: "INTEGER", nullable: true), + RunOnceUtc = table.Column(type: "INTEGER", nullable: true), + ScriptId = table.Column(type: "TEXT", nullable: false), + TimeZoneId = table.Column(type: "TEXT", nullable: false), + UpdatedBy = table.Column(type: "TEXT", nullable: true), + UpdatedUtc = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ScheduledRuns", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledRuns_NextRunUtc", + table: "ScheduledRuns", + column: "NextRunUtc"); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledRuns_ScriptId", + table: "ScheduledRuns", + column: "ScriptId"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807185825_AddDevicePublicIp.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20260807185825_AddDevicePublicIp.Designer.cs new file mode 100644 index 0000000..18857ff --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807185825_AddDevicePublicIp.Designer.cs @@ -0,0 +1,748 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + [Migration("20260807185825_AddDevicePublicIp")] + partial class AddDevicePublicIp + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("PublicIp") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("NextRunUtc"); + + b.ToTable("Schedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("SecretBindingsJson") + .HasColumnType("TEXT"); + + b.Property("SecretsVariableName") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("ScheduleId") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScriptSchedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("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.ScriptScheduleEntity", b => + { + b.HasOne("Backend.Data.ScheduleEntity", null) + .WithMany() + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.ScriptEntity", null) + .WithMany() + .HasForeignKey("ScriptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807185825_AddDevicePublicIp.cs b/src/Backend/Data/Migrations/Sqlite/20260807185825_AddDevicePublicIp.cs new file mode 100644 index 0000000..9027bae --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807185825_AddDevicePublicIp.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddDevicePublicIp : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "PublicIp", + table: "Devices", + type: "TEXT", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "PublicIp", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs index c58afd0..fe76967 100644 --- a/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs @@ -17,6 +17,28 @@ namespace Backend.Data.Migrations.Sqlite #pragma warning disable 612, 618 modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => { b.Property("Id") @@ -138,6 +160,9 @@ namespace Backend.Data.Migrations.Sqlite b.Property("OsVersion") .HasColumnType("TEXT"); + b.Property("PublicIp") + .HasColumnType("TEXT"); + b.Property("ReadyUtc") .HasColumnType("INTEGER"); @@ -367,6 +392,57 @@ namespace Backend.Data.Migrations.Sqlite b.ToTable("OidcProviders", (string)null); }); + modelBuilder.Entity("Backend.Data.ScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("NextRunUtc"); + + b.ToTable("Schedules", (string)null); + }); + modelBuilder.Entity("Backend.Data.ScriptEntity", b => { b.Property("Id") @@ -400,6 +476,12 @@ namespace Backend.Data.Migrations.Sqlite b.Property("ParametersJson") .HasColumnType("TEXT"); + b.Property("SecretBindingsJson") + .HasColumnType("TEXT"); + + b.Property("SecretsVariableName") + .HasColumnType("TEXT"); + b.Property("UpdatedBy") .HasColumnType("TEXT"); @@ -413,6 +495,51 @@ namespace Backend.Data.Migrations.Sqlite b.ToTable("Scripts", (string)null); }); + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("ScheduleId") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScriptSchedules", (string)null); + }); + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => { b.Property("Id") @@ -475,6 +602,41 @@ namespace Backend.Data.Migrations.Sqlite b.ToTable("ScriptTriggerRuns", (string)null); }); + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => { b.Property("Id") @@ -558,6 +720,21 @@ namespace Backend.Data.Migrations.Sqlite .IsRequired(); }); + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.HasOne("Backend.Data.ScheduleEntity", null) + .WithMany() + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.ScriptEntity", null) + .WithMany() + .HasForeignKey("ScriptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Backend.Data.DeviceEntity", b => { b.Navigation("Inventory"); diff --git a/src/Backend/Enrollment/EnrollmentEndpoints.cs b/src/Backend/Enrollment/EnrollmentEndpoints.cs index 3bfdbb8..0b5507a 100644 --- a/src/Backend/Enrollment/EnrollmentEndpoints.cs +++ b/src/Backend/Enrollment/EnrollmentEndpoints.cs @@ -116,6 +116,7 @@ public static class EnrollmentEndpoints device.OsCaption = request.Device.OsCaption; device.OsVersion = request.Device.OsVersion; device.AgentVersion = request.AgentVersion; + device.PublicIp = remoteIp; token.Uses++; @@ -225,6 +226,14 @@ public static class EnrollmentEndpoints return Results.Unauthorized(); } + // A verified refresh is the freshest sighting of the agent's public IP. + var publicIp = ClientIp.EffectiveText(context); + if (!string.Equals(device.PublicIp, publicIp, StringComparison.Ordinal)) + { + device.PublicIp = publicIp; + await db.SaveChangesAsync(cancellationToken); + } + var userJwt = issuer.IssueAgentCredential(request.ClientId, request.NkeyPublic); return Results.Ok(new CredentialRefreshResponse(userJwt, CredentialExpiresUtc: null)); } diff --git a/src/Backend/Enrollment/InstallEndpoints.cs b/src/Backend/Enrollment/InstallEndpoints.cs index da3974c..ff083b3 100644 --- a/src/Backend/Enrollment/InstallEndpoints.cs +++ b/src/Backend/Enrollment/InstallEndpoints.cs @@ -46,24 +46,29 @@ public static class InstallEndpoints return Results.Text(script, "text/plain; charset=utf-8"); } - private static async Task GetAgentPackage(HttpContext context, IConfiguration configuration, string? type) + private static async Task GetAgentPackage( + Files.AgentPackageService packages, string? type, CancellationToken cancellationToken) { - var directory = configuration["AGENT_PACKAGE_PATH"]; - if (string.IsNullOrWhiteSpace(directory)) + var packageType = Files.AgentPackageService.NormalizeType(type); + var fileName = packageType == "zip" ? "Agent.zip" : "Agent.msi"; + + // When S3 offload is on, hand the endpoint a presigned URL so the + // transfer never touches the control plane. Falls through to local + // delivery if presigning fails for any reason. + var offloadUrl = await packages.TryGetOffloadUrlAsync(packageType, cancellationToken); + if (offloadUrl is not null) { - directory = "/data/agent"; + return Results.Redirect(offloadUrl, permanent: false); } - var packageType = type?.ToLowerInvariant() == "zip" ? "zip" : "msi"; - var fileName = packageType == "zip" ? "Agent.zip" : "Agent.msi"; - var path = Path.Combine(directory, fileName); - - if (!File.Exists(path)) + var path = packages.ResolveLocalPath(packageType); + if (path is null) { return Results.NotFound(new { - error = $"Agent package '{fileName}' is not available. " + - "Place the built package in AGENT_PACKAGE_PATH (default /data/agent).", + error = $"Agent package '{fileName}' is not available. CI bakes it into the backend " + + "image; for a local build run scripts/Package-Agent.ps1 and mount the output " + + "at AGENT_PACKAGE_PATH (or /data/agent).", }); } @@ -73,16 +78,7 @@ public static class InstallEndpoints } private static string ResolveBaseUrl(HttpContext context, IConfiguration configuration) - { - var configured = configuration["PUBLIC_SERVER_URL"]; - if (!string.IsNullOrWhiteSpace(configured)) - { - return configured.TrimEnd('/'); - } - - // Derived from forwarded headers (proxy-aware) after ForwardedHeaders ran. - return $"{context.Request.Scheme}://{context.Request.Host}"; - } + => Backend.Proxy.PublicUrl.Resolve(context, configuration); // NOTE: $$""" — interpolations are {{ }}, single braces are literal PowerShell. private static string BuildMsiScript(string baseUrl, string token, string packageUrl) => $$""" @@ -110,7 +106,7 @@ public static class InstallEndpoints Write-Host 'Installing ExecuteR Agent (portable)...' $server = '{{baseUrl}}' $token = '{{token}}' - $dest = Join-Path $env:ProgramFiles 'Grace Solution\ExecuteR Agent' + $dest = Join-Path $env:ProgramFiles 'ExecuteR Agent' $zip = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.zip') try { Invoke-WebRequest -Uri '{{packageUrl}}' -OutFile $zip -UseBasicParsing diff --git a/src/Backend/Files/AgentPackageService.cs b/src/Backend/Files/AgentPackageService.cs new file mode 100644 index 0000000..e23d5ec --- /dev/null +++ b/src/Backend/Files/AgentPackageService.cs @@ -0,0 +1,226 @@ +using System.Security.Cryptography; +using Amazon.S3; +using Amazon.S3.Model; +using Shared.Contracts.Api; + +namespace Backend.Files; + +/// +/// Locates the agent installer that the URL-install flow hands out. +/// +/// Search order: +/// 1. AGENT_PACKAGE_PATH, when explicitly configured +/// 2. /opt/executer/agent — baked into the backend image by CI +/// 3. /data/agent — a manually seeded volume (legacy / air-gapped) +/// +/// CI copies the Windows-built package into the image, so a stock deployment +/// serves the agent with no manual step. When S3 offload is enabled the same +/// package is uploaded once and served as a presigned URL instead, which keeps +/// large downloads off the control plane. +/// +public sealed class AgentPackageService( + IConfiguration configuration, + S3SettingsService s3Settings, + ILogger logger) +{ + public const string BakedInPath = "/opt/executer/agent"; + public const string SeededPath = "/data/agent"; + + private static string FileNameFor(string packageType) => packageType == "zip" ? "Agent.zip" : "Agent.msi"; + + public static string NormalizeType(string? type) + => string.Equals(type, "zip", StringComparison.OrdinalIgnoreCase) ? "zip" : "msi"; + + /// Directories searched, most specific first. + private IEnumerable CandidateDirectories() + { + var configured = configuration["AGENT_PACKAGE_PATH"]; + if (!string.IsNullOrWhiteSpace(configured)) + { + yield return configured; + } + + yield return BakedInPath; + yield return SeededPath; + } + + /// Full path to the package on local disk, or null when absent. + public string? ResolveLocalPath(string packageType) + { + var fileName = FileNameFor(packageType); + foreach (var directory in CandidateDirectories()) + { + var path = Path.Combine(directory, fileName); + if (File.Exists(path)) + { + return path; + } + } + + return null; + } + + public async Task GetStatusAsync(string packageType, CancellationToken cancellationToken) + { + var offloadEnabled = await s3Settings.GetAgentOffloadEnabledAsync(cancellationToken); + var objectKey = await s3Settings.GetAgentObjectKeyAsync(packageType, cancellationToken); + var path = ResolveLocalPath(packageType); + + if (path is null) + { + return new AgentPackageStatusDto( + Available: offloadEnabled && objectKey is not null, + Source: offloadEnabled && objectKey is not null ? "s3" : "none", + FileName: FileNameFor(packageType), + SizeBytes: null, Sha256: null, BuiltUtc: null, Version: null, + OffloadEnabled: offloadEnabled, + OffloadUploaded: objectKey is not null); + } + + var info = new FileInfo(path); + return new AgentPackageStatusDto( + Available: true, + Source: offloadEnabled && objectKey is not null ? "s3" : DescribeSource(path), + FileName: info.Name, + SizeBytes: info.Length, + Sha256: await ComputeSha256Async(path, cancellationToken), + BuiltUtc: new DateTimeOffset(info.LastWriteTimeUtc, TimeSpan.Zero), + Version: ReadVersionMarker(info.DirectoryName), + OffloadEnabled: offloadEnabled, + OffloadUploaded: objectKey is not null); + } + + private static string DescribeSource(string path) + => path.Replace('\\', '/').StartsWith(BakedInPath, StringComparison.OrdinalIgnoreCase) + ? "image" + : "volume"; + + /// CI writes a VERSION file beside the package. + private static string? ReadVersionMarker(string? directory) + { + if (directory is null) + { + return null; + } + + var marker = Path.Combine(directory, "VERSION"); + try + { + return File.Exists(marker) ? File.ReadAllText(marker).Trim() : null; + } + catch (IOException) + { + return null; + } + } + + public static async Task ComputeSha256Async(string path, CancellationToken cancellationToken) + { + await using var stream = File.OpenRead(path); + return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, cancellationToken)); + } + + /// + /// Uploads the local package to S3 and records its object key. Re-uploading + /// an unchanged package is skipped by comparing the stored hash. + /// + public async Task<(bool Ok, string Message)> UploadToS3Async( + string packageType, string? actor, CancellationToken cancellationToken) + { + var path = ResolveLocalPath(packageType); + if (path is null) + { + return (false, $"No {FileNameFor(packageType)} available to upload."); + } + + var options = await s3Settings.GetEffectiveAsync(cancellationToken); + if (!options.IsUsable) + { + return (false, "S3 is not configured."); + } + + var sha = await ComputeSha256Async(path, cancellationToken); + var objectKey = $"executer/agent/{sha[..12]}/{FileNameFor(packageType)}"; + + using var client = S3ClientFactory.Create(options); + try + { + // Skip the transfer when this exact build is already present. + try + { + var head = await client.GetObjectMetadataAsync(options.Bucket, objectKey, cancellationToken); + if (head.HttpStatusCode == System.Net.HttpStatusCode.OK) + { + await s3Settings.SetAsync( + S3SettingsService.Keys.AgentObjectKeyPrefix + packageType, objectKey, false, actor, cancellationToken); + return (true, $"Already present in S3 ({objectKey}); nothing re-uploaded."); + } + } + catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) + { + // Expected on first upload. + } + + await client.PutObjectAsync(new PutObjectRequest + { + BucketName = options.Bucket, + Key = objectKey, + FilePath = path, + }, cancellationToken); + + await s3Settings.SetAsync( + S3SettingsService.Keys.AgentObjectKeyPrefix + packageType, objectKey, false, actor, cancellationToken); + + logger.LogInformation("Agent package {Type} uploaded to S3 as {Key}", packageType, objectKey); + return (true, $"Uploaded to {objectKey}."); + } + catch (Exception ex) + { + logger.LogError(ex, "Agent package upload to S3 failed"); + return (false, ex is AmazonS3Exception s3 ? $"{s3.ErrorCode}: {s3.Message}" : ex.Message); + } + } + + /// + /// Presigned URL for the offloaded package, or null when offload is off or + /// nothing has been uploaded yet. + /// + public async Task TryGetOffloadUrlAsync(string packageType, CancellationToken cancellationToken) + { + if (!await s3Settings.GetAgentOffloadEnabledAsync(cancellationToken)) + { + return null; + } + + var objectKey = await s3Settings.GetAgentObjectKeyAsync(packageType, cancellationToken); + if (objectKey is null) + { + return null; + } + + var options = await s3Settings.GetEffectiveAsync(cancellationToken); + if (!options.IsUsable) + { + return null; + } + + try + { + using var client = S3ClientFactory.Create(options); + return client.GetPreSignedURL(new GetPreSignedUrlRequest + { + BucketName = options.Bucket, + Key = objectKey, + Verb = HttpVerb.GET, + Expires = DateTime.UtcNow.AddSeconds(options.PresignExpirySeconds), + }); + } + catch (Exception ex) + { + // Never break installs because the offload path is unhealthy — + // the caller falls back to streaming from local disk. + logger.LogWarning(ex, "Presigning the offloaded agent package failed; falling back to local delivery"); + return null; + } + } +} diff --git a/src/Backend/Files/FileDeliveryEndpoints.cs b/src/Backend/Files/FileDeliveryEndpoints.cs index f8770de..f5a0a6b 100644 --- a/src/Backend/Files/FileDeliveryEndpoints.cs +++ b/src/Backend/Files/FileDeliveryEndpoints.cs @@ -42,7 +42,7 @@ public static class FileDeliveryEndpoints return Results.BadRequest(new { error = "clientId, objectKey and destinationPath are required." }); } - if (!s3.IsConfigured) + if (!await s3.IsConfiguredAsync(cancellationToken)) { return Results.Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "S3 file delivery is not configured."); } @@ -53,7 +53,7 @@ public static class FileDeliveryEndpoints return Results.NotFound(); } - var (url, expiresUtc) = s3.PresignGet(request.ObjectKey); + var (url, expiresUtc) = await s3.PresignGetAsync(request.ObjectKey, cancellationToken); var actor = context.User.Identity?.Name; var job = new JobEntity diff --git a/src/Backend/Files/S3Client.cs b/src/Backend/Files/S3Client.cs new file mode 100644 index 0000000..77a1799 --- /dev/null +++ b/src/Backend/Files/S3Client.cs @@ -0,0 +1,162 @@ +using System.Diagnostics; +using System.Text; +using Amazon; +using Amazon.S3; +using Amazon.S3.Model; + +namespace Backend.Files; + +/// One step of the connectivity test, surfaced individually in the UI. +public sealed record S3TestStep(string Name, bool Ok, string? Detail); + +/// Result of a full S3 round-trip test. +public sealed record S3TestResult(bool Ok, IReadOnlyList Steps, long ElapsedMs); + +/// +/// Builds S3 clients from a given set of options (not just the ambient ones), +/// so candidate settings can be validated before they are saved. +/// +public static class S3ClientFactory +{ + public static IAmazonS3 Create(S3Options options) + { + var config = new AmazonS3Config + { + ForcePathStyle = options.ForcePathStyle, + RegionEndpoint = RegionEndpoint.GetBySystemName(options.Region), + Timeout = TimeSpan.FromSeconds(20), + }; + + if (!string.IsNullOrWhiteSpace(options.Endpoint)) + { + config.ServiceURL = options.Endpoint; + config.AuthenticationRegion = options.Region; + } + + return new AmazonS3Client(options.AccessKey, options.SecretKey, config); + } + + /// + /// Exercises the credentials for real: bucket reachable, then write, read + /// back, presign and delete a small probe object. Each step is reported + /// separately so a partial failure (e.g. read-only credentials) is obvious. + /// + public static async Task TestAsync(S3Options options, CancellationToken cancellationToken) + { + var steps = new List(); + var stopwatch = Stopwatch.StartNew(); + + if (!options.IsUsable) + { + steps.Add(new S3TestStep("configuration", false, + "Enabled, bucket, access key and secret key are all required.")); + return new S3TestResult(false, steps, stopwatch.ElapsedMilliseconds); + } + + IAmazonS3? client = null; + var key = $"executer-connectivity-check/{Guid.NewGuid():N}.txt"; + var payload = $"ExecuteR connectivity check {DateTimeOffset.UtcNow:O}"; + + try + { + client = Create(options); + + // 1. Bucket reachable / credentials valid. + try + { + await client.GetBucketLocationAsync(options.Bucket, cancellationToken); + steps.Add(new S3TestStep("bucket", true, $"'{options.Bucket}' reachable")); + } + catch (AmazonS3Exception ex) + { + // Some S3-compatible stores do not implement GetBucketLocation; + // a listing probe is a fair substitute. + try + { + await client.ListObjectsV2Async( + new ListObjectsV2Request { BucketName = options.Bucket, MaxKeys = 1 }, cancellationToken); + steps.Add(new S3TestStep("bucket", true, $"'{options.Bucket}' reachable (via list)")); + } + catch (Exception inner) + { + steps.Add(new S3TestStep("bucket", false, Describe(ex, inner))); + return new S3TestResult(false, steps, stopwatch.ElapsedMilliseconds); + } + } + + // 2. Write. + await client.PutObjectAsync(new PutObjectRequest + { + BucketName = options.Bucket, + Key = key, + ContentBody = payload, + }, cancellationToken); + steps.Add(new S3TestStep("write", true, "probe object uploaded")); + + // 3. Read back and compare. + using (var response = await client.GetObjectAsync(options.Bucket, key, cancellationToken)) + using (var reader = new StreamReader(response.ResponseStream, Encoding.UTF8)) + { + var read = await reader.ReadToEndAsync(cancellationToken); + var matches = read == payload; + steps.Add(new S3TestStep("read", matches, + matches ? "content matches" : "content did not match what was written")); + } + + // 4. Presign — this is the mechanism agents actually use. + var url = client.GetPreSignedURL(new GetPreSignedUrlRequest + { + BucketName = options.Bucket, + Key = key, + Verb = HttpVerb.GET, + Expires = DateTime.UtcNow.AddMinutes(5), + }); + using (var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) }) + { + var fetched = await http.GetAsync(url, cancellationToken); + steps.Add(new S3TestStep("presigned download", fetched.IsSuccessStatusCode, + fetched.IsSuccessStatusCode + ? "presigned URL downloadable" + : $"presigned GET returned HTTP {(int)fetched.StatusCode} — check the endpoint is reachable from agents")); + } + + // 5. Clean up. + await client.DeleteObjectAsync(options.Bucket, key, cancellationToken); + steps.Add(new S3TestStep("delete", true, "probe object removed")); + } + catch (Exception ex) + { + steps.Add(new S3TestStep("error", false, Describe(ex))); + try + { + if (client is not null) + { + await client.DeleteObjectAsync(options.Bucket, key, CancellationToken.None); + } + } + catch (Exception) + { + // Best-effort cleanup. + } + } + finally + { + client?.Dispose(); + } + + stopwatch.Stop(); + return new S3TestResult(steps.All(s => s.Ok), steps, stopwatch.ElapsedMilliseconds); + } + + private static string Describe(params Exception[] exceptions) + { + var ex = exceptions[^1]; + return ex switch + { + AmazonS3Exception s3 => $"{s3.ErrorCode ?? "S3Error"}: {s3.Message}", + HttpRequestException http => $"Network: {http.Message}", + TaskCanceledException => "Timed out contacting the endpoint.", + _ => ex.Message, + }; + } +} diff --git a/src/Backend/Files/S3PresignService.cs b/src/Backend/Files/S3PresignService.cs index be605ad..812136b 100644 --- a/src/Backend/Files/S3PresignService.cs +++ b/src/Backend/Files/S3PresignService.cs @@ -1,4 +1,3 @@ -using Amazon; using Amazon.S3; using Amazon.S3.Model; @@ -6,46 +5,26 @@ namespace Backend.Files; /// /// Issues short-lived presigned GET URLs so agents can download objects -/// without ever holding S3 credentials. +/// without ever holding S3 credentials. Settings are resolved per call, so +/// changes saved in the UI take effect without restarting the backend. /// -public sealed class S3PresignService : IDisposable +public sealed class S3PresignService(S3SettingsService settings) { - private readonly S3Options options; - private readonly IAmazonS3? client; + public async Task IsConfiguredAsync(CancellationToken cancellationToken) + => (await settings.GetEffectiveAsync(cancellationToken)).IsUsable; - public S3PresignService(S3Options options) + public async Task<(string Url, DateTimeOffset ExpiresUtc)> PresignGetAsync( + string objectKey, CancellationToken cancellationToken) { - this.options = options; + var options = await settings.GetEffectiveAsync(cancellationToken); if (!options.IsUsable) - { - return; - } - - var config = new AmazonS3Config - { - ForcePathStyle = options.ForcePathStyle, - RegionEndpoint = RegionEndpoint.GetBySystemName(options.Region), - }; - - if (!string.IsNullOrWhiteSpace(options.Endpoint)) - { - config.ServiceURL = options.Endpoint; - config.AuthenticationRegion = options.Region; - } - - client = new AmazonS3Client(options.AccessKey, options.SecretKey, config); - } - - public bool IsConfigured => client is not null; - - public (string Url, DateTimeOffset ExpiresUtc) PresignGet(string objectKey) - { - if (client is null) { throw new InvalidOperationException("S3 is not configured."); } var expires = DateTime.UtcNow.AddSeconds(options.PresignExpirySeconds); + + using var client = S3ClientFactory.Create(options); var url = client.GetPreSignedURL(new GetPreSignedUrlRequest { BucketName = options.Bucket, @@ -56,6 +35,4 @@ public sealed class S3PresignService : IDisposable return (url, new DateTimeOffset(expires, TimeSpan.Zero)); } - - public void Dispose() => client?.Dispose(); } diff --git a/src/Backend/Files/S3SettingsService.cs b/src/Backend/Files/S3SettingsService.cs new file mode 100644 index 0000000..296480e --- /dev/null +++ b/src/Backend/Files/S3SettingsService.cs @@ -0,0 +1,87 @@ +using Backend.Settings; + +namespace Backend.Files; + +/// +/// Resolves the effective S3 configuration: values saved from the UI override +/// the environment, which acts as the bootstrap default. Also creates clients +/// against the effective settings so a "Test" can validate candidate values +/// before they are saved. +/// +public sealed class S3SettingsService(SettingsStore store, S3Options environmentDefaults) +{ + public const string Prefix = "s3."; + + public static class Keys + { + public const string Enabled = Prefix + "enabled"; + public const string Endpoint = Prefix + "endpoint"; + public const string Region = Prefix + "region"; + public const string Bucket = Prefix + "bucket"; + public const string AccessKey = Prefix + "accessKey"; + public const string SecretKey = Prefix + "secretKey"; + public const string ForcePathStyle = Prefix + "forcePathStyle"; + public const string PresignExpirySeconds = Prefix + "presignExpirySeconds"; + + /// Serve the agent package from S3 instead of local disk. + public const string AgentOffloadEnabled = Prefix + "agentOffloadEnabled"; + /// Object key of the uploaded agent package. + public const string AgentObjectKeyPrefix = Prefix + "agentObjectKey."; + /// Last verified round-trip, ISO-8601. + public const string LastTestUtc = Prefix + "lastTestUtc"; + } + + /// Effective options: database overrides, environment defaults. + public async Task GetEffectiveAsync(CancellationToken cancellationToken) + { + var saved = await store.GetAllAsync(Prefix, cancellationToken); + + return new S3Options + { + Enabled = Bool(saved, Keys.Enabled, environmentDefaults.Enabled), + Endpoint = Str(saved, Keys.Endpoint, environmentDefaults.Endpoint), + Region = Str(saved, Keys.Region, environmentDefaults.Region) ?? "us-east-1", + Bucket = Str(saved, Keys.Bucket, environmentDefaults.Bucket), + AccessKey = Str(saved, Keys.AccessKey, environmentDefaults.AccessKey), + SecretKey = Str(saved, Keys.SecretKey, environmentDefaults.SecretKey), + ForcePathStyle = Bool(saved, Keys.ForcePathStyle, environmentDefaults.ForcePathStyle), + PresignExpirySeconds = Int(saved, Keys.PresignExpirySeconds, environmentDefaults.PresignExpirySeconds), + }; + } + + public async Task GetAgentOffloadEnabledAsync(CancellationToken cancellationToken) + { + var saved = await store.GetAllAsync(Prefix, cancellationToken); + return Bool(saved, Keys.AgentOffloadEnabled, false); + } + + public async Task GetAgentObjectKeyAsync(string packageType, CancellationToken cancellationToken) + { + var saved = await store.GetAllAsync(Prefix, cancellationToken); + return Str(saved, Keys.AgentObjectKeyPrefix + packageType, null); + } + + public async Task GetLastTestUtcAsync(CancellationToken cancellationToken) + { + var saved = await store.GetAllAsync(Prefix, cancellationToken); + var raw = Str(saved, Keys.LastTestUtc, null); + return DateTimeOffset.TryParse(raw, out var value) ? value : null; + } + + public Task SetAsync(string key, string? value, bool isSecret, string? actor, CancellationToken cancellationToken) + => store.SetAsync(key, value, isSecret, actor, cancellationToken); + + /// True when the environment supplied a value, so the UI can show it as inherited. + public S3Options EnvironmentDefaults => environmentDefaults; + + private static string? Str(IReadOnlyDictionary saved, string key, string? fallback) + => saved.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value) ? value : fallback; + + private static bool Bool(IReadOnlyDictionary saved, string key, bool fallback) + => saved.TryGetValue(key, out var value) ? value is "1" or "true" or "True" : fallback; + + private static int Int(IReadOnlyDictionary saved, string key, int fallback) + => saved.TryGetValue(key, out var value) && int.TryParse(value, out var parsed) && parsed > 0 + ? parsed + : fallback; +} diff --git a/src/Backend/Groups/ScriptTriggerService.cs b/src/Backend/Groups/ScriptTriggerService.cs index 0fcb95c..5b0d271 100644 --- a/src/Backend/Groups/ScriptTriggerService.cs +++ b/src/Backend/Groups/ScriptTriggerService.cs @@ -17,8 +17,7 @@ namespace Backend.Groups; public sealed class ScriptTriggerService( AppDbContext db, DeviceGroupService groups, - CommandDispatcher dispatcher, - BrowserEventBroadcaster broadcaster, + JobRunner runner, ILogger logger) { public async Task FireAsync(ScriptTriggerType triggerType, string clientId, CancellationToken cancellationToken) @@ -61,17 +60,8 @@ public sealed class ScriptTriggerService( continue; } - var job = new JobEntity - { - JobId = Guid.NewGuid(), - ClientId = clientId, - ScriptId = script.Id, - ScriptName = script.Name, - State = JobState.Queued, - CreatedUtc = DateTimeOffset.UtcNow, - RequestedBy = $"trigger:{triggerType}", - }; - db.Jobs.Add(job); + var job = await runner.CreateJobAsync( + script, clientId, $"trigger:{triggerType}", cancellationToken); if (trigger.OncePerDevice) { @@ -82,31 +72,29 @@ public sealed class ScriptTriggerService( JobId = job.JobId, FiredUtc = DateTimeOffset.UtcNow, }); - } - - await db.SaveChangesAsync(cancellationToken); - - var parameters = ScriptEndpoints.DeserializeParameters(script.ParametersJson); - var moduleIds = ScriptEndpoints.DeserializeModuleIds(script.FunctionModuleIdsJson); - var prelude = await ComposePreludeAsync(moduleIds, cancellationToken); - - var dispatched = await dispatcher.DispatchScriptAsync(clientId, new ScriptCommandPayload( - job.JobId, script.Id, script.Name, script.Content, - ProtocolDefaults.DefaultScriptTimeoutSeconds, - Prelude: prelude, - Parameters: parameters.Count > 0 ? parameters : null, - Arguments: null), cancellationToken); - - if (dispatched) - { - job.State = JobState.Dispatched; await db.SaveChangesAsync(cancellationToken); } - await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( - "job-created", + // The job row exists before secret resolution so a vault outage + // is visible as a failed job — triggers have no operator watching. + PreparedScript prepared; + try + { + prepared = await runner.PrepareAsync(script, cancellationToken); + } + catch (Backend.Secrets.SecretResolutionException ex) + { + await runner.MarkFailedAsync(job, ex.Message, cancellationToken); + logger.LogWarning( + "Trigger {TriggerId} job {JobId} failed: {Message}", + trigger.Id, job.JobId, ex.Message); + continue; + } + + await runner.DispatchAsync( + prepared, job, arguments: null, $"Trigger ({triggerType}) queued “{script.Name}” for {device.Hostname}", - clientId, job.JobId, DateTimeOffset.UtcNow), cancellationToken); + cancellationToken); logger.LogInformation( "Trigger {TriggerId} ({TriggerType}) fired for {ClientId} as job {JobId}", @@ -120,23 +108,4 @@ public sealed class ScriptTriggerService( } } - private async Task ComposePreludeAsync(IReadOnlyList moduleIds, CancellationToken cancellationToken) - { - if (moduleIds.Count == 0) - { - return null; - } - - var modules = await db.FunctionModules.AsNoTracking() - .Where(m => moduleIds.Contains(m.Id)) - .ToListAsync(cancellationToken); - - var ordered = moduleIds - .Select(id => modules.FirstOrDefault(m => m.Id == id)) - .Where(m => m is not null) - .Select(m => $"# --- function module: {m!.Name} ---\n{m.Content}") - .ToList(); - - return ordered.Count > 0 ? string.Join("\n\n", ordered) : null; - } } diff --git a/src/Backend/Jobs/JobEndpoints.cs b/src/Backend/Jobs/JobEndpoints.cs index ebb04b6..9e21094 100644 --- a/src/Backend/Jobs/JobEndpoints.cs +++ b/src/Backend/Jobs/JobEndpoints.cs @@ -76,12 +76,44 @@ public static class JobEndpoints private static async Task CreateAsync( CreateJobRequest request, AppDbContext db, - CommandDispatcher dispatcher, - BrowserEventBroadcaster broadcaster, + JobRunner runner, + Backend.Groups.DeviceGroupService groups, AuditService audit, HttpContext context, CancellationToken cancellationToken) { + if ((request.ClientId is null) == (request.GroupId is null)) + { + return Results.BadRequest(new { error = "Target exactly one of clientId or groupId." }); + } + + var script = await db.Scripts.AsNoTracking() + .SingleOrDefaultAsync(s => s.Id == request.ScriptId, cancellationToken); + if (script is null) + { + return Results.NotFound(new { error = "Script not found." }); + } + + var actor = context.User.Identity?.Name; + + // Secrets and the prelude are prepared once, before any job rows exist: + // a vault failure surfaces immediately instead of minting failed jobs. + PreparedScript prepared; + try + { + prepared = await runner.PrepareAsync(script, cancellationToken); + } + catch (Backend.Secrets.SecretResolutionException ex) + { + return Results.Problem(ex.Message, statusCode: StatusCodes.Status502BadGateway); + } + + if (request.GroupId is { } groupId) + { + return await RunOnGroupAsync( + groupId, prepared, request, db, runner, groups, audit, actor, cancellationToken); + } + if (!SubjectIdentifier.IsValid(request.ClientId)) { return Results.BadRequest(new { error = "Invalid client id." }); @@ -102,83 +134,67 @@ public static class JobEndpoints }); } - var script = await db.Scripts.AsNoTracking() - .SingleOrDefaultAsync(s => s.Id == request.ScriptId, cancellationToken); - if (script is null) - { - return Results.NotFound(new { error = "Script not found." }); - } - - var actor = context.User.Identity?.Name; - var job = new JobEntity - { - JobId = Guid.NewGuid(), - ClientId = device.ClientId, - ScriptId = script.Id, - ScriptName = script.Name, - State = JobState.Queued, - CreatedUtc = DateTimeOffset.UtcNow, - RequestedBy = actor, - }; - db.Jobs.Add(job); - await db.SaveChangesAsync(cancellationToken); - - // Compose the prelude from attached function modules so the main script - // stays small; parameters/arguments drive typed variable injection. - var parameters = Backend.Scripts.ScriptEndpoints.DeserializeParameters(script.ParametersJson); - var moduleIds = Backend.Scripts.ScriptEndpoints.DeserializeModuleIds(script.FunctionModuleIdsJson); - var prelude = await ComposePreludeAsync(db, moduleIds, cancellationToken); - - var dispatched = await dispatcher.DispatchScriptAsync( - device.ClientId, - new ScriptCommandPayload( - job.JobId, script.Id, script.Name, script.Content, - ProtocolDefaults.DefaultScriptTimeoutSeconds, - Prelude: prelude, - Parameters: parameters.Count > 0 ? parameters : null, - Arguments: request.Arguments), - cancellationToken); - - if (dispatched) - { - job.State = JobState.Dispatched; - await db.SaveChangesAsync(cancellationToken); - } + var job = await runner.CreateJobAsync(script, device.ClientId, actor, cancellationToken); + await runner.DispatchAsync( + prepared, job, request.Arguments, + $"Job “{script.Name}” queued for {device.Hostname}", cancellationToken); await audit.LogAsync(AuditCategories.Jobs, "created", actor, clientId: device.ClientId, detail: $"script={script.Name} job={job.JobId}", cancellationToken: cancellationToken); - await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( - "job-created", - $"Job “{script.Name}” queued for {device.Hostname}", - device.ClientId, - job.JobId, - DateTimeOffset.UtcNow), cancellationToken); - return Results.Created(ApiRoutes.For.Job(job.JobId), ToDto(job, device.Hostname)); } - private static async Task ComposePreludeAsync( - AppDbContext db, IReadOnlyList moduleIds, CancellationToken cancellationToken) + /// One job per non-orphaned member; devices currently offline still + /// get one because dispatch is durable (JetStream holds it until they return). + private static async Task RunOnGroupAsync( + Guid groupId, + PreparedScript prepared, + CreateJobRequest request, + AppDbContext db, + JobRunner runner, + Backend.Groups.DeviceGroupService groups, + AuditService audit, + string? actor, + CancellationToken cancellationToken) { - if (moduleIds.Count == 0) + var group = await db.DeviceGroups.AsNoTracking() + .SingleOrDefaultAsync(g => g.Id == groupId, cancellationToken); + if (group is null) { - return null; + return Results.NotFound(new { error = "Group not found." }); } - var modules = await db.FunctionModules.AsNoTracking() - .Where(m => moduleIds.Contains(m.Id)) + var memberIds = await groups.GetMembersAsync(group, cancellationToken); + var devices = await db.Devices.AsNoTracking() + .Where(d => memberIds.Contains(d.ClientId)) .ToListAsync(cancellationToken); - // Preserve the author's declared order. - var ordered = moduleIds - .Select(id => modules.FirstOrDefault(m => m.Id == id)) - .Where(m => m is not null) - .Select(m => $"# --- function module: {m!.Name} ---\n{m.Content}") - .ToList(); + var jobs = new List(); + var skipped = new List(); - return ordered.Count > 0 ? string.Join("\n\n", ordered) : null; + foreach (var device in devices) + { + if (device.IsOrphaned) + { + skipped.Add(device.Hostname); + continue; + } + + var job = await runner.CreateJobAsync(prepared.Script, device.ClientId, actor, cancellationToken); + await runner.DispatchAsync( + prepared, job, request.Arguments, + $"Job “{prepared.Script.Name}” queued for {device.Hostname} (group “{group.Name}”)", + cancellationToken); + jobs.Add(ToDto(job, device.Hostname)); + } + + await audit.LogAsync(AuditCategories.Jobs, "group-run", actor, + detail: $"script={prepared.Script.Name} group={group.Name} jobs={jobs.Count} skipped={skipped.Count}", + cancellationToken: cancellationToken); + + return Results.Ok(new GroupRunDto(jobs, skipped)); } private static JobDto ToDto(JobEntity job, string? hostname) => new( diff --git a/src/Backend/Jobs/JobRunner.cs b/src/Backend/Jobs/JobRunner.cs new file mode 100644 index 0000000..d1d8eb7 --- /dev/null +++ b/src/Backend/Jobs/JobRunner.cs @@ -0,0 +1,133 @@ +using System.Text.Json; +using Backend.Data; +using Backend.Messaging; +using Backend.Secrets; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Infrastructure.Constants; + +namespace Backend.Jobs; + +/// +/// A script made ready to dispatch: function-module prelude composed, typed +/// parameters deserialized and secret bindings resolved (once — a group +/// fan-out reuses the same values for every member). +/// +public sealed record PreparedScript( + ScriptEntity Script, + string? Prelude, + IReadOnlyList? Parameters, + IReadOnlyList? Secrets); + +/// +/// The one path from "run this script on this device" to a dispatched job. +/// Manual runs, group fan-outs, lifecycle triggers and schedules all go +/// through here so they share prelude composition, server-side secret +/// resolution, durable dispatch and activity broadcasting. +/// +public sealed class JobRunner( + AppDbContext db, + CommandDispatcher dispatcher, + BrowserEventBroadcaster broadcaster, + SecretsProviderService secretsService) +{ + /// Composes the prelude and resolves secrets. Throws . + public async Task PrepareAsync(ScriptEntity script, CancellationToken cancellationToken) + { + var parameters = Backend.Scripts.ScriptEndpoints.DeserializeParameters(script.ParametersJson); + var moduleIds = Backend.Scripts.ScriptEndpoints.DeserializeModuleIds(script.FunctionModuleIdsJson); + var prelude = await ComposePreludeAsync(moduleIds, cancellationToken); + + IReadOnlyList? secrets = null; + var bindings = Backend.Scripts.ScriptEndpoints.DeserializeSecretBindings(script.SecretBindingsJson); + if (bindings.Count > 0) + { + secrets = await secretsService.ResolveAsync(bindings, cancellationToken); + } + + return new PreparedScript(script, prelude, parameters.Count > 0 ? parameters : null, secrets); + } + + public async Task CreateJobAsync( + ScriptEntity script, string clientId, string? requestedBy, CancellationToken cancellationToken) + { + var job = new JobEntity + { + JobId = Guid.NewGuid(), + ClientId = clientId, + ScriptId = script.Id, + ScriptName = script.Name, + State = JobState.Queued, + CreatedUtc = DateTimeOffset.UtcNow, + RequestedBy = requestedBy, + }; + db.Jobs.Add(job); + await db.SaveChangesAsync(cancellationToken); + return job; + } + + /// Publishes the durable command and broadcasts the activity item. + public async Task DispatchAsync( + PreparedScript prepared, + JobEntity job, + IReadOnlyDictionary? arguments, + string activityText, + CancellationToken cancellationToken) + { + var script = prepared.Script; + var dispatched = await dispatcher.DispatchScriptAsync( + job.ClientId, + new ScriptCommandPayload( + job.JobId, script.Id, script.Name, script.Content, + ProtocolDefaults.DefaultScriptTimeoutSeconds, + Prelude: prepared.Prelude, + Parameters: prepared.Parameters, + Arguments: arguments, + SecretsVariableName: script.SecretsVariableName, + Secrets: prepared.Secrets), + cancellationToken); + + if (dispatched) + { + job.State = JobState.Dispatched; + await db.SaveChangesAsync(cancellationToken); + } + + await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( + "job-created", activityText, job.ClientId, job.JobId, DateTimeOffset.UtcNow), cancellationToken); + + return dispatched; + } + + /// Terminal failure before dispatch (e.g. the vault was unreachable). + public async Task MarkFailedAsync(JobEntity job, string message, CancellationToken cancellationToken) + { + job.State = JobState.Failed; + job.CompletedUtc = DateTimeOffset.UtcNow; + job.OutputSummary = message; + await db.SaveChangesAsync(cancellationToken); + } + + private async Task ComposePreludeAsync( + IReadOnlyList moduleIds, CancellationToken cancellationToken) + { + if (moduleIds.Count == 0) + { + return null; + } + + var modules = await db.FunctionModules.AsNoTracking() + .Where(m => moduleIds.Contains(m.Id)) + .ToListAsync(cancellationToken); + + // Preserve the author's declared order. + var ordered = moduleIds + .Select(id => modules.FirstOrDefault(m => m.Id == id)) + .Where(m => m is not null) + .Select(m => $"# --- function module: {m!.Name} ---\n{m.Content}") + .ToList(); + + return ordered.Count > 0 ? string.Join("\n\n", ordered) : null; + } +} diff --git a/src/Backend/Jobs/ScheduleCron.cs b/src/Backend/Jobs/ScheduleCron.cs new file mode 100644 index 0000000..0533c1b --- /dev/null +++ b/src/Backend/Jobs/ScheduleCron.cs @@ -0,0 +1,70 @@ +using Cronos; + +namespace Backend.Jobs; + +/// +/// Cron evaluation for schedules: standard 5-field expressions, evaluated in +/// the schedule's time zone (so "daily at 01:00" tracks DST there), with all +/// stored/compared instants in UTC. +/// +public static class ScheduleCron +{ + /// Parses and validates; returns an error message or null when valid. + public static string? Validate(string cronExpression, string timeZoneId) + { + try + { + CronExpression.Parse(cronExpression); + } + catch (CronFormatException ex) + { + return $"Invalid cron expression: {ex.Message}"; + } + + try + { + TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); + } + catch (TimeZoneNotFoundException) + { + return $"Unknown time zone “{timeZoneId}”."; + } + catch (InvalidTimeZoneException) + { + return $"Invalid time zone “{timeZoneId}”."; + } + + return null; + } + + public static DateTimeOffset? NextOccurrence( + string cronExpression, string timeZoneId, DateTimeOffset after) + { + var expression = CronExpression.Parse(cronExpression); + var timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); + return expression.GetNextOccurrence(after, timeZone); + } + + public static IReadOnlyList NextOccurrences( + string cronExpression, string timeZoneId, DateTimeOffset after, int count) + { + var expression = CronExpression.Parse(cronExpression); + var timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); + + var result = new List(count); + var cursor = after; + for (var i = 0; i < count; i++) + { + var next = expression.GetNextOccurrence(cursor, timeZone); + if (next is null) + { + break; + } + + result.Add(next.Value); + cursor = next.Value; + } + + return result; + } +} diff --git a/src/Backend/Jobs/ScheduleEndpoints.cs b/src/Backend/Jobs/ScheduleEndpoints.cs new file mode 100644 index 0000000..bc1ec87 --- /dev/null +++ b/src/Backend/Jobs/ScheduleEndpoints.cs @@ -0,0 +1,400 @@ +using Backend.Auth; +using Backend.Data; +using Backend.Security; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Contracts.Serialization; + +namespace Backend.Jobs; + +/// +/// Schedules are reusable cadence objects; scripts honor them through +/// assignments (script + target + stored run values). The worker fires every +/// enabled assignment when its schedule comes due. +/// +public static class ScheduleEndpoints +{ + public static void Map(WebApplication app) + { + app.MapGet(ApiRoutes.Schedules, ListAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapPost(ApiRoutes.Schedules, CreateAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapPut(ApiRoutes.Schedule, UpdateAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapDelete(ApiRoutes.Schedule, DeleteAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapPost(ApiRoutes.SchedulePreview, Preview).RequireAuthorization(AuthConstants.PolicyOperator); + + app.MapGet(ApiRoutes.ScheduleAssignments, ListAssignmentsAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapPost(ApiRoutes.ScheduleAssignments, CreateAssignmentAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapPut(ApiRoutes.ScheduleAssignment, UpdateAssignmentAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapDelete(ApiRoutes.ScheduleAssignment, DeleteAssignmentAsync).RequireAuthorization(AuthConstants.PolicyOperator); + } + + // ── Schedule objects ───────────────────────────────────────────────── + + private static async Task ListAsync(AppDbContext db, CancellationToken cancellationToken) + { + var schedules = await db.Schedules.AsNoTracking() + .OrderBy(s => s.NextRunUtc == null).ThenBy(s => s.NextRunUtc) + .ToListAsync(cancellationToken); + var assignments = await LoadAssignmentDtosAsync(db, null, null, cancellationToken); + + return Results.Ok(schedules.Select(s => ToDto( + s, assignments.Where(a => a.ScheduleId == s.Id).ToList())).ToList()); + } + + private static async Task CreateAsync( + SaveScheduleRequest request, + AppDbContext db, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + var (error, next) = Validate(request); + if (error is not null) + { + return Results.BadRequest(new { error }); + } + + if (await db.Schedules.AnyAsync(s => s.Name == request.Name.Trim(), cancellationToken)) + { + return Results.BadRequest(new { error = "A schedule with that name already exists." }); + } + + var actor = context.User.Identity?.Name; + var schedule = new ScheduleEntity + { + Id = Guid.NewGuid(), + Name = request.Name.Trim(), + CreatedUtc = DateTimeOffset.UtcNow, + CreatedBy = actor, + }; + Apply(schedule, request, next, actor); + db.Schedules.Add(schedule); + await db.SaveChangesAsync(cancellationToken); + + await audit.LogAsync(AuditCategories.Jobs, "schedule-created", actor, + detail: $"schedule={schedule.Name} next={schedule.NextRunUtc:O}", cancellationToken: cancellationToken); + + return Results.Created(ApiRoutes.For.Schedule(schedule.Id), ToDto(schedule, [])); + } + + private static async Task UpdateAsync( + Guid id, + SaveScheduleRequest request, + AppDbContext db, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + var schedule = await db.Schedules.SingleOrDefaultAsync(s => s.Id == id, cancellationToken); + if (schedule is null) + { + return Results.NotFound(); + } + + var (error, next) = Validate(request); + if (error is not null) + { + return Results.BadRequest(new { error }); + } + + if (await db.Schedules.AnyAsync( + s => s.Id != id && s.Name == request.Name.Trim(), cancellationToken)) + { + return Results.BadRequest(new { error = "A schedule with that name already exists." }); + } + + var actor = context.User.Identity?.Name; + schedule.Name = request.Name.Trim(); + Apply(schedule, request, next, actor); + await db.SaveChangesAsync(cancellationToken); + + await audit.LogAsync(AuditCategories.Jobs, "schedule-updated", actor, + detail: $"schedule={schedule.Name} enabled={schedule.Enabled}", cancellationToken: cancellationToken); + + var assignments = await LoadAssignmentDtosAsync(db, null, schedule.Id, cancellationToken); + return Results.Ok(ToDto(schedule, assignments)); + } + + private static async Task DeleteAsync( + Guid id, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) + { + var schedule = await db.Schedules.SingleOrDefaultAsync(s => s.Id == id, cancellationToken); + if (schedule is null) + { + return Results.NotFound(); + } + + // Assignments cascade with the schedule. + db.Schedules.Remove(schedule); + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Jobs, "schedule-deleted", context.User.Identity?.Name, + detail: schedule.Name, cancellationToken: cancellationToken); + return Results.NoContent(); + } + + /// Validates a cron and returns its next occurrences — the UI's ground truth. + private static IResult Preview(SchedulePreviewRequest request) + { + var timeZoneId = string.IsNullOrWhiteSpace(request.TimeZoneId) ? "UTC" : request.TimeZoneId; + var error = ScheduleCron.Validate(request.CronExpression, timeZoneId); + if (error is not null) + { + return Results.Ok(new SchedulePreviewDto(false, error, [])); + } + + var next = ScheduleCron.NextOccurrences( + request.CronExpression, timeZoneId, DateTimeOffset.UtcNow, count: 5); + return Results.Ok(new SchedulePreviewDto(true, null, next)); + } + + // ── Assignments ────────────────────────────────────────────────────── + + private static async Task ListAssignmentsAsync( + AppDbContext db, Guid? scriptId, Guid? scheduleId, CancellationToken cancellationToken) + => Results.Ok(await LoadAssignmentDtosAsync(db, scriptId, scheduleId, cancellationToken)); + + private static async Task CreateAssignmentAsync( + SaveScheduleAssignmentRequest request, + AppDbContext db, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + if (await ValidateAssignmentAsync(request, db, cancellationToken) is { } error) + { + return Results.BadRequest(new { error }); + } + + var actor = context.User.Identity?.Name; + var assignment = new ScriptScheduleEntity + { + Id = Guid.NewGuid(), + ScheduleId = request.ScheduleId, + ScriptId = request.ScriptId, + ClientId = request.ClientId, + GroupId = request.GroupId, + ArgumentsJson = request.Arguments is { Count: > 0 } ? JsonDefaults.Serialize(request.Arguments) : null, + Enabled = request.Enabled, + CreatedUtc = DateTimeOffset.UtcNow, + CreatedBy = actor, + }; + db.ScriptSchedules.Add(assignment); + await db.SaveChangesAsync(cancellationToken); + + await audit.LogAsync(AuditCategories.Jobs, "schedule-attached", actor, + detail: $"schedule={request.ScheduleId} script={request.ScriptId}", cancellationToken: cancellationToken); + + var dtos = await LoadAssignmentDtosAsync(db, null, null, cancellationToken); + return Results.Created( + ApiRoutes.For.ScheduleAssignment(assignment.Id), + dtos.Single(a => a.Id == assignment.Id)); + } + + private static async Task UpdateAssignmentAsync( + Guid id, + SaveScheduleAssignmentRequest request, + AppDbContext db, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + var assignment = await db.ScriptSchedules.SingleOrDefaultAsync(a => a.Id == id, cancellationToken); + if (assignment is null) + { + return Results.NotFound(); + } + + if (await ValidateAssignmentAsync(request, db, cancellationToken) is { } error) + { + return Results.BadRequest(new { error }); + } + + assignment.ScheduleId = request.ScheduleId; + assignment.ScriptId = request.ScriptId; + assignment.ClientId = request.ClientId; + assignment.GroupId = request.GroupId; + assignment.Enabled = request.Enabled; + // Null keeps stored values so enable/disable round-trips. + if (request.Arguments is { Count: > 0 }) + { + assignment.ArgumentsJson = JsonDefaults.Serialize(request.Arguments); + } + + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Jobs, "schedule-assignment-updated", context.User.Identity?.Name, + detail: $"assignment={id} enabled={assignment.Enabled}", cancellationToken: cancellationToken); + + var dtos = await LoadAssignmentDtosAsync(db, null, null, cancellationToken); + return Results.Ok(dtos.Single(a => a.Id == id)); + } + + private static async Task DeleteAssignmentAsync( + Guid id, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) + { + var assignment = await db.ScriptSchedules.SingleOrDefaultAsync(a => a.Id == id, cancellationToken); + if (assignment is null) + { + return Results.NotFound(); + } + + db.ScriptSchedules.Remove(assignment); + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Jobs, "schedule-detached", context.User.Identity?.Name, + detail: $"assignment={id}", cancellationToken: cancellationToken); + return Results.NoContent(); + } + + // ── Helpers ────────────────────────────────────────────────────────── + + private static (string? Error, DateTimeOffset? NextRunUtc) Validate(SaveScheduleRequest request) + { + if (string.IsNullOrWhiteSpace(request.Name)) + { + return ("Schedule name is required.", null); + } + + var hasCron = !string.IsNullOrWhiteSpace(request.CronExpression); + if (hasCron == (request.RunOnceUtc is not null)) + { + return ("Provide exactly one of cronExpression (recurring) or runOnceUtc (one-shot).", null); + } + + var timeZoneId = string.IsNullOrWhiteSpace(request.TimeZoneId) ? "UTC" : request.TimeZoneId; + + if (hasCron) + { + var error = ScheduleCron.Validate(request.CronExpression!, timeZoneId); + if (error is not null) + { + return (error, null); + } + + var next = ScheduleCron.NextOccurrence(request.CronExpression!, timeZoneId, DateTimeOffset.UtcNow); + return next is null ? ("The cron expression never fires.", null) : (null, next); + } + + return request.RunOnceUtc <= DateTimeOffset.UtcNow.AddMinutes(-1) + ? ("The one-shot time is in the past.", null) + : (null, request.RunOnceUtc); + } + + private static void Apply( + ScheduleEntity schedule, SaveScheduleRequest request, DateTimeOffset? next, string? actor) + { + schedule.CronExpression = string.IsNullOrWhiteSpace(request.CronExpression) + ? null + : request.CronExpression.Trim(); + schedule.RunOnceUtc = request.RunOnceUtc; + schedule.TimeZoneId = string.IsNullOrWhiteSpace(request.TimeZoneId) ? "UTC" : request.TimeZoneId; + schedule.Enabled = request.Enabled; + schedule.NextRunUtc = request.Enabled ? next : null; + schedule.UpdatedUtc = DateTimeOffset.UtcNow; + schedule.UpdatedBy = actor; + } + + private static async Task ValidateAssignmentAsync( + SaveScheduleAssignmentRequest request, AppDbContext db, CancellationToken cancellationToken) + { + if ((request.ClientId is null) == (request.GroupId is null)) + { + return "Target exactly one of clientId or groupId."; + } + + if (!await db.Schedules.AnyAsync(s => s.Id == request.ScheduleId, cancellationToken)) + { + return "Schedule not found."; + } + + if (!await db.Scripts.AnyAsync(s => s.Id == request.ScriptId, cancellationToken)) + { + return "Script not found."; + } + + if (request.ClientId is { } clientId + && !await db.Devices.AnyAsync(d => d.ClientId == clientId, cancellationToken)) + { + return "Device not found."; + } + + if (request.GroupId is { } groupId + && !await db.DeviceGroups.AnyAsync(g => g.Id == groupId, cancellationToken)) + { + return "Group not found."; + } + + return null; + } + + private static async Task> LoadAssignmentDtosAsync( + AppDbContext db, Guid? scriptId, Guid? scheduleId, CancellationToken cancellationToken) + { + var query = db.ScriptSchedules.AsNoTracking().AsQueryable(); + if (scriptId is { } sid) + { + query = query.Where(a => a.ScriptId == sid); + } + + if (scheduleId is { } schedId) + { + query = query.Where(a => a.ScheduleId == schedId); + } + + var assignments = await query.OrderBy(a => a.CreatedUtc).ToListAsync(cancellationToken); + + var scheduleIds = assignments.Select(a => a.ScheduleId).Distinct().ToList(); + var schedules = await db.Schedules.AsNoTracking() + .Where(s => scheduleIds.Contains(s.Id)) + .ToDictionaryAsync(s => s.Id, cancellationToken); + + var scriptIds = assignments.Select(a => a.ScriptId).Distinct().ToList(); + var scriptNames = await db.Scripts.AsNoTracking() + .Where(s => scriptIds.Contains(s.Id)) + .ToDictionaryAsync(s => s.Id, s => s.Name, cancellationToken); + + var clientIds = assignments.Where(a => a.ClientId != null).Select(a => a.ClientId!).Distinct().ToList(); + var hostnames = await db.Devices.AsNoTracking() + .Where(d => clientIds.Contains(d.ClientId)) + .ToDictionaryAsync(d => d.ClientId, d => d.Hostname, cancellationToken); + + var groupIds = assignments.Where(a => a.GroupId != null).Select(a => a.GroupId!.Value).Distinct().ToList(); + var groupNames = await db.DeviceGroups.AsNoTracking() + .Where(g => groupIds.Contains(g.Id)) + .ToDictionaryAsync(g => g.Id, g => g.Name, cancellationToken); + + return assignments.Select(a => + { + var schedule = schedules.GetValueOrDefault(a.ScheduleId); + return new ScheduleAssignmentDto( + a.Id, + a.ScheduleId, + schedule?.Name, + schedule?.CronExpression, + schedule?.RunOnceUtc, + schedule?.TimeZoneId ?? "UTC", + schedule?.Enabled ?? false, + schedule?.NextRunUtc, + a.ScriptId, + scriptNames.GetValueOrDefault(a.ScriptId), + a.ClientId, + a.ClientId is null ? null : hostnames.GetValueOrDefault(a.ClientId), + a.GroupId, + a.GroupId is null ? null : groupNames.GetValueOrDefault(a.GroupId.Value), + a.Enabled, + a.LastRunUtc, + a.LastResult); + }).ToList(); + } + + internal static ScheduleDto ToDto(ScheduleEntity s, IReadOnlyList assignments) => new( + s.Id, + s.Name, + s.CronExpression, + s.RunOnceUtc, + s.TimeZoneId, + s.Enabled, + s.NextRunUtc, + s.LastRunUtc, + s.UpdatedUtc, + s.UpdatedBy, + assignments); +} diff --git a/src/Backend/Jobs/ScheduleWorker.cs b/src/Backend/Jobs/ScheduleWorker.cs new file mode 100644 index 0000000..139534a --- /dev/null +++ b/src/Backend/Jobs/ScheduleWorker.cs @@ -0,0 +1,226 @@ +using System.Text.Json; +using Backend.Data; +using Backend.Groups; +using Backend.Secrets; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Serialization; + +namespace Backend.Jobs; + +/// +/// Fires due schedules: every enabled assignment (script + target + stored run +/// values) honoring the schedule runs through the normal job pipeline. +/// Recurrence advances from "now" after each firing, so downtime never causes +/// a storm of catch-up runs — at most one late firing per schedule. +/// +public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger logger) + : BackgroundService +{ + private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(30); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + await FireDueSchedulesAsync(stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (Exception ex) + { + logger.LogError(ex, "Schedule sweep failed"); + } + + try + { + await Task.Delay(PollInterval, stoppingToken); + } + catch (OperationCanceledException) + { + return; + } + } + } + + internal async Task FireDueSchedulesAsync(CancellationToken cancellationToken) + { + using var scope = scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var runner = scope.ServiceProvider.GetRequiredService(); + var groups = scope.ServiceProvider.GetRequiredService(); + + var now = DateTimeOffset.UtcNow; + var due = await db.Schedules + .Where(s => s.Enabled && s.NextRunUtc != null && s.NextRunUtc <= now) + .ToListAsync(cancellationToken); + + foreach (var schedule in due) + { + try + { + await FireAsync(schedule, db, runner, groups, cancellationToken); + } + catch (Exception ex) + { + logger.LogError(ex, "Schedule {ScheduleId} ({Name}) failed to fire", schedule.Id, schedule.Name); + } + + Advance(schedule); + await db.SaveChangesAsync(cancellationToken); + } + } + + private async Task FireAsync( + ScheduleEntity schedule, + AppDbContext db, + JobRunner runner, + DeviceGroupService groups, + CancellationToken cancellationToken) + { + var assignments = await db.ScriptSchedules + .Where(a => a.ScheduleId == schedule.Id && a.Enabled) + .ToListAsync(cancellationToken); + if (assignments.Count == 0) + { + return; + } + + // One preparation (prelude + secrets) per script per firing, shared by + // every assignment and target using it. + var prepared = new Dictionary(); + + foreach (var assignment in assignments) + { + try + { + await FireAssignmentAsync(schedule, assignment, prepared, db, runner, groups, cancellationToken); + } + catch (Exception ex) + { + assignment.LastRunUtc = DateTimeOffset.UtcNow; + assignment.LastResult = ex.Message; + logger.LogError(ex, + "Schedule {Name}: assignment {AssignmentId} failed", schedule.Name, assignment.Id); + } + } + } + + private async Task FireAssignmentAsync( + ScheduleEntity schedule, + ScriptScheduleEntity assignment, + Dictionary prepared, + AppDbContext db, + JobRunner runner, + DeviceGroupService groups, + CancellationToken cancellationToken) + { + assignment.LastRunUtc = DateTimeOffset.UtcNow; + + var script = await db.Scripts.AsNoTracking() + .SingleOrDefaultAsync(s => s.Id == assignment.ScriptId, cancellationToken); + if (script is null) + { + assignment.Enabled = false; + assignment.LastResult = "Disabled: the script no longer exists."; + return; + } + + var devices = await ResolveTargetsAsync(assignment, db, groups, cancellationToken); + if (devices.Count == 0) + { + assignment.LastResult = "No eligible devices at fire time."; + return; + } + + if (!prepared.TryGetValue(script.Id, out var preparedScript)) + { + try + { + preparedScript = await runner.PrepareAsync(script, cancellationToken); + prepared[script.Id] = preparedScript; + } + catch (SecretResolutionException ex) + { + assignment.LastResult = ex.Message; + logger.LogWarning("Schedule {Name}: {Message}", schedule.Name, ex.Message); + return; + } + } + + var arguments = string.IsNullOrWhiteSpace(assignment.ArgumentsJson) + ? null + : JsonDefaults.Deserialize>(assignment.ArgumentsJson); + + var queued = 0; + foreach (var device in devices) + { + var job = await runner.CreateJobAsync( + script, device.ClientId, $"schedule:{schedule.Name}", cancellationToken); + await runner.DispatchAsync( + prepared[script.Id], job, arguments, + $"Schedule “{schedule.Name}” queued “{script.Name}” for {device.Hostname}", + cancellationToken); + queued++; + } + + assignment.LastResult = $"{queued} job(s) queued"; + logger.LogInformation( + "Schedule {Name} queued {Count} job(s) of “{Script}”", schedule.Name, queued, script.Name); + } + + private static async Task> ResolveTargetsAsync( + ScriptScheduleEntity assignment, + AppDbContext db, + DeviceGroupService groups, + CancellationToken cancellationToken) + { + if (assignment.ClientId is { } clientId) + { + var device = await db.Devices.AsNoTracking() + .SingleOrDefaultAsync(d => d.ClientId == clientId && !d.IsOrphaned, cancellationToken); + return device is null ? [] : [device]; + } + + var group = await db.DeviceGroups.AsNoTracking() + .SingleOrDefaultAsync(g => g.Id == assignment.GroupId, cancellationToken); + if (group is null) + { + return []; + } + + var memberIds = await groups.GetMembersAsync(group, cancellationToken); + return await db.Devices.AsNoTracking() + .Where(d => memberIds.Contains(d.ClientId) && !d.IsOrphaned) + .ToListAsync(cancellationToken); + } + + private static void Advance(ScheduleEntity schedule) + { + schedule.LastRunUtc = DateTimeOffset.UtcNow; + + if (schedule.CronExpression is { } cron) + { + try + { + schedule.NextRunUtc = ScheduleCron.NextOccurrence( + cron, schedule.TimeZoneId, DateTimeOffset.UtcNow); + } + catch (Exception) + { + // Stored expression went bad (should be impossible past validation). + schedule.Enabled = false; + schedule.NextRunUtc = null; + } + } + else + { + // One-shot: done. + schedule.Enabled = false; + schedule.NextRunUtc = null; + } + } +} diff --git a/src/Backend/Program.cs b/src/Backend/Program.cs index 967bb97..f3d082b 100644 --- a/src/Backend/Program.cs +++ b/src/Backend/Program.cs @@ -11,7 +11,9 @@ using Backend.Nats; using Backend.Proxy; using Backend.Scripts; using Backend.Security; +using Backend.Settings; using Backend.Shell; +using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; using Serilog; @@ -26,6 +28,13 @@ if (args.Length > 0 && args[0] == "nats-auth") return NatsAuthCli.Run(args[1..]); } +// CLI mode: lockout recovery — disable OIDC and restore local sign-in. +if (args.Length > 0 && args[0] == "auth-reset") +{ + var cliConfig = new ConfigurationBuilder().AddEnvironmentVariables().Build(); + return await AuthResetCli.RunAsync(args[1..], cliConfig); +} + var builder = WebApplication.CreateBuilder(args); // ── Logging ────────────────────────────────────────────────────────────── @@ -62,10 +71,11 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); // ── Authentication / authorization ───────────────────────────────────────── -var oidcOptions = OidcOptions.FromConfiguration(builder.Configuration); -builder.Services.AddSingleton(oidcOptions); +// Environment values bootstrap authentication; the Settings UI overrides them +// and the OIDC handler is rebuilt on save without a restart. +var authBootstrap = AuthBootstrap.FromConfiguration(builder.Configuration); builder.Services.AddScoped(); -builder.AddControlPlaneAuth(oidcOptions); +builder.AddControlPlaneAuth(authBootstrap); // ── Messaging ──────────────────────────────────────────────────────────── builder.Services.AddSingleton(); @@ -74,10 +84,26 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddScoped(); +// S3: environment values are the bootstrap defaults; anything saved from the +// Settings UI overrides them, so these are resolved per-request. builder.Services.AddSingleton(S3Options.FromConfiguration(builder.Configuration)); -builder.Services.AddSingleton(); +builder.Services.AddDataProtection().PersistKeysToFileSystem( + new DirectoryInfo(builder.Configuration["DATAPROTECTION_PATH"] is { Length: > 0 } dp + ? dp + : Path.Combine(Path.GetDirectoryName(Path.GetFullPath( + builder.Configuration["DATABASE_PATH"] ?? "data/app.db")) ?? "data", "keys"))); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +// Secrets providers: pluggable drivers; add implementations here. +builder.Services.AddHttpClient(); +builder.Services.AddSingleton(); +builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); +builder.Services.AddHostedService(); builder.Services.AddHostedService(sp => sp.GetRequiredService()); // ── Rate limiting ──────────────────────────────────────────────────────── @@ -237,19 +263,23 @@ app.MapGet(ApiRoutes.Ready, async (AppDbContext db, NatsHub hub, NatsCredentialI return ready ? Results.Ok(payload) : Results.Json(payload, statusCode: StatusCodes.Status503ServiceUnavailable); }); -AuthEndpoints.Map(app, oidcOptions); +AuthEndpoints.Map(app); +AuthSettingsEndpoints.Map(app); EnrollmentEndpoints.Map(app); InstallEndpoints.Map(app); DeviceEndpoints.Map(app); ScriptEndpoints.Map(app); FunctionEndpoints.Map(app); JobEndpoints.Map(app); +ScheduleEndpoints.Map(app); BootstrapTokenEndpoints.Map(app); MessagingEndpoints.Map(app); ShellEndpoints.Map(app); FileDeliveryEndpoints.Map(app); GroupEndpoints.Map(app); TriggerEndpoints.Map(app); +SettingsEndpoints.Map(app); +Backend.Secrets.SecretsEndpoints.Map(app); app.Run(); return 0; diff --git a/src/Backend/Proxy/PublicUrl.cs b/src/Backend/Proxy/PublicUrl.cs new file mode 100644 index 0000000..76853f8 --- /dev/null +++ b/src/Backend/Proxy/PublicUrl.cs @@ -0,0 +1,21 @@ +namespace Backend.Proxy; + +/// +/// The externally reachable base URL: PUBLIC_SERVER_URL when set, +/// otherwise derived from the request after the forwarded-headers middleware +/// applied scheme/host from trusted proxies. Used everywhere a URL is shown +/// to an operator or baked into an install command. +/// +public static class PublicUrl +{ + public static string Resolve(HttpContext context, IConfiguration configuration) + { + var configured = configuration["PUBLIC_SERVER_URL"]; + return !string.IsNullOrWhiteSpace(configured) + ? configured.TrimEnd('/') + : $"{context.Request.Scheme}://{context.Request.Host}"; + } + + public static bool IsConfigured(IConfiguration configuration) + => !string.IsNullOrWhiteSpace(configuration["PUBLIC_SERVER_URL"]); +} diff --git a/src/Backend/Scripts/ScriptEndpoints.cs b/src/Backend/Scripts/ScriptEndpoints.cs index ca04f43..1c29b8a 100644 --- a/src/Backend/Scripts/ScriptEndpoints.cs +++ b/src/Backend/Scripts/ScriptEndpoints.cs @@ -43,6 +43,11 @@ public static class ScriptEndpoints return Results.BadRequest(new { error = "Script name is required." }); } + if (ValidateSecrets(request) is { } secretsProblem) + { + return secretsProblem; + } + var now = DateTimeOffset.UtcNow; var actor = context.User.Identity?.Name; var script = new ScriptEntity @@ -54,6 +59,8 @@ public static class ScriptEndpoints Content = request.Content ?? string.Empty, ParametersJson = SerializeParameters(request.Parameters), FunctionModuleIdsJson = SerializeModuleIds(request.FunctionModuleIds), + SecretBindingsJson = SerializeSecretBindings(request.SecretBindings), + SecretsVariableName = NormalizeVariableName(request.SecretsVariableName), CreatedUtc = now, UpdatedUtc = now, CreatedBy = actor, @@ -80,11 +87,18 @@ public static class ScriptEndpoints return Results.BadRequest(new { error = "Script name is required." }); } + if (ValidateSecrets(request) is { } secretsProblem) + { + return secretsProblem; + } + script.Name = request.Name.Trim(); script.Description = request.Description; script.Content = request.Content ?? string.Empty; script.ParametersJson = SerializeParameters(request.Parameters); script.FunctionModuleIdsJson = SerializeModuleIds(request.FunctionModuleIds); + script.SecretBindingsJson = SerializeSecretBindings(request.SecretBindings); + script.SecretsVariableName = NormalizeVariableName(request.SecretsVariableName); script.UpdatedUtc = DateTimeOffset.UtcNow; script.UpdatedBy = context.User.Identity?.Name; await db.SaveChangesAsync(cancellationToken); @@ -114,15 +128,63 @@ public static class ScriptEndpoints script.Id, script.Name, script.Description, script.Language, script.Content, DeserializeParameters(script.ParametersJson), DeserializeModuleIds(script.FunctionModuleIdsJson), - script.CreatedUtc, script.UpdatedUtc, script.CreatedBy, script.UpdatedBy); + script.CreatedUtc, script.UpdatedUtc, script.CreatedBy, script.UpdatedBy, + DeserializeSecretBindings(script.SecretBindingsJson), + script.SecretsVariableName); + + /// The injected dictionary must bind to a legal PowerShell variable name. + private static IResult? ValidateSecrets(SaveScriptRequest request) + { + var name = request.SecretsVariableName?.Trim(); + if (!string.IsNullOrEmpty(name) + && !System.Text.RegularExpressions.Regex.IsMatch(name, "^[A-Za-z_][A-Za-z0-9_]*$")) + { + return Results.BadRequest(new + { + error = "Secrets variable name must be a valid PowerShell variable name (letters, digits, underscore).", + }); + } + + if (request.SecretBindings?.Any(b => string.IsNullOrWhiteSpace(b.Name) || string.IsNullOrWhiteSpace(b.SecretName)) == true) + { + return Results.BadRequest(new { error = "Every secret binding needs a name and a secret to fetch." }); + } + + return null; + } + + internal static string? NormalizeVariableName(string? name) + => string.IsNullOrWhiteSpace(name) ? null : name.Trim(); internal static string? SerializeParameters(IReadOnlyList? parameters) => parameters is null || parameters.Count == 0 ? null : JsonDefaults.Serialize(parameters); internal static IReadOnlyList DeserializeParameters(string? json) + { + if (string.IsNullOrWhiteSpace(json)) + { + return []; + } + + try + { + return JsonDefaults.Deserialize>(json) ?? []; + } + catch (System.Text.Json.JsonException) + { + // Schema drift in stored definitions (e.g. removed enum values): + // degrade to "no parameters" instead of breaking every script read. + return []; + } + } + + internal static string? SerializeSecretBindings(IReadOnlyList? bindings) + => bindings is null || bindings.Count == 0 ? null : JsonDefaults.Serialize(bindings); + + internal static IReadOnlyList DeserializeSecretBindings(string? json) => string.IsNullOrWhiteSpace(json) ? [] - : JsonDefaults.Deserialize>(json) ?? []; + : JsonDefaults.Deserialize>(json) ?? []; internal static string? SerializeModuleIds(IReadOnlyList? ids) => ids is null || ids.Count == 0 ? null : JsonDefaults.Serialize(ids); diff --git a/src/Backend/Secrets/ISecretsProviderDriver.cs b/src/Backend/Secrets/ISecretsProviderDriver.cs new file mode 100644 index 0000000..3391dea --- /dev/null +++ b/src/Backend/Secrets/ISecretsProviderDriver.cs @@ -0,0 +1,45 @@ +using Shared.Contracts.Api; + +namespace Backend.Secrets; + +/// +/// One kind of external secrets store. Drivers are stateless singletons; the +/// per-provider connection settings arrive as the decrypted driver-specific +/// config JSON. Register additional implementations to add providers. +/// +public interface ISecretsProviderDriver +{ + /// Stable identifier stored on providers (e.g. "infisical"). + string Kind { get; } + + /// Display name for the UI. + string DisplayName { get; } + + /// + /// Config field names (camelCase) whose values are sensitive. They are + /// omitted from API responses, and empty values on save keep what is stored. + /// + IReadOnlyList SecretFields { get; } + + /// Non-secret config fields (camelCase) the UI should render, in order. + IReadOnlyList Fields { get; } + + /// Validates connectivity and credentials against the live store. + Task> TestAsync(string configJson, CancellationToken cancellationToken); + + /// Lists secret names (never values) for the script editor's picker. + Task> ListSecretNamesAsync(string configJson, string? path, CancellationToken cancellationToken); + + /// Lists child folder paths of for the path browser. + Task> ListFolderPathsAsync(string configJson, string? path, CancellationToken cancellationToken); + + /// Fetches one secret value. Callers must never log the result. + Task GetSecretAsync(string configJson, string secretName, string? path, CancellationToken cancellationToken); +} + +/// Describes one driver config field so the UI can render a generic form. +public sealed record ConfigField(string Name, string Label, bool Secret = false, string? Placeholder = null); + +/// A secret binding could not be resolved. Message is value-free. +public sealed class SecretResolutionException(string message, Exception? inner = null) + : Exception(message, inner); diff --git a/src/Backend/Secrets/InfisicalDriver.cs b/src/Backend/Secrets/InfisicalDriver.cs new file mode 100644 index 0000000..04da7c4 --- /dev/null +++ b/src/Backend/Secrets/InfisicalDriver.cs @@ -0,0 +1,250 @@ +using System.Net.Http.Json; +using System.Text.Json; +using Shared.Contracts.Api; +using Shared.Contracts.Serialization; + +namespace Backend.Secrets; + +/// +/// Infisical driver using Universal Auth (machine identity): logs in with +/// clientId/clientSecret for a short-lived access token, then reads secrets +/// through the v3 raw API scoped to project + environment + path. +/// +public sealed class InfisicalDriver(IHttpClientFactory httpClientFactory) : ISecretsProviderDriver +{ + public string Kind => "infisical"; + + public string DisplayName => "Infisical"; + + public IReadOnlyList SecretFields { get; } = ["clientSecret"]; + + public IReadOnlyList Fields { get; } = + [ + new("baseUrl", "Base URL", Placeholder: "https://app.infisical.com (or self-hosted URL)"), + new("clientId", "Machine identity client ID"), + new("clientSecret", "Machine identity client secret", Secret: true), + new("projectId", "Project ID"), + new("environment", "Environment slug", Placeholder: "prod"), + new("path", "Default secret path", Placeholder: "/"), + ]; + + private sealed record Config( + string? BaseUrl, + string? ClientId, + string? ClientSecret, + string? ProjectId, + string? Environment, + string? Path); + + public async Task> TestAsync(string configJson, CancellationToken cancellationToken) + { + var steps = new List(); + var config = Parse(configJson); + + var missing = MissingFields(config); + if (missing.Count > 0) + { + steps.Add(new S3TestStepDto("config", false, $"Missing: {string.Join(", ", missing)}")); + return steps; + } + + steps.Add(new S3TestStepDto("config", true, BaseUrl(config))); + + string token; + try + { + token = await LoginAsync(config, cancellationToken); + steps.Add(new S3TestStepDto("authenticate", true, "universal-auth login ok")); + } + catch (Exception ex) + { + steps.Add(new S3TestStepDto("authenticate", false, ex.Message)); + return steps; + } + + try + { + var names = await ListNamesAsync(config, token, config.Path, cancellationToken); + steps.Add(new S3TestStepDto( + "list secrets", true, + $"{names.Count} secret(s) at {config.Environment}:{NormalizePath(config.Path)}")); + } + catch (Exception ex) + { + steps.Add(new S3TestStepDto("list secrets", false, ex.Message)); + } + + return steps; + } + + public async Task> ListSecretNamesAsync( + string configJson, string? path, CancellationToken cancellationToken) + { + var config = Parse(configJson); + Require(config); + var token = await LoginAsync(config, cancellationToken); + return await ListNamesAsync(config, token, path ?? config.Path, cancellationToken); + } + + public async Task> ListFolderPathsAsync( + string configJson, string? path, CancellationToken cancellationToken) + { + var config = Parse(configJson); + Require(config); + var token = await LoginAsync(config, cancellationToken); + + using var http = CreateClient(config); + http.DefaultRequestHeaders.Authorization = new("Bearer", token); + + var basePath = NormalizePath(path ?? config.Path); + var url = "api/v1/folders" + + $"?workspaceId={Uri.EscapeDataString(config.ProjectId!)}" + + $"&environment={Uri.EscapeDataString(config.Environment!)}" + + $"&path={Uri.EscapeDataString(basePath)}"; + + using var response = await http.GetAsync(url, cancellationToken); + if (!response.IsSuccessStatusCode) + { + throw new SecretResolutionException( + $"Infisical folder listing failed with HTTP {(int)response.StatusCode}."); + } + + using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken)); + if (!document.RootElement.TryGetProperty("folders", out var folders) + || folders.ValueKind != JsonValueKind.Array) + { + return []; + } + + var prefix = basePath == "/" ? "/" : basePath.TrimEnd('/') + "/"; + return folders.EnumerateArray() + .Select(f => f.TryGetProperty("name", out var name) ? name.GetString() : null) + .Where(name => !string.IsNullOrEmpty(name)) + .Select(name => prefix + name) + .OrderBy(p => p, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + public async Task GetSecretAsync( + string configJson, string secretName, string? path, CancellationToken cancellationToken) + { + var config = Parse(configJson); + Require(config); + var token = await LoginAsync(config, cancellationToken); + + using var http = CreateClient(config); + http.DefaultRequestHeaders.Authorization = new("Bearer", token); + + var url = $"api/v3/secrets/raw/{Uri.EscapeDataString(secretName)}" + + $"?workspaceId={Uri.EscapeDataString(config.ProjectId!)}" + + $"&environment={Uri.EscapeDataString(config.Environment!)}" + + $"&secretPath={Uri.EscapeDataString(NormalizePath(path ?? config.Path))}"; + + using var response = await http.GetAsync(url, cancellationToken); + if (!response.IsSuccessStatusCode) + { + throw new SecretResolutionException( + $"Infisical returned HTTP {(int)response.StatusCode} for secret “{secretName}”."); + } + + using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken)); + if (!document.RootElement.TryGetProperty("secret", out var secret) + || !secret.TryGetProperty("secretValue", out var value)) + { + throw new SecretResolutionException( + $"Infisical response for “{secretName}” had no secretValue."); + } + + return value.GetString() ?? string.Empty; + } + + private async Task LoginAsync(Config config, CancellationToken cancellationToken) + { + using var http = CreateClient(config); + using var response = await http.PostAsJsonAsync( + "api/v1/auth/universal-auth/login", + new { clientId = config.ClientId, clientSecret = config.ClientSecret }, + cancellationToken); + + if (!response.IsSuccessStatusCode) + { + throw new SecretResolutionException( + $"Infisical universal-auth login failed with HTTP {(int)response.StatusCode}."); + } + + using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken)); + return document.RootElement.TryGetProperty("accessToken", out var token) + ? token.GetString() ?? throw new SecretResolutionException("Infisical login returned an empty token.") + : throw new SecretResolutionException("Infisical login response had no accessToken."); + } + + private async Task> ListNamesAsync( + Config config, string token, string? path, CancellationToken cancellationToken) + { + using var http = CreateClient(config); + http.DefaultRequestHeaders.Authorization = new("Bearer", token); + + var url = "api/v3/secrets/raw" + + $"?workspaceId={Uri.EscapeDataString(config.ProjectId!)}" + + $"&environment={Uri.EscapeDataString(config.Environment!)}" + + $"&secretPath={Uri.EscapeDataString(NormalizePath(path))}"; + + using var response = await http.GetAsync(url, cancellationToken); + if (!response.IsSuccessStatusCode) + { + throw new SecretResolutionException( + $"Infisical secret listing failed with HTTP {(int)response.StatusCode}."); + } + + using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken)); + if (!document.RootElement.TryGetProperty("secrets", out var secrets) + || secrets.ValueKind != JsonValueKind.Array) + { + return []; + } + + return secrets.EnumerateArray() + .Select(s => s.TryGetProperty("secretKey", out var key) ? key.GetString() : null) + .Where(name => !string.IsNullOrEmpty(name)) + .Select(name => name!) + .OrderBy(name => name, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + private HttpClient CreateClient(Config config) + { + var http = httpClientFactory.CreateClient("infisical"); + http.BaseAddress = new Uri(BaseUrl(config).TrimEnd('/') + "/"); + http.Timeout = TimeSpan.FromSeconds(20); + return http; + } + + private static Config Parse(string configJson) + => JsonDefaults.Deserialize(configJson) ?? new Config(null, null, null, null, null, null); + + private static string BaseUrl(Config config) + => string.IsNullOrWhiteSpace(config.BaseUrl) ? "https://app.infisical.com" : config.BaseUrl; + + private static string NormalizePath(string? path) + => string.IsNullOrWhiteSpace(path) ? "/" : path.StartsWith('/') ? path : "/" + path; + + private static List MissingFields(Config config) + { + var missing = new List(); + if (string.IsNullOrWhiteSpace(config.ClientId)) missing.Add("clientId"); + if (string.IsNullOrWhiteSpace(config.ClientSecret)) missing.Add("clientSecret"); + if (string.IsNullOrWhiteSpace(config.ProjectId)) missing.Add("projectId"); + if (string.IsNullOrWhiteSpace(config.Environment)) missing.Add("environment"); + return missing; + } + + private static void Require(Config config) + { + var missing = MissingFields(config); + if (missing.Count > 0) + { + throw new SecretResolutionException( + $"Infisical provider is missing required settings: {string.Join(", ", missing)}."); + } + } +} diff --git a/src/Backend/Secrets/SecretsEndpoints.cs b/src/Backend/Secrets/SecretsEndpoints.cs new file mode 100644 index 0000000..9ae0c2f --- /dev/null +++ b/src/Backend/Secrets/SecretsEndpoints.cs @@ -0,0 +1,193 @@ +using Backend.Auth; +using Backend.Security; +using Shared.Contracts.Api; + +namespace Backend.Secrets; + +/// +/// Secrets provider management. Values never leave the backend: list/detail +/// responses omit secret config fields, and the names endpoint returns secret +/// names only for the script editor's picker. +/// +public static class SecretsEndpoints +{ + public static void Map(WebApplication app) + { + app.MapGet(ApiRoutes.SecretsProviders, ListAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapPost(ApiRoutes.SecretsProviders, CreateAsync).RequireAuthorization(AuthConstants.PolicyAdmin); + app.MapPut(ApiRoutes.SecretsProvider, UpdateAsync).RequireAuthorization(AuthConstants.PolicyAdmin); + app.MapDelete(ApiRoutes.SecretsProvider, DeleteAsync).RequireAuthorization(AuthConstants.PolicyAdmin); + app.MapPost(ApiRoutes.SecretsProviderTest, TestAsync).RequireAuthorization(AuthConstants.PolicyAdmin); + app.MapGet(ApiRoutes.SecretsProviderNames, ListNamesAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapGet(ApiRoutes.SecretsProviderFolders, ListFoldersAsync).RequireAuthorization(AuthConstants.PolicyOperator); + } + + private static async Task ListFoldersAsync( + Guid id, + string? path, + SecretsProviderService service, + CancellationToken cancellationToken) + { + var entity = await service.FindAsync(id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + var driver = service.Driver(entity.Kind); + if (driver is null) + { + return Results.BadRequest(new { error = $"No driver for provider kind “{entity.Kind}”." }); + } + + try + { + var folders = await driver.ListFolderPathsAsync( + service.DecryptConfigJson(entity), path, cancellationToken); + return Results.Ok(folders); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // Vault unreachable / DNS / TLS failures included — the picker + // falls back to manual entry either way. + return Results.Problem(ex.Message, statusCode: StatusCodes.Status502BadGateway); + } + } + + private static async Task ListAsync( + SecretsProviderService service, CancellationToken cancellationToken) + { + var providers = await service.ListAsync(cancellationToken); + var kinds = service.Drivers + .Select(d => new { kind = d.Kind, displayName = d.DisplayName, fields = d.Fields }) + .ToList(); + return Results.Ok(new { providers, kinds }); + } + + private static async Task CreateAsync( + SaveSecretsProviderRequest request, + SecretsProviderService service, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + if (Validate(request, service) is { } problem) + { + return problem; + } + + var actor = context.User.Identity?.Name; + var dto = await service.CreateAsync(request, actor, cancellationToken); + await audit.LogAsync(AuditCategories.Settings, "secrets-provider-created", actor, + detail: $"{request.Kind}:{request.Name}", cancellationToken: cancellationToken); + return Results.Created(ApiRoutes.For.SecretsProvider(dto.Id), dto); + } + + private static async Task UpdateAsync( + Guid id, + SaveSecretsProviderRequest request, + SecretsProviderService service, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + if (Validate(request, service) is { } problem) + { + return problem; + } + + var entity = await service.FindAsync(id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + var actor = context.User.Identity?.Name; + var dto = await service.UpdateAsync(entity, request, actor, cancellationToken); + await audit.LogAsync(AuditCategories.Settings, "secrets-provider-updated", actor, + detail: $"{request.Kind}:{request.Name}", cancellationToken: cancellationToken); + return Results.Ok(dto); + } + + private static async Task DeleteAsync( + Guid id, + SecretsProviderService service, + Backend.Data.AppDbContext db, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + var entity = await service.FindAsync(id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + db.SecretsProviders.Remove(entity); + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Settings, "secrets-provider-deleted", + context.User.Identity?.Name, detail: entity.Name, cancellationToken: cancellationToken); + return Results.NoContent(); + } + + private static async Task TestAsync( + TestSecretsProviderRequest request, + SecretsProviderService service, + CancellationToken cancellationToken) + { + var driver = service.Driver(request.Kind); + if (driver is null) + { + return Results.BadRequest(new { error = $"Unknown provider kind “{request.Kind}”." }); + } + + var configJson = await service.ResolveTestConfigAsync(request, cancellationToken); + var steps = await driver.TestAsync(configJson, cancellationToken); + return Results.Ok(new SecretsTestResultDto(steps.Count > 0 && steps.All(s => s.Ok), steps)); + } + + private static async Task ListNamesAsync( + Guid id, + string? path, + SecretsProviderService service, + CancellationToken cancellationToken) + { + var entity = await service.FindAsync(id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + var driver = service.Driver(entity.Kind); + if (driver is null) + { + return Results.BadRequest(new { error = $"No driver for provider kind “{entity.Kind}”." }); + } + + try + { + var names = await driver.ListSecretNamesAsync( + service.DecryptConfigJson(entity), path, cancellationToken); + return Results.Ok(names); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + return Results.Problem(ex.Message, statusCode: StatusCodes.Status502BadGateway); + } + } + + private static IResult? Validate(SaveSecretsProviderRequest request, SecretsProviderService service) + { + if (string.IsNullOrWhiteSpace(request.Name)) + { + return Results.BadRequest(new { error = "Provider name is required." }); + } + + if (service.Driver(request.Kind) is null) + { + return Results.BadRequest(new { error = $"Unknown provider kind “{request.Kind}”." }); + } + + return null; + } +} diff --git a/src/Backend/Secrets/SecretsProviderService.cs b/src/Backend/Secrets/SecretsProviderService.cs new file mode 100644 index 0000000..5e2e6fc --- /dev/null +++ b/src/Backend/Secrets/SecretsProviderService.cs @@ -0,0 +1,207 @@ +using System.Text.Json; +using Backend.Data; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; + +namespace Backend.Secrets; + +/// +/// Stores secrets provider configurations (encrypted at rest with Data +/// Protection) and resolves script secret bindings server-side, so agents +/// and browsers never hold vault credentials or contact the vault. +/// +public sealed class SecretsProviderService( + AppDbContext db, + IDataProtectionProvider protectionProvider, + IEnumerable drivers) +{ + private readonly IDataProtector protector = protectionProvider.CreateProtector("Backend.SecretsProviders.v1"); + + public IReadOnlyList Drivers => drivers.ToList(); + + public ISecretsProviderDriver? Driver(string kind) + => drivers.FirstOrDefault(d => string.Equals(d.Kind, kind, StringComparison.OrdinalIgnoreCase)); + + public async Task> ListAsync(CancellationToken cancellationToken) + { + var rows = await db.SecretsProviders.AsNoTracking() + .OrderBy(p => p.Name) + .ToListAsync(cancellationToken); + return rows.Select(ToDto).ToList(); + } + + public Task FindAsync(Guid id, CancellationToken cancellationToken) + => db.SecretsProviders.SingleOrDefaultAsync(p => p.Id == id, cancellationToken); + + public async Task CreateAsync( + SaveSecretsProviderRequest request, string? actor, CancellationToken cancellationToken) + { + var entity = new SecretsProviderEntity + { + Id = Guid.NewGuid(), + Name = request.Name.Trim(), + Kind = request.Kind, + ConfigProtected = protector.Protect(JsonDefaults.Serialize(Compact(request.Config))), + CreatedUtc = DateTimeOffset.UtcNow, + UpdatedUtc = DateTimeOffset.UtcNow, + UpdatedBy = actor, + }; + db.SecretsProviders.Add(entity); + await db.SaveChangesAsync(cancellationToken); + return ToDto(entity); + } + + public async Task UpdateAsync( + SecretsProviderEntity entity, SaveSecretsProviderRequest request, string? actor, + CancellationToken cancellationToken) + { + entity.Name = request.Name.Trim(); + entity.Kind = request.Kind; + entity.ConfigProtected = protector.Protect( + JsonDefaults.Serialize(MergeSecrets(request.Kind, Compact(request.Config), DecryptConfig(entity)))); + entity.UpdatedUtc = DateTimeOffset.UtcNow; + entity.UpdatedBy = actor; + await db.SaveChangesAsync(cancellationToken); + return ToDto(entity); + } + + /// Candidate config for a pre-save test, with stored secrets merged when masked. + public async Task ResolveTestConfigAsync(TestSecretsProviderRequest request, CancellationToken cancellationToken) + { + var candidate = Compact(request.Config); + if (request.Id is { } id) + { + var stored = await FindAsync(id, cancellationToken); + if (stored is not null) + { + candidate = MergeSecrets(request.Kind, candidate, DecryptConfig(stored)); + } + } + + return JsonDefaults.Serialize(candidate); + } + + public string DecryptConfigJson(SecretsProviderEntity entity) + => JsonDefaults.Serialize(DecryptConfig(entity)); + + /// + /// Fetches every bound secret from its provider. Values are returned in + /// binding order and must never be logged or persisted by callers. + /// + public async Task> ResolveAsync( + IReadOnlyList bindings, CancellationToken cancellationToken) + { + var providerIds = bindings.Select(b => b.ProviderId).Distinct().ToList(); + var providers = await db.SecretsProviders.AsNoTracking() + .Where(p => providerIds.Contains(p.Id)) + .ToDictionaryAsync(p => p.Id, cancellationToken); + + var configCache = new Dictionary(); + var result = new List(bindings.Count); + + foreach (var binding in bindings) + { + if (!providers.TryGetValue(binding.ProviderId, out var provider)) + { + throw new SecretResolutionException( + $"Secret “{binding.Name}”: its provider no longer exists."); + } + + var driver = Driver(provider.Kind) + ?? throw new SecretResolutionException( + $"Secret “{binding.Name}”: no driver for provider kind “{provider.Kind}”."); + + if (!configCache.TryGetValue(provider.Id, out var configJson)) + { + configJson = DecryptConfigJson(provider); + configCache[provider.Id] = configJson; + } + + try + { + var value = await driver.GetSecretAsync( + configJson, binding.SecretName, binding.Path, cancellationToken); + result.Add(new ScriptSecret(binding.Name, value)); + } + catch (SecretResolutionException ex) + { + throw new SecretResolutionException( + $"Secret “{binding.Name}” from provider “{provider.Name}”: {ex.Message}", ex); + } + catch (Exception ex) + { + throw new SecretResolutionException( + $"Secret “{binding.Name}” from provider “{provider.Name}” could not be fetched: {ex.Message}", ex); + } + } + + return result; + } + + public SecretsProviderDto ToDto(SecretsProviderEntity entity) + { + var config = DecryptConfig(entity); + var secretFields = Driver(entity.Kind)?.SecretFields ?? []; + + var sanitized = config + .Where(kv => !secretFields.Contains(kv.Key, StringComparer.OrdinalIgnoreCase)) + .ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase); + + var set = secretFields + .Where(f => config.TryGetValue(f, out var v) && !string.IsNullOrEmpty(v)) + .ToList(); + + return new SecretsProviderDto( + entity.Id, entity.Name, entity.Kind, sanitized, set, entity.UpdatedUtc, entity.UpdatedBy); + } + + private Dictionary DecryptConfig(SecretsProviderEntity entity) + { + try + { + var json = protector.Unprotect(entity.ConfigProtected); + return JsonDefaults.Deserialize>(json) + ?? new Dictionary(StringComparer.OrdinalIgnoreCase); + } + catch (Exception) + { + // Key ring rotated or data corrupt: surface as an empty config so + // the provider shows as unconfigured instead of erroring every read. + return new Dictionary(StringComparer.OrdinalIgnoreCase); + } + } + + /// Keeps stored secret fields when the request leaves them empty. + private Dictionary MergeSecrets( + string kind, Dictionary incoming, Dictionary stored) + { + foreach (var field in Driver(kind)?.SecretFields ?? []) + { + var provided = incoming.TryGetValue(field, out var value) && !string.IsNullOrEmpty(value); + if (!provided && stored.TryGetValue(field, out var kept) && !string.IsNullOrEmpty(kept)) + { + incoming[field] = kept; + } + } + + return incoming; + } + + private static Dictionary Compact(Dictionary config) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (key, value) in config) + { + if (!string.IsNullOrWhiteSpace(value)) + { + result[key] = value.Trim(); + } + } + + return result; + } +} diff --git a/src/Backend/Security/AuditService.cs b/src/Backend/Security/AuditService.cs index 97db65d..ea40494 100644 --- a/src/Backend/Security/AuditService.cs +++ b/src/Backend/Security/AuditService.cs @@ -37,4 +37,5 @@ public static class AuditCategories public const string Scripts = "scripts"; public const string Shell = "shell"; public const string Admin = "admin"; + public const string Settings = "settings"; } diff --git a/src/Backend/Settings/SettingsEndpoints.cs b/src/Backend/Settings/SettingsEndpoints.cs new file mode 100644 index 0000000..01da8e8 --- /dev/null +++ b/src/Backend/Settings/SettingsEndpoints.cs @@ -0,0 +1,171 @@ +using Backend.Auth; +using Backend.Files; +using Backend.Security; +using Shared.Contracts.Api; +using K = Backend.Files.S3SettingsService.Keys; + +namespace Backend.Settings; + +/// +/// Operator-editable S3 configuration and agent-package delivery. All routes +/// are Admin-only: they read and write storage credentials. +/// +public static class SettingsEndpoints +{ + public static void Map(WebApplication app) + { + app.MapGet(ApiRoutes.S3Settings, GetS3Async).RequireAuthorization(AuthConstants.PolicyAdmin); + app.MapPut(ApiRoutes.S3Settings, SaveS3Async).RequireAuthorization(AuthConstants.PolicyAdmin); + app.MapPost(ApiRoutes.S3SettingsTest, TestS3Async).RequireAuthorization(AuthConstants.PolicyAdmin); + + app.MapGet(ApiRoutes.AgentPackageStatus, AgentStatusAsync).RequireAuthorization(AuthConstants.PolicyAdmin); + app.MapPost(ApiRoutes.AgentPackageOffload, OffloadAsync).RequireAuthorization(AuthConstants.PolicyAdmin); + + app.MapGet(ApiRoutes.ServerInfo, GetServerInfo).RequireAuthorization(AuthConstants.PolicyOperator); + } + + /// + /// The externally reachable base URL for display and generated commands: + /// PUBLIC_SERVER_URL when set, else derived from trusted forwarded headers. + /// + private static IResult GetServerInfo(HttpContext context, IConfiguration configuration) + => Results.Ok(new + { + baseUrl = Backend.Proxy.PublicUrl.Resolve(context, configuration), + fromEnvironment = Backend.Proxy.PublicUrl.IsConfigured(configuration), + }); + + private static async Task GetS3Async(S3SettingsService settings, CancellationToken cancellationToken) + { + var effective = await settings.GetEffectiveAsync(cancellationToken); + return Results.Ok(new S3SettingsDto( + Enabled: effective.Enabled, + Endpoint: effective.Endpoint, + Region: effective.Region, + Bucket: effective.Bucket, + AccessKey: effective.AccessKey, + SecretKey: null, // never returned + ForcePathStyle: effective.ForcePathStyle, + PresignExpirySeconds: effective.PresignExpirySeconds, + SecretKeyIsSet: !string.IsNullOrWhiteSpace(effective.SecretKey), + AgentOffloadEnabled: await settings.GetAgentOffloadEnabledAsync(cancellationToken), + LastTestUtc: await settings.GetLastTestUtcAsync(cancellationToken), + FromEnvironment: settings.EnvironmentDefaults.IsUsable)); + } + + private static async Task SaveS3Async( + S3SettingsDto request, + S3SettingsService settings, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + var actor = context.User.Identity?.Name; + + await settings.SetAsync(K.Enabled, request.Enabled ? "1" : "0", false, actor, cancellationToken); + await settings.SetAsync(K.Endpoint, request.Endpoint, false, actor, cancellationToken); + await settings.SetAsync(K.Region, request.Region, false, actor, cancellationToken); + await settings.SetAsync(K.Bucket, request.Bucket, false, actor, cancellationToken); + await settings.SetAsync(K.AccessKey, request.AccessKey, false, actor, cancellationToken); + await settings.SetAsync(K.ForcePathStyle, request.ForcePathStyle ? "1" : "0", false, actor, cancellationToken); + await settings.SetAsync( + K.PresignExpirySeconds, request.PresignExpirySeconds.ToString(), false, actor, cancellationToken); + + // A null secret means "leave the stored one alone". + if (!string.IsNullOrWhiteSpace(request.SecretKey)) + { + await settings.SetAsync(K.SecretKey, request.SecretKey, true, actor, cancellationToken); + } + + // Offload can only be turned on once a round-trip test has passed. + if (request.AgentOffloadEnabled) + { + if (await settings.GetLastTestUtcAsync(cancellationToken) is null) + { + return Results.BadRequest(new + { + error = "Run a successful S3 test before enabling agent offload.", + }); + } + + await settings.SetAsync(K.AgentOffloadEnabled, "1", false, actor, cancellationToken); + } + else + { + await settings.SetAsync(K.AgentOffloadEnabled, "0", false, actor, cancellationToken); + } + + await audit.LogAsync(AuditCategories.Admin, "s3-settings-updated", actor, + detail: $"enabled={request.Enabled} bucket={request.Bucket} offload={request.AgentOffloadEnabled}", + cancellationToken: cancellationToken); + + return await GetS3Async(settings, cancellationToken); + } + + /// + /// Tests the supplied candidate values when provided, otherwise the saved + /// ones — so settings can be validated before being committed. + /// + private static async Task TestS3Async( + S3SettingsDto? request, + S3SettingsService settings, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + var effective = await settings.GetEffectiveAsync(cancellationToken); + + var candidate = request is null + ? effective + : new S3Options + { + Enabled = request.Enabled, + Endpoint = string.IsNullOrWhiteSpace(request.Endpoint) ? effective.Endpoint : request.Endpoint, + Region = string.IsNullOrWhiteSpace(request.Region) ? effective.Region : request.Region, + Bucket = string.IsNullOrWhiteSpace(request.Bucket) ? effective.Bucket : request.Bucket, + AccessKey = string.IsNullOrWhiteSpace(request.AccessKey) ? effective.AccessKey : request.AccessKey, + // Blank secret in the request = keep using the stored one. + SecretKey = string.IsNullOrWhiteSpace(request.SecretKey) ? effective.SecretKey : request.SecretKey, + ForcePathStyle = request.ForcePathStyle, + PresignExpirySeconds = request.PresignExpirySeconds > 0 + ? request.PresignExpirySeconds + : effective.PresignExpirySeconds, + }; + + var result = await S3ClientFactory.TestAsync(candidate, cancellationToken); + + if (result.Ok) + { + await settings.SetAsync( + S3SettingsService.Keys.LastTestUtc, + DateTimeOffset.UtcNow.ToString("O"), + false, + context.User.Identity?.Name, + cancellationToken); + } + + await audit.LogAsync(AuditCategories.Admin, "s3-test", context.User.Identity?.Name, + detail: result.Ok ? "passed" : "failed", cancellationToken: cancellationToken); + + return Results.Ok(new S3TestResultDto( + result.Ok, + result.Steps.Select(s => new S3TestStepDto(s.Name, s.Ok, s.Detail)).ToList(), + result.ElapsedMs)); + } + + private static async Task AgentStatusAsync( + AgentPackageService packages, string? type, CancellationToken cancellationToken) + => Results.Ok(await packages.GetStatusAsync(AgentPackageService.NormalizeType(type), cancellationToken)); + + private static async Task OffloadAsync( + AgentPackageService packages, string? type, HttpContext context, CancellationToken cancellationToken) + { + var packageType = AgentPackageService.NormalizeType(type); + var (ok, message) = await packages.UploadToS3Async( + packageType, context.User.Identity?.Name, cancellationToken); + + return ok + ? Results.Ok(new { message, status = await packages.GetStatusAsync(packageType, cancellationToken) }) + : Results.BadRequest(new { error = message }); + } +} diff --git a/src/Backend/Settings/SettingsStore.cs b/src/Backend/Settings/SettingsStore.cs new file mode 100644 index 0000000..2cdae62 --- /dev/null +++ b/src/Backend/Settings/SettingsStore.cs @@ -0,0 +1,91 @@ +using Backend.Data; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.EntityFrameworkCore; + +namespace Backend.Settings; + +/// +/// Key/value application settings that override environment defaults. +/// Secret values are encrypted at rest with Data Protection so the database +/// never holds plaintext credentials. +/// +public sealed class SettingsStore(AppDbContext db, IDataProtectionProvider protectionProvider) +{ + private readonly IDataProtector protector = protectionProvider.CreateProtector("Backend.Settings.v1"); + + public async Task> GetAllAsync(string prefix, CancellationToken cancellationToken) + { + var rows = await db.AppSettings.AsNoTracking() + .Where(s => s.Key.StartsWith(prefix)) + .ToListAsync(cancellationToken); + + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var row in rows) + { + if (row.Value is null) + { + continue; + } + + if (row.IsSecret) + { + try + { + result[row.Key] = protector.Unprotect(row.Value); + } + catch (Exception) + { + // Key ring rotated or data corrupt — treat as unset rather + // than failing every read of the settings page. + } + } + else + { + result[row.Key] = row.Value; + } + } + + return result; + } + + /// + /// Upserts a value. A null for a secret leaves the + /// stored secret untouched, so the UI can submit a masked placeholder + /// without wiping the credential. + /// + public async Task SetAsync( + string key, string? value, bool isSecret, string? actor, CancellationToken cancellationToken) + { + var row = await db.AppSettings.SingleOrDefaultAsync(s => s.Key == key, cancellationToken); + + if (value is null && isSecret && row is not null) + { + return; + } + + var stored = value is null + ? null + : isSecret ? protector.Protect(value) : value; + + if (row is null) + { + db.AppSettings.Add(new AppSettingEntity + { + Key = key, + Value = stored, + IsSecret = isSecret, + UpdatedUtc = DateTimeOffset.UtcNow, + UpdatedBy = actor, + }); + } + else + { + row.Value = stored; + row.IsSecret = isSecret; + row.UpdatedUtc = DateTimeOffset.UtcNow; + row.UpdatedBy = actor; + } + + await db.SaveChangesAsync(cancellationToken); + } +} diff --git a/src/Infra/backend/Dockerfile b/src/Infra/backend/Dockerfile index d47b191..6e3aab1 100644 --- a/src/Infra/backend/Dockerfile +++ b/src/Infra/backend/Dockerfile @@ -33,6 +33,12 @@ RUN apt-get update \ WORKDIR /app COPY --from=build /app . +# Agent installer baked in by CI so the URL-install flow works out of the box. +# CI stages the Windows-built package into ./artifacts/agent-package before +# building this image; the .dockerignore keeps it empty otherwise, and the +# backend falls back to /data/agent (or S3 offload) when it is absent. +COPY src/Infra/backend/agent-package/ /opt/executer/agent/ + ENV ASPNETCORE_URLS=http://0.0.0.0:8080 \ DATABASE_PATH=/data/app.db diff --git a/src/Infra/backend/agent-package/.gitkeep b/src/Infra/backend/agent-package/.gitkeep new file mode 100644 index 0000000..fc6bd30 --- /dev/null +++ b/src/Infra/backend/agent-package/.gitkeep @@ -0,0 +1,5 @@ +# CI stages Agent.msi / Agent.zip / VERSION into this directory before the +# backend image is built, so the installer ships inside the image and the URL +# install flow needs no manual seeding. +# +# Left empty in git: the built packages are artifacts, not source. diff --git a/src/Infra/nginx/executer.conf b/src/Infra/nginx/executer.conf index 6a09662..ee0d6e5 100644 --- a/src/Infra/nginx/executer.conf +++ b/src/Infra/nginx/executer.conf @@ -165,6 +165,8 @@ server { } # ── Backend API ─────────────────────────────────────────────────────── + # Also covers the OIDC callback, fixed at /api/auth/oidc/callback (it + # rides the rate-limited /api/auth/ location above — one hit per sign-in). location ^~ /api/ { proxy_pass http://executer_api; proxy_http_version 1.1; @@ -172,13 +174,6 @@ server { proxy_read_timeout 120s; } - # ── OIDC callback (handled by the backend) ──────────────────────────── - location = /signin-oidc { - proxy_pass http://executer_api; - proxy_http_version 1.1; - proxy_set_header Connection ""; - } - # ── WebUI (everything else) ─────────────────────────────────────────── location / { proxy_pass http://executer_webui; diff --git a/src/Installer/Agent.Installer.wixproj b/src/Installer/Agent.Installer.wixproj index c7b1269..3b02dc5 100644 --- a/src/Installer/Agent.Installer.wixproj +++ b/src/Installer/Agent.Installer.wixproj @@ -19,6 +19,7 @@ + diff --git a/src/Installer/Policies/ExecuteR.admx b/src/Installer/Policies/ExecuteR.admx index 81344be..84dd91e 100644 --- a/src/Installer/Policies/ExecuteR.admx +++ b/src/Installer/Policies/ExecuteR.admx @@ -4,20 +4,21 @@ Policies write to the GPO policy key the agent reads with highest precedence: HKLM\SOFTWARE\Policies\ExecuteR - (GroupPolicy > normal registry > compiled defaults). Interval/delay values are - written as REG_SZ (seconds); the toggles as REG_DWORD. The one-time bootstrap - token is intentionally NOT a policy — it is a secret delivered via MSI/API. + (Group Policy > normal registry [HKLM\SOFTWARE\ExecuteR] > compiled defaults). + Interval/delay values are written as REG_SZ (seconds or hh:mm:ss); the toggles + as REG_DWORD. The one-time bootstrap token is intentionally NOT a policy — it + is a secret delivered via MSI property or the URL install command. --> - + - + @@ -27,10 +28,7 @@ - - - - + diff --git a/src/Installer/Policies/README.md b/src/Installer/Policies/README.md index 23bf0b6..dc2547f 100644 --- a/src/Installer/Policies/README.md +++ b/src/Installer/Policies/README.md @@ -18,7 +18,7 @@ copy en-US\ExecuteR.adml %WINDIR%\PolicyDefinitions\en-US\ ``` Then open `gpedit.msc` → Computer Configuration → Administrative Templates → -Grace Solution → ExecuteR Agent. +ExecuteR Agent. ## Install (domain central store) @@ -32,13 +32,18 @@ copy en-US\ExecuteR.adml \\\SYSVOL\\Policies\PolicyDefinitions\ | Policy | Registry value | Type | Notes | |--------|----------------|------|-------| | Server URL | `ServerURL` | REG_SZ | `https://host`; agent derives `wss://…/messaging/agent` | -| Log level | `LogLevel` | REG_SZ | Trace/Debug/Information/Warning/Error | -| Inventory interval (seconds) | `InventoryInterval` | REG_SZ | default 900 | -| Reconnect minimum delay (seconds) | `ReconnectMinDelay` | REG_SZ | default 1 | -| Reconnect maximum delay (seconds) | `ReconnectMaxDelay` | REG_SZ | default 60 | -| Allow remote interactive shell | `AllowRemoteShell` | REG_DWORD | default off | +| Log level | `LogLevel` | REG_SZ | Trace/Debug/Information/Warning/Error; default Information | +| Inventory publish interval | `InventoryInterval` | REG_SZ | seconds or `hh:mm:ss`; default 900 | +| Reconnect delay — minimum | `ReconnectMinDelay` | REG_SZ | seconds or `hh:mm:ss`; default 1 | +| Reconnect delay — maximum | `ReconnectMaxDelay` | REG_SZ | seconds or `hh:mm:ss`; default 60 | +| Allow remote interactive shell | `AllowRemoteShell` | REG_DWORD | default off (opt-in) | | Allow PowerShell script execution | `AllowScriptExecution` | REG_DWORD | default on | +Every policy's full behavior — defaults, valid ranges, security implications +and when changes take effect (service restart) — is in the GPMC explain text. +Configuration is read at service start; restart the **ExecuteR Agent** service +(`ExecuteRAgent`) after changing values. + The one-time **bootstrap token** is deliberately not a policy — it is a secret delivered via the MSI `BOOTSTRAPTOKEN` property or the URL install command, and is erased from the registry after successful enrollment. diff --git a/src/Installer/Policies/en-US/ExecuteR.adml b/src/Installer/Policies/en-US/ExecuteR.adml index 9b4b907..b476353 100644 --- a/src/Installer/Policies/en-US/ExecuteR.adml +++ b/src/Installer/Policies/en-US/ExecuteR.adml @@ -1,65 +1,130 @@ ExecuteR Agent Administrative template for the ExecuteR endpoint management agent. ExecuteR Agent 1.0 or later - Grace Solution ExecuteR Agent Server URL - The control-plane base URL the agent connects to, for example https://control.example.com. The agent derives the NATS WebSocket endpoint (https -> wss) automatically. Do not include ws:// or wss://. + Specifies the base URL of the ExecuteR control plane this device reports to, for example https://control.example.com. + +The agent makes all of its connections through this one address: HTTPS for enrollment and credential refresh, and a WebSocket (derived automatically, https becomes wss) for live messaging. Enter a plain https:// URL — do not enter ws:// or wss://, and do not append /api or any other path. + +If you enable this policy, the value overrides both the URL provided at install time (the SERVERURL MSI property) and any locally set registry value, on every refresh. + +If you disable or do not configure this policy, the agent uses the locally configured value in HKLM\SOFTWARE\ExecuteR (normally written by the installer). + +Note: this URL tells the agent where to connect, but the device's enrollment credentials are issued by a specific server. Pointing already-enrolled devices at a different ExecuteR instance requires re-enrollment with a new bootstrap token. + +The agent reads configuration at service start; restart the "ExecuteR Agent" service (ExecuteRAgent) to apply a change immediately. Log level - Minimum severity written to the agent log. - Trace + Specifies the minimum severity the agent writes to its log files in %ProgramData%\ExecuteR\logs. + +Levels, from most to least verbose: Trace, Debug, Information, Warning, Error. Each level includes everything above it. + +Information is the recommended day-to-day setting. Use Debug or Trace only while investigating an issue — they are noisy, and although log files rotate at 5 MB with the 3 most recent kept (so disk usage is bounded), verbose levels churn through that window quickly and push out the history you may want later. Trace may include message-level protocol detail. + +If you disable or do not configure this policy, the agent uses the locally configured value, or Information by default. + +The agent reads configuration at service start; restart the "ExecuteR Agent" service (ExecuteRAgent) to apply a change immediately. + Trace (most verbose) Debug - Information + Information (default) Warning - Error + Error (least verbose) - Inventory interval (seconds) - How often the agent publishes a full inventory snapshot, in seconds. Default is 900 (15 minutes). + Inventory publish interval + Specifies how often the agent collects and publishes a full hardware/software inventory snapshot (identity, OS, CPU, memory, disks with their volumes, network adapters) while connected. - Reconnect minimum delay (seconds) - Minimum backoff delay before a NATS reconnect attempt, in seconds. Default is 1. +Enter a number of seconds (for example 900) or a time span in hh:mm:ss form (for example 00:15:00). The value must be greater than zero; an invalid value is ignored and the default is used instead. - Reconnect maximum delay (seconds) - Maximum backoff delay between NATS reconnect attempts, in seconds. Default is 60. +The default is 900 seconds (15 minutes). Inventory is also published immediately whenever the agent connects, and on demand when an operator clicks "Refresh inventory" — this interval only controls the steady-state cadence in between. + +Consider the trade-off: dynamic device groups and the details shown in the console evaluate against the most recent snapshot, so a longer interval means membership and hardware changes are reflected more slowly; a very short interval adds WMI collection load on the device and traffic to the server for data that rarely changes. + +If you disable or do not configure this policy, the agent uses the locally configured value, or 900 seconds by default. + +The agent reads configuration at service start; restart the "ExecuteR Agent" service (ExecuteRAgent) to apply a change immediately. + + Reconnect delay — minimum + Specifies the shortest wait before the agent retries its messaging connection after it drops. Together with "Reconnect delay — maximum" this bounds the exponential backoff: retries start at the minimum and grow toward the maximum, where they stay until the connection is restored. + +Enter a number of seconds (for example 1) or a time span in hh:mm:ss form. The value must be greater than zero and should not exceed the configured maximum. + +The default is 1 second. Raising it slightly (for example to 5) softens reconnect bursts when many devices lose the same network path at once — such as a site outage — at the cost of each device coming back a little later. + +Missed work is not lost while disconnected: jobs are held durably on the server and delivered when the agent reconnects. + +If you disable or do not configure this policy, the agent uses the locally configured value, or 1 second by default. + +The agent reads configuration at service start; restart the "ExecuteR Agent" service (ExecuteRAgent) to apply a change immediately. + + Reconnect delay — maximum + Specifies the longest wait between reconnect attempts once exponential backoff has grown from the configured minimum. While the server stays unreachable the agent keeps retrying at roughly this cadence indefinitely. + +Enter a number of seconds (for example 60) or a time span in hh:mm:ss form. The value must be greater than zero and should be at least the configured minimum. + +The default is 60 seconds. A larger value reduces background traffic during long outages but delays how quickly devices come back online — and with them presence, inventory and delivery of any jobs queued while they were away. Note that a device silent past the server's orphan window (30 days by default) is orphaned and must re-enroll, so extreme values here only postpone reconnection, they never substitute for it. + +If you disable or do not configure this policy, the agent uses the locally configured value, or 60 seconds by default. + +The agent reads configuration at service start; restart the "ExecuteR Agent" service (ExecuteRAgent) to apply a change immediately. Allow remote interactive shell - When enabled, operators may open an interactive ConPTY shell on this device. When disabled, shell open commands are refused. Default is disabled. + Controls whether operators may open a live interactive terminal (a full Windows pseudoconsole running as the agent service account, LocalSystem by default) on this device from the ExecuteR console. + +If you enable this policy, shell requests from authorized operators are accepted. + +If you disable this policy, every shell open command is refused on the device itself — the server-side role check still applies, but this setting is enforced locally regardless of what the server asks for. + +If you do not configure this policy, the agent uses the locally configured value; the compiled default is Disabled — the remote shell is deliberately opt-in because an interactive SYSTEM shell is the most powerful capability the agent exposes. + +Scoping guidance: apply Enabled narrowly (for example to a helpdesk-managed OU) rather than broadly, and leave it unset elsewhere so the safe default holds. This policy does not affect script execution, which is controlled separately by "Allow PowerShell script execution". + +The agent reads configuration at service start; restart the "ExecuteR Agent" service (ExecuteRAgent) to apply a change immediately. Allow PowerShell script execution - When enabled, the agent runs dispatched PowerShell jobs. When disabled, script commands are refused. Default is enabled. + Controls whether this device runs PowerShell jobs dispatched from the ExecuteR console — manual runs, group fan-outs, schedules and lifecycle triggers alike. Scripts execute in-process under the agent service account (LocalSystem by default). + +If you enable this policy, dispatched script jobs run normally. + +If you disable this policy, the device refuses every script command: jobs sent to it fail rather than execute, including scheduled and triggered runs. Enforcement is local to the device, so it holds even against a compromised or misconfigured server. Inventory reporting, presence and file delivery are not affected. + +If you do not configure this policy, the agent uses the locally configured value, or Enabled by default — script execution is the agent's primary purpose. + +Use Disabled as a hard opt-out for sensitive machines that should be visible in inventory but never remotely scripted. + +The agent reads configuration at service start; restart the "ExecuteR Agent" service (ExecuteRAgent) to apply a change immediately. - + - Log level + Minimum level written to the log: - + - + - + diff --git a/src/Installer/Product.wxs b/src/Installer/Product.wxs index bab60b9..b46395f 100644 --- a/src/Installer/Product.wxs +++ b/src/Installer/Product.wxs @@ -1,5 +1,6 @@ + xmlns:util="http://wixtoolset.org/schemas/v4/wxs/util" + xmlns:ui="http://wixtoolset.org/schemas/v4/wxs/ui"> + + + + Key="$(var.AgentRegKey)" Name="ServerURL" Type="raw" /> + Key="$(var.AgentRegKey)" Name="LogLevel" Type="raw" /> + Key="$(var.AgentRegKey)" Name="AllowRemoteShell" Type="raw" /> + Key="$(var.AgentRegKey)" Name="AllowScriptExecution" Type="raw" /> - - - + @@ -93,23 +100,23 @@ - - - - - @@ -150,6 +157,59 @@ Execute="deferred" Impersonate="no" Return="ignore" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $"/api/groups/{id:D}/members"; public static string DeviceTags(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}/tags"; public static string Trigger(Guid id) => $"/api/triggers/{id:D}"; + public static string SecretsProvider(Guid id) => $"/api/secrets/providers/{id:D}"; + public static string SecretsProviderNames(Guid id) => $"/api/secrets/providers/{id:D}/secret-names"; public static string Job(Guid jobId) => $"/api/jobs/{jobId:D}"; + public static string Schedule(Guid id) => $"/api/schedules/{id:D}"; + public static string ScheduleAssignment(Guid id) => $"/api/schedule-assignments/{id:D}"; public static string JobOutput(Guid jobId) => $"/api/jobs/{jobId:D}/output"; public static string AdminBootstrapToken(Guid id) => $"/api/admin/bootstrap-tokens/{id:D}"; } diff --git a/src/Shared.Contracts/Api/AuthDtos.cs b/src/Shared.Contracts/Api/AuthDtos.cs index a5a04ac..40d7cd4 100644 --- a/src/Shared.Contracts/Api/AuthDtos.cs +++ b/src/Shared.Contracts/Api/AuthDtos.cs @@ -5,6 +5,40 @@ namespace Shared.Contracts.Api; /// POST /api/auth/login request body. public sealed record LoginRequest(string Username, string Password); +/// +/// GET /api/auth/config — anonymous. Tells the sign-in page what to render; +/// contains nothing sensitive. +/// +public sealed record AuthConfigDto( + bool OidcAvailable, + bool ShowLocalFields, + bool AutoRedirect, + string? ProviderName); + +/// GET/PUT /api/settings/auth — admin only. The client secret is never returned. +public sealed record AuthSettingsDto( + bool OidcEnabled, + string? Authority, + string? ClientId, + string? ClientSecret, + string? ProviderName, + string Scopes, + string? NameClaim, + string? RoleClaim, + string? AdminRole, + string? OperatorRole, + string? ViewerRole, + UserRole DefaultRole, + bool RequireMappedRole, + string LoginMode, + bool ClientSecretIsSet, + bool ForcedLocalByEnvironment, + string CallbackPath, + string RedirectUri); + +/// POST /api/settings/auth/test — validates the discovery document. +public sealed record AuthTestResultDto(bool Ok, IReadOnlyList Steps); + /// GET /api/auth/session response body. public sealed record SessionResponse( bool Authenticated, diff --git a/src/Shared.Contracts/Api/ResourceDtos.cs b/src/Shared.Contracts/Api/ResourceDtos.cs index f20f1cb..13eccee 100644 --- a/src/Shared.Contracts/Api/ResourceDtos.cs +++ b/src/Shared.Contracts/Api/ResourceDtos.cs @@ -16,7 +16,8 @@ public sealed record DeviceDto( DateTimeOffset? LastSeenUtc, DateTimeOffset EnrolledUtc, IReadOnlyList? Tags = null, - bool IsOrphaned = false); + bool IsOrphaned = false, + string? PublicIp = null); /// Device group resource. public sealed record DeviceGroupDto( @@ -90,7 +91,9 @@ public sealed record ScriptDto( DateTimeOffset CreatedUtc, DateTimeOffset UpdatedUtc, string? CreatedBy, - string? UpdatedBy); + string? UpdatedBy, + IReadOnlyList? SecretBindings = null, + string? SecretsVariableName = null); /// POST/PUT /api/scripts request body. public sealed record SaveScriptRequest( @@ -98,7 +101,41 @@ public sealed record SaveScriptRequest( string? Description, string Content, IReadOnlyList? Parameters = null, - IReadOnlyList? FunctionModuleIds = null); + IReadOnlyList? FunctionModuleIds = null, + IReadOnlyList? SecretBindings = null, + string? SecretsVariableName = null); + +/// +/// Configured secrets provider. Config is driver-specific and sanitized: +/// secret fields are omitted, with SecretFieldsSet reporting which of +/// them currently hold a value. +/// +public sealed record SecretsProviderDto( + Guid Id, + string Name, + string Kind, + IReadOnlyDictionary Config, + IReadOnlyList SecretFieldsSet, + DateTimeOffset UpdatedUtc, + string? UpdatedBy); + +/// +/// POST/PUT /api/secrets/providers body. Empty/null secret config fields keep +/// the stored value, so the UI can submit a masked form without wiping them. +/// +public sealed record SaveSecretsProviderRequest( + string Name, + string Kind, + Dictionary Config); + +/// POST /api/secrets/providers/test body (Id merges stored secrets). +public sealed record TestSecretsProviderRequest( + string Kind, + Dictionary Config, + Guid? Id = null); + +/// Result of a secrets provider connectivity test. +public sealed record SecretsTestResultDto(bool Ok, IReadOnlyList Steps); /// Reusable PowerShell function module (prepended to scripts that reference it). public sealed record FunctionModuleDto( @@ -133,10 +170,89 @@ public sealed record JobDto( /// POST /api/jobs request body. maps /// parameter name → typed JSON value per the script's parameter schema. +/// Targets exactly one of ClientId (single device) or GroupId (fan-out). public sealed record CreateJobRequest( - string ClientId, + string? ClientId, Guid ScriptId, - IReadOnlyDictionary? Arguments = null); + IReadOnlyDictionary? Arguments = null, + Guid? GroupId = null); + +/// Result of a group fan-out run: one job per eligible member. +public sealed record GroupRunDto( + IReadOnlyList Jobs, + IReadOnlyList SkippedOrphaned); + +/// +/// A reusable cadence object. Scripts honor a schedule through assignments — +/// the schedule itself carries no script or target. +/// +public sealed record ScheduleDto( + Guid Id, + string Name, + string? CronExpression, + DateTimeOffset? RunOnceUtc, + string TimeZoneId, + bool Enabled, + DateTimeOffset? NextRunUtc, + DateTimeOffset? LastRunUtc, + DateTimeOffset UpdatedUtc, + string? UpdatedBy, + IReadOnlyList Assignments); + +/// +/// POST/PUT /api/schedules body. Exactly one of +/// CronExpression/RunOnceUtc. +/// +public sealed record SaveScheduleRequest( + string Name, + string? CronExpression, + DateTimeOffset? RunOnceUtc, + string? TimeZoneId = null, + bool Enabled = true); + +/// +/// One script honoring a schedule against one device or group. Carries the +/// schedule's cadence so consumers can describe it without a second lookup. +/// +public sealed record ScheduleAssignmentDto( + Guid Id, + Guid ScheduleId, + string? ScheduleName, + string? CronExpression, + DateTimeOffset? RunOnceUtc, + string TimeZoneId, + bool ScheduleEnabled, + DateTimeOffset? NextRunUtc, + Guid ScriptId, + string? ScriptName, + string? ClientId, + string? TargetHostname, + Guid? GroupId, + string? GroupName, + bool Enabled, + DateTimeOffset? LastRunUtc, + string? LastResult); + +/// +/// POST/PUT /api/schedule-assignments body. Exactly one of +/// ClientId/GroupId. Null Arguments keeps stored values. +/// +public sealed record SaveScheduleAssignmentRequest( + Guid ScheduleId, + Guid ScriptId, + string? ClientId, + Guid? GroupId, + IReadOnlyDictionary? Arguments = null, + bool Enabled = true); + +/// POST /api/schedules/preview body. +public sealed record SchedulePreviewRequest(string CronExpression, string? TimeZoneId = null); + +/// Validation + the next concrete occurrences, so the UI never guesses. +public sealed record SchedulePreviewDto( + bool Valid, + string? Error, + IReadOnlyList NextRunsUtc); /// One stored output record for GET /api/jobs/{jobId}/output. public sealed record JobOutputRecordDto( @@ -164,6 +280,44 @@ public sealed record CreateFileDeliveryRequest( string DestinationPath, string? Sha256); +// ── S3 settings and agent delivery ──────────────────────────────────────── + +/// +/// GET/PUT /api/settings/s3. The secret key is never returned; a non-null +/// value on PUT replaces it, null leaves the stored secret untouched. +/// +public sealed record S3SettingsDto( + bool Enabled, + string? Endpoint, + string Region, + string? Bucket, + string? AccessKey, + string? SecretKey, + bool ForcePathStyle, + int PresignExpirySeconds, + bool SecretKeyIsSet, + bool AgentOffloadEnabled, + DateTimeOffset? LastTestUtc, + bool FromEnvironment); + +/// One step of the S3 connectivity test. +public sealed record S3TestStepDto(string Name, bool Ok, string? Detail); + +/// POST /api/settings/s3/test response. +public sealed record S3TestResultDto(bool Ok, IReadOnlyList Steps, long ElapsedMs); + +/// Where the agent installer package is currently served from. +public sealed record AgentPackageStatusDto( + bool Available, + string Source, + string? FileName, + long? SizeBytes, + string? Sha256, + DateTimeOffset? BuiltUtc, + string? Version, + bool OffloadEnabled, + bool OffloadUploaded); + /// POST /api/admin/bootstrap-tokens request body. public sealed record CreateBootstrapTokenRequest( int? ValidMinutes, diff --git a/src/Shared.Contracts/Messages/Payloads.cs b/src/Shared.Contracts/Messages/Payloads.cs index e3e6b4d..37cc33b 100644 --- a/src/Shared.Contracts/Messages/Payloads.cs +++ b/src/Shared.Contracts/Messages/Payloads.cs @@ -33,12 +33,21 @@ public static class AgentEventKinds public const string Ready = "ready"; } +/// +/// One resolved secret delivered with a job. The backend fetched the value +/// from the configured provider; the agent injects it into a case-insensitive +/// ordered dictionary (default variable $Secrets) and must never log it. +/// +public sealed record ScriptSecret(string Name, string Value); + /// /// Durable script execution command on agent.<clientId>.command.script. /// holds reusable function-module content run first in the /// same runspace (so the main keeps its param() block /// first). declares typed parameters and /// supplies their values (coerced by the agent). +/// are server-resolved values injected as a session +/// variable named (default Secrets). /// public sealed record ScriptCommandPayload( Guid JobId, @@ -48,7 +57,9 @@ public sealed record ScriptCommandPayload( int? TimeoutSeconds, string? Prelude = null, IReadOnlyList? Parameters = null, - IReadOnlyDictionary? Arguments = null); + IReadOnlyDictionary? Arguments = null, + string? SecretsVariableName = null, + IReadOnlyList? Secrets = null); /// Inventory refresh command on agent.<clientId>.command.inventory. public sealed record InventoryCommandPayload(string? Reason); diff --git a/src/Shared.Contracts/Models/InventoryReport.cs b/src/Shared.Contracts/Models/InventoryReport.cs index 4f1207c..b213070 100644 --- a/src/Shared.Contracts/Models/InventoryReport.cs +++ b/src/Shared.Contracts/Models/InventoryReport.cs @@ -48,13 +48,17 @@ public sealed record InventoryDisk( string? Model, string? SerialNumber, long SizeBytes, - string? BusType); + string? BusType, + int? Index = null); +/// ties the volume to its physical disk +/// (via Win32 partition associations); null when the relation is unknown. public sealed record InventoryVolume( string DriveLetter, string? FileSystem, long TotalSizeBytes, - long FreeSpaceBytes); + long FreeSpaceBytes, + int? DiskIndex = null); public sealed record InventoryNetworkAdapter( string? Description, diff --git a/src/Shared.Contracts/Models/ScriptParameter.cs b/src/Shared.Contracts/Models/ScriptParameter.cs index a8377dd..fbfad1d 100644 --- a/src/Shared.Contracts/Models/ScriptParameter.cs +++ b/src/Shared.Contracts/Models/ScriptParameter.cs @@ -20,11 +20,31 @@ public enum ScriptParameterType Hashtable, } +/// +/// String values expand on the target device in the background by default — +/// %TEMP%\out.log and $env:COMPUTERNAME resolve with the +/// device's environment, not the operator's. Opt a parameter out with +/// when the raw text itself is the value. +/// +public enum ValueExpansion +{ + /// + /// Default: [System.Environment]::ExpandEnvironmentVariables + /// (%VAR%) followed by $ExecutionContext.InvokeCommand.ExpandString + /// ($env:VAR, $(…)) in the job's runspace. + /// + Auto, + + /// The value is passed through exactly as typed. + Literal, +} + /// /// One declared parameter of a script. For , -/// applies; for , -/// and apply (hashtable keys carry -/// their own primitive type selection). +/// applies. Hashtable entries are typed per entry at +/// run time — each key and value carries its own primitive type, preserved as +/// native JSON and rebuilt by the agent. applies to +/// string values (scalars, string array elements, string hashtable values). /// public sealed record ScriptParameter( string Name, @@ -32,6 +52,5 @@ public sealed record ScriptParameter( bool Required = false, string? Description = null, PrimitiveType? ElementType = null, - PrimitiveType? KeyType = null, - PrimitiveType? ValueType = null, - JsonElement? DefaultValue = null); + JsonElement? DefaultValue = null, + ValueExpansion Expansion = ValueExpansion.Auto); diff --git a/src/Shared.Contracts/Models/SecretBinding.cs b/src/Shared.Contracts/Models/SecretBinding.cs new file mode 100644 index 0000000..ff796a9 --- /dev/null +++ b/src/Shared.Contracts/Models/SecretBinding.cs @@ -0,0 +1,16 @@ +namespace Shared.Contracts.Models; + +/// +/// Binds one entry of a script's secrets dictionary to a secret held by a +/// configured secrets provider. The backend resolves bindings at dispatch +/// time and sends only the values — agents never talk to the vault. +/// +/// Key inside the injected dictionary (e.g. $Secrets.ApiKey). +/// Configured secrets provider to fetch from. +/// Name of the secret at the provider. +/// Optional provider path/folder override (provider default when null). +public sealed record SecretBinding( + string Name, + Guid ProviderId, + string SecretName, + string? Path = null); diff --git a/src/Shared.Infrastructure/Constants/Branding.cs b/src/Shared.Infrastructure/Constants/Branding.cs index 0b5de4c..869e2a2 100644 --- a/src/Shared.Infrastructure/Constants/Branding.cs +++ b/src/Shared.Infrastructure/Constants/Branding.cs @@ -1,18 +1,13 @@ namespace Shared.Infrastructure.Constants; /// -/// The ONLY place product/company branding may appear in code. Branding is -/// allowed in UI text, executable names, service display names, MSI metadata, -/// registry paths and documentation — never in NATS subjects, API routes, -/// message types, headers or table names (those stay generic). +/// The ONLY place product branding may appear in code. Branding is allowed in +/// UI text, executable names, service display names, MSI metadata, registry +/// paths and documentation — never in NATS subjects, API routes, message +/// types, headers or table names (those stay generic). /// public static class Branding { - public const string CompanyName = "Grace Solution"; - - /// Registry/file-system safe company key (no spaces). - public const string CompanyKey = "GraceSolution"; - public const string ProductName = "ExecuteR"; /// Registry/file-system safe product key. diff --git a/src/WebUI/src/lib/api/client.ts b/src/WebUI/src/lib/api/client.ts index 6cc9341..6f81fcb 100644 --- a/src/WebUI/src/lib/api/client.ts +++ b/src/WebUI/src/lib/api/client.ts @@ -9,12 +9,29 @@ import type { GroupFieldDescriptor, GroupKind, GroupRuleSet, + GroupRunDto, JobDto, JobOutputRecordDto, + AgentPackageStatusDto, + AuthConfigDto, + AuthSettingsDto, + AuthTestResultDto, + S3SettingsDto, + S3TestResultDto, + SaveScheduleAssignmentBody, + SaveScheduleBody, + ScheduleAssignmentDto, + ScheduleDto, + SchedulePreviewDto, ScriptDto, + ServerInfoDto, ScriptParameter, ScriptTriggerDto, ScriptTriggerType, + SecretBinding, + SecretsProviderDto, + SecretsProvidersResponse, + SecretsTestResultDto, SessionResponse } from './types'; @@ -24,6 +41,14 @@ interface SaveScriptBody { content: string; parameters?: ScriptParameter[]; functionModuleIds?: string[]; + secretBindings?: SecretBinding[]; + secretsVariableName?: string; +} + +interface SaveSecretsProviderBody { + name: string; + kind: string; + config: Record; } interface SaveGroupBody { @@ -164,6 +189,43 @@ export const api = { method: 'POST', body: JSON.stringify({ clientId, scriptId, arguments: args }) }), + createGroupJob: (groupId: string, scriptId: string, args?: Record) => + request('/api/jobs', { + method: 'POST', + body: JSON.stringify({ groupId, scriptId, arguments: args }) + }), + + // Schedules (cadence objects) + assignments (script honors schedule) + schedules: () => request('/api/schedules'), + createSchedule: (body: SaveScheduleBody) => + request('/api/schedules', { method: 'POST', body: JSON.stringify(body) }), + updateSchedule: (id: string, body: SaveScheduleBody) => + request(`/api/schedules/${id}`, { method: 'PUT', body: JSON.stringify(body) }), + deleteSchedule: (id: string) => request(`/api/schedules/${id}`, { method: 'DELETE' }), + previewSchedule: (cronExpression: string, timeZoneId?: string) => + request('/api/schedules/preview', { + method: 'POST', + body: JSON.stringify({ cronExpression, timeZoneId }) + }), + scheduleAssignments: (scriptId?: string, scheduleId?: string) => { + const params = new URLSearchParams(); + if (scriptId) params.set('scriptId', scriptId); + if (scheduleId) params.set('scheduleId', scheduleId); + const qs = params.size > 0 ? `?${params}` : ''; + return request(`/api/schedule-assignments${qs}`); + }, + createScheduleAssignment: (body: SaveScheduleAssignmentBody) => + request('/api/schedule-assignments', { + method: 'POST', + body: JSON.stringify(body) + }), + updateScheduleAssignment: (id: string, body: SaveScheduleAssignmentBody) => + request(`/api/schedule-assignments/${id}`, { + method: 'PUT', + body: JSON.stringify(body) + }), + deleteScheduleAssignment: (id: string) => + request(`/api/schedule-assignments/${id}`, { method: 'DELETE' }), // Groups groups: () => request('/api/groups'), @@ -209,6 +271,59 @@ export const api = { body: JSON.stringify({ nkeyPublic, browserSessionId }) }), + // Settings: authentication + authConfig: () => request('/api/auth/config'), + authSettings: () => request('/api/settings/auth'), + saveAuthSettings: (body: AuthSettingsDto) => + request('/api/settings/auth', { method: 'PUT', body: JSON.stringify(body) }), + testAuthSettings: (body: AuthSettingsDto) => + request('/api/settings/auth/test', { method: 'POST', body: JSON.stringify(body) }), + + // Settings: S3 + agent package delivery + s3Settings: () => request('/api/settings/s3'), + saveS3Settings: (body: S3SettingsDto) => + request('/api/settings/s3', { method: 'PUT', body: JSON.stringify(body) }), + testS3Settings: (body: S3SettingsDto) => + request('/api/settings/s3/test', { method: 'POST', body: JSON.stringify(body) }), + agentPackage: (type: 'msi' | 'zip' = 'msi') => + request(`/api/settings/agent-package?type=${type}`), + offloadAgentPackage: (type: 'msi' | 'zip' = 'msi') => + request<{ message: string; status: AgentPackageStatusDto }>( + `/api/settings/agent-package/offload?type=${type}`, + { method: 'POST' } + ), + + // Secrets providers + secretsProviders: () => request('/api/secrets/providers'), + createSecretsProvider: (body: SaveSecretsProviderBody) => + request('/api/secrets/providers', { + method: 'POST', + body: JSON.stringify(body) + }), + updateSecretsProvider: (id: string, body: SaveSecretsProviderBody) => + request(`/api/secrets/providers/${id}`, { + method: 'PUT', + body: JSON.stringify(body) + }), + deleteSecretsProvider: (id: string) => + request(`/api/secrets/providers/${id}`, { method: 'DELETE' }), + testSecretsProvider: (body: SaveSecretsProviderBody & { id?: string }) => + request('/api/secrets/providers/test', { + method: 'POST', + body: JSON.stringify(body) + }), + secretNames: (providerId: string, path?: string) => + request( + `/api/secrets/providers/${providerId}/secret-names${path ? `?path=${encodeURIComponent(path)}` : ''}` + ), + secretFolders: (providerId: string, path?: string) => + request( + `/api/secrets/providers/${providerId}/folders${path ? `?path=${encodeURIComponent(path)}` : ''}` + ), + + // Server info (public base URL for generated commands) + serverInfo: () => request('/api/settings/server'), + // Admin bootstrapTokens: () => request('/api/admin/bootstrap-tokens'), createBootstrapToken: (body: { validMinutes?: number; maxUses?: number; note?: string }) => diff --git a/src/WebUI/src/lib/api/types.ts b/src/WebUI/src/lib/api/types.ts index e2b29d8..9be2cc5 100644 --- a/src/WebUI/src/lib/api/types.ts +++ b/src/WebUI/src/lib/api/types.ts @@ -35,6 +35,8 @@ export interface DeviceDto { lastSeenUtc?: string; enrolledUtc: string; tags?: string[]; + /** Public IP the agent was last seen from (trusted headers at enroll/refresh). */ + publicIp?: string; } // ── Device grouping ─────────────────────────────────────────────────── @@ -103,6 +105,82 @@ export interface DeviceGroupRefDto { kind: GroupKind; } +export interface AuthConfigDto { + oidcAvailable: boolean; + showLocalFields: boolean; + autoRedirect: boolean; + providerName?: string; +} + +export type LoginMode = 'LocalOnly' | 'Both' | 'OidcOnly' | 'OidcAutoRedirect'; + +export interface AuthSettingsDto { + oidcEnabled: boolean; + authority?: string; + clientId?: string; + clientSecret?: string | null; + /** Friendly IdP name shown on the sign-in button (e.g. "Authentik", "Entra ID"). */ + providerName?: string; + scopes: string; + nameClaim?: string; + roleClaim?: string; + adminRole?: string; + operatorRole?: string; + viewerRole?: string; + defaultRole: UserRole; + requireMappedRole: boolean; + loginMode: LoginMode; + clientSecretIsSet: boolean; + forcedLocalByEnvironment: boolean; + callbackPath: string; + redirectUri: string; +} + +export interface AuthTestResultDto { + ok: boolean; + steps: S3TestStepDto[]; +} + +export interface S3SettingsDto { + enabled: boolean; + endpoint?: string; + region: string; + bucket?: string; + accessKey?: string; + secretKey?: string | null; + forcePathStyle: boolean; + presignExpirySeconds: number; + secretKeyIsSet: boolean; + agentOffloadEnabled: boolean; + lastTestUtc?: string; + fromEnvironment: boolean; +} + +export interface S3TestStepDto { + name: string; + ok: boolean; + detail?: string; +} + +export interface S3TestResultDto { + ok: boolean; + steps: S3TestStepDto[]; + elapsedMs: number; +} + +export interface AgentPackageStatusDto { + available: boolean; + /** image | volume | s3 | none */ + source: string; + fileName?: string; + sizeBytes?: number; + sha256?: string; + builtUtc?: string; + version?: string; + offloadEnabled: boolean; + offloadUploaded: boolean; +} + export type ScriptTriggerType = 'onRegistration' | 'onAgentReady'; export interface ScriptTriggerDto { @@ -147,12 +225,19 @@ export interface InventoryReport { speedMhz?: number; }[]; totalPhysicalMemoryBytes: number; - disks: { model?: string; serialNumber?: string; sizeBytes: number; busType?: string }[]; + disks: { + model?: string; + serialNumber?: string; + sizeBytes: number; + busType?: string; + index?: number; + }[]; volumes: { driveLetter: string; fileSystem?: string; totalSizeBytes: number; freeSpaceBytes: number; + diskIndex?: number; }[]; network: { description?: string; @@ -175,15 +260,99 @@ export interface DeviceDetailDto { export type PrimitiveType = 'string' | 'number' | 'boolean'; export type ScriptParameterType = 'string' | 'number' | 'boolean' | 'array' | 'hashtable'; +/** + * String values expand on the target device in the background by default + * (%VAR%, $env:VAR, $()); 'literal' passes the value through exactly as typed. + */ +export type ValueExpansion = 'auto' | 'literal'; + export interface ScriptParameter { name: string; type: ScriptParameterType; required?: boolean; description?: string; elementType?: PrimitiveType; - keyType?: PrimitiveType; - valueType?: PrimitiveType; defaultValue?: unknown; + expansion?: ValueExpansion; +} + +/** Result of a group fan-out run: one job per eligible member. */ +export interface GroupRunDto { + jobs: JobDto[]; + skippedOrphaned: string[]; +} + +/** A reusable cadence object; scripts honor it through assignments. */ +export interface ScheduleDto { + id: string; + name: string; + cronExpression?: string; + runOnceUtc?: string; + timeZoneId: string; + enabled: boolean; + nextRunUtc?: string; + lastRunUtc?: string; + updatedUtc: string; + updatedBy?: string; + assignments: ScheduleAssignmentDto[]; +} + +export interface SaveScheduleBody { + name: string; + cronExpression?: string; + runOnceUtc?: string; + timeZoneId?: string; + enabled: boolean; +} + +/** One script honoring a schedule against one device or group. */ +export interface ScheduleAssignmentDto { + id: string; + scheduleId: string; + scheduleName?: string; + cronExpression?: string; + runOnceUtc?: string; + timeZoneId: string; + scheduleEnabled: boolean; + nextRunUtc?: string; + scriptId: string; + scriptName?: string; + clientId?: string; + targetHostname?: string; + groupId?: string; + groupName?: string; + enabled: boolean; + lastRunUtc?: string; + lastResult?: string; +} + +export interface SaveScheduleAssignmentBody { + scheduleId: string; + scriptId: string; + clientId?: string; + groupId?: string; + arguments?: Record; + enabled: boolean; +} + +export interface SchedulePreviewDto { + valid: boolean; + error?: string; + nextRunsUtc: string[]; +} + +export interface ServerInfoDto { + baseUrl: string; + fromEnvironment: boolean; +} + +/** One entry of a script's secrets dictionary, resolved server-side at dispatch. */ +export interface SecretBinding { + /** Key inside the injected dictionary (e.g. $Secrets.ApiKey). */ + name: string; + providerId: string; + secretName: string; + path?: string; } export interface ScriptDto { @@ -198,6 +367,38 @@ export interface ScriptDto { updatedUtc: string; createdBy?: string; updatedBy?: string; + secretBindings?: SecretBinding[]; + secretsVariableName?: string; +} + +// ── Secrets providers ───────────────────────────────────────────────── + +export interface SecretsProviderDto { + id: string; + name: string; + kind: string; + /** Driver-specific non-secret settings. */ + config: Record; + /** Secret config fields that currently hold a value. */ + secretFieldsSet: string[]; + updatedUtc: string; + updatedBy?: string; +} + +export interface SecretsProviderKindDto { + kind: string; + displayName: string; + fields: { name: string; label: string; secret: boolean; placeholder?: string }[]; +} + +export interface SecretsProvidersResponse { + providers: SecretsProviderDto[]; + kinds: SecretsProviderKindDto[]; +} + +export interface SecretsTestResultDto { + ok: boolean; + steps: S3TestStepDto[]; } export interface FunctionModuleDto { diff --git a/src/WebUI/src/lib/components/AuthSettings.svelte b/src/WebUI/src/lib/components/AuthSettings.svelte new file mode 100644 index 0000000..8301f94 --- /dev/null +++ b/src/WebUI/src/lib/components/AuthSettings.svelte @@ -0,0 +1,379 @@ + + +
+

Authentication

+ + {#if settings?.forcedLocalByEnvironment} + + {/if} + + {#if !settings} +
loading…
+ {:else} +
+ Sign-in page +
+ {#each modes as mode (mode.value)} + + {/each} +
+ {#if ssoModeChosen && !settings.oidcEnabled} +

Enable and configure OIDC below, or saving will be rejected.

+ {/if} +
+ + + +
+ + + + + + + +
+ +
+ Redirect URI to register at your provider: + {settings.redirectUri} + +
+

+ This path is fixed. It must match the provider registration exactly, and letting it drift is + a common cause of sign-in failures with no clear error. +

+ +

Group to role mapping

+

+ Values from the group/role claim above. The first match wins, checked Admin → Operator → + Viewer. +

+
+ + + + +
+ + +
+ + + {#if statusText}{statusText}{/if} +
+ + {#if test} +
    + {#each test.steps as step (step.name)} +
  • + {step.ok ? '✔' : '✕'} + {step.name} + {step.detail ?? ''} +
  • + {/each} +
+ {/if} + + + {/if} +
+ + diff --git a/src/WebUI/src/lib/components/CopyChip.svelte b/src/WebUI/src/lib/components/CopyChip.svelte new file mode 100644 index 0000000..037f16d --- /dev/null +++ b/src/WebUI/src/lib/components/CopyChip.svelte @@ -0,0 +1,65 @@ + + + + + diff --git a/src/WebUI/src/lib/components/ParameterInputs.svelte b/src/WebUI/src/lib/components/ParameterInputs.svelte index d9e1205..1548082 100644 --- a/src/WebUI/src/lib/components/ParameterInputs.svelte +++ b/src/WebUI/src/lib/components/ParameterInputs.svelte @@ -3,17 +3,24 @@ let { parameters }: { parameters: ScriptParameter[] } = $props(); - // Local editable state keyed by parameter name. - type HashEntry = { key: string; value: string }; + // Local editable state keyed by parameter name. Hashtable entries carry + // their own key and value primitive types. + type HashEntry = { keyType: PrimitiveType; key: string; valueType: PrimitiveType; value: string }; let scalars = $state>({}); let bools = $state>({}); let arrays = $state>({}); let hashes = $state>({}); + const primitives: PrimitiveType[] = ['string', 'number', 'boolean']; + + function newEntry(): HashEntry { + return { keyType: 'string', key: '', valueType: 'string', value: '' }; + } + $effect(() => { for (const p of parameters) { if (p.type === 'array' && !(p.name in arrays)) arrays[p.name] = ['']; - if (p.type === 'hashtable' && !(p.name in hashes)) hashes[p.name] = [{ key: '', value: '' }]; + if (p.type === 'hashtable' && !(p.name in hashes)) hashes[p.name] = [newEntry()]; } }); @@ -38,9 +45,10 @@ .filter((v) => v !== '') .map((v) => coerce(p.elementType, v)); else if (p.type === 'hashtable') + // Native JSON types carry each entry's chosen primitives to the agent. args[p.name] = (hashes[p.name] ?? []) .filter((e) => e.key !== '') - .map((e) => ({ key: coerce(p.keyType, e.key), value: coerce(p.valueType, e.value) })); + .map((e) => ({ key: coerce(e.keyType, e.key), value: coerce(e.valueType, e.value) })); } return args; } @@ -52,7 +60,7 @@ arrays[name] = (arrays[name] ?? []).filter((_, idx) => idx !== i); } function addHashRow(name: string) { - hashes[name] = [...(hashes[name] ?? []), { key: '', value: '' }]; + hashes[name] = [...(hashes[name] ?? []), newEntry()]; } function removeHashRow(name: string, i: number) { hashes[name] = (hashes[name] ?? []).filter((_, idx) => idx !== i); @@ -66,7 +74,12 @@ {#if p.description}
{p.description}
{/if} @@ -101,24 +114,54 @@ {:else if p.type === 'hashtable'}
{#each hashes[p.name] ?? [] as _, i (i)} -
- - {#if p.valueType === 'boolean'} - + {#each primitives as prim (prim)} + + {/each} + + {#if hashes[p.name][i].keyType === 'boolean'} + {:else} + {/if} + = + + {#if hashes[p.name][i].valueType === 'boolean'} + + {:else} + {/if} @@ -164,6 +207,16 @@ color: var(--danger); } + .literal-tag { + font-family: var(--font-mono); + font-size: 10px; + color: var(--text-muted); + background: var(--surface-muted); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + padding: 1px 5px; + } + .desc { font-size: 11px; } @@ -192,6 +245,22 @@ flex: 1; } + .hrow { + display: grid; + grid-template-columns: 74px minmax(60px, 1fr) 12px 74px minmax(60px, 1fr) 26px; + gap: 4px; + align-items: center; + } + + .hrow .ptype { + font-size: 11px; + padding: 4px 4px; + } + + .eq { + text-align: center; + } + .tiny { padding: 3px 8px; font-size: 11px; diff --git a/src/WebUI/src/lib/components/ParameterSchemaEditor.svelte b/src/WebUI/src/lib/components/ParameterSchemaEditor.svelte index 4a40199..c71869e 100644 --- a/src/WebUI/src/lib/components/ParameterSchemaEditor.svelte +++ b/src/WebUI/src/lib/components/ParameterSchemaEditor.svelte @@ -6,8 +6,17 @@ const paramTypes: ScriptParameterType[] = ['string', 'number', 'boolean', 'array', 'hashtable']; const primitives: PrimitiveType[] = ['string', 'number', 'boolean']; + /** Expansion only applies where string values can occur. */ + function canExpand(p: ScriptParameter): boolean { + return ( + p.type === 'string' || + p.type === 'hashtable' || + (p.type === 'array' && p.elementType !== 'number' && p.elementType !== 'boolean') + ); + } + function add() { - parameters = [...parameters, { name: '', type: 'string', required: false }]; + parameters = [...parameters, { name: '', type: 'string', required: false, expansion: 'auto' }]; } function remove(index: number) { @@ -16,24 +25,33 @@
-
-

Parameters

- -
- {#if parameters.length === 0} -

No parameters. Add one to prompt for a typed value at run time.

+

No parameters yet. Each parameter becomes a typed input when the script runs.

{:else} -
- {#each parameters as param, i (i)} -
- - +
+ Name + Type + Items + Description + + Literal + + Req. + +
+ {#each parameters as param, i (i)} +
+ + +
{#if param.type === 'array'} {:else if param.type === 'hashtable'} - - + + typed per entry + + {:else} + — {/if} - - -
- {/each} -
+ + + {#if canExpand(param)} + + {:else} + — + {/if} + + +
+ {/each} {/if} + +
+ +
diff --git a/src/WebUI/src/lib/components/S3Settings.svelte b/src/WebUI/src/lib/components/S3Settings.svelte new file mode 100644 index 0000000..b36c03c --- /dev/null +++ b/src/WebUI/src/lib/components/S3Settings.svelte @@ -0,0 +1,347 @@ + + +
+

Object storage (S3)

+

+ Used for pushing files to devices and, optionally, for serving the agent installer. Any + S3-compatible store works — AWS S3, MinIO, Backblaze B2. + {#if settings?.fromEnvironment} +
Environment variables provide the current defaults; saving here overrides them. + {/if} +

+ + {#if !settings} +
loading…
+ {:else} +
+ + + + + + + + +
+ +
+ + + {#if statusText}{statusText}{/if} + {#if settings.lastTestUtc} + Last successful test {new Date(settings.lastTestUtc).toLocaleString()} + {/if} +
+ + {#if test} +
    + {#each test.steps as step (step.name)} +
  • + {step.ok ? '✔' : '✕'} + {step.name} + {step.detail ?? ''} +
  • + {/each} +
+ {/if} + {/if} +
+ +
+

Agent installer delivery

+

+ CI bakes the built installer into the backend image, so the URL install command works without + seeding anything. With S3 configured you can optionally offload it, and installs are redirected + to a presigned URL instead of streaming through the control plane. +

+ + {#if !agent} +
loading…
+ {:else} +
+
Status
+
+ {#if agent.available} + Available + {:else} + Missing + {/if} + {sourceLabel[agent.source] ?? agent.source} +
+
File
+
{agent.fileName ?? '—'}{sizeMb ? ` · ${sizeMb} MB` : ''}
+
Version
+
{agent.version ?? '—'}
+
SHA-256
+
{agent.sha256 ?? '—'}
+
+ + {#if !agent.available} +

+ No installer present. It ships in images built by CI; for a local build run + scripts/Package-Agent.ps1 and mount the output at /data/agent. +

+ {/if} + +
+ + + {#if agent.offloadUploaded}Uploaded{/if} +
+

+ Enabling the toggle takes effect after Save. Uploads are skipped when the same build is + already in the bucket. +

+ {/if} +
+ + diff --git a/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte b/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte new file mode 100644 index 0000000..71d798a --- /dev/null +++ b/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte @@ -0,0 +1,291 @@ + + + + +
+ + + {#if freq === 'minutes' || freq === 'hours'} + + {:else if freq === 'daily' || freq === 'weekly' || freq === 'monthly'} + + {#if freq === 'weekly'} +
+ {#each allDays as day (day)} + + {/each} +
+ {:else if freq === 'monthly'} + + {/if} + {:else if freq === 'once'} + + {:else if freq === 'cron'} + + {/if} + + {#if freq !== 'once'} + + {/if} + +
+ {description} + {#if preview && freq !== 'once'} + {#if preview.valid} + + Next: {preview.nextRunsUtc + .slice(0, 3) + .map((t) => new Date(t).toLocaleString()) + .join(' · ')} + + {:else} + {preview.error} + {/if} + {/if} +
+
+ + diff --git a/src/WebUI/src/lib/components/SchedulesCard.svelte b/src/WebUI/src/lib/components/SchedulesCard.svelte new file mode 100644 index 0000000..1c41a53 --- /dev/null +++ b/src/WebUI/src/lib/components/SchedulesCard.svelte @@ -0,0 +1,277 @@ + + +
+
+

Schedules

+ {#if !adding} + + {/if} +
+ + {#if assignments.length === 0 && !adding} +

+ No schedules attached. Attach a cadence from Schedules to run this + script automatically. +

+ {/if} + + {#each assignments as assignment (assignment.id)} +
+
+ {assignment.scheduleName ?? '?'} + {scheduleCadence(assignment)} · {targetLabel(assignment)} + + {#if !assignment.scheduleEnabled} + Schedule paused + {:else if assignment.enabled && assignment.nextRunUtc} + Next: {new Date(assignment.nextRunUtc).toLocaleString()} + {:else if !assignment.enabled} + Disabled here + {/if} + {#if assignment.lastResult} + · Last: {assignment.lastResult} + {/if} + +
+
+ + +
+
+ {/each} + + {#if adding} +
+ {#if allSchedules.length === 0} +

+ No schedules defined yet — create one on the + Schedules page first. +

+ {:else} + + + + +

Current run values are stored and used for every firing.

+ +
+ + +
+ {/if} + {#if errorText}

{errorText}

{/if} +
+ {/if} +
+ + diff --git a/src/WebUI/src/lib/components/SecretBindingsEditor.svelte b/src/WebUI/src/lib/components/SecretBindingsEditor.svelte new file mode 100644 index 0000000..849dd7f --- /dev/null +++ b/src/WebUI/src/lib/components/SecretBindingsEditor.svelte @@ -0,0 +1,310 @@ + + +
+ {#if providers.length === 0} +

+ No secrets providers configured. Add one under Settings → Secrets providers first. +

+ {:else} +
+ +

+ The server fetches each value at run time and injects them, in order, as a + case-insensitive dictionary: use ${effectiveVar}.{bindings[0]?.name || 'SecretName'} + anywhere in the script. Devices never contact the vault. +

+
+ + {#if bindings.length > 0} +
+ Key (${effectiveVar}.…) + Provider + Path + Secret + +
+ {#each bindings as binding, i (i)} + {@const path = effectivePath(binding)} + {@const key = cacheKey(binding.providerId, path)} + {@const root = defaultPath(binding.providerId)} + {@const parent = parentOf(path, root)} + {@const listed = names[key]} + {@const failed = key in loadErrors} +
+ + + + + + + {#if manual[i] || failed || (listed && listed.length === 0)} + + {#if listed && listed.length > 0} + + {/if} + {:else} + + + {/if} + + + +
+ {#if failed} +

+ Listing failed ({loadErrors[key]}) — type the path and secret name manually. +

+ {/if} + {/each} + {/if} + +
+ +
+ {/if} +
+ + diff --git a/src/WebUI/src/lib/components/SecretsProviders.svelte b/src/WebUI/src/lib/components/SecretsProviders.svelte new file mode 100644 index 0000000..997aeef --- /dev/null +++ b/src/WebUI/src/lib/components/SecretsProviders.svelte @@ -0,0 +1,364 @@ + + +
+
+

Secrets providers

+ {#if !formOpen} + + {/if} +
+

+ External vaults scripts can pull secrets from. The server fetches values at dispatch time and + injects them as a dictionary variable (default $Secrets) — devices and browsers + never talk to the vault, and connection details are encrypted at rest. +

+ + {#if providers.length === 0 && !formOpen} +

No providers configured.

+ {:else if providers.length > 0} +
+ + + + + + + + + + + + {#each providers as provider (provider.id)} + + + + + + + + {#if rowTests[provider.id]} + {@const rowTest = rowTests[provider.id]} + + + + {/if} + {/each} + +
NameKindCredentialsUpdated
{provider.name} + {kinds.find((k) => k.kind === provider.kind)?.displayName ?? provider.kind} + + {#if provider.secretFieldsSet.length > 0} + stored + {:else} + missing + {/if} + {new Date(provider.updatedUtc).toLocaleString()} + + + +
+
    + {#each rowTest?.steps ?? [] as step (step.name)} +
  • + {step.ok ? '✔' : '✕'} + {step.name} + {step.detail ?? ''} +
  • + {/each} +
+
+
+ {/if} + + {#if formOpen} +
+

{editing ? `Edit “${editing.name}”` : 'New provider'}

+
+ + + {#each kindDef?.fields ?? [] as field (field.name)} + + {/each} +
+ +
+ + + + {#if statusText}{statusText}{/if} +
+ + {#if test} +
    + {#each test.steps as step (step.name)} +
  • + {step.ok ? '✔' : '✕'} + {step.name} + {step.detail ?? ''} +
  • + {/each} +
+ {/if} +
+ {/if} +
+ + diff --git a/src/WebUI/src/lib/schedule/cron-describe.ts b/src/WebUI/src/lib/schedule/cron-describe.ts new file mode 100644 index 0000000..acf201b --- /dev/null +++ b/src/WebUI/src/lib/schedule/cron-describe.ts @@ -0,0 +1,99 @@ +// Best-effort plain-English description of a 5-field cron expression. +// Covers everything the schedule builder generates plus common hand-written +// shapes; anything else returns null and the UI falls back to the raw cron +// (the server-computed next-run preview stays the ground truth either way). + +const dayNames: Record = { + '0': 'Sun', + '1': 'Mon', + '2': 'Tue', + '3': 'Wed', + '4': 'Thu', + '5': 'Fri', + '6': 'Sat', + '7': 'Sun', + SUN: 'Sun', + MON: 'Mon', + TUE: 'Tue', + WED: 'Wed', + THU: 'Thu', + FRI: 'Fri', + SAT: 'Sat' +}; + +function time(minute: string, hour: string): string | null { + const m = Number(minute); + const h = Number(hour); + if (!Number.isInteger(m) || !Number.isInteger(h) || m < 0 || m > 59 || h < 0 || h > 23) { + return null; + } + return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`; +} + +function days(field: string): string | null { + const parts = field.split(',').map((d) => dayNames[d.trim().toUpperCase()]); + return parts.every(Boolean) ? parts.join(', ') : null; +} + +export function describeCron(expression: string): string | null { + const fields = expression.trim().split(/\s+/); + if (fields.length !== 5) return null; + const [minute, hour, dayOfMonth, month, dayOfWeek] = fields; + + if (month !== '*') return null; + + // */N * * * * — every N minutes + let match = /^\*\/(\d+)$/.exec(minute); + if (match && hour === '*' && dayOfMonth === '*' && dayOfWeek === '*') { + return match[1] === '1' ? 'Every minute' : `Every ${match[1]} minutes`; + } + + // M */N * * * — every N hours at minute M + match = /^\*\/(\d+)$/.exec(hour); + if (match && dayOfMonth === '*' && dayOfWeek === '*' && /^\d+$/.test(minute)) { + const at = minute === '0' ? '' : ` at :${minute.padStart(2, '0')}`; + return match[1] === '1' ? `Hourly${at}` : `Every ${match[1]} hours${at}`; + } + + // M * * * * — hourly at minute M + if (/^\d+$/.test(minute) && hour === '*' && dayOfMonth === '*' && dayOfWeek === '*') { + return minute === '0' ? 'Hourly' : `Hourly at :${minute.padStart(2, '0')}`; + } + + const at = time(minute, hour); + if (!at) return null; + + // M H * * * — daily + if (dayOfMonth === '*' && dayOfWeek === '*') { + return `Daily at ${at}`; + } + + // M H * * DAYS — weekly + if (dayOfMonth === '*' && dayOfWeek !== '*') { + const named = days(dayOfWeek); + return named ? `Weekly on ${named} at ${at}` : null; + } + + // M H D * * — monthly + if (dayOfWeek === '*' && /^\d+$/.test(dayOfMonth)) { + return `Monthly on day ${dayOfMonth} at ${at}`; + } + + return null; +} + +/** One-line cadence for a stored schedule or assignment (falls back to the raw cron). */ +export function scheduleCadence(schedule: { + cronExpression?: string; + runOnceUtc?: string; + timeZoneId: string; +}): string { + if (schedule.runOnceUtc) { + return `Once at ${new Date(schedule.runOnceUtc).toLocaleString()}`; + } + if (schedule.cronExpression) { + const text = describeCron(schedule.cronExpression) ?? schedule.cronExpression; + return schedule.timeZoneId === 'UTC' ? text : `${text} (${schedule.timeZoneId})`; + } + return '—'; +} diff --git a/src/WebUI/src/routes/+layout.svelte b/src/WebUI/src/routes/+layout.svelte index c20d8e2..84e303d 100644 --- a/src/WebUI/src/routes/+layout.svelte +++ b/src/WebUI/src/routes/+layout.svelte @@ -19,6 +19,7 @@ { href: '/scripts', label: 'Scripts', icon: '⌘' }, { href: '/functions', label: 'Functions', icon: 'ƒ' }, { href: '/jobs', label: 'Jobs', icon: '≡' }, + { href: '/schedules', label: 'Schedules', icon: '◷' }, { href: '/settings', label: 'Settings', icon: '⚙' } ]; diff --git a/src/WebUI/src/routes/devices/[clientId]/+page.svelte b/src/WebUI/src/routes/devices/[clientId]/+page.svelte index 14a93be..e230610 100644 --- a/src/WebUI/src/routes/devices/[clientId]/+page.svelte +++ b/src/WebUI/src/routes/devices/[clientId]/+page.svelte @@ -9,6 +9,7 @@ import JobStateBadge from '$lib/components/JobStateBadge.svelte'; import RelativeTime from '$lib/components/RelativeTime.svelte'; import EmptyState from '$lib/components/EmptyState.svelte'; + import CopyChip from '$lib/components/CopyChip.svelte'; const clientId = $derived(page.params.clientId!); @@ -20,7 +21,19 @@ let actionMessage = $state(''); const device = $derived(detail?.device); + // The public IP is operationally sensitive-ish; keep it masked until asked. + let showPublicIp = $state(false); const inventory = $derived(detail?.inventory); + // Volumes the partition-association walk could not tie to a disk. + const unmappedVolumes = $derived( + inventory + ? inventory.volumes.filter( + (v) => + v.diskIndex == null || + !inventory.disks.some((d, i) => (d.index ?? i) === v.diskIndex) + ) + : [] + ); const online = $derived(device?.status === 'online'); async function refresh() { @@ -237,6 +250,28 @@
IP addresses
{device.ipAddresses.join(', ') || '—'}
+
Public IP
+
+ {#if !device.publicIp} + — + {:else if showPublicIp} + + + + + {:else} + + •••.•••.•••.••• + + + {/if} +
Inventory updated
@@ -281,40 +316,71 @@

Storage

-
- - - - - - {#each inventory.disks as disk, i (i)} - - - - - - + {#each inventory.disks as disk, i (i)} + {@const diskIndex = disk.index ?? i} + {@const diskVolumes = inventory.volumes.filter((v) => v.diskIndex === diskIndex)} +
+
+ + 🖴 + {disk.model ?? `Disk ${diskIndex}`} + + + Disk {diskIndex} · {disk.busType ?? '?'} · {formatBytes(disk.sizeBytes)} + + {#if disk.serialNumber} + + {/if} +
+ {#if diskVolumes.length === 0} +

No mapped volumes.

+ {:else} +
+ {#each diskVolumes as vol (vol.driveLetter)} + {@const used = vol.totalSizeBytes - vol.freeSpaceBytes} + {@const pct = vol.totalSizeBytes > 0 ? Math.round((used / vol.totalSizeBytes) * 100) : 0} +
+
+ {vol.driveLetter} + {vol.fileSystem ?? '—'} + + {formatBytes(vol.freeSpaceBytes)} free of {formatBytes(vol.totalSizeBytes)} + +
+
+
= 85} style="width: {pct}%">
+
+
+ {/each} +
+ {/if} +
+ {/each} + {#if unmappedVolumes.length > 0} +
+
+ Volumes without a disk mapping +
+
+ {#each unmappedVolumes as vol (vol.driveLetter)} + {@const used = vol.totalSizeBytes - vol.freeSpaceBytes} + {@const pct = vol.totalSizeBytes > 0 ? Math.round((used / vol.totalSizeBytes) * 100) : 0} +
+
+ {vol.driveLetter} + {vol.fileSystem ?? '—'} + + {formatBytes(vol.freeSpaceBytes)} free of {formatBytes(vol.totalSizeBytes)} + +
+
+
= 85} style="width: {pct}%">
+
+
{/each} -
-
DiskSerialBusSize
{disk.model ?? '—'}{disk.serialNumber ?? '—'}{disk.busType ?? '—'}{formatBytes(disk.sizeBytes)}
-
-
- - - - - - {#each inventory.volumes as vol (vol.driveLetter)} - - - - - - - {/each} - -
VolumeFile systemSizeFree
{vol.driveLetter}{vol.fileSystem ?? '—'}{formatBytes(vol.totalSizeBytes)}{formatBytes(vol.freeSpaceBytes)}
-
+
+
+ {/if}
{/if} @@ -326,18 +392,22 @@ {#each inventory.network as adapter, i (i)}

{adapter.description ?? `Adapter ${i + 1}`}

-
-
MAC
-
{adapter.macAddress ?? '—'}
-
IPv4
-
{adapter.ipv4Addresses.join(', ') || '—'}
-
IPv6
-
{adapter.ipv6Addresses.join(', ') || '—'}
-
Gateways
-
{adapter.gateways.join(', ') || '—'}
-
DNS
-
{adapter.dnsServers.join(', ') || '—'}
-
+
+ {#each [{ label: 'MAC', values: adapter.macAddress ? [adapter.macAddress] : [] }, { label: 'IPv4', values: adapter.ipv4Addresses }, { label: 'IPv6', values: adapter.ipv6Addresses }, { label: 'Gateways', values: adapter.gateways }, { label: 'DNS', values: adapter.dnsServers }] as row (row.label)} +
+ {row.label} +
+ {#if row.values.length === 0} + — + {:else} + {#each row.values as value (value)} + + {/each} + {/if} +
+
+ {/each} +
{/each} @@ -488,6 +558,114 @@ gap: var(--space-4); } + .public-ip { + display: inline-flex; + align-items: center; + gap: var(--space-2); + } + + .tiny { + padding: 3px 8px; + font-size: 11px; + } + + .disk { + border: 1px solid var(--border); + border-radius: var(--radius-sm); + padding: var(--space-3); + margin-top: var(--space-3); + } + + .disk-head { + display: flex; + align-items: center; + gap: var(--space-3); + flex-wrap: wrap; + } + + .disk-name { + font-weight: 600; + font-size: 13.5px; + display: flex; + align-items: center; + gap: 6px; + } + + .disk-glyph { + color: var(--text-muted); + } + + .volumes { + margin-top: var(--space-3); + display: flex; + flex-direction: column; + gap: var(--space-3); + padding-left: var(--space-4); + border-left: 2px solid var(--border); + } + + .vol-line { + display: flex; + align-items: baseline; + gap: var(--space-2); + margin-bottom: 4px; + } + + .vol-letter { + font-weight: 600; + } + + .vol-free { + margin-left: auto; + color: var(--text-muted); + } + + .vol-track { + height: 8px; + border-radius: 999px; + background: var(--surface-muted); + overflow: hidden; + } + + .vol-fill { + height: 100%; + border-radius: 999px; + background: var(--accent); + } + + .vol-fill.hot { + background: var(--danger); + } + + .vol-note { + margin-top: var(--space-2); + } + + .net-rows { + display: flex; + flex-direction: column; + gap: var(--space-2); + margin-top: var(--space-3); + } + + .net-row { + display: grid; + grid-template-columns: 76px 1fr; + gap: var(--space-2); + align-items: baseline; + } + + .net-label { + font-size: 12px; + } + + .net-values { + display: flex; + flex-wrap: wrap; + gap: 4px; + min-width: 0; + } + .section { padding: var(--space-4); } diff --git a/src/WebUI/src/routes/groups/+page.svelte b/src/WebUI/src/routes/groups/+page.svelte index 669b2b6..9da0b62 100644 --- a/src/WebUI/src/routes/groups/+page.svelte +++ b/src/WebUI/src/routes/groups/+page.svelte @@ -242,7 +242,12 @@ {/if}
-

Script triggers

+
+

Script triggers

+ +

Run a script automatically when a device registers, or when its agent connects and is ready for jobs. @@ -266,7 +271,6 @@ {/each} - {#if triggers.length > 0} @@ -456,6 +460,13 @@ font-size: 13px; } + .trigger-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-3); + } + .trigger-form { display: flex; gap: var(--space-2); diff --git a/src/WebUI/src/routes/login/+page.svelte b/src/WebUI/src/routes/login/+page.svelte index 4ffc952..c51e870 100644 --- a/src/WebUI/src/routes/login/+page.svelte +++ b/src/WebUI/src/routes/login/+page.svelte @@ -1,12 +1,33 @@ @@ -33,32 +60,64 @@

-
+
X ExecuteR

Sign in

- - - {#if error} {/if} - + {#if config?.autoRedirect && !error} +

Redirecting to single sign-on…

+ {:else} + {#if showLocal} + + + + + + {/if} - Sign in with single sign-on - + {#if showLocal && showSso} +
or
+ {/if} + + {#if showSso} + + Authenticate using OIDC + Provider: {config?.providerName ?? 'OIDC'} + + {/if} + + {#if !showLocal && !showSso} +

No sign-in method is configured.

+ {/if} + + {#if !showLocal} + + Use a local account instead + {/if} + {/if} +
diff --git a/src/WebUI/src/routes/schedules/+page.svelte b/src/WebUI/src/routes/schedules/+page.svelte new file mode 100644 index 0000000..62d02ae --- /dev/null +++ b/src/WebUI/src/routes/schedules/+page.svelte @@ -0,0 +1,357 @@ + + +
+
+

Schedules

+

+ Reusable cadences. Attach one to a script (with a device or group target) from the script's + Schedules panel — every assignment fires when the schedule comes due. +

+
+ {#if !formOpen} + + {/if} +
+ +{#if errorText}

{errorText}

{/if} + +{#if formOpen} +
+

{editing ? `Edit “${editing.name}”` : 'New schedule'}

+
+ + {#key editing?.id ?? 'new'} + + {/key} +
+
+ + +
+
+{/if} + +
+ {#if schedules === null} +
+ {#each Array(3) as _, i (i)} +
loading…
+ {/each} +
+ {:else if schedules.length === 0} + + {:else} + + + + + + + + + + + + + + {#each schedules as schedule (schedule.id)} + {@const s = status(schedule)} + + + + + + + + + + {/each} + +
StatusNameCadenceNext runLast firedUsed by
{s.label}{schedule.name}{scheduleCadence(schedule)} + {schedule.enabled && schedule.nextRunUtc + ? new Date(schedule.nextRunUtc).toLocaleString() + : '—'} + + {#if schedule.lastRunUtc} + + {:else} + — + {/if} + + {#if schedule.assignments.length === 0} + nothing yet + {:else} + + {/if} + + {#if !(schedule.runOnceUtc && schedule.lastRunUtc)} + + {/if} + + +
+ {/if} +
+ + diff --git a/src/WebUI/src/routes/scripts/[id]/+page.svelte b/src/WebUI/src/routes/scripts/[id]/+page.svelte index 1cb418f..cb02855 100644 --- a/src/WebUI/src/routes/scripts/[id]/+page.svelte +++ b/src/WebUI/src/routes/scripts/[id]/+page.svelte @@ -5,16 +5,20 @@ import { api } from '$lib/api/client'; import type { DeviceDto, + DeviceGroupDto, FunctionModuleDto, JobDto, JobProgressPayload, JobState, - ScriptParameter + ScriptParameter, + SecretBinding } from '$lib/api/types'; import { nats, type JobEvent } from '$lib/messaging/nats'; import JobStateBadge from '$lib/components/JobStateBadge.svelte'; import ParameterSchemaEditor from '$lib/components/ParameterSchemaEditor.svelte'; import ParameterInputs from '$lib/components/ParameterInputs.svelte'; + import SecretBindingsEditor from '$lib/components/SecretBindingsEditor.svelte'; + import SchedulesCard from '$lib/components/SchedulesCard.svelte'; const scriptId = $derived(page.params.id!); const isNew = $derived(scriptId === 'new'); @@ -29,21 +33,31 @@ let statusText = $state(''); let devices = $state([]); - let targetClientId = $state(''); + let allGroups = $state([]); + // 'device:' or 'group:' + let targetKey = $state(''); let parameters = $state([]); let functionModuleIds = $state([]); let allFunctions = $state([]); let paramInputs = $state | null>(null); let showParamEditor = $state(false); + let secretBindings = $state([]); + let secretsVariableName = $state('Secrets'); - // Live run state + // Live run state (single-device run) let job = $state(null); let jobState = $state(null); let outputLines = $state<{ seq: number; stream: string; text: string }[]>([]); let progress = $state(null); let unsubscribeJob: (() => void) | null = null; + // Live run state (group fan-out) + let groupJobs = $state([]); + let jobStates = $state>({}); + let skippedOrphaned = $state([]); + let focusJobId = $state(null); + let editorHost: HTMLDivElement; // eslint-disable-next-line @typescript-eslint/no-explicit-any let editor: any = null; @@ -66,6 +80,8 @@ content = script.content; parameters = script.parameters ?? []; functionModuleIds = script.functionModuleIds ?? []; + secretBindings = script.secretBindings ?? []; + secretsVariableName = script.secretsVariableName ?? 'Secrets'; } allFunctions = await api.functions().catch(() => []); loaded = true; @@ -87,12 +103,12 @@ }); editor.onDidChangeModelContent(() => (content = editor.getValue())); - devices = await api.devices(); + [devices, allGroups] = await Promise.all([api.devices(), api.groups().catch(() => [])]); const requested = page.url.searchParams.get('target'); if (requested && devices.some((d) => d.clientId === requested)) { - targetClientId = requested; + targetKey = `device:${requested}`; } else if (devices.length > 0) { - targetClientId = devices[0].clientId; + targetKey = `device:${devices[0].clientId}`; } })(); @@ -109,7 +125,15 @@ } saving = true; statusText = ''; - const body = { name, description, content, parameters, functionModuleIds }; + const body = { + name, + description, + content, + parameters, + functionModuleIds, + secretBindings: secretBindings.filter((b) => b.name.trim() && b.secretName.trim()), + secretsVariableName: secretsVariableName.trim() || undefined + }; try { if (isNew) { const created = await api.createScript(body); @@ -128,18 +152,58 @@ } } + function appendOutput(payload: { sequence: number; stream: string; text: string }) { + outputLines = [ + ...outputLines, + { seq: payload.sequence, stream: payload.stream, text: payload.text } + ].slice(-2000); + } + + /** Switches the output panel to one job of a group run. */ + async function focusJob(jobId: string) { + focusJobId = jobId; + outputLines = []; + progress = null; + const stored = await api.jobOutput(jobId).catch(() => []); + if (focusJobId === jobId && outputLines.length === 0) { + outputLines = stored.map((r) => ({ seq: r.sequence, stream: r.stream, text: r.text })); + } + } + async function run() { const id = await save(); - if (!id || !targetClientId) return; + if (!id || !targetKey) return; outputLines = []; progress = null; jobState = null; + job = null; + groupJobs = []; + jobStates = {}; + skippedOrphaned = []; + focusJobId = null; + + const args = paramInputs?.collect() ?? {}; + const isGroup = targetKey.startsWith('group:'); + const targetId = targetKey.slice(targetKey.indexOf(':') + 1); try { - const args = paramInputs?.collect() ?? {}; - job = await api.createJob(targetClientId, id, args); - jobState = job.state; + if (isGroup) { + const result = await api.createGroupJob(targetId, id, args); + groupJobs = result.jobs; + skippedOrphaned = result.skippedOrphaned; + for (const groupJob of result.jobs) { + jobStates[groupJob.jobId] = groupJob.state; + } + if (result.jobs.length === 0) { + statusText = 'The group has no devices able to run jobs.'; + return; + } + void focusJob(result.jobs[0].jobId); + } else { + job = await api.createJob(targetId, id, args); + jobState = job.state; + } } catch (e) { statusText = e instanceof Error ? e.message : 'Failed to start job.'; return; @@ -147,26 +211,46 @@ unsubscribeJob?.(); unsubscribeJob = nats.onJobEvent((jobId: string, event: JobEvent) => { - if (jobId !== job?.jobId) return; - if (event.type === 'job.output') { - outputLines = [ - ...outputLines, - { seq: event.payload.sequence, stream: event.payload.stream, text: event.payload.text } - ].slice(-2000); - } else if (event.type === 'job.progress') { - progress = event.payload; - } else if (event.type === 'job.state') { - jobState = event.payload.state; - if (['succeeded', 'failed', 'cancelled', 'timedOut'].includes(event.payload.state)) { - progress = null; + if (job && jobId === job.jobId) { + if (event.type === 'job.output') { + appendOutput(event.payload); + } else if (event.type === 'job.progress') { + progress = event.payload; + } else if (event.type === 'job.state') { + jobState = event.payload.state; + if (['succeeded', 'failed', 'cancelled', 'timedOut'].includes(event.payload.state)) { + progress = null; + } + } + return; + } + + if (jobId in jobStates) { + if (event.type === 'job.state') { + jobStates[jobId] = event.payload.state; + } + if (jobId === focusJobId) { + if (event.type === 'job.output') { + appendOutput(event.payload); + } else if (event.type === 'job.progress') { + progress = event.payload; + } else if ( + event.type === 'job.state' && + ['succeeded', 'failed', 'cancelled', 'timedOut'].includes(event.payload.state) + ) { + progress = null; + } } } }); - // Recovery model: fetch any output persisted before our subscription. - const stored = await api.jobOutput(job.jobId).catch(() => []); - if (stored.length > 0 && outputLines.length === 0) { - outputLines = stored.map((r) => ({ seq: r.sequence, stream: r.stream, text: r.text })); + if (job) { + // Recovery model: fetch any output persisted before our subscription. + const singleJobId = job.jobId; + const stored = await api.jobOutput(singleJobId).catch(() => []); + if (stored.length > 0 && outputLines.length === 0) { + outputLines = stored.map((r) => ({ seq: r.sequence, stream: r.stream, text: r.text })); + } } } @@ -177,8 +261,18 @@ await goto('/scripts'); } + const terminal = ['succeeded', 'failed', 'cancelled', 'timedOut']; + const groupRunning = $derived( + groupJobs.some((g) => !terminal.includes(jobStates[g.jobId] ?? 'queued')) + ); + const groupFinished = $derived( + groupJobs.filter((g) => terminal.includes(jobStates[g.jobId] ?? 'queued')).length + ); const running = $derived( - jobState !== null && !['succeeded', 'failed', 'cancelled', 'timedOut'].includes(jobState) + (jobState !== null && !terminal.includes(jobState)) || (groupJobs.length > 0 && groupRunning) + ); + const focusHostname = $derived( + groupJobs.find((g) => g.jobId === focusJobId)?.hostname ?? null ); @@ -201,53 +295,46 @@ {/if} - -
-
- {#if !loaded} -
loading editor…
- {/if} -
+
+
+
+

Parameters, secrets & functions

+ + {parameters.length === 0 + ? 'No parameters' + : `${parameters.length} parameter${parameters.length === 1 ? '' : 's'}`} + · {secretBindings.length} secret{secretBindings.length === 1 ? '' : 's'} + · {functionModuleIds.length} function module{functionModuleIds.length === 1 ? '' : 's'} + +
+
-