diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 7a0d401..78480ac 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -85,7 +85,7 @@ jobs: shell: pwsh run: | ./scripts/Package-Agent.ps1 -Version ${{ steps.ver.outputs.version }} ` - -Runtimes win-x64,linux-x64,linux-arm64,osx-x64,osx-arm64 + -Runtimes win-x64,win-arm64,linux-x64,linux-arm64,osx-x64,osx-arm64 $stage = 'artifacts/agent-package' New-Item -ItemType Directory -Force $stage | Out-Null $msi = "artifacts/Agent-${{ steps.ver.outputs.version }}.msi" @@ -119,6 +119,7 @@ jobs: artifacts/Agent-*.msi artifacts/Agent-*-checksums.txt artifacts/Server-*.zip + artifacts/Server-*.msi artifacts/Server-*-checksums.txt retention-days: 7 diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 8658d1f..c100e74 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -51,7 +51,7 @@ jobs: shell: pwsh run: | ./scripts/Package-Agent.ps1 -Version ${{ steps.ver.outputs.version }} ` - -Runtimes win-x64,linux-x64,linux-arm64,osx-x64,osx-arm64 -SkipIcon + -Runtimes win-x64,win-arm64,linux-x64,linux-arm64,osx-x64,osx-arm64 -SkipIcon - name: Package server (win-x64 + linux-x64) shell: pwsh diff --git a/README.md b/README.md index 57062a7..7742768 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,23 @@ # ExecuteR -Secure Windows endpoint management: a self-contained .NET agent enrolls over -ordinary HTTPS, establishes **scoped NATS messaging over WebSocket** through the -same reverse-proxy edge, publishes live state, accepts durable work, runs -PowerShell in-process, and provides a secured interactive terminal — while the -browser uses a WebSocket-connected NATS client for near-real-time UI updates -with **no SignalR, SSE, or polling**. +Secure cross-platform endpoint management: a self-contained .NET agent enrolls +over ordinary HTTPS, establishes **scoped NATS messaging over WebSocket** +through the same reverse-proxy edge, publishes live state, accepts durable +work, runs PowerShell in-process, and provides a secured interactive terminal — +while the browser uses a WebSocket-connected NATS client for near-real-time UI +updates with **no SignalR, SSE, or polling**. -- **Agent** — single self-contained Windows x64 executable / Windows service - (.NET 10). Deterministic hardware identity, secure one-time bootstrap, - CIM inventory, in-process PowerShell (System.Management.Automation), ConPTY - remote shell, presigned-URL file delivery. +- **Agent** — single self-contained executable for Windows, Linux and macOS + (x64 + arm64, .NET 10), running as a Windows service / systemd unit / + launchd daemon. Deterministic hardware identity, secure one-time bootstrap, + hardware inventory, in-process PowerShell (System.Management.Automation) + plus PowerShell 5 and Bash engines, ConPTY remote shell (Windows), + presigned-URL file delivery. - **Backend** — ASP.NET Core control plane: REST API, SQLite, local + OIDC auth, RBAC, NATS operator/JWT issuance, JetStream command dispatch, live event relay. - **WebUI** — SvelteKit dashboard: live device status, Monaco PowerShell editor - with typed parameters and reusable function modules, live job output and + with typed parameters and reusable Functions, live job output and progress, xterm.js remote shell. ![Dashboard](docs/screenshots/dashboard.png) @@ -40,7 +42,7 @@ with **no SignalR, SSE, or polling**. 14. [Bootstrap and URL install](#bootstrap-and-url-install) 15. [Local login and OIDC](#local-login-and-oidc) 16. [Custom roles and permissions](#custom-roles-and-permissions) -17. [Typed script parameters and function modules](#typed-script-parameters-and-function-modules) +17. [Typed script parameters and Functions](#typed-script-parameters-and-functions) 18. [Script engines](#script-engines) 19. [Secrets providers and $Secrets](#secrets-providers-and-secrets) 20. [Device groups and script triggers](#device-groups-and-script-triggers) @@ -322,22 +324,40 @@ docker compose up -d --build ## Standalone server binary -For a quick spin-up without containers, one self-contained binary serves the -WebUI (static SPA), the API, the `/messaging/*` WebSocket relay, and supervises -a bundled `nats-server` sidecar. CI publishes `Server--win-x64.zip` -and `…-linux-x64.zip` (build locally with `./scripts/Package-Server.ps1`): +For a quick spin-up without containers, one self-contained `ExecuteR-Server` +binary serves the WebUI (static SPA), the API, the `/messaging/*` WebSocket +relay, and supervises a `nats-server` sidecar. CI publishes +`Server--win-x64.zip`, `…-linux-x64.zip` **and `Server-.msi`** +(build locally with `./scripts/Package-Server.ps1`): ```text -ExecuteRServer setup generate NATS keys, sidecar config, appsettings.json -# edit appsettings.json: set INITIAL_ADMIN_PASSWORD (first start only) -ExecuteRServer run in the foreground on http://0.0.0.0:9080 -ExecuteRServer service install Windows service / systemd unit -ExecuteRServer service uninstall +ExecuteR-Server setup + Generates NATS keys, the sidecar config and appsettings.json with the + admin/admin sign-in (override with --admin-user/--admin-password) — and + downloads nats-server for this OS/architecture if it is not bundled. +ExecuteR-Server run in the foreground on http://0.0.0.0:9080 +ExecuteR-Server service install Windows service / systemd unit +ExecuteR-Server service uninstall ``` -Agents enroll against the same base URL. Put a TLS-terminating reverse proxy -in front for production use; the compose stack remains the recommended -deployment for anything long-lived. +When the password was left at the default, the **first sign-in demands a new +password** before any session is issued — valid credentials return a +must-change signal, and the sign-in page walks straight into a set-new-password +form. Choosing a literal `admin` password (CLI flag or MSI wizard) triggers +the same reset. + +![First sign-in password reset](docs/screenshots/login-reset.png) + +The **Windows MSI** wraps the same flow: an Administrator account page in the +wizard (defaults admin / admin; `ADMINUSERNAME=… ADMINPASSWORD=…` for silent +installs) then the binary's own `setup` + `service install`. Upgrades never +overwrite existing configuration, and uninstall stops and removes the service. + +Bundles ship the **agent installers** (`agent-package/` with `Agent.msi`, +`Agent.zip`, `VERSION`), so the URL install command works immediately — no +seeding, no S3. Agents enroll against the same base URL. Put a TLS-terminating +reverse proxy in front for production use; the compose stack remains the +recommended deployment for anything long-lived. --- @@ -531,7 +551,7 @@ assigned users cannot be dropped. --- -## Typed script parameters and function modules +## Typed script parameters and Functions Scripts can declare typed parameters whose editor input changes by type: string, number, boolean, array (with element type), and hashtable. Hashtable @@ -551,23 +571,30 @@ 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 +Reusable **Functions** can be attached to a script; the backend prepends them as a prelude executed first in the same runspace, so individual scripts stay small and duplication is avoided. +Scripts, Functions, schedules, groups (rules and static members included) and +roles all support one-click **Clone** — the copy lands as "Name (copy)" ready +to edit. Role clones copy permissions and device scope but never OIDC claim +values, so identity mappings stay unambiguous; system roles clone into custom +roles, making Admin/Operator/Viewer handy templates. + ![Script editor](docs/screenshots/script-editor.png) --- ## Script engines -Each script selects its engine in the editor (Monaco switches syntax -highlighting to match): +Each script picks its **Script Engine** in the editor — the selector shows a +one-line hint describing the selected engine's platform behavior, and Monaco +switches syntax highlighting to match: - **PowerShell 7 (default)** — the embedded PowerShell SDK in the agent process on every platform. Full feature set: live progress records, typed - parameters, `$Secrets`, function-module preludes. -- **Windows PowerShell 5.1** — shells out to `powershell.exe` with near + parameters, `$Secrets`, Functions preludes. +- **PowerShell 5** — shells out to `powershell.exe` on Windows with near parity: a generated wrapper renders parameters as typed PowerShell literals (hashtables and arrays included), defines the case-insensitive secrets dictionary, dot-sources the prelude and splats the payload. Stdout/stderr @@ -576,8 +603,18 @@ highlighting to match): and secrets arrive as environment variables; complex values are JSON strings (`jq` friendly). The prelude is concatenated ahead of the script. -An engine unavailable on a device (5.1 on Linux, bash without Git Bash on -Windows) fails the job immediately with a clear message instead of running. +An engine unavailable on a device (PowerShell 5 on Linux, bash without Git +Bash on Windows) fails the job immediately with a clear message instead of +running. + +The editor itself pops out to fill the window (Esc restores) and offers +optional **IntelliSense** — a curated offline provider with common cmdlets, +keywords, snippets, plus the script's own parameters, `$Secrets` bindings and +`$Files` entries (typed as FileInfo or DirectoryInfo); no language server +involved. Execution flows vertically beneath the editor: target and +**Execution values**, Schedules, Triggers, then full-width output. + +![Script execution flow](docs/screenshots/script-execution.png) The packaged agent bundles **PSResourceGet**, **Archive** and **ThreadJob** next to the binary and prepends that directory to `PSModulePath` — so @@ -636,7 +673,10 @@ and both conditions and groups have an independent **NOT**. Operators: `equals`, `notEquals`, `contains`, `notContains`, `startsWith`, `endsWith`, `regex`, `in`, `notIn`, `>`, `>=`, `<`, `<=`, `exists`, -`notExists`. +`notExists`, `inCidr`, `notInCidr`. The CIDR operators evaluate IP fields +against comma-separated ranges (`10.20.0.0/16, 192.168.1.0/24`) using the +BCL `System.Net.IPNetwork` — IPv4 and IPv6, bare IPs mean equality, and host +bits in the base address are normalized. Fields come from hardware inventory, tags, hostname/identity, and live status — the full catalogue is served by `GET /api/groups/fields`, so the rule builder @@ -646,9 +686,16 @@ always matches what the server can evaluate: |----------|----------| | Identity | `hostname`, `clientId`, `status`, `tags`, `agentVersion`, `domain` | | Hardware | `manufacturer`, `model`, `serialNumber`, `cpu.cores`, `memory.totalGb` | -| Operating system | `os.caption`, `os.version`, `os.build`, `os.architecture` | +| Operating system | `os.platform` (windows/linux/macos), `os.caption`, `os.version`, `os.build` | | Storage | `disk.count`, `disk.totalGb`, `volume.freeGb` | -| Network | `network.ipv4`, `network.mac`, `network.dns` | +| Network | `network.ipv4`, `network.mac`, `network.dns`, `network.interface` | + +Every deployment starts with six **default platform groups** — Windows +Servers, Windows Workstations, Linux, Linux Servers, Linux Workstations, +macOS — driven by `os.platform` and, for the Linux split, `os.edition` +(the unix agent reports Workstation when the device boots to a graphical +session, Server otherwise). Seeded only while no groups exist, so edits and +deletions stick. Multi-valued fields (tags, IPs, MACs, DNS) match when **any** value satisfies a positive operator, and require **all** values for the negative ones. A missing @@ -659,8 +706,9 @@ matches and never throws. ![Group rule builder](docs/screenshots/groups-rule-builder.png) -**Script triggers** run a script automatically on a device lifecycle event, -targeted at a group (or all devices): +**Triggers** belong to scripts (the Triggers card on the script editor): run +the script automatically on a device lifecycle event, scoped to a group or +all devices: | Trigger | Fires when | |---------|-----------| @@ -668,8 +716,8 @@ targeted at a group (or all devices): | `onAgentReady` | The agent is connected *and* its durable command consumer is bound — genuinely ready for jobs | Triggers default to **once per device** (recorded durably), and triggered runs -use the normal job pipeline, so they carry the script's function-module prelude -and typed parameters and appear alongside manual runs. +use the normal job pipeline, so they carry the script's Functions prelude and +typed parameters and appear alongside manual runs. --- @@ -683,8 +731,10 @@ 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. +at fire time) + stored execution values. One "Nightly at 1am" cadence can +drive any number of scripts, and pausing the cadence pauses everything +attached to it. Four starter cadences are seeded on first boot (hourly, daily +1 AM, weekdays 7 AM, weekly Sunday 2 AM — UTC) while the table is empty. The cadence builder leads with friendly selectors — *every N minutes/hours*, *daily/weekly/monthly at a time* with weekday chips — and compiles them to @@ -710,7 +760,7 @@ Semantics worth knowing: 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; +- Execution values captured when a schedule is attached are used for every firing; secret bindings resolve fresh server-side at each fire time. --- @@ -864,6 +914,19 @@ Configure an S3-compatible store (AWS S3, MinIO, Backblaze B2) from **Device → Actions → Send file**. Credentials stay on the server — the endpoint only ever sees a short-lived URL. +**Script file bindings** integrate delivery into execution: in the script +editor's define strip, bind S3 objects (or whole prefixes, delivered +recursively) that download to the device **before the script runs**. The +destination path expands on the device (`%TEMP%`, `$env:ProgramData`, +`$(…)`), and each entry reaches the script through a case-insensitive ordered +dictionary — `$Files.Name` is a **FileInfo** for single objects or a +**DirectoryInfo** for prefixes. The server lists and presigns everything at +dispatch, so agents never hold S3 credentials. Per-entry **continue on +failure** logs a warning and still runs the script (`$Files.Name.Exists` +tells you what arrived); otherwise a failed delivery fails the job before +execution. PowerShell 5 receives the same `$Files` dictionary; bash gets one +environment variable per entry holding the delivered path. + **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. @@ -970,11 +1033,12 @@ Gitea Actions workflows live in `.gitea/workflows`: - **Pull request to `main`** — restore, build, unit + integration tests, Svelte check. No image push, no release. - **Push to `dev`** — build + test, agent binaries for every platform - (win-x64, linux-x64, linux-arm64, osx-x64, osx-arm64) + MSI, the standalone - server (win-x64, linux-x64), backend/webui images tagged `dev` and - `-dev`. All binaries upload as the `binaries` run artifact. + (win-x64, win-arm64, linux-x64, linux-arm64, osx-x64, osx-arm64) + MSI, the + standalone server (win-x64 + MSI, linux-x64), backend/webui images tagged + `dev` and `-dev`. All binaries upload as the `binaries` run + artifact. - **Push to `main`** — the same set, images tagged `` and `latest`, - and a Gitea release with every agent ZIP, the MSI, the Server ZIPs and + and a Gitea release with every agent ZIP, both MSIs, the Server ZIPs and checksums. Scripts discover context from optional environment variables and fall back @@ -1042,8 +1106,8 @@ metadata), and the frontend build metadata. | ![Device detail](docs/screenshots/device-detail.png) **Device overview, tags and groups** | ![Hardware](docs/screenshots/device-hardware.png) **Hardware inventory** | | ![Network](docs/screenshots/device-network.png) **Network inventory** | ![Actions](docs/screenshots/device-actions.png) **Device actions and file delivery** | | ![Groups](docs/screenshots/groups.png) **Groups** | ![Static members](docs/screenshots/groups-static-members.png) **Static group membership** | -| ![Script editor](docs/screenshots/script-editor.png) **Monaco PowerShell editor** | ![Parameters](docs/screenshots/script-parameters.png) **Typed parameters** | -| ![Jobs](docs/screenshots/jobs.png) **Jobs and stored output** | ![Functions](docs/screenshots/functions.png) **Function modules** | +| ![Script editor](docs/screenshots/script-editor.png) **Monaco editor with IntelliSense and pop-out** | ![Script Configuration](docs/screenshots/script-parameters.png) **Script Configuration: parameters, secrets, files, Functions** | +| ![Jobs](docs/screenshots/jobs.png) **Jobs and stored output** | ![Functions](docs/screenshots/functions.png) **Functions** | | ![Access](docs/screenshots/access.png) **Users and custom roles** | ![Role editor](docs/screenshots/access-role-editor.png) **Role permissions and device scope** | | ![Settings](docs/screenshots/settings-install-command.png) **Bootstrap token and install command** | ![Light theme](docs/screenshots/dashboard-light.png) **Light theme** | diff --git a/assets/icons/app.ico b/assets/icons/app.ico new file mode 100644 index 0000000..28d03a0 Binary files /dev/null and b/assets/icons/app.ico differ diff --git a/docs/screenshots/access.png b/docs/screenshots/access.png index b1ba8f2..d2c580b 100644 Binary files a/docs/screenshots/access.png and b/docs/screenshots/access.png differ diff --git a/docs/screenshots/device-detail.png b/docs/screenshots/device-detail.png index 278ef93..51a187f 100644 Binary files a/docs/screenshots/device-detail.png and b/docs/screenshots/device-detail.png differ diff --git a/docs/screenshots/device-network.png b/docs/screenshots/device-network.png index 7d8d25e..e122b39 100644 Binary files a/docs/screenshots/device-network.png and b/docs/screenshots/device-network.png differ diff --git a/docs/screenshots/functions.png b/docs/screenshots/functions.png index 1ec9786..5c2beca 100644 Binary files a/docs/screenshots/functions.png and b/docs/screenshots/functions.png differ diff --git a/docs/screenshots/groups.png b/docs/screenshots/groups.png index 1df0058..f0fbf06 100644 Binary files a/docs/screenshots/groups.png and b/docs/screenshots/groups.png differ diff --git a/docs/screenshots/login-reset.png b/docs/screenshots/login-reset.png new file mode 100644 index 0000000..157f832 Binary files /dev/null and b/docs/screenshots/login-reset.png differ diff --git a/docs/screenshots/schedules.png b/docs/screenshots/schedules.png index 37bf559..d8ad18c 100644 Binary files a/docs/screenshots/schedules.png and b/docs/screenshots/schedules.png differ diff --git a/docs/screenshots/script-editor.png b/docs/screenshots/script-editor.png index fe7b0f9..e8b00fe 100644 Binary files a/docs/screenshots/script-editor.png and b/docs/screenshots/script-editor.png differ diff --git a/docs/screenshots/script-execution.png b/docs/screenshots/script-execution.png new file mode 100644 index 0000000..918f91b Binary files /dev/null and b/docs/screenshots/script-execution.png differ diff --git a/docs/screenshots/script-parameters.png b/docs/screenshots/script-parameters.png index 7f558b7..d5cca90 100644 Binary files a/docs/screenshots/script-parameters.png and b/docs/screenshots/script-parameters.png differ diff --git a/scripts/Package-Server.ps1 b/scripts/Package-Server.ps1 index 321f433..2f1a903 100644 --- a/scripts/Package-Server.ps1 +++ b/scripts/Package-Server.ps1 @@ -17,6 +17,7 @@ param( [string]$Version, [string[]]$Runtimes = @('win-x64', 'linux-x64'), [switch]$SkipNats, + [switch]$SkipMsi, [switch]$SkipIcon ) @@ -64,15 +65,30 @@ foreach ($rid in $Runtimes) { # Single-file apphosts tolerate renames; ship a recognizable binary name. if ($rid -like 'win-*') { - Rename-Item (Join-Path $publishDir 'Backend.exe') 'ExecuteRServer.exe' + Rename-Item (Join-Path $publishDir 'Backend.exe') 'ExecuteR-Server.exe' } else { - Rename-Item (Join-Path $publishDir 'Backend') 'ExecuteRServer' + Rename-Item (Join-Path $publishDir 'Backend') 'ExecuteR-Server' } # ── Embed the WebUI ────────────────────────────────────────────────────── Copy-Item $staticBuild (Join-Path $publishDir 'wwwroot') -Recurse + # ── Bundle the agent installers so URL install works out of the box ───── + $agentStage = Join-Path $publishDir 'agent-package' + New-Item -ItemType Directory -Force $agentStage | Out-Null + $agentMsi = Join-Path $artifacts "Agent-$Version.msi" + $agentZip = Join-Path $artifacts "Agent-$Version-win-x64.zip" + $staged = $false + if (Test-Path $agentMsi) { Copy-Item $agentMsi (Join-Path $agentStage 'Agent.msi'); $staged = $true } + if (Test-Path $agentZip) { Copy-Item $agentZip (Join-Path $agentStage 'Agent.zip'); $staged = $true } + if ($staged) { + $Version | Set-Content (Join-Path $agentStage 'VERSION') -NoNewline + } + else { + Write-Warning "No agent artifacts for $Version found — run Package-Agent first for a complete bundle." + } + # ── Bundle nats-server for the sidecar ─────────────────────────────────── if (-not $SkipNats) { $natsDir = Join-Path $publishDir 'nats' @@ -107,21 +123,23 @@ foreach ($rid in $Runtimes) { } # ── Quick-start note ───────────────────────────────────────────────────── - $exeName = if ($rid -like 'win-*') { 'ExecuteRServer.exe' } else { './ExecuteRServer' } + $exeName = if ($rid -like 'win-*') { 'ExecuteR-Server.exe' } else { './ExecuteR-Server' } Set-Content (Join-Path $publishDir 'QUICKSTART.txt') @" ExecuteR standalone server $Version ($rid) 1. $exeName setup - Generates NATS keys, the sidecar config and appsettings.json. -2. Edit appsettings.json: set INITIAL_ADMIN_PASSWORD (first start only). -3. $exeName + Generates NATS keys, the sidecar config and appsettings.json with + the admin/admin sign-in (override with --admin-user/--admin-password; + change the password after the first sign-in either way). +2. $exeName Serves the UI + API on http://0.0.0.0:9080 with the NATS sidecar. ...or run in the background: $exeName service install (Windows service / systemd unit) $exeName service uninstall -Put a TLS-terminating reverse proxy in front for production use. -Agents enroll against the same base URL (Settings -> bootstrap token). +Agent installers ship in ./agent-package, so the URL install command +works immediately. Put a TLS-terminating reverse proxy in front for +production use; agents enroll against the same base URL. "@ # ── Zip it ─────────────────────────────────────────────────────────────── @@ -131,6 +149,33 @@ Agents enroll against the same base URL (Settings -> bootstrap token). Write-Host "Created $zipPath" } +# ── Server MSI (win-x64): admin-account wizard + service install ──────────── +$serverWix = Join-Path $repoRoot 'src/Installer.Server/Server.Installer.wixproj' +$winPublish = Join-Path $artifacts "server/$Version/win-x64" +if (-not $SkipMsi -and (Test-Path $serverWix) -and (Test-Path $winPublish)) { + # Deterministic MSI ProductVersion transform (same as the agent): + # yyyy.MM.dd.HHmm -> (yyyy-2000).(MM).((dd-1)*1440 + HH*60 + mm) + $parts = $Version.Split('.') + $hhmm = [int]$parts[3] + $msiVersion = '{0}.{1}.{2}' -f ([int]$parts[0] - 2000), [int]$parts[1], + ((([int]$parts[2] - 1) * 1440) + ([math]::Floor($hhmm / 100) * 60) + ($hhmm % 100)) + Write-Host "Server MSI ProductVersion: $msiVersion" + + dotnet build $serverWix -c Release --nologo ` + "-p:UnifiedVersion=$Version" ` + "-p:MsiProductVersion=$msiVersion" ` + "-p:ServerPublishDir=$winPublish" + if ($LASTEXITCODE -ne 0) { throw "Server MSI build failed ($LASTEXITCODE)." } + + $msi = Get-ChildItem (Join-Path $repoRoot 'src/Installer.Server/bin/Release') -Filter '*.msi' -Recurse | + Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1 + if ($msi) { + $msiTarget = Join-Path $artifacts "Server-$Version.msi" + Copy-Item $msi.FullName $msiTarget -Force + Write-Host "Created $msiTarget" + } +} + # Checksums for release attachment. $checksums = Join-Path $artifacts "Server-$Version-checksums.txt" Get-ChildItem $artifacts -File | Where-Object { $_.Name -like "Server-$Version*" -and $_.Extension -ne '.txt' } | ForEach-Object { diff --git a/src/Agent/Agent.csproj b/src/Agent/Agent.csproj index f1355db..aaf8311 100644 --- a/src/Agent/Agent.csproj +++ b/src/Agent/Agent.csproj @@ -8,15 +8,16 @@ net10.0-windows;net10.0 Agent Agent - win-x64;linux-x64;linux-arm64;osx-x64;osx-arm64 + win-x64;win-arm64;linux-x64;linux-arm64;osx-x64;osx-arm64 true en false - - $(MSBuildThisFileDirectory)..\..\artifacts\icons\app.ico + + $(MSBuildThisFileDirectory)..\..\assets\icons\app.ico diff --git a/src/Agent/Inventory/InventoryCollector.cs b/src/Agent/Inventory/InventoryCollector.cs index 4c3b71d..6d2ab72 100644 --- a/src/Agent/Inventory/InventoryCollector.cs +++ b/src/Agent/Inventory/InventoryCollector.cs @@ -199,9 +199,22 @@ public sealed class InventoryCollector(IHardwareIdentitySource identitySource) : private static List CollectNetwork() { + // The friendly interface name ("Ethernet0") lives on Win32_NetworkAdapter, + // joinable to the configuration rows through the shared Index. + var interfaceNames = new Dictionary(); + Query( + "SELECT Index, NetConnectionID FROM Win32_NetworkAdapter WHERE NetConnectionID IS NOT NULL", + obj => + { + if (obj["Index"] is uint index && obj["NetConnectionID"] is string name && name.Length > 0) + { + interfaceNames[index] = name; + } + }); + var adapters = new List(); Query( - "SELECT Description, MACAddress, IPAddress, DefaultIPGateway, DNSServerSearchOrder FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE", + "SELECT Index, Description, MACAddress, IPAddress, DefaultIPGateway, DNSServerSearchOrder FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE", obj => { var addresses = obj["IPAddress"] as string[] ?? []; @@ -211,7 +224,8 @@ public sealed class InventoryCollector(IHardwareIdentitySource identitySource) : Ipv4Addresses: [.. addresses.Where(a => !a.Contains(':'))], Ipv6Addresses: [.. addresses.Where(a => a.Contains(':'))], Gateways: [.. obj["DefaultIPGateway"] as string[] ?? []], - DnsServers: [.. obj["DNSServerSearchOrder"] as string[] ?? []])); + DnsServers: [.. obj["DNSServerSearchOrder"] as string[] ?? []], + InterfaceName: obj["Index"] is uint index ? interfaceNames.GetValueOrDefault(index) : null)); }); return adapters; } diff --git a/src/Agent/Inventory/UnixInventoryCollector.cs b/src/Agent/Inventory/UnixInventoryCollector.cs index 79f0def..64274e1 100644 --- a/src/Agent/Inventory/UnixInventoryCollector.cs +++ b/src/Agent/Inventory/UnixInventoryCollector.cs @@ -36,7 +36,7 @@ public sealed class UnixInventoryCollector(IHardwareIdentitySource identitySourc Architecture: System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString(), InstallDateUtc: null, LastBootUtc: ReadLastBoot(), - Edition: null); + Edition: DetectEdition()); return new InventoryReport( Identity: identity, @@ -50,6 +50,43 @@ public sealed class UnixInventoryCollector(IHardwareIdentitySource identitySourc CollectedUtc: DateTimeOffset.UtcNow); } + /// + /// "Workstation" or "Server". macOS is always a workstation; linux is a + /// workstation when it boots to a graphical session (default systemd + /// target, or installed desktop session files as the fallback). + /// + private static string DetectEdition() + { + if (OperatingSystem.IsMacOS()) + { + return "Workstation"; + } + + var defaultTarget = UnixHardwareIdentitySource.Exec("systemctl", "get-default")?.Trim(); + if (!string.IsNullOrEmpty(defaultTarget)) + { + return defaultTarget.Contains("graphical", StringComparison.OrdinalIgnoreCase) + ? "Workstation" + : "Server"; + } + + var hasDesktopSessions = + HasEntries("/usr/share/xsessions") || HasEntries("/usr/share/wayland-sessions"); + return hasDesktopSessions ? "Workstation" : "Server"; + + static bool HasEntries(string path) + { + try + { + return Directory.Exists(path) && Directory.EnumerateFiles(path).Any(); + } + catch (Exception) + { + return false; + } + } + } + private static (string? Name, string? Version) ReadOsRelease() { if (OperatingSystem.IsMacOS()) @@ -237,12 +274,13 @@ public sealed class UnixInventoryCollector(IHardwareIdentitySource identitySourc var mac = nic.GetPhysicalAddress().GetAddressBytes(); adapters.Add(new InventoryNetworkAdapter( - Description: nic.Name, + Description: string.IsNullOrWhiteSpace(nic.Description) ? nic.Name : nic.Description, MacAddress: mac.Length > 0 ? string.Join(':', mac.Select(b => b.ToString("X2"))) : null, Ipv4Addresses: v4, Ipv6Addresses: v6, Gateways: props.GatewayAddresses.Select(g => g.Address.ToString()).ToList(), - DnsServers: props.DnsAddresses.Select(d => d.ToString()).ToList())); + DnsServers: props.DnsAddresses.Select(d => d.ToString()).ToList(), + InterfaceName: nic.Name)); } catch (Exception) { diff --git a/src/Agent/PowerShell/ExternalScriptRunner.cs b/src/Agent/PowerShell/ExternalScriptRunner.cs index 4bf2ffb..227767b 100644 --- a/src/Agent/PowerShell/ExternalScriptRunner.cs +++ b/src/Agent/PowerShell/ExternalScriptRunner.cs @@ -36,7 +36,8 @@ public static class ExternalScriptRunner IReadOnlyList? secrets, string secretsVariableName, Action onRecord, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + System.Collections.Specialized.OrderedDictionary? files = null) { // Child processes inherit PSModulePath, so 5.1 also sees the bundled // gallery modules (PSResourceGet supports Windows PowerShell 5.1+). @@ -48,8 +49,8 @@ public static class ExternalScriptRunner { return engine == ScriptEngine.WindowsPowerShell ? await RunWindowsPowerShellAsync( - content, prelude, parameters, secrets, secretsVariableName, workDir, onRecord, cancellationToken) - : await RunBashAsync(content, prelude, parameters, secrets, workDir, onRecord, cancellationToken); + content, prelude, parameters, secrets, secretsVariableName, files, workDir, onRecord, cancellationToken) + : await RunBashAsync(content, prelude, parameters, secrets, files, workDir, onRecord, cancellationToken); } finally { @@ -70,6 +71,7 @@ public static class ExternalScriptRunner IReadOnlyDictionary parameters, IReadOnlyList? secrets, string secretsVariableName, + System.Collections.Specialized.OrderedDictionary? files, string workDir, Action onRecord, CancellationToken cancellationToken) @@ -95,6 +97,17 @@ public static class ExternalScriptRunner } } + if (files is { Count: > 0 }) + { + wrapper.AppendLine("$Files = @{}"); + foreach (System.Collections.DictionaryEntry entry in files) + { + var type = entry.Value is DirectoryInfo ? "System.IO.DirectoryInfo" : "System.IO.FileInfo"; + var path = ((FileSystemInfo)entry.Value!).FullName; + wrapper.AppendLine($"$Files[{PsLiteral(entry.Key)}] = [{type}]{PsLiteral(path)}"); + } + } + wrapper.AppendLine("$__splat = @{}"); foreach (var (name, value) in parameters) { @@ -120,6 +133,7 @@ public static class ExternalScriptRunner string? prelude, IReadOnlyDictionary parameters, IReadOnlyList? secrets, + System.Collections.Specialized.OrderedDictionary? files, string workDir, Action onRecord, CancellationToken cancellationToken) @@ -157,6 +171,15 @@ public static class ExternalScriptRunner environment[secret.Name] = secret.Value; } + // Delivered file paths arrive as env vars named after the binding. + if (files is not null) + { + foreach (System.Collections.DictionaryEntry entry in files) + { + environment[(string)entry.Key] = ((FileSystemInfo)entry.Value!).FullName; + } + } + return await RunProcessAsync(bash, $"\"{scriptPath}\"", environment, onRecord, cancellationToken); } diff --git a/src/Agent/PowerShell/PowerShellJobHandler.cs b/src/Agent/PowerShell/PowerShellJobHandler.cs index a661739..62e6106 100644 --- a/src/Agent/PowerShell/PowerShellJobHandler.cs +++ b/src/Agent/PowerShell/PowerShellJobHandler.cs @@ -69,7 +69,40 @@ public sealed class PowerShellJobHandler( int exitCode; string? message = null; - if (command.Engine != ScriptEngine.PowerShell) + // S3 file deliveries land before the script starts. Destination + // paths expand on the device (%VAR% natively; $env:/$(…) through a + // short-lived runspace, regardless of engine), and the resolved + // FileInfo/DirectoryInfo dictionary becomes $Files. + System.Collections.Specialized.OrderedDictionary? filesDict = null; + string? deliveryFailure = null; + if (command.Files is { Count: > 0 }) + { + using var expansionRunspace = PowerShellRunspaceFactory.Create(); + var fetch = await ScriptFileFetcher.FetchAsync( + command.Files, + path => ExpandDeliveryPath(path, expansionRunspace), + record => pending.Add(PublishOutputAsync(record, Interlocked.Increment(ref sequence))), + timeoutCts.Token); + if (fetch.FailureMessage is not null) + { + deliveryFailure = fetch.FailureMessage; + } + else + { + filesDict = fetch.Files; + sessionVariables ??= []; + sessionVariables["Files"] = filesDict; + } + } + + if (deliveryFailure is not null) + { + finalState = JobState.Failed; + exitCode = 1; + message = deliveryFailure; + await Task.WhenAll(pending); + } + else if (command.Engine != ScriptEngine.PowerShell) { // Out-of-process engine: Windows PowerShell 5.1 or Bash. if (!ExternalScriptRunner.IsAvailable(command.Engine)) @@ -89,7 +122,8 @@ public sealed class PowerShellJobHandler( command.Secrets, string.IsNullOrWhiteSpace(command.SecretsVariableName) ? "Secrets" : command.SecretsVariableName, record => pending.Add(PublishOutputAsync(record, Interlocked.Increment(ref sequence))), - timeoutCts.Token); + timeoutCts.Token, + files: filesDict); if (external.WasCancelled && cancellationToken.IsCancellationRequested) { @@ -168,6 +202,28 @@ public sealed class PowerShellJobHandler( Interlocked.Decrement(ref activeJobs); } + // File destination paths get the full expansion treatment: %VAR% via + // the environment, then $env:/$(…) as double-quoted string content in + // a dedicated runspace (available whatever engine runs the script). + static string ExpandDeliveryPath(string path, System.Management.Automation.Runspaces.Runspace runspace) + { + var expanded = Environment.ExpandEnvironmentVariables(path); + if (!expanded.Contains('$') && !expanded.Contains('`')) + { + return expanded; + } + + try + { + return runspace.SessionStateProxy.InvokeCommand.ExpandString(expanded); + } + catch (Exception ex) when ( + ex is System.Management.Automation.RuntimeException or InvalidOperationException) + { + return expanded; + } + } + // External engines cannot use the in-runspace ExpandString pass; // %VAR% expansion via the device environment still applies to // non-literal string values. diff --git a/src/Agent/PowerShell/ScriptFileFetcher.cs b/src/Agent/PowerShell/ScriptFileFetcher.cs new file mode 100644 index 0000000..971107e --- /dev/null +++ b/src/Agent/PowerShell/ScriptFileFetcher.cs @@ -0,0 +1,158 @@ +using System.Collections.Specialized; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; + +namespace Agent.PowerShell; + +/// +/// Downloads a job's file deliveries before the script starts. Destination +/// paths arrive already expanded; every delivery lands in a case-insensitive +/// ordered dictionary as a FileInfo (single object) or DirectoryInfo +/// (recursive prefix) — the script sees it as $Files.Name even when a +/// continue-on-failure delivery did not arrive (check .Exists). +/// +public static class ScriptFileFetcher +{ + public sealed record FetchResult(OrderedDictionary Files, string? FailureMessage); + + private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(30) }; + + public static async Task FetchAsync( + IReadOnlyList deliveries, + Func expandPath, + Action onRecord, + CancellationToken cancellationToken) + { + var files = new OrderedDictionary(StringComparer.OrdinalIgnoreCase); + + foreach (var delivery in deliveries) + { + string destination; + try + { + destination = Path.GetFullPath(expandPath(delivery.DestinationPath)); + } + catch (Exception ex) + { + var problem = $"File “{delivery.Name}”: destination “{delivery.DestinationPath}” is invalid ({ex.Message})."; + if (!delivery.ContinueOnFailure) + { + return new FetchResult(files, problem); + } + + onRecord(new NormalizedOutputRecord(OutputStreamKind.Warning, problem)); + continue; + } + + files[delivery.Name] = delivery.Directory + ? new DirectoryInfo(destination) + : new FileInfo(destination); + + if (delivery.Error is not null) + { + var problem = $"File “{delivery.Name}” was not delivered: {delivery.Error}"; + if (!delivery.ContinueOnFailure) + { + return new FetchResult(files, problem); + } + + onRecord(new NormalizedOutputRecord(OutputStreamKind.Warning, problem)); + continue; + } + + try + { + foreach (var item in delivery.Items) + { + var target = item.RelativePath.Length == 0 + ? destination + : SafeCombine(destination, item.RelativePath); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + var bytes = await DownloadAsync(item.Url, target, cancellationToken); + onRecord(new NormalizedOutputRecord(OutputStreamKind.Output, + $"Delivered {delivery.Name}{(item.RelativePath.Length > 0 ? "/" + item.RelativePath : "")} → {target} ({FormatSize(bytes)})")); + } + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + var problem = $"File “{delivery.Name}” failed to download: {ex.Message}"; + if (!delivery.ContinueOnFailure) + { + return new FetchResult(files, problem); + } + + onRecord(new NormalizedOutputRecord(OutputStreamKind.Warning, $"{problem} — continuing.")); + } + } + + return new FetchResult(files, null); + } + + /// Streams to a temp file, then moves into place (no partial files). + private static async Task DownloadAsync(string url, string target, CancellationToken cancellationToken) + { + var temp = target + ".executer-download"; + try + { + using var response = await Http.GetAsync( + url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + response.EnsureSuccessStatusCode(); + + await using (var file = File.Create(temp)) + { + await response.Content.CopyToAsync(file, cancellationToken); + } + + File.Move(temp, target, overwrite: true); + return new FileInfo(target).Length; + } + finally + { + try + { + if (File.Exists(temp)) + { + File.Delete(temp); + } + } + catch (IOException) + { + // Best effort. + } + } + } + + /// + /// Joins a relative S3 key onto the destination directory, refusing rooted + /// paths and traversal that would escape it. + /// + internal static string SafeCombine(string root, string relativePath) + { + var normalized = relativePath.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar); + if (Path.IsPathRooted(normalized)) + { + throw new InvalidOperationException($"Refusing rooted relative path “{relativePath}”."); + } + + var rootFull = Path.GetFullPath(root); + var combined = Path.GetFullPath(Path.Combine(rootFull, normalized)); + if (!combined.StartsWith(rootFull.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException($"Refusing path traversal in “{relativePath}”."); + } + + return combined; + } + + private static string FormatSize(long bytes) => bytes switch + { + >= 1_073_741_824 => $"{bytes / 1_073_741_824d:F1} GB", + >= 1_048_576 => $"{bytes / 1_048_576d:F1} MB", + >= 1024 => $"{bytes / 1024d:F1} KB", + _ => $"{bytes} bytes", + }; +} diff --git a/src/Backend/Auth/AuthEndpoints.cs b/src/Backend/Auth/AuthEndpoints.cs index eef23e0..b0f9774 100644 --- a/src/Backend/Auth/AuthEndpoints.cs +++ b/src/Backend/Auth/AuthEndpoints.cs @@ -2,6 +2,7 @@ using System.Security.Claims; using Backend.Proxy; using Backend.Security; using Microsoft.AspNetCore.Authentication; +using Microsoft.EntityFrameworkCore; using Shared.Contracts.Api; using Shared.Contracts.Models; @@ -15,6 +16,10 @@ public static class AuthEndpoints .RequireRateLimiting(RateLimitPolicies.Auth) .AllowAnonymous(); + app.MapPost(ApiRoutes.AuthChangePassword, ChangePasswordAsync) + .RequireRateLimiting(RateLimitPolicies.Auth) + .AllowAnonymous(); + app.MapPost(ApiRoutes.AuthLogout, (Delegate)LogoutAsync); app.MapGet(ApiRoutes.AuthSession, GetSessionAsync).AllowAnonymous(); @@ -54,6 +59,63 @@ public static class AuthEndpoints return Results.Unauthorized(); } + // Valid credentials, but a defaulted password: no session until a real + // one is set (POST /api/auth/change-password completes the sign-in). + if (user.MustChangePassword) + { + await audit.LogAsync(AuditCategories.Auth, "login-password-change-required", + actor: user.Username, remoteIp: remoteIp, cancellationToken: cancellationToken); + return Results.Ok(new SessionResponse( + false, user.Username, user.DisplayName, null, AuthConstants.ProviderLocal, + MustChangePassword: true)); + } + + var session = await IssueSessionAsync(user, roles, context, cancellationToken); + await audit.LogAsync(AuditCategories.Auth, "login-succeeded", + actor: user.Username, remoteIp: remoteIp, cancellationToken: cancellationToken); + return Results.Ok(session); + } + + private static async Task ChangePasswordAsync( + ChangePasswordRequest request, + Backend.Data.AppDbContext db, + UserService users, + RoleCache roles, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + var remoteIp = ClientIp.EffectiveText(context); + + if (request.NewPassword.Length < 8) + { + return Results.BadRequest(new { error = "The new password must be at least 8 characters." }); + } + + var user = await users.ValidateCredentialsAsync( + request.Username, request.CurrentPassword, cancellationToken); + if (user is null) + { + await audit.LogAsync(AuditCategories.Auth, "password-change-failed", + actor: request.Username, remoteIp: remoteIp, cancellationToken: cancellationToken); + return Results.Unauthorized(); + } + + var tracked = await db.Users.SingleAsync(u => u.Id == user.Id, cancellationToken); + tracked.PasswordHash = users.HashPassword(tracked, request.NewPassword); + tracked.MustChangePassword = false; + await db.SaveChangesAsync(cancellationToken); + + var session = await IssueSessionAsync(tracked, roles, context, cancellationToken); + await audit.LogAsync(AuditCategories.Auth, "password-changed", + actor: tracked.Username, remoteIp: remoteIp, cancellationToken: cancellationToken); + return Results.Ok(session); + } + + /// Issues the cookie session + CSRF token and builds the response body. + private static async Task IssueSessionAsync( + Backend.Data.UserEntity user, RoleCache roles, HttpContext context, CancellationToken cancellationToken) + { var role = user.RoleId is { } roleId ? await roles.FindByIdAsync(roleId, cancellationToken) : null; role ??= await roles.FindByNameAsync(user.Role.ToString(), cancellationToken); @@ -63,14 +125,11 @@ public static class AuthEndpoints await context.SignInAsync(AuthConstants.CookieScheme, principal); CsrfProtection.IssueToken(context); - await audit.LogAsync(AuditCategories.Auth, "login-succeeded", - actor: user.Username, remoteIp: remoteIp, cancellationToken: cancellationToken); - var permissions = role?.Permissions.Order(StringComparer.Ordinal).ToList() ?? []; - return Results.Ok(new SessionResponse( + return new SessionResponse( true, user.Username, user.DisplayName, role is null ? user.Role : Permissions.Tier(role.Permissions), - AuthConstants.ProviderLocal, role?.Name, permissions)); + AuthConstants.ProviderLocal, role?.Name, permissions); } private static async Task LogoutAsync(HttpContext context) diff --git a/src/Backend/Auth/CsrfProtection.cs b/src/Backend/Auth/CsrfProtection.cs index 4e8291e..2507a53 100644 --- a/src/Backend/Auth/CsrfProtection.cs +++ b/src/Backend/Auth/CsrfProtection.cs @@ -65,8 +65,10 @@ public static class CsrfProtection return false; } - // Login establishes the session; protected by rate limiting + credentials. - if (path.StartsWithSegments("/api/auth/login")) + // Login and the pre-session password change establish the session; + // both are protected by rate limiting + credentials. + if (path.StartsWithSegments("/api/auth/login") + || path.StartsWithSegments("/api/auth/change-password")) { return false; } diff --git a/src/Backend/Auth/UserService.cs b/src/Backend/Auth/UserService.cs index 2e20967..04d5845 100644 --- a/src/Backend/Auth/UserService.cs +++ b/src/Backend/Auth/UserService.cs @@ -19,7 +19,8 @@ public sealed class UserService(AppDbContext db, ILogger logger) /// Never overwrites an existing admin's password. Runs after system-role /// seeding so the account lands on the Admin role. /// - public async Task EnsureInitialAdminAsync(string? username, string? password, CancellationToken cancellationToken) + public async Task EnsureInitialAdminAsync( + string? username, string? password, bool mustChangePassword, CancellationToken cancellationToken) { if (await db.Users.AnyAsync(cancellationToken)) { @@ -46,6 +47,7 @@ public sealed class UserService(AppDbContext db, ILogger logger) Role = UserRole.Admin, RoleId = adminRoleId, AuthProvider = AuthConstants.ProviderLocal, + MustChangePassword = mustChangePassword, CreatedUtc = DateTimeOffset.UtcNow, }; admin.PasswordHash = hasher.HashPassword(admin, password); diff --git a/src/Backend/Backend.csproj b/src/Backend/Backend.csproj index 8669c56..9378987 100644 --- a/src/Backend/Backend.csproj +++ b/src/Backend/Backend.csproj @@ -5,7 +5,9 @@ Backend backend-dev-secrets - $(MSBuildThisFileDirectory)..\..\artifacts\icons\app.ico + + $(MSBuildThisFileDirectory)..\..\assets\icons\app.ico diff --git a/src/Backend/Data/DefaultSeeder.cs b/src/Backend/Data/DefaultSeeder.cs new file mode 100644 index 0000000..ad09bfc --- /dev/null +++ b/src/Backend/Data/DefaultSeeder.cs @@ -0,0 +1,110 @@ +using Backend.Jobs; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; + +namespace Backend.Data; + +/// +/// First-boot defaults every deployment gets: platform dynamic groups and a +/// few common schedule cadences. Each family seeds only while its table is +/// empty, so operator edits and deletions are never fought. +/// +public static class DefaultSeeder +{ + public static async Task SeedAsync(AppDbContext db, CancellationToken cancellationToken) + { + await SeedGroupsAsync(db, cancellationToken); + await SeedSchedulesAsync(db, cancellationToken); + } + + private static async Task SeedGroupsAsync(AppDbContext db, CancellationToken cancellationToken) + { + if (await db.DeviceGroups.AnyAsync(cancellationToken)) + { + return; + } + + var now = DateTimeOffset.UtcNow; + foreach (var (name, description, rules) in PlatformGroups()) + { + db.DeviceGroups.Add(new DeviceGroupEntity + { + Id = Guid.NewGuid(), + Name = name, + Description = description, + Kind = GroupKind.Dynamic, + RulesJson = JsonDefaults.Serialize(rules), + CreatedUtc = now, + UpdatedUtc = now, + UpdatedBy = "system", + }); + } + + await db.SaveChangesAsync(cancellationToken); + } + + private static async Task SeedSchedulesAsync(AppDbContext db, CancellationToken cancellationToken) + { + if (await db.Schedules.AnyAsync(cancellationToken)) + { + return; + } + + var now = DateTimeOffset.UtcNow; + foreach (var (name, cron) in new[] + { + ("Hourly", "0 * * * *"), + ("Daily at 1:00 AM", "0 1 * * *"), + ("Weekdays at 7:00 AM", "0 7 * * MON-FRI"), + ("Weekly · Sunday 2:00 AM", "0 2 * * SUN"), + }) + { + db.Schedules.Add(new ScheduleEntity + { + Id = Guid.NewGuid(), + Name = name, + CronExpression = cron, + TimeZoneId = "UTC", + Enabled = true, + NextRunUtc = ScheduleCron.NextOccurrence(cron, "UTC", now), + CreatedUtc = now, + UpdatedUtc = now, + CreatedBy = "system", + UpdatedBy = "system", + }); + } + + await db.SaveChangesAsync(cancellationToken); + } + + private static IEnumerable<(string Name, string Description, GroupRuleSet Rules)> PlatformGroups() + { + static GroupRuleSet Set(params RuleCondition[] conditions) + => new(RuleCombine.And, [new RuleGroup(RuleCombine.And, conditions)]); + + yield return ("Windows Servers", "Every Windows Server edition.", + Set(new RuleCondition("os.platform", RuleOperator.Equals, "windows"), + new RuleCondition("os.caption", RuleOperator.Contains, "Server"))); + + yield return ("Windows Workstations", "Windows clients (10, 11, ...).", + Set(new RuleCondition("os.platform", RuleOperator.Equals, "windows"), + new RuleCondition("os.caption", RuleOperator.NotContains, "Server"))); + + yield return ("Linux", "All Linux devices.", + Set(new RuleCondition("os.platform", RuleOperator.Equals, "linux"))); + + // The unix agent reports os.edition from the boot target / installed + // desktop sessions: graphical => Workstation, headless => Server. + yield return ("Linux Servers", "Headless Linux (no graphical session).", + Set(new RuleCondition("os.platform", RuleOperator.Equals, "linux"), + new RuleCondition("os.edition", RuleOperator.Equals, "Server"))); + + yield return ("Linux Workstations", "Linux with a desktop environment.", + Set(new RuleCondition("os.platform", RuleOperator.Equals, "linux"), + new RuleCondition("os.edition", RuleOperator.Equals, "Workstation"))); + + yield return ("macOS", "All Apple devices.", + Set(new RuleCondition("os.platform", RuleOperator.Equals, "macos"))); + } +} diff --git a/src/Backend/Data/DevSeeder.cs b/src/Backend/Data/DevSeeder.cs index 65f21d8..2dbd076 100644 --- a/src/Backend/Data/DevSeeder.cs +++ b/src/Backend/Data/DevSeeder.cs @@ -64,7 +64,7 @@ public static class DevSeeder 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"])], + [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"], InterfaceName: "Ethernet0")], now - seenAgo); db.DeviceInventory.Add(new DeviceInventoryEntity diff --git a/src/Backend/Data/Entities.cs b/src/Backend/Data/Entities.cs index d3e45a1..c1c5594 100644 --- a/src/Backend/Data/Entities.cs +++ b/src/Backend/Data/Entities.cs @@ -12,6 +12,8 @@ public sealed class UserEntity public UserRole Role { get; set; } /// Assigned ; null falls back to the legacy tier. public Guid? RoleId { get; set; } + /// Sign-in must set a new password first (e.g. the defaulted admin/admin). + public bool MustChangePassword { get; set; } /// "local" or "oidc". public required string AuthProvider { get; set; } /// OIDC subject claim for external users. @@ -160,6 +162,8 @@ public sealed class ScriptEntity public string? SecretBindingsJson { get; set; } /// Session variable the resolved secrets dictionary binds to (default "Secrets"). public string? SecretsVariableName { get; set; } + /// JSON array of ScriptFileBinding definitions (S3 objects delivered before execution). + public string? FileBindingsJson { get; set; } public DateTimeOffset CreatedUtc { get; set; } public DateTimeOffset UpdatedUtc { get; set; } public string? CreatedBy { get; set; } diff --git a/src/Backend/Data/Migrations/Postgres/20260808140726_AddMustChangePassword.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260808140726_AddMustChangePassword.Designer.cs new file mode 100644 index 0000000..003544f --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260808140726_AddMustChangePassword.Designer.cs @@ -0,0 +1,809 @@ +// +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("20260808140726_AddMustChangePassword")] + partial class AddMustChangePassword + { + /// + 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.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("text"); + + b.Property("IsSystem") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("text"); + + b.Property("PermissionsJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (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("MustChangePassword") + .HasColumnType("boolean"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + 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/20260808140726_AddMustChangePassword.cs b/src/Backend/Data/Migrations/Postgres/20260808140726_AddMustChangePassword.cs new file mode 100644 index 0000000..8f73418 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260808140726_AddMustChangePassword.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddMustChangePassword : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "MustChangePassword", + table: "Users", + type: "boolean", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "MustChangePassword", + table: "Users"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260808150344_AddScriptFileBindings.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260808150344_AddScriptFileBindings.Designer.cs new file mode 100644 index 0000000..b725596 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260808150344_AddScriptFileBindings.Designer.cs @@ -0,0 +1,812 @@ +// +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("20260808150344_AddScriptFileBindings")] + partial class AddScriptFileBindings + { + /// + 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.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("text"); + + b.Property("IsSystem") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("text"); + + b.Property("PermissionsJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (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("FileBindingsJson") + .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("MustChangePassword") + .HasColumnType("boolean"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + 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/20260808150344_AddScriptFileBindings.cs b/src/Backend/Data/Migrations/Postgres/20260808150344_AddScriptFileBindings.cs new file mode 100644 index 0000000..197f732 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260808150344_AddScriptFileBindings.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddScriptFileBindings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "FileBindingsJson", + table: "Scripts", + type: "text", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "FileBindingsJson", + table: "Scripts"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs index 58bb899..a741e51 100644 --- a/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs @@ -515,6 +515,9 @@ namespace Backend.Data.Migrations.Postgres b.Property("Description") .HasColumnType("text"); + b.Property("FileBindingsJson") + .HasColumnType("text"); + b.Property("FunctionModuleIdsJson") .HasColumnType("text"); @@ -747,6 +750,9 @@ namespace Backend.Data.Migrations.Postgres b.Property("LastLoginUtc") .HasColumnType("timestamp with time zone"); + b.Property("MustChangePassword") + .HasColumnType("boolean"); + b.Property("PasswordHash") .HasColumnType("text"); diff --git a/src/Backend/Data/Migrations/SqlServer/20260808140730_AddMustChangePassword.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260808140730_AddMustChangePassword.Designer.cs new file mode 100644 index 0000000..b3848dd --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260808140730_AddMustChangePassword.Designer.cs @@ -0,0 +1,809 @@ +// +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("20260808140730_AddMustChangePassword")] + partial class AddMustChangePassword + { + /// + 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.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSystem") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PermissionsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (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("MustChangePassword") + .HasColumnType("bit"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + 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/20260808140730_AddMustChangePassword.cs b/src/Backend/Data/Migrations/SqlServer/20260808140730_AddMustChangePassword.cs new file mode 100644 index 0000000..310cda4 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260808140730_AddMustChangePassword.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddMustChangePassword : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "MustChangePassword", + table: "Users", + type: "bit", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "MustChangePassword", + table: "Users"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260808150347_AddScriptFileBindings.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260808150347_AddScriptFileBindings.Designer.cs new file mode 100644 index 0000000..3c0861d --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260808150347_AddScriptFileBindings.Designer.cs @@ -0,0 +1,812 @@ +// +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("20260808150347_AddScriptFileBindings")] + partial class AddScriptFileBindings + { + /// + 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.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSystem") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PermissionsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (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("FileBindingsJson") + .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("MustChangePassword") + .HasColumnType("bit"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + 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/20260808150347_AddScriptFileBindings.cs b/src/Backend/Data/Migrations/SqlServer/20260808150347_AddScriptFileBindings.cs new file mode 100644 index 0000000..9aa154c --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260808150347_AddScriptFileBindings.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddScriptFileBindings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "FileBindingsJson", + table: "Scripts", + type: "nvarchar(max)", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "FileBindingsJson", + table: "Scripts"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs index ecfd8b9..e37f31b 100644 --- a/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs @@ -515,6 +515,9 @@ namespace Backend.Data.Migrations.SqlServer b.Property("Description") .HasColumnType("nvarchar(max)"); + b.Property("FileBindingsJson") + .HasColumnType("nvarchar(max)"); + b.Property("FunctionModuleIdsJson") .HasColumnType("nvarchar(max)"); @@ -747,6 +750,9 @@ namespace Backend.Data.Migrations.SqlServer b.Property("LastLoginUtc") .HasColumnType("datetimeoffset"); + b.Property("MustChangePassword") + .HasColumnType("bit"); + b.Property("PasswordHash") .HasColumnType("nvarchar(max)"); diff --git a/src/Backend/Data/Migrations/Sqlite/20260808140722_AddMustChangePassword.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20260808140722_AddMustChangePassword.Designer.cs new file mode 100644 index 0000000..1080584 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260808140722_AddMustChangePassword.Designer.cs @@ -0,0 +1,796 @@ +// +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("20260808140722_AddMustChangePassword")] + partial class AddMustChangePassword + { + /// + 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.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("TEXT"); + + b.Property("PermissionsJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (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("MustChangePassword") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RoleId") + .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/20260808140722_AddMustChangePassword.cs b/src/Backend/Data/Migrations/Sqlite/20260808140722_AddMustChangePassword.cs new file mode 100644 index 0000000..7ac4113 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260808140722_AddMustChangePassword.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddMustChangePassword : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "MustChangePassword", + table: "Users", + type: "INTEGER", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "MustChangePassword", + table: "Users"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260808150341_AddScriptFileBindings.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20260808150341_AddScriptFileBindings.Designer.cs new file mode 100644 index 0000000..5b0a196 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260808150341_AddScriptFileBindings.Designer.cs @@ -0,0 +1,799 @@ +// +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("20260808150341_AddScriptFileBindings")] + partial class AddScriptFileBindings + { + /// + 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.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("TEXT"); + + b.Property("PermissionsJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (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("FileBindingsJson") + .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("MustChangePassword") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RoleId") + .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/20260808150341_AddScriptFileBindings.cs b/src/Backend/Data/Migrations/Sqlite/20260808150341_AddScriptFileBindings.cs new file mode 100644 index 0000000..bebac24 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260808150341_AddScriptFileBindings.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddScriptFileBindings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "FileBindingsJson", + table: "Scripts", + type: "TEXT", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "FileBindingsJson", + table: "Scripts"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs index 9eec497..4b2788d 100644 --- a/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs @@ -504,6 +504,9 @@ namespace Backend.Data.Migrations.Sqlite b.Property("Description") .HasColumnType("TEXT"); + b.Property("FileBindingsJson") + .HasColumnType("TEXT"); + b.Property("FunctionModuleIdsJson") .HasColumnType("TEXT"); @@ -734,6 +737,9 @@ namespace Backend.Data.Migrations.Sqlite b.Property("LastLoginUtc") .HasColumnType("INTEGER"); + b.Property("MustChangePassword") + .HasColumnType("INTEGER"); + b.Property("PasswordHash") .HasColumnType("TEXT"); diff --git a/src/Backend/Files/FileResolutionException.cs b/src/Backend/Files/FileResolutionException.cs new file mode 100644 index 0000000..2448381 --- /dev/null +++ b/src/Backend/Files/FileResolutionException.cs @@ -0,0 +1,9 @@ +namespace Backend.Files; + +/// +/// A script's file bindings could not be resolved (S3 unconfigured, listing or +/// presign failure) for an entry that does not continue on failure. Surfaces +/// before any job rows exist, exactly like secret resolution failures. +/// +public sealed class FileResolutionException(string message, Exception? inner = null) + : Exception(message, inner); diff --git a/src/Backend/Files/S3PresignService.cs b/src/Backend/Files/S3PresignService.cs index 812136b..564ae6e 100644 --- a/src/Backend/Files/S3PresignService.cs +++ b/src/Backend/Files/S3PresignService.cs @@ -35,4 +35,47 @@ public sealed class S3PresignService(S3SettingsService settings) return (url, new DateTimeOffset(expires, TimeSpan.Zero)); } + + /// + /// Every object key under a prefix (recursive), with sizes. Used for + /// directory file bindings; capped to keep a runaway prefix from turning + /// into a giant payload. + /// + public async Task> ListKeysAsync( + string prefix, CancellationToken cancellationToken, int maxKeys = 2000) + { + var options = await settings.GetEffectiveAsync(cancellationToken); + if (!options.IsUsable) + { + throw new InvalidOperationException("S3 is not configured."); + } + + using var client = S3ClientFactory.Create(options); + var results = new List<(string, long)>(); + var request = new ListObjectsV2Request { BucketName = options.Bucket, Prefix = prefix }; + + ListObjectsV2Response response; + do + { + response = await client.ListObjectsV2Async(request, cancellationToken); + foreach (var entry in response.S3Objects ?? []) + { + // Zero-byte "folder marker" objects are not downloadable content. + if (!entry.Key.EndsWith('/')) + { + results.Add((entry.Key, entry.Size ?? 0)); + } + + if (results.Count >= maxKeys) + { + return results; + } + } + + request.ContinuationToken = response.NextContinuationToken; + } + while (response.IsTruncated == true); + + return results; + } } diff --git a/src/Backend/Groups/DeviceGroupService.cs b/src/Backend/Groups/DeviceGroupService.cs index f4b5b8a..f8a9754 100644 --- a/src/Backend/Groups/DeviceGroupService.cs +++ b/src/Backend/Groups/DeviceGroupService.cs @@ -11,33 +11,89 @@ namespace Backend.Groups; /// /// Resolves group membership. Static groups use the explicit member table; /// dynamic groups evaluate their rules against each device's field bag -/// (inventory + tags + status + identity). +/// (inventory + tags + status + identity). Inventory parsing goes through +/// , so fleet-wide evaluation stays cheap at +/// thousands of devices: snapshots are re-fetched and re-parsed only when +/// their UpdatedUtc moved. /// -public sealed class DeviceGroupService(AppDbContext db) +public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inventoryCache) { /// Builds the rule field bag for one device. - public static DeviceFieldBag BuildFields(DeviceEntity device, string? inventoryJson, DateTimeOffset now) - { - InventoryReport? inventory = null; - if (!string.IsNullOrWhiteSpace(inventoryJson)) - { - try - { - inventory = JsonDefaults.Deserialize(inventoryJson); - } - catch (Exception) - { - // Corrupt snapshot: evaluate on identity fields only. - } - } - - return DeviceFieldBag.Build( + public static DeviceFieldBag BuildFields(DeviceEntity device, InventoryReport? inventory, DateTimeOffset now) + => DeviceFieldBag.Build( device.ClientId, device.Hostname, ProtocolDefaults.CalculateStatus(device.LastSeenUtc, now), device.AgentVersion, ParseTags(device.TagsJson), - inventory); + inventory, + fallbackOsCaption: device.OsCaption, + fallbackOsVersion: device.OsVersion); + + /// + /// Cached inventory for one device: metadata probe first, JSON fetched + /// only when the snapshot changed since it was last parsed. + /// + private async Task GetInventoryAsync(string clientId, CancellationToken cancellationToken) + { + var meta = await db.DeviceInventory.AsNoTracking() + .Where(i => i.ClientId == clientId) + .Select(i => new { i.UpdatedUtc }) + .FirstOrDefaultAsync(cancellationToken); + if (meta is null) + { + return null; + } + + if (inventoryCache.TryGet(clientId, meta.UpdatedUtc, out var cached)) + { + return cached; + } + + var json = await db.DeviceInventory.AsNoTracking() + .Where(i => i.ClientId == clientId) + .Select(i => i.ReportJson) + .FirstOrDefaultAsync(cancellationToken); + return inventoryCache.Store(clientId, meta.UpdatedUtc, json); + } + + /// Cached inventory for every device, fetching only changed snapshots. + private async Task> GetAllInventoryAsync(CancellationToken cancellationToken) + { + var metadata = await db.DeviceInventory.AsNoTracking() + .Select(i => new { i.ClientId, i.UpdatedUtc }) + .ToListAsync(cancellationToken); + + var result = new Dictionary(metadata.Count); + var misses = new List(); + foreach (var row in metadata) + { + if (inventoryCache.TryGet(row.ClientId, row.UpdatedUtc, out var cached)) + { + result[row.ClientId] = cached; + } + else + { + misses.Add(row.ClientId); + } + } + + if (misses.Count > 0) + { + var updatedByClient = metadata.ToDictionary(m => m.ClientId, m => m.UpdatedUtc); + var rows = await db.DeviceInventory.AsNoTracking() + .Where(i => misses.Contains(i.ClientId)) + .Select(i => new { i.ClientId, i.ReportJson }) + .ToListAsync(cancellationToken); + foreach (var row in rows) + { + result[row.ClientId] = inventoryCache.Store( + row.ClientId, updatedByClient[row.ClientId], row.ReportJson); + } + } + + inventoryCache.Prune(metadata.Select(m => m.ClientId).ToHashSet(StringComparer.Ordinal)); + return result; } public static IReadOnlyList ParseTags(string? tagsJson) @@ -86,17 +142,13 @@ public sealed class DeviceGroupService(AppDbContext db) public async Task> EvaluateAsync(GroupRuleSet rules, CancellationToken cancellationToken) { var now = DateTimeOffset.UtcNow; - var rows = await db.Devices.AsNoTracking() - .GroupJoin( - db.DeviceInventory.AsNoTracking(), - d => d.ClientId, - i => i.ClientId, - (d, inv) => new { Device = d, Inventory = inv.Select(x => x.ReportJson).FirstOrDefault() }) - .ToListAsync(cancellationToken); + var devices = await db.Devices.AsNoTracking().ToListAsync(cancellationToken); + var inventory = await GetAllInventoryAsync(cancellationToken); - return rows - .Where(r => RuleEvaluator.Matches(rules, BuildFields(r.Device, r.Inventory, now))) - .Select(r => r.Device.ClientId) + return devices + .Where(d => RuleEvaluator.Matches( + rules, BuildFields(d, inventory.GetValueOrDefault(d.ClientId), now))) + .Select(d => d.ClientId) .ToList(); } @@ -116,17 +168,14 @@ public sealed class DeviceGroupService(AppDbContext db) return []; } - var inventoryJson = await db.DeviceInventory.AsNoTracking() - .Where(i => i.ClientId == clientId) - .Select(i => i.ReportJson) - .FirstOrDefaultAsync(cancellationToken); + var inventory = await GetInventoryAsync(clientId, cancellationToken); var staticGroupIds = await db.DeviceGroupMembers.AsNoTracking() .Where(m => m.ClientId == clientId) .Select(m => m.GroupId) .ToListAsync(cancellationToken); - var fields = BuildFields(device, inventoryJson, DateTimeOffset.UtcNow); + var fields = BuildFields(device, inventory, DateTimeOffset.UtcNow); var result = new List(); foreach (var group in groups) @@ -176,11 +225,7 @@ public sealed class DeviceGroupService(AppDbContext db) return false; } - var inventoryJson = await db.DeviceInventory.AsNoTracking() - .Where(i => i.ClientId == clientId) - .Select(i => i.ReportJson) - .FirstOrDefaultAsync(cancellationToken); - - return RuleEvaluator.Matches(rules, BuildFields(device, inventoryJson, DateTimeOffset.UtcNow)); + var inventory = await GetInventoryAsync(clientId, cancellationToken); + return RuleEvaluator.Matches(rules, BuildFields(device, inventory, DateTimeOffset.UtcNow)); } } diff --git a/src/Backend/Groups/InventoryReportCache.cs b/src/Backend/Groups/InventoryReportCache.cs new file mode 100644 index 0000000..7609d12 --- /dev/null +++ b/src/Backend/Groups/InventoryReportCache.cs @@ -0,0 +1,65 @@ +using System.Collections.Concurrent; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; + +namespace Backend.Groups; + +/// +/// Parsed inventory snapshots keyed by device, invalidated by the snapshot's +/// UpdatedUtc. Dynamic-group evaluation runs against every device on every +/// use (member listings, fan-out, schedule fires, trigger scoping), and +/// deserializing thousands of inventory blobs each time is the hot cost — +/// cached, an evaluation only parses snapshots that actually changed and only +/// fetches JSON for those from the database. +/// +public sealed class InventoryReportCache +{ + private sealed record Entry(DateTimeOffset UpdatedUtc, InventoryReport? Report); + + private readonly ConcurrentDictionary entries = new(); + + /// The cached report, when the caller's UpdatedUtc still matches. + public bool TryGet(string clientId, DateTimeOffset updatedUtc, out InventoryReport? report) + { + if (entries.TryGetValue(clientId, out var entry) && entry.UpdatedUtc == updatedUtc) + { + report = entry.Report; + return true; + } + + report = null; + return false; + } + + /// Parses and stores a fresh snapshot (corrupt JSON caches as null). + public InventoryReport? Store(string clientId, DateTimeOffset updatedUtc, string? reportJson) + { + InventoryReport? report = null; + if (!string.IsNullOrWhiteSpace(reportJson)) + { + try + { + report = JsonDefaults.Deserialize(reportJson); + } + catch (Exception) + { + // Corrupt snapshot: evaluate on identity fields only. + } + } + + entries[clientId] = new Entry(updatedUtc, report); + return report; + } + + /// Drops entries for devices that no longer exist. + public void Prune(IReadOnlySet liveClientIds) + { + foreach (var key in entries.Keys) + { + if (!liveClientIds.Contains(key)) + { + entries.TryRemove(key, out _); + } + } + } +} diff --git a/src/Backend/Jobs/JobEndpoints.cs b/src/Backend/Jobs/JobEndpoints.cs index 972e0db..05bcfa7 100644 --- a/src/Backend/Jobs/JobEndpoints.cs +++ b/src/Backend/Jobs/JobEndpoints.cs @@ -97,14 +97,16 @@ public static class JobEndpoints 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. + // Secrets, file presigns and the prelude are prepared once, before any + // job rows exist: a vault or S3 failure surfaces immediately instead + // of minting failed jobs. PreparedScript prepared; try { prepared = await runner.PrepareAsync(script, cancellationToken); } - catch (Backend.Secrets.SecretResolutionException ex) + catch (Exception ex) when ( + ex is Backend.Secrets.SecretResolutionException or Backend.Files.FileResolutionException) { return Results.Problem(ex.Message, statusCode: StatusCodes.Status502BadGateway); } diff --git a/src/Backend/Jobs/JobRunner.cs b/src/Backend/Jobs/JobRunner.cs index 9514ade..4b5ce63 100644 --- a/src/Backend/Jobs/JobRunner.cs +++ b/src/Backend/Jobs/JobRunner.cs @@ -11,14 +11,15 @@ 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). +/// parameters deserialized, secret bindings resolved and file bindings +/// presigned (once — a group fan-out reuses the same values for every member). /// public sealed record PreparedScript( ScriptEntity Script, string? Prelude, IReadOnlyList? Parameters, - IReadOnlyList? Secrets); + IReadOnlyList? Secrets, + IReadOnlyList? Files = null); /// /// The one path from "run this script on this device" to a dispatched job. @@ -30,9 +31,14 @@ public sealed class JobRunner( AppDbContext db, CommandDispatcher dispatcher, BrowserEventBroadcaster broadcaster, - SecretsProviderService secretsService) + SecretsProviderService secretsService, + Backend.Files.S3PresignService s3) { - /// Composes the prelude and resolves secrets. Throws . + /// + /// Composes the prelude, resolves secrets and presigns file bindings. + /// Throws / + /// . + /// public async Task PrepareAsync(ScriptEntity script, CancellationToken cancellationToken) { var parameters = Backend.Scripts.ScriptEndpoints.DeserializeParameters(script.ParametersJson); @@ -46,7 +52,75 @@ public sealed class JobRunner( secrets = await secretsService.ResolveAsync(bindings, cancellationToken); } - return new PreparedScript(script, prelude, parameters.Count > 0 ? parameters : null, secrets); + var files = await ResolveFilesAsync( + Backend.Scripts.ScriptEndpoints.DeserializeFileBindings(script.FileBindingsJson), cancellationToken); + + return new PreparedScript(script, prelude, parameters.Count > 0 ? parameters : null, secrets, files); + } + + /// + /// Presigns every file binding: single objects become one item, directory + /// bindings list the prefix recursively and presign each object. Failures + /// throw unless the binding continues on failure, in which case the entry + /// ships with the error so the agent can log it and still run the script. + /// + private async Task?> ResolveFilesAsync( + IReadOnlyList bindings, CancellationToken cancellationToken) + { + if (bindings.Count == 0) + { + return null; + } + + var deliveries = new List(bindings.Count); + foreach (var binding in bindings) + { + try + { + if (binding.Directory) + { + var prefix = binding.ObjectKey.TrimEnd('/') + "/"; + var keys = await s3.ListKeysAsync(prefix, cancellationToken); + if (keys.Count == 0) + { + throw new Backend.Files.FileResolutionException( + $"File binding “{binding.Name}”: no objects under “{prefix}”."); + } + + var items = new List(keys.Count); + foreach (var (key, size) in keys) + { + var (url, _) = await s3.PresignGetAsync(key, cancellationToken); + items.Add(new ScriptFileItem(key[prefix.Length..], url, size)); + } + + deliveries.Add(new ScriptFileDelivery( + binding.Name, binding.DestinationPath, true, binding.ContinueOnFailure, items)); + } + else + { + var (url, _) = await s3.PresignGetAsync(binding.ObjectKey, cancellationToken); + deliveries.Add(new ScriptFileDelivery( + binding.Name, binding.DestinationPath, false, binding.ContinueOnFailure, + [new ScriptFileItem(string.Empty, url)])); + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + var message = ex is Backend.Files.FileResolutionException + ? ex.Message + : $"File binding “{binding.Name}”: {ex.Message}"; + if (!binding.ContinueOnFailure) + { + throw new Backend.Files.FileResolutionException(message, ex); + } + + deliveries.Add(new ScriptFileDelivery( + binding.Name, binding.DestinationPath, binding.Directory, true, [], message)); + } + } + + return deliveries; } public async Task CreateJobAsync( @@ -86,7 +160,8 @@ public sealed class JobRunner( Arguments: arguments, SecretsVariableName: script.SecretsVariableName, Secrets: prepared.Secrets, - Engine: Backend.Scripts.ScriptEndpoints.ParseEngine(script.Language)), + Engine: Backend.Scripts.ScriptEndpoints.ParseEngine(script.Language), + Files: prepared.Files), cancellationToken); if (dispatched) diff --git a/src/Backend/Jobs/ScheduleWorker.cs b/src/Backend/Jobs/ScheduleWorker.cs index 139534a..936bde6 100644 --- a/src/Backend/Jobs/ScheduleWorker.cs +++ b/src/Backend/Jobs/ScheduleWorker.cs @@ -143,7 +143,8 @@ public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger 0 && args[0] == "auth-reset") // CLI mode: standalone single-binary server management. if (args.Length > 0 && args[0] == "setup") { - return Backend.Standalone.ServerCli.RunSetup(); + return await Backend.Standalone.ServerCli.RunSetupAsync(args[1..]); } if (args.Length > 0 && args[0] == "service") @@ -46,7 +46,15 @@ if (args.Length > 0 && args[0] == "service") return Backend.Standalone.ServerCli.RunService(args[1..]); } -var builder = WebApplication.CreateBuilder(args); +// Standalone bundle: when setup generated an appsettings.json next to the +// binary, anchor the content root there so the server behaves identically +// however it is launched (console from any directory, SCM, systemd). +var standaloneSettings = Path.Combine(AppContext.BaseDirectory, "appsettings.json"); +var builder = WebApplication.CreateBuilder(new WebApplicationOptions +{ + Args = args, + ContentRootPath = File.Exists(standaloneSettings) ? AppContext.BaseDirectory : null, +}); // Standalone mode: run cleanly as a Windows service or under systemd // (both are no-ops when launched normally or inside a container). @@ -83,6 +91,7 @@ builder.Services.AddApplicationDatabase(databaseOptions); builder.Services.AddScoped(); builder.Services.AddSingleton(DeviceLifecycleOptions.FromConfiguration(builder.Configuration)); +builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); @@ -127,7 +136,12 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); -builder.Services.AddHostedService(); +// SCHEDULE_WORKER=0 keeps the background sweep out of test hosts, where it +// races the tests' deterministic manual sweeps. +if (builder.Configuration["SCHEDULE_WORKER"] != "0") +{ + builder.Services.AddHostedService(); +} builder.Services.AddHostedService(sp => sp.GetRequiredService()); // ── Rate limiting ──────────────────────────────────────────────────────── @@ -170,10 +184,16 @@ using (var scope = app.Services.CreateScope()) // System roles must exist before any user is created or resolved. await scope.ServiceProvider.GetRequiredService().EnsureSystemRolesAsync(CancellationToken.None); - // First-boot initial admin from environment secrets (never a default password). + // First-boot defaults: platform dynamic groups + starter schedules. + await DefaultSeeder.SeedAsync(db, CancellationToken.None); + + // First-boot initial admin from environment secrets. INITIAL_ADMIN_MUST_CHANGE + // (set by standalone `setup` when the admin/admin default was used) forces a + // password reset on the first sign-in. await scope.ServiceProvider.GetRequiredService().EnsureInitialAdminAsync( builder.Configuration["INITIAL_ADMIN_USERNAME"], builder.Configuration["INITIAL_ADMIN_PASSWORD"], + builder.Configuration["INITIAL_ADMIN_MUST_CHANGE"] == "1", CancellationToken.None); if (app.Environment.IsDevelopment() && !db.Scripts.Any()) diff --git a/src/Backend/Scripts/ScriptEndpoints.cs b/src/Backend/Scripts/ScriptEndpoints.cs index 247255b..402b3bc 100644 --- a/src/Backend/Scripts/ScriptEndpoints.cs +++ b/src/Backend/Scripts/ScriptEndpoints.cs @@ -48,6 +48,11 @@ public static class ScriptEndpoints return secretsProblem; } + if (ValidateFiles(request) is { } filesProblem) + { + return filesProblem; + } + var now = DateTimeOffset.UtcNow; var actor = context.User.Identity?.Name; var script = new ScriptEntity @@ -61,6 +66,7 @@ public static class ScriptEndpoints FunctionModuleIdsJson = SerializeModuleIds(request.FunctionModuleIds), SecretBindingsJson = SerializeSecretBindings(request.SecretBindings), SecretsVariableName = NormalizeVariableName(request.SecretsVariableName), + FileBindingsJson = SerializeFileBindings(request.FileBindings), CreatedUtc = now, UpdatedUtc = now, CreatedBy = actor, @@ -92,6 +98,11 @@ public static class ScriptEndpoints return secretsProblem; } + if (ValidateFiles(request) is { } filesProblem) + { + return filesProblem; + } + script.Name = request.Name.Trim(); script.Description = request.Description; script.Language = request.Engine.ToString(); @@ -100,6 +111,7 @@ public static class ScriptEndpoints script.FunctionModuleIdsJson = SerializeModuleIds(request.FunctionModuleIds); script.SecretBindingsJson = SerializeSecretBindings(request.SecretBindings); script.SecretsVariableName = NormalizeVariableName(request.SecretsVariableName); + script.FileBindingsJson = SerializeFileBindings(request.FileBindings); script.UpdatedUtc = DateTimeOffset.UtcNow; script.UpdatedBy = context.User.Identity?.Name; await db.SaveChangesAsync(cancellationToken); @@ -131,7 +143,8 @@ public static class ScriptEndpoints DeserializeModuleIds(script.FunctionModuleIdsJson), script.CreatedUtc, script.UpdatedUtc, script.CreatedBy, script.UpdatedBy, DeserializeSecretBindings(script.SecretBindingsJson), - script.SecretsVariableName); + script.SecretsVariableName, + DeserializeFileBindings(script.FileBindingsJson)); /// The injected dictionary must bind to a legal PowerShell variable name. private static IResult? ValidateSecrets(SaveScriptRequest request) @@ -185,6 +198,57 @@ public static class ScriptEndpoints } } + /// Dictionary keys must be legal variable-ish names; every entry needs a key and destination. + private static IResult? ValidateFiles(SaveScriptRequest request) + { + foreach (var binding in request.FileBindings ?? []) + { + if (string.IsNullOrWhiteSpace(binding.Name) + || !System.Text.RegularExpressions.Regex.IsMatch(binding.Name.Trim(), "^[A-Za-z_][A-Za-z0-9_]*$")) + { + return Results.BadRequest(new + { + error = "Every file binding needs a name usable as $Files. (letters, digits, underscore).", + }); + } + + if (string.IsNullOrWhiteSpace(binding.ObjectKey) || string.IsNullOrWhiteSpace(binding.DestinationPath)) + { + return Results.BadRequest(new + { + error = $"File binding “{binding.Name}” needs an S3 key and a destination path.", + }); + } + + // A directory delivery unpacks a tree INTO the destination — a + // leaf file path (extension on the last segment) is a mistake. + if (binding.Directory && LooksLikeFilePath(binding.DestinationPath)) + { + return Results.BadRequest(new + { + error = $"File binding “{binding.Name}” is a directory delivery — the destination " + + "must be a directory, not a file path.", + }); + } + } + + return null; + } + + internal static bool LooksLikeFilePath(string destinationPath) + { + var leaf = Path.GetFileName(destinationPath.TrimEnd('/', '\\')); + return System.Text.RegularExpressions.Regex.IsMatch(leaf, @"\.[A-Za-z][A-Za-z0-9]{0,6}$"); + } + + internal static string? SerializeFileBindings(IReadOnlyList? bindings) + => bindings is null || bindings.Count == 0 ? null : JsonDefaults.Serialize(bindings); + + internal static IReadOnlyList DeserializeFileBindings(string? json) + => string.IsNullOrWhiteSpace(json) + ? [] + : JsonDefaults.Deserialize>(json) ?? []; + internal static string? SerializeSecretBindings(IReadOnlyList? bindings) => bindings is null || bindings.Count == 0 ? null : JsonDefaults.Serialize(bindings); diff --git a/src/Backend/Standalone/ServerCli.cs b/src/Backend/Standalone/ServerCli.cs index 367abb8..a566e75 100644 --- a/src/Backend/Standalone/ServerCli.cs +++ b/src/Backend/Standalone/ServerCli.cs @@ -1,4 +1,7 @@ using System.Diagnostics; +using System.Formats.Tar; +using System.IO.Compression; +using System.Runtime.InteropServices; using Backend.Nats; namespace Backend.Standalone; @@ -6,7 +9,9 @@ namespace Backend.Standalone; /// /// Standalone-server commands for the combined single-binary deployment: /// -/// setup — generate NATS keys + sidecar config + appsettings +/// setup [--admin-user U] [--admin-password P] +/// — generate NATS keys + sidecar config + appsettings, +/// downloading nats-server for this platform if absent /// service install — register as a Windows service / systemd unit /// service uninstall — stop and remove the service /// @@ -18,8 +23,32 @@ public static class ServerCli public const string WindowsServiceName = "ExecuteRServer"; public const string SystemdUnitName = "executer-server"; - public static int RunSetup() + private const string NatsVersion = "2.14.4"; + + public static async Task RunSetupAsync(string[] args) { + // Bare `setup` fully configures the server: admin/admin unless the + // flags override — and the defaulted password forces a reset prompt + // on the first sign-in. + var adminUser = "admin"; + var adminPassword = "admin"; + var passwordDefaulted = true; + for (var i = 0; i < args.Length - 1; i++) + { + switch (args[i]) + { + case "--admin-user": + adminUser = args[++i]; + break; + case "--admin-password": + adminPassword = args[++i]; + // The MSI passes the flag even when the wizard default was + // kept: a literal "admin" password always forces the reset. + passwordDefaulted = adminPassword == "admin"; + break; + } + } + var baseDir = AppContext.BaseDirectory; var natsDir = Path.Combine(baseDir, "nats"); var secretsDir = Path.Combine(baseDir, "secrets", "nats"); @@ -27,6 +56,14 @@ public static class ServerCli Directory.CreateDirectory(natsDir); Directory.CreateDirectory(dataDir); + // The sidecar binary: packaged bundles ship it; a bare binary (MSI or + // direct download) fetches it here so setup works the same everywhere. + var ensured = await EnsureNatsServerAsync(natsDir); + if (ensured != 0) + { + return ensured; + } + // NATS operator/account keys + resolver preload (idempotent). if (!File.Exists(Path.Combine(secretsDir, "resolver.conf"))) { @@ -83,28 +120,125 @@ public static class ServerCli "DATABASE_PATH": "{{Path.Combine(dataDir, "app.db").Replace('\\', '/')}}", "DATAPROTECTION_PATH": "{{Path.Combine(dataDir, "keys").Replace('\\', '/')}}", "LOG_PATH": "{{Path.Combine(dataDir, "logs").Replace('\\', '/')}}", + "AGENT_PACKAGE_PATH": "{{Path.Combine(baseDir, "agent-package").Replace('\\', '/')}}", "NATS_URL": "nats://127.0.0.1:4222", "NATS_SIDECAR": "1", "NATS_WS_PROXY": "ws://127.0.0.1:9222", "NATS_ACCOUNT_SIGNING_SEED": "{{signingSeed}}", "NATS_ACCOUNT_PUBLIC_KEY": "{{accountPublic}}", - "INITIAL_ADMIN_USERNAME": "admin", - "INITIAL_ADMIN_PASSWORD": "" + "INITIAL_ADMIN_USERNAME": "{{adminUser}}", + "INITIAL_ADMIN_PASSWORD": "{{adminPassword}}", + "INITIAL_ADMIN_MUST_CHANGE": "{{(passwordDefaulted ? "1" : "0")}}" } """); Console.WriteLine($"Wrote {appsettings}"); - Console.WriteLine(); - Console.WriteLine("Set INITIAL_ADMIN_PASSWORD in appsettings.json before first start."); } Console.WriteLine(); - Console.WriteLine("Setup complete. Next:"); - Console.WriteLine(" 1. Set INITIAL_ADMIN_PASSWORD in appsettings.json (first start only)."); - Console.WriteLine(" 2. Run the binary directly, or `service install` to run in the background."); - Console.WriteLine(" 3. Put a TLS-terminating proxy in front for production use."); + Console.WriteLine("Setup complete."); + Console.WriteLine(passwordDefaulted + ? $" - First sign-in: {adminUser} / admin — a new password is required immediately." + : $" - First sign-in: {adminUser} / ."); + Console.WriteLine(" - Run the binary directly, or `service install` to run in the background."); + Console.WriteLine(" - Put a TLS-terminating proxy in front for production use."); return 0; } + /// + /// Downloads and unpacks nats-server for the current OS/architecture when + /// it is not already next to the binary. Idempotent; packaged bundles ship + /// the sidecar so this is normally a no-op. + /// + private static async Task EnsureNatsServerAsync(string natsDir) + { + var binaryName = OperatingSystem.IsWindows() ? "nats-server.exe" : "nats-server"; + var target = Path.Combine(natsDir, binaryName); + if (File.Exists(target)) + { + return 0; + } + + var os = OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "darwin" : "linux"; + var arch = RuntimeInformation.OSArchitecture switch + { + Architecture.Arm64 => "arm64", + Architecture.X64 => "amd64", + var other => other.ToString().ToLowerInvariant(), + }; + var extension = OperatingSystem.IsWindows() ? "zip" : "tar.gz"; + var archive = $"nats-server-v{NatsVersion}-{os}-{arch}.{extension}"; + var url = $"https://github.com/nats-io/nats-server/releases/download/v{NatsVersion}/{archive}"; + + Console.WriteLine($"Downloading {archive} ..."); + var staging = Path.Combine(natsDir, ".download"); + try + { + using var http = new HttpClient(); + await using var download = await http.GetStreamAsync(url); + + if (Directory.Exists(staging)) + { + Directory.Delete(staging, recursive: true); + } + + Directory.CreateDirectory(staging); + if (extension == "zip") + { + var zipPath = Path.Combine(staging, archive); + await using (var file = File.Create(zipPath)) + { + await download.CopyToAsync(file); + } + + ZipFile.ExtractToDirectory(zipPath, staging); + } + else + { + await using var gzip = new GZipStream(download, CompressionMode.Decompress); + await TarFile.ExtractToDirectoryAsync(gzip, staging, overwriteFiles: true); + } + + var extracted = Directory.EnumerateFiles(staging, binaryName, SearchOption.AllDirectories).FirstOrDefault(); + if (extracted is null) + { + Console.Error.WriteLine($"{binaryName} was not found inside {archive}."); + return 1; + } + + File.Move(extracted, target, overwrite: true); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(target, + UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute + | UnixFileMode.GroupRead | UnixFileMode.GroupExecute + | UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + } + + Console.WriteLine($"nats-server v{NatsVersion} installed to {target}"); + return 0; + } + catch (Exception ex) when (ex is HttpRequestException or IOException or InvalidDataException) + { + Console.Error.WriteLine($"Could not download nats-server: {ex.Message}"); + Console.Error.WriteLine($"Place {binaryName} in {natsDir} manually and re-run setup."); + return 1; + } + finally + { + try + { + if (Directory.Exists(staging)) + { + Directory.Delete(staging, recursive: true); + } + } + catch (IOException) + { + // Best effort. + } + } + } + public static int RunService(string[] args) { if (args.Length == 0) @@ -126,10 +260,13 @@ public static class ServerCli private static int InstallWindows(string exe) { - Run("sc.exe", $"create {WindowsServiceName} binPath= \"\\\"{exe}\\\"\" start= delayed-auto DisplayName= \"ExecuteR Server\""); + // Idempotent: create may fail when the service exists (repair or MSI + // upgrade); config then points it at the current binary either way. + Run("sc.exe", $"create {WindowsServiceName} binPath= \"\\\"{exe}\\\"\" start= delayed-auto DisplayName= \"ExecuteR Server\"", ignoreErrors: true); + Run("sc.exe", $"config {WindowsServiceName} binPath= \"\\\"{exe}\\\"\" start= delayed-auto"); Run("sc.exe", $"description {WindowsServiceName} \"ExecuteR control plane (UI, API, messaging).\""); Run("sc.exe", $"failure {WindowsServiceName} reset= 86400 actions= restart/30000/restart/30000/restart/30000"); - Run("sc.exe", $"start {WindowsServiceName}"); + Run("sc.exe", $"start {WindowsServiceName}", ignoreErrors: true); Console.WriteLine($"Service {WindowsServiceName} installed and started."); return 0; } diff --git a/src/Installer.Server/Product.wxs b/src/Installer.Server/Product.wxs new file mode 100644 index 0000000..39e13e9 --- /dev/null +++ b/src/Installer.Server/Product.wxs @@ -0,0 +1,159 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Installer.Server/Server.Installer.wixproj b/src/Installer.Server/Server.Installer.wixproj new file mode 100644 index 0000000..a18d991 --- /dev/null +++ b/src/Installer.Server/Server.Installer.wixproj @@ -0,0 +1,24 @@ + + + + + Server + x64 + + ICE61;ICE60 + 0.0.0 + + $(MSBuildThisFileDirectory)..\..\artifacts\server\current\win-x64 + $(MSBuildThisFileDirectory)..\..\assets\icons\app.ico + $(DefineConstants);UnifiedVersion=$(UnifiedVersion);MsiProductVersion=$(MsiProductVersion);ServerPublishDir=$(ServerPublishDir);AppIconPath=$(AppIconPath) + + + + + + + + diff --git a/src/Installer/Agent.Installer.wixproj b/src/Installer/Agent.Installer.wixproj index 3b02dc5..4aaec55 100644 --- a/src/Installer/Agent.Installer.wixproj +++ b/src/Installer/Agent.Installer.wixproj @@ -12,7 +12,7 @@ 0.0.0 $(MSBuildThisFileDirectory)..\Agent\bin\Release\net10.0-windows\win-x64\publish - $(MSBuildThisFileDirectory)..\..\artifacts\icons\app.ico + $(MSBuildThisFileDirectory)..\..\assets\icons\app.ico $(DefineConstants);UnifiedVersion=$(UnifiedVersion);MsiProductVersion=$(MsiProductVersion);AgentPublishDir=$(AgentPublishDir) $(DefineConstants);AppIconPath=$(AppIconPath) diff --git a/src/Shared.Contracts/Api/ApiRoutes.cs b/src/Shared.Contracts/Api/ApiRoutes.cs index d14d3fc..c5102f5 100644 --- a/src/Shared.Contracts/Api/ApiRoutes.cs +++ b/src/Shared.Contracts/Api/ApiRoutes.cs @@ -11,6 +11,7 @@ public static class ApiRoutes public const string Ready = "/api/ready"; public const string AuthLogin = "/api/auth/login"; + public const string AuthChangePassword = "/api/auth/change-password"; public const string AuthLogout = "/api/auth/logout"; public const string AuthSession = "/api/auth/session"; public const string AuthConfig = "/api/auth/config"; diff --git a/src/Shared.Contracts/Api/AuthDtos.cs b/src/Shared.Contracts/Api/AuthDtos.cs index 1e57a15..5272c34 100644 --- a/src/Shared.Contracts/Api/AuthDtos.cs +++ b/src/Shared.Contracts/Api/AuthDtos.cs @@ -5,6 +5,13 @@ namespace Shared.Contracts.Api; /// POST /api/auth/login request body. public sealed record LoginRequest(string Username, string Password); +/// +/// POST /api/auth/change-password request body. Pre-session: the current +/// password authenticates the request, so this also completes the forced +/// first-sign-in reset of the defaulted admin account. +/// +public sealed record ChangePasswordRequest(string Username, string CurrentPassword, string NewPassword); + /// /// GET /api/auth/config — anonymous. Tells the sign-in page what to render; /// contains nothing sensitive. @@ -52,7 +59,9 @@ public sealed record SessionResponse( UserRole? Role, string? AuthProvider, string? RoleName = null, - IReadOnlyList? Permissions = null); + IReadOnlyList? Permissions = null, + // Credentials were valid but a new password must be set before a session is issued. + bool MustChangePassword = false); /// /// POST /api/messaging/credential request body. Pass the previously issued diff --git a/src/Shared.Contracts/Api/ResourceDtos.cs b/src/Shared.Contracts/Api/ResourceDtos.cs index 2ec98c0..99ae51d 100644 --- a/src/Shared.Contracts/Api/ResourceDtos.cs +++ b/src/Shared.Contracts/Api/ResourceDtos.cs @@ -93,7 +93,8 @@ public sealed record ScriptDto( string? CreatedBy, string? UpdatedBy, IReadOnlyList? SecretBindings = null, - string? SecretsVariableName = null); + string? SecretsVariableName = null, + IReadOnlyList? FileBindings = null); /// POST/PUT /api/scripts request body. public sealed record SaveScriptRequest( @@ -104,7 +105,8 @@ public sealed record SaveScriptRequest( IReadOnlyList? FunctionModuleIds = null, IReadOnlyList? SecretBindings = null, string? SecretsVariableName = null, - ScriptEngine Engine = ScriptEngine.PowerShell); + ScriptEngine Engine = ScriptEngine.PowerShell, + IReadOnlyList? FileBindings = null); /// /// Configured secrets provider. Config is driver-specific and sanitized: diff --git a/src/Shared.Contracts/Messages/Payloads.cs b/src/Shared.Contracts/Messages/Payloads.cs index 8c43a18..7d0648c 100644 --- a/src/Shared.Contracts/Messages/Payloads.cs +++ b/src/Shared.Contracts/Messages/Payloads.cs @@ -40,6 +40,28 @@ public static class AgentEventKinds /// public sealed record ScriptSecret(string Name, string Value); +/// One downloadable piece of a script file delivery (presigned). +public sealed record ScriptFileItem( + // Path relative to the delivery's destination; empty for a single file + // (the destination IS the file path). + string RelativePath, + string Url, + long? SizeBytes = null); + +/// +/// One resolved file binding delivered with a job: the agent downloads every +/// item before the script starts, expanding on +/// the device. carries a server-side resolution failure +/// for continue-on-failure entries (the agent logs it and runs the script). +/// +public sealed record ScriptFileDelivery( + string Name, + string DestinationPath, + bool Directory, + bool ContinueOnFailure, + IReadOnlyList Items, + string? Error = null); + /// /// Durable script execution command on agent.<clientId>.command.script. /// holds reusable function-module content run first in the @@ -60,7 +82,8 @@ public sealed record ScriptCommandPayload( IReadOnlyDictionary? Arguments = null, string? SecretsVariableName = null, IReadOnlyList? Secrets = null, - Shared.Contracts.Models.ScriptEngine Engine = Shared.Contracts.Models.ScriptEngine.PowerShell); + Shared.Contracts.Models.ScriptEngine Engine = Shared.Contracts.Models.ScriptEngine.PowerShell, + IReadOnlyList? Files = null); /// Inventory refresh command on agent.<clientId>.command.inventory. public sealed record InventoryCommandPayload(string? Reason); diff --git a/src/Shared.Contracts/Models/GroupRules.cs b/src/Shared.Contracts/Models/GroupRules.cs index ce40661..6903db2 100644 --- a/src/Shared.Contracts/Models/GroupRules.cs +++ b/src/Shared.Contracts/Models/GroupRules.cs @@ -32,6 +32,10 @@ public enum RuleOperator LessOrEqual, Exists, NotExists, + + /// Value is an IP address inside any of the listed CIDR ranges (or equals a bare IP). + InCidr, + NotInCidr, } /// @@ -93,6 +97,7 @@ public static class GroupFields new("systemType", "System type", "Hardware"), new("domain", "Domain / workgroup", "Identity"), new("partOfDomain", "Domain joined", "Identity"), + new("os.platform", "Platform (windows/linux/macos)", "Operating system"), new("os.caption", "OS name", "Operating system"), new("os.version", "OS version", "Operating system"), new("os.build", "OS build", "Operating system"), @@ -108,5 +113,6 @@ public static class GroupFields new("network.ipv4", "IPv4 address", "Network", MultiValue: true), new("network.mac", "MAC address", "Network", MultiValue: true), new("network.dns", "DNS server", "Network", MultiValue: true), + new("network.interface", "Interface name", "Network", MultiValue: true), ]; } diff --git a/src/Shared.Contracts/Models/InventoryReport.cs b/src/Shared.Contracts/Models/InventoryReport.cs index b213070..714b95f 100644 --- a/src/Shared.Contracts/Models/InventoryReport.cs +++ b/src/Shared.Contracts/Models/InventoryReport.cs @@ -66,4 +66,6 @@ public sealed record InventoryNetworkAdapter( IReadOnlyList Ipv4Addresses, IReadOnlyList Ipv6Addresses, IReadOnlyList Gateways, - IReadOnlyList DnsServers); + IReadOnlyList DnsServers, + // OS interface name: "Ethernet0" on Windows, "eth0"/"en0" on unix. + string? InterfaceName = null); diff --git a/src/Shared.Contracts/Models/ScriptFileBinding.cs b/src/Shared.Contracts/Models/ScriptFileBinding.cs new file mode 100644 index 0000000..f9c66fd --- /dev/null +++ b/src/Shared.Contracts/Models/ScriptFileBinding.cs @@ -0,0 +1,18 @@ +namespace Shared.Contracts.Models; + +/// +/// An S3 object (or prefix) delivered to the device before the script runs. +/// The destination path expands on the device (%VAR%, $env:VAR, $(…)) and the +/// resolved location is handed to the script through a case-insensitive +/// ordered dictionary ($Files.Name) as a FileInfo — or a DirectoryInfo +/// when requests a recursive prefix download. +/// +public sealed record ScriptFileBinding( + string Name, + string ObjectKey, + string DestinationPath, + bool Directory = false, + // A failed delivery logs a warning and lets the script run ($Files.Name + // still points at the intended path; check .Exists). Off = fail the job + // before execution. + bool ContinueOnFailure = false); diff --git a/src/Shared.Infrastructure/Grouping/DeviceFieldBag.cs b/src/Shared.Infrastructure/Grouping/DeviceFieldBag.cs index 6023d37..8ffba39 100644 --- a/src/Shared.Infrastructure/Grouping/DeviceFieldBag.cs +++ b/src/Shared.Infrastructure/Grouping/DeviceFieldBag.cs @@ -65,7 +65,9 @@ public sealed class DeviceFieldBag DeviceStatus status, string? agentVersion, IEnumerable? tags, - InventoryReport? inventory) + InventoryReport? inventory, + string? fallbackOsCaption = null, + string? fallbackOsVersion = null) { var bag = new DeviceFieldBag(); bag.Set("clientId", clientId); @@ -76,6 +78,12 @@ public sealed class DeviceFieldBag if (inventory is null) { + // Enrollment already captured the OS, so platform-based groups + // (and the triggers scoped to them) work before the first + // inventory snapshot lands. + bag.Set("os.platform", DerivePlatform(fallbackOsCaption)); + bag.Set("os.caption", fallbackOsCaption); + bag.Set("os.version", fallbackOsVersion); return bag; } @@ -87,6 +95,7 @@ public sealed class DeviceFieldBag bag.Set("domain", inventory.Identity.DomainOrWorkgroup); bag.Set("partOfDomain", inventory.Identity.PartOfDomain ? "true" : "false"); + bag.Set("os.platform", DerivePlatform(inventory.Os.Caption)); bag.Set("os.caption", inventory.Os.Caption); bag.Set("os.version", inventory.Os.Version); bag.Set("os.build", inventory.Os.Build); @@ -116,7 +125,28 @@ public sealed class DeviceFieldBag bag.SetMany("network.ipv4", inventory.Network.SelectMany(n => n.Ipv4Addresses)); bag.SetMany("network.mac", inventory.Network.Select(n => n.MacAddress).Where(m => m is not null)!); bag.SetMany("network.dns", inventory.Network.SelectMany(n => n.DnsServers)); + bag.SetMany("network.interface", inventory.Network.Select(n => n.InterfaceName).Where(i => i is not null)!); return bag; } + + /// Coarse platform from the OS caption: windows, macos or linux. + public static string? DerivePlatform(string? osCaption) + { + if (string.IsNullOrWhiteSpace(osCaption)) + { + return null; + } + + if (osCaption.Contains("windows", StringComparison.OrdinalIgnoreCase)) + { + return "windows"; + } + + return osCaption.Contains("macos", StringComparison.OrdinalIgnoreCase) + || osCaption.Contains("mac os", StringComparison.OrdinalIgnoreCase) + || osCaption.Contains("darwin", StringComparison.OrdinalIgnoreCase) + ? "macos" + : "linux"; + } } diff --git a/src/Shared.Infrastructure/Grouping/RuleEvaluator.cs b/src/Shared.Infrastructure/Grouping/RuleEvaluator.cs index e468b5c..35cf29f 100644 --- a/src/Shared.Infrastructure/Grouping/RuleEvaluator.cs +++ b/src/Shared.Infrastructure/Grouping/RuleEvaluator.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Net; using System.Text.RegularExpressions; using Shared.Contracts.Models; @@ -15,7 +16,8 @@ public static class RuleEvaluator /// Operators that are inherently negative and so must hold for ALL values. private static bool IsUniversal(RuleOperator op) - => op is RuleOperator.NotEquals or RuleOperator.NotContains or RuleOperator.NotIn or RuleOperator.NotExists; + => op is RuleOperator.NotEquals or RuleOperator.NotContains or RuleOperator.NotIn + or RuleOperator.NotExists or RuleOperator.NotInCidr; public static bool Matches(GroupRuleSet? ruleSet, DeviceFieldBag fields) { @@ -129,11 +131,78 @@ public static class RuleEvaluator case RuleOperator.LessOrEqual: return CompareNumeric(actual, expected, condition.Operator); + case RuleOperator.InCidr: + return MatchesCidr(actual, expected); + case RuleOperator.NotInCidr: + return !MatchesCidr(actual, expected); + default: return false; } } + /// + /// True when is an IP address inside any of the + /// comma-separated CIDR ranges (bare IPs compare for equality). Uses the + /// BCL ; IPv4 and IPv6 both work. + /// + private static bool MatchesCidr(string actual, string expected) + { + if (!IPAddress.TryParse(actual.Trim(), out var address)) + { + return false; + } + + foreach (var item in SplitList(expected)) + { + if (item.Contains('/')) + { + if (TryParseNetwork(item, out var network) && network.Contains(address)) + { + return true; + } + } + else if (IPAddress.TryParse(item, out var single) && single.Equals(address)) + { + return true; + } + } + + return false; + } + + /// + /// Lenient CIDR parse: host bits in the base address are tolerated, so + /// "10.30.9.27/24" means the same network as "10.30.9.0/24" (the strict + /// BCL parser rejects non-zero host bits). + /// + private static bool TryParseNetwork(string cidr, out IPNetwork network) + { + network = default; + var slash = cidr.IndexOf('/'); + if (slash <= 0 + || !IPAddress.TryParse(cidr[..slash].Trim(), out var baseAddress) + || !int.TryParse(cidr[(slash + 1)..].Trim(), out var prefix)) + { + return false; + } + + var bytes = baseAddress.GetAddressBytes(); + if (prefix < 0 || prefix > bytes.Length * 8) + { + return false; + } + + for (var i = 0; i < bytes.Length; i++) + { + var bitsForByte = Math.Clamp(prefix - (i * 8), 0, 8); + bytes[i] &= (byte)(0xFF << (8 - bitsForByte)); + } + + network = new IPNetwork(new IPAddress(bytes), prefix); + return true; + } + private static bool CompareNumeric(string actual, string expected, RuleOperator op) { if (!double.TryParse(actual, NumberStyles.Float, CultureInfo.InvariantCulture, out var left) diff --git a/src/WebUI/src/lib/api/client.ts b/src/WebUI/src/lib/api/client.ts index ca279f4..77619cc 100644 --- a/src/WebUI/src/lib/api/client.ts +++ b/src/WebUI/src/lib/api/client.ts @@ -30,6 +30,7 @@ import type { ScriptDto, ServerInfoDto, ScriptParameter, + ScriptFileBinding, ScriptTriggerDto, ScriptTriggerType, SecretBinding, @@ -48,6 +49,7 @@ interface SaveScriptBody { secretBindings?: SecretBinding[]; secretsVariableName?: string; engine?: string; + fileBindings?: ScriptFileBinding[]; } interface SaveSecretsProviderBody { @@ -134,6 +136,11 @@ export const api = { method: 'POST', body: JSON.stringify({ username, password }) }), + changePassword: (username: string, currentPassword: string, newPassword: string) => + request('/api/auth/change-password', { + method: 'POST', + body: JSON.stringify({ username, currentPassword, newPassword }) + }), logout: () => request('/api/auth/logout', { method: 'POST' }), // Devices diff --git a/src/WebUI/src/lib/api/types.ts b/src/WebUI/src/lib/api/types.ts index bc5c50d..9803700 100644 --- a/src/WebUI/src/lib/api/types.ts +++ b/src/WebUI/src/lib/api/types.ts @@ -58,7 +58,9 @@ export type RuleOperator = | 'lessThan' | 'lessOrEqual' | 'exists' - | 'notExists'; + | 'notExists' + | 'inCidr' + | 'notInCidr'; export interface RuleCondition { field: string; @@ -246,6 +248,8 @@ export interface InventoryReport { ipv6Addresses: string[]; gateways: string[]; dnsServers: string[]; + /** OS interface name: "Ethernet0" on Windows, "eth0"/"en0" on unix. */ + interfaceName?: string; }[]; collectedUtc: string; } @@ -266,6 +270,20 @@ export type ScriptParameterType = 'string' | 'number' | 'boolean' | 'array' | 'h */ export type ValueExpansion = 'auto' | 'literal'; +/** + * An S3 object (or prefix) delivered to the device before the script runs. + * The destination expands on the device (%VAR%, $env:VAR, $(…)) and the + * resolved location reaches the script as $Files.Name — a FileInfo, or a + * DirectoryInfo when directory (recursive) is set. + */ +export interface ScriptFileBinding { + name: string; + objectKey: string; + destinationPath: string; + directory?: boolean; + continueOnFailure?: boolean; +} + export interface ScriptParameter { name: string; type: ScriptParameterType; @@ -377,6 +395,7 @@ export interface ScriptDto { updatedBy?: string; secretBindings?: SecretBinding[]; secretsVariableName?: string; + fileBindings?: ScriptFileBinding[]; } // ── Secrets providers ───────────────────────────────────────────────── @@ -451,6 +470,8 @@ export interface SessionResponse { roleName?: string; /** Effective permission keys; '*' grants everything. */ permissions?: string[]; + /** Credentials were valid but a new password must be set before a session is issued. */ + mustChangePassword?: boolean; } export interface RoleDto { diff --git a/src/WebUI/src/lib/components/FileBindingsEditor.svelte b/src/WebUI/src/lib/components/FileBindingsEditor.svelte new file mode 100644 index 0000000..1f9fb73 --- /dev/null +++ b/src/WebUI/src/lib/components/FileBindingsEditor.svelte @@ -0,0 +1,109 @@ + + +

+ Downloaded to the device before the script runs. Destinations expand on the device + (%TEMP%, $env:ProgramData, $(…)) and each entry reaches + the script as $Files.Name — a FileInfo, or a DirectoryInfo when the S3 key is a + prefix delivered recursively. Requires S3 (Settings → File delivery). +

+ +{#each bindings as binding, i (i)} +
+ + + + + + +
+ {#if binding.directory && looksLikeFile(binding.destinationPath)} +

+ A directory delivery unpacks into the destination — give a directory, not a file path. +

+ {/if} +{/each} + + + + diff --git a/src/WebUI/src/lib/components/RuleBuilder.svelte b/src/WebUI/src/lib/components/RuleBuilder.svelte index f67e509..f9e0741 100644 --- a/src/WebUI/src/lib/components/RuleBuilder.svelte +++ b/src/WebUI/src/lib/components/RuleBuilder.svelte @@ -27,7 +27,9 @@ { value: 'lessThan', label: '<', needsValue: true }, { value: 'lessOrEqual', label: '<=', needsValue: true }, { value: 'exists', label: 'exists', needsValue: false }, - { value: 'notExists', label: 'does not exist', needsValue: false } + { value: 'notExists', label: 'does not exist', needsValue: false }, + { value: 'inCidr', label: 'in CIDR range', needsValue: true }, + { value: 'notInCidr', label: 'not in CIDR range', needsValue: true } ]; const needsValue = (op: RuleOperator) => operators.find((o) => o.value === op)?.needsValue ?? true; diff --git a/src/WebUI/src/lib/components/TriggersCard.svelte b/src/WebUI/src/lib/components/TriggersCard.svelte new file mode 100644 index 0000000..374ec21 --- /dev/null +++ b/src/WebUI/src/lib/components/TriggersCard.svelte @@ -0,0 +1,155 @@ + + +
+

Triggers

+

+ Run this script automatically when a device registers, or when its agent connects and is ready + for jobs. +

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

{errorText}

{/if} + + {#if mine.length === 0} +

No triggers yet.

+ {:else} +
    + {#each mine as trigger (trigger.id)} +
  • + + {labels[trigger.triggerType]} + · {trigger.groupName ?? 'All devices'} + {#if trigger.oncePerDevice}· once per device{/if} + + +
  • + {/each} +
+ {/if} +
+ + diff --git a/src/WebUI/src/lib/editor/powershell-completions.ts b/src/WebUI/src/lib/editor/powershell-completions.ts new file mode 100644 index 0000000..5880a42 --- /dev/null +++ b/src/WebUI/src/lib/editor/powershell-completions.ts @@ -0,0 +1,274 @@ +/** + * Lightweight PowerShell IntelliSense for the Monaco editor: a curated set of + * common cmdlets, language keywords, automatic variables and snippets, plus + * dynamic entries for the script's own parameters and secret bindings. No + * language server involved — fast, offline and optional. + */ + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +const CMDLETS = [ + 'Get-ChildItem', + 'Get-Content', + 'Set-Content', + 'Add-Content', + 'Get-Item', + 'Get-ItemProperty', + 'Set-ItemProperty', + 'New-Item', + 'New-ItemProperty', + 'Remove-Item', + 'Copy-Item', + 'Move-Item', + 'Rename-Item', + 'Test-Path', + 'Join-Path', + 'Split-Path', + 'Resolve-Path', + 'Get-Location', + 'Set-Location', + 'Get-Process', + 'Stop-Process', + 'Start-Process', + 'Wait-Process', + 'Get-Service', + 'Start-Service', + 'Stop-Service', + 'Restart-Service', + 'Set-Service', + 'Get-CimInstance', + 'Invoke-CimMethod', + 'Get-Date', + 'Start-Sleep', + 'Write-Output', + 'Write-Host', + 'Write-Error', + 'Write-Warning', + 'Write-Verbose', + 'Write-Debug', + 'Write-Progress', + 'Read-Host', + 'Out-String', + 'Out-Null', + 'Out-File', + 'ForEach-Object', + 'Where-Object', + 'Select-Object', + 'Sort-Object', + 'Group-Object', + 'Measure-Object', + 'Compare-Object', + 'Select-String', + 'ConvertTo-Json', + 'ConvertFrom-Json', + 'ConvertTo-Csv', + 'ConvertFrom-Csv', + 'Export-Csv', + 'Import-Csv', + 'Invoke-RestMethod', + 'Invoke-WebRequest', + 'Invoke-Expression', + 'Invoke-Command', + 'Test-Connection', + 'Test-NetConnection', + 'Resolve-DnsName', + 'Get-NetIPAddress', + 'Get-NetAdapter', + 'Compress-Archive', + 'Expand-Archive', + 'Get-FileHash', + 'New-Guid', + 'Get-Random', + 'Get-WinEvent', + 'Get-EventLog', + 'Get-HotFix', + 'Get-ComputerInfo', + 'Restart-Computer', + 'Stop-Computer', + 'Get-LocalUser', + 'Get-LocalGroup', + 'Add-LocalGroupMember', + 'Get-ScheduledTask', + 'Register-ScheduledTask', + 'Unregister-ScheduledTask', + 'Get-Module', + 'Import-Module', + 'Install-PSResource', + 'Find-PSResource', + 'Start-ThreadJob', + 'Get-Job', + 'Receive-Job', + 'Wait-Job', + 'Remove-Job', + 'Get-Variable', + 'Set-Variable', + 'Get-Command', + 'Get-Member', + 'Get-Help', + 'Get-Error', + 'New-Object', + 'Add-Type', + 'Get-Acl', + 'Set-Acl', + 'ConvertTo-SecureString', + 'ConvertFrom-SecureString' +]; + +const KEYWORDS = [ + 'if', + 'elseif', + 'else', + 'switch', + 'foreach', + 'for', + 'while', + 'do', + 'until', + 'break', + 'continue', + 'return', + 'function', + 'param', + 'begin', + 'process', + 'end', + 'try', + 'catch', + 'finally', + 'throw', + 'trap', + 'class', + 'enum', + 'using', + 'in', + 'exit' +]; + +const AUTOMATIC_VARIABLES = [ + '$_', + '$PSItem', + '$args', + '$error', + '$LASTEXITCODE', + '$PSVersionTable', + '$PSScriptRoot', + '$env:COMPUTERNAME', + '$env:USERNAME', + '$env:TEMP', + '$env:ProgramFiles', + '$true', + '$false', + '$null', + '$ErrorActionPreference', + '$ProgressPreference' +]; + +const SNIPPETS: { label: string; detail: string; insert: string }[] = [ + { + label: 'param block', + detail: 'Script parameter declaration', + insert: 'param(\n [string]$${1:Name}${2:,\n [int]$${3:Count} = ${4:1}}\n)\n' + }, + { + label: 'try / catch', + detail: 'Error handling block', + insert: 'try {\n ${1}\n}\ncatch {\n Write-Error "${2:Operation failed}: $_"\n}\n' + }, + { + label: 'foreach loop', + detail: 'Iterate a collection', + insert: 'foreach ($${1:item} in $${2:collection}) {\n ${3}\n}\n' + }, + { + label: 'progress loop', + detail: 'Loop reporting Write-Progress', + insert: + '1..${1:10} | ForEach-Object {\n Write-Progress -Activity \'${2:Working}\' -Status "Step $_ of ${1:10}" -PercentComplete ($_ * ${3:10})\n ${4}\n}\n' + } +]; + +export interface CompletionContext { + /** Names of the script's declared parameters. */ + parameterNames: () => string[]; + /** Names bound in the secrets dictionary. */ + secretNames: () => string[]; + /** The secrets variable name (default "Secrets"). */ + secretsVariable: () => string; + /** Names bound in the $Files dictionary, with directory flags. */ + fileBindings?: () => { name: string; directory: boolean }[]; +} + +/** Registers the provider for the given language; returns its disposable. */ +export function registerPowerShellCompletions( + monaco: any, + language: string, + context: CompletionContext +): { dispose(): void } { + return monaco.languages.registerCompletionItemProvider(language, { + triggerCharacters: ['-', '$', '.'], + provideCompletionItems(model: any, position: any) { + const word = model.getWordUntilPosition(position); + const range = { + startLineNumber: position.lineNumber, + endLineNumber: position.lineNumber, + startColumn: word.startColumn, + endColumn: word.endColumn + }; + const kinds = monaco.languages.CompletionItemKind; + + const suggestions: any[] = [ + ...CMDLETS.map((c) => ({ + label: c, + kind: kinds.Function, + insertText: c, + range + })), + ...KEYWORDS.map((k) => ({ + label: k, + kind: kinds.Keyword, + insertText: k, + range + })), + ...AUTOMATIC_VARIABLES.map((v) => ({ + label: v, + kind: kinds.Variable, + insertText: v, + range + })), + ...SNIPPETS.map((s) => ({ + label: s.label, + kind: kinds.Snippet, + detail: s.detail, + insertText: s.insert, + insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet, + range + })), + ...context.parameterNames().map((p) => ({ + label: `$${p}`, + kind: kinds.Variable, + detail: 'Script parameter', + insertText: `$${p}`, + range + })), + ...context.secretNames().map((s) => ({ + label: `$${context.secretsVariable()}.${s}`, + kind: kinds.Variable, + detail: 'Secret binding', + insertText: `$${context.secretsVariable()}.${s}`, + range + })), + ...(context.fileBindings?.() ?? []).map((f) => ({ + label: `$Files.${f.name}`, + kind: kinds.File, + detail: f.directory + ? 'Delivered directory (DirectoryInfo)' + : 'Delivered file (FileInfo)', + insertText: `$Files.${f.name}`, + range + })) + ]; + + return { suggestions }; + } + }); +} diff --git a/src/WebUI/src/routes/access/+page.svelte b/src/WebUI/src/routes/access/+page.svelte index 06ed6e9..80b386e 100644 --- a/src/WebUI/src/routes/access/+page.svelte +++ b/src/WebUI/src/routes/access/+page.svelte @@ -126,6 +126,33 @@ } } + const copyName = (base: string, existing: string[]) => { + let candidate = `${base} (copy)`; + for (let i = 2; existing.includes(candidate); i++) candidate = `${base} (copy ${i})`; + return candidate; + }; + + /** + * Copies permissions and device scope into a new custom role — works on + * system roles too, as a template. OIDC claim values deliberately do NOT + * copy: two roles matching the same claims would be a mapping trap. + */ + async function cloneRole(role: RoleDto) { + errorText = ''; + try { + await api.createRole({ + name: copyName(role.name, (roles ?? []).map((r) => r.name)), + description: role.description, + permissions: [...role.permissions], + oidcClaimValues: [], + deviceScopeGroupIds: [...role.deviceScopeGroupIds] + }); + await refresh(); + } catch (e) { + errorText = e instanceof Error ? e.message : 'Clone failed.'; + } + } + function openCreateUser() { creatingUser = true; editingUser = null; @@ -436,6 +463,7 @@ {role.userCount} + {#if !role.isSystem} diff --git a/src/WebUI/src/routes/devices/[clientId]/+page.svelte b/src/WebUI/src/routes/devices/[clientId]/+page.svelte index e230610..93ae874 100644 --- a/src/WebUI/src/routes/devices/[clientId]/+page.svelte +++ b/src/WebUI/src/routes/devices/[clientId]/+page.svelte @@ -140,7 +140,7 @@ {:else}
-
Devices / {clientId.slice(0, 12)}…
+
Devices / {device.hostname}

{device.hostname}

@@ -148,6 +148,9 @@
{[device.manufacturer, device.model].filter(Boolean).join(' · ')}
+
+ +
+

Functions

+

@@ -81,7 +103,7 @@ {#each Array(3) as _, i (i)}

loading…
{/each}
{:else if modules.length === 0} - + {:else}
    {#each modules as m (m.id)} @@ -102,6 +124,7 @@ {#if statusText}{statusText}{/if}
    {#if selected}{/if} + {#if selected}{/if}
diff --git a/src/WebUI/src/routes/groups/+page.svelte b/src/WebUI/src/routes/groups/+page.svelte index 9da0b62..c204ead 100644 --- a/src/WebUI/src/routes/groups/+page.svelte +++ b/src/WebUI/src/routes/groups/+page.svelte @@ -6,10 +6,7 @@ DeviceGroupDto, GroupFieldDescriptor, GroupKind, - GroupRuleSet, - ScriptDto, - ScriptTriggerDto, - ScriptTriggerType + GroupRuleSet } from '$lib/api/types'; import RuleBuilder from '$lib/components/RuleBuilder.svelte'; import StatusBadge from '$lib/components/StatusBadge.svelte'; @@ -18,8 +15,6 @@ let groups = $state(null); let fields = $state([]); let devices = $state([]); - let scripts = $state([]); - let triggers = $state([]); let selected = $state(null); let name = $state(''); @@ -31,19 +26,8 @@ let statusText = $state(''); let busy = $state(false); - // New trigger form - let triggerScriptId = $state(''); - let triggerGroupId = $state(''); - let triggerType = $state('onRegistration'); - let triggerOnce = $state(true); - async function refresh() { - [groups, devices, scripts, triggers] = await Promise.all([ - api.groups(), - api.devices(), - api.scripts().catch(() => []), - api.triggers().catch(() => []) - ]); + [groups, devices] = await Promise.all([api.groups(), api.devices()]); } onMount(async () => { @@ -100,6 +84,36 @@ await refresh(); } + const copyName = (base: string, existing: string[]) => { + let candidate = `${base} (copy)`; + for (let i = 2; existing.includes(candidate); i++) candidate = `${base} (copy ${i})`; + return candidate; + }; + + /** Copies rules (dynamic) or the member list (static) into a new group. */ + async function cloneGroup() { + if (!selected) return; + busy = true; + try { + const created = await api.createGroup({ + name: copyName(name, (groups ?? []).map((g) => g.name)), + description, + kind, + rules: kind === 'dynamic' ? rules : undefined + }); + if (kind === 'static' && members.length > 0) { + await api.updateGroupMembers(created.id, members.map((m) => m.clientId), []); + } + await refresh(); + await edit(created); + statusText = 'Cloned — you are editing the copy.'; + } catch (e) { + statusText = e instanceof Error ? e.message : 'Clone failed.'; + } finally { + busy = false; + } + } + async function runPreview() { busy = true; try { @@ -119,30 +133,7 @@ await refresh(); } - async function addTrigger() { - if (!triggerScriptId) { - statusText = 'Pick a script for the trigger.'; - return; - } - await api.createTrigger({ - scriptId: triggerScriptId, - groupId: triggerGroupId || undefined, - triggerType, - oncePerDevice: triggerOnce - }); - triggers = await api.triggers(); - } - - async function removeTrigger(id: string) { - await api.deleteTrigger(id); - triggers = await api.triggers(); - } - const memberIds = $derived(new Set(members.map((m) => m.clientId))); - const triggerLabels: Record = { - onRegistration: 'On registration', - onAgentReady: 'On agent ready' - };
@@ -186,6 +177,7 @@
{#if statusText}{statusText}{/if} {#if selected}{/if} + {#if selected}{/if}
@@ -241,59 +233,6 @@ {/if} -
-
-

Script triggers

- -
-

- Run a script automatically when a device registers, or when its agent connects and is ready - for jobs. -

- -
- - - - -
- - {#if triggers.length > 0} -
- - - - - - {#each triggers as t (t.id)} - - - - - - - - {/each} - -
ScriptWhenTargetOnce
{t.scriptName}{triggerLabels[t.triggerType]}{t.groupName}{t.oncePerDevice ? 'yes' : 'no'}
-
- {/if} -
@@ -460,33 +399,6 @@ 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); - flex-wrap: wrap; - align-items: center; - } - - .trigger-form .select { - flex: 1; - min-width: 150px; - } - - .once { - display: flex; - align-items: center; - gap: 4px; - font-size: 12px; - color: var(--text-muted); - } - .loading { padding: var(--space-3); display: flex; diff --git a/src/WebUI/src/routes/login/+page.svelte b/src/WebUI/src/routes/login/+page.svelte index c51e870..c24422b 100644 --- a/src/WebUI/src/routes/login/+page.svelte +++ b/src/WebUI/src/routes/login/+page.svelte @@ -12,6 +12,11 @@ let busy = $state(false); let config = $state(null); + // Forced first-sign-in reset (defaulted admin/admin credentials). + let mustChange = $state(false); + let newPassword = $state(''); + let confirmPassword = $state(''); + onMount(async () => { // A failed SSO round-trip comes back as ?error= so the operator sees why // instead of an identity-provider error page. @@ -34,7 +39,11 @@ error = ''; busy = true; try { - await session.login(username, password); + const result = await session.login(username, password); + if (result.mustChangePassword) { + mustChange = true; + return; + } await goto('/'); } catch (e) { error = @@ -48,6 +57,34 @@ } } + async function submitNewPassword(event: SubmitEvent) { + event.preventDefault(); + error = ''; + if (newPassword.length < 8) { + error = 'The new password must be at least 8 characters.'; + return; + } + if (newPassword !== confirmPassword) { + error = 'The passwords do not match.'; + return; + } + busy = true; + try { + await api.changePassword(username, password, newPassword); + await session.initialize(); + await goto('/'); + } catch (e) { + error = + e instanceof ApiError && e.status === 401 + ? 'The current password no longer matches — start over.' + : e instanceof ApiError && e.status === 429 + ? 'Too many attempts — try again in a minute.' + : 'Could not set the new password.'; + } finally { + busy = false; + } + } + // ?local=1 always reveals the local form — the way back in when the identity // provider is unavailable. const forceLocal = $derived(page.url.searchParams.get('local') === '1'); @@ -65,13 +102,43 @@ X ExecuteR -

Sign in

+

{mustChange ? 'Set a new password' : 'Sign in'}

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

+ This account still uses the default password. Choose a new one to finish signing in as + {username}. +

+
+ + + +
+ {:else if config?.autoRedirect && !error}

Redirecting to single sign-on…

{:else} {#if showLocal} @@ -235,4 +302,8 @@ text-align: center; font-size: 12px; } + + .small { + font-size: 12.5px; + } diff --git a/src/WebUI/src/routes/schedules/+page.svelte b/src/WebUI/src/routes/schedules/+page.svelte index 62d02ae..a36a785 100644 --- a/src/WebUI/src/routes/schedules/+page.svelte +++ b/src/WebUI/src/routes/schedules/+page.svelte @@ -89,6 +89,29 @@ await refresh(); } + const copyName = (base: string, existing: string[]) => { + let candidate = `${base} (copy)`; + for (let i = 2; existing.includes(candidate); i++) candidate = `${base} (copy ${i})`; + return candidate; + }; + + /** Copies the cadence only — assignments stay with the original. */ + async function clone(schedule: ScheduleDto) { + errorText = ''; + try { + await api.createSchedule({ + name: copyName(schedule.name, (schedules ?? []).map((s) => s.name)), + cronExpression: schedule.cronExpression, + runOnceUtc: schedule.runOnceUtc, + timeZoneId: schedule.timeZoneId, + enabled: schedule.enabled + }); + await refresh(); + } catch (e) { + errorText = e instanceof Error ? e.message : 'Clone failed.'; + } + } + async function remove(schedule: ScheduleDto) { const uses = schedule.assignments.length; if ( @@ -230,6 +253,7 @@ {/if} + diff --git a/src/WebUI/src/routes/scripts/[id]/+page.svelte b/src/WebUI/src/routes/scripts/[id]/+page.svelte index efbf817..0cc67fb 100644 --- a/src/WebUI/src/routes/scripts/[id]/+page.svelte +++ b/src/WebUI/src/routes/scripts/[id]/+page.svelte @@ -11,14 +11,18 @@ JobProgressPayload, JobState, ScriptParameter, + ScriptFileBinding, SecretBinding } from '$lib/api/types'; import { nats, type JobEvent } from '$lib/messaging/nats'; + import { registerPowerShellCompletions } from '$lib/editor/powershell-completions'; 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 FileBindingsEditor from '$lib/components/FileBindingsEditor.svelte'; import SchedulesCard from '$lib/components/SchedulesCard.svelte'; + import TriggersCard from '$lib/components/TriggersCard.svelte'; const scriptId = $derived(page.params.id!); const isNew = $derived(scriptId === 'new'); @@ -47,6 +51,12 @@ let showParamEditor = $state(false); let secretBindings = $state([]); let secretsVariableName = $state('Secrets'); + let fileBindings = $state([]); + + // Editor chrome + let fullscreen = $state(false); + let intellisense = $state(true); + let completionDisposable: { dispose(): void } | null = null; // Live run state (single-device run) let job = $state(null); @@ -65,7 +75,45 @@ // eslint-disable-next-line @typescript-eslint/no-explicit-any let editor: any = null; + const engineHints: Record = { + PowerShell: 'Runs inside the agent — full progress, parameters and secrets on every platform.', + WindowsPowerShell: + 'Runs via powershell.exe on Windows devices. Near parity; live progress bars are not captured.', + Bash: 'Runs on Linux/macOS devices (or Windows with Git Bash). Parameters and secrets arrive as environment variables.' + }; + + function applyIntellisense() { + completionDisposable?.dispose(); + completionDisposable = null; + if (intellisense && monacoRef && engine !== 'Bash') { + completionDisposable = registerPowerShellCompletions(monacoRef, 'powershell', { + parameterNames: () => parameters.map((p) => p.name).filter(Boolean), + secretNames: () => secretBindings.map((b) => b.name).filter(Boolean), + secretsVariable: () => secretsVariableName.trim() || 'Secrets', + fileBindings: () => + fileBindings + .filter((b) => b.name.trim()) + .map((b) => ({ name: b.name, directory: b.directory ?? false })) + }); + } + } + + function toggleIntellisense() { + intellisense = !intellisense; + localStorage.setItem('editor-intellisense', intellisense ? '1' : '0'); + applyIntellisense(); + } + + function onEngineChange() { + if (monacoRef && editor) { + monacoRef.editor.setModelLanguage(editor.getModel(), engine === 'Bash' ? 'shell' : 'powershell'); + } + applyIntellisense(); + } + onMount(() => { + intellisense = localStorage.getItem('editor-intellisense') !== '0'; + void (async () => { const [monaco, editorWorker] = await Promise.all([ import('monaco-editor'), @@ -85,6 +133,7 @@ functionModuleIds = script.functionModuleIds ?? []; secretBindings = script.secretBindings ?? []; secretsVariableName = script.secretsVariableName ?? 'Secrets'; + fileBindings = script.fileBindings ?? []; if (script.language === 'WindowsPowerShell' || script.language === 'Bash') { engine = script.language; } @@ -109,6 +158,7 @@ renderWhitespace: 'selection' }); editor.onDidChangeModelContent(() => (content = editor.getValue())); + applyIntellisense(); [devices, allGroups] = await Promise.all([api.devices(), api.groups().catch(() => [])]); const requested = page.url.searchParams.get('target'); @@ -121,6 +171,7 @@ return () => { unsubscribeJob?.(); + completionDisposable?.dispose(); editor?.dispose(); }; }); @@ -140,7 +191,8 @@ parameters, functionModuleIds, secretBindings: secretBindings.filter((b) => b.name.trim() && b.secretName.trim()), - secretsVariableName: secretsVariableName.trim() || undefined + secretsVariableName: secretsVariableName.trim() || undefined, + fileBindings: fileBindings.filter((b) => b.name.trim() && b.objectKey.trim() && b.destinationPath.trim()) }; try { if (isNew) { @@ -269,6 +321,33 @@ await goto('/scripts'); } + /** Creates a copy with the current editor state and switches to it. */ + async function clone() { + if (isNew) return; + statusText = ''; + try { + const created = await api.createScript({ + name: `${name} (copy)`, + description, + content, + engine, + parameters, + functionModuleIds, + secretBindings: secretBindings.filter((b) => b.name.trim() && b.secretName.trim()), + secretsVariableName: secretsVariableName.trim() || undefined, + fileBindings: fileBindings.filter( + (b) => b.name.trim() && b.objectKey.trim() && b.destinationPath.trim() + ) + }); + // The editor state already matches the clone; adopt its identity. + name = created.name; + await goto(`/scripts/${created.id}`); + statusText = 'Cloned — you are editing the copy.'; + } catch (e) { + statusText = e instanceof Error ? e.message : 'Clone failed.'; + } + } + const terminal = ['succeeded', 'failed', 'cancelled', 'timedOut']; const groupRunning = $derived( groupJobs.some((g) => !terminal.includes(jobStates[g.jobId] ?? 'queued')) @@ -284,6 +363,12 @@ ); + { + if (e.key === 'Escape' && fullscreen) fullscreen = false; + }} +/> +
Scripts / {isNew ? 'New' : name || '…'}
@@ -294,25 +379,17 @@ bind:value={description} aria-label="Description" /> - +
+ + {engineHints[engine]} +
{#if statusText} @@ -320,6 +397,7 @@ {/if} {#if !isNew} + {/if} + +
+ {#if !loaded} +
loading editor…
+ {/if} +
+ - + {#if !isNew && loaded} + paramInputs?.collect() ?? {}} + /> + + {/if} +{#if groupJobs.length > 0} +
+
+

Group run

+ {groupFinished}/{groupJobs.length} finished +
+ {#if skippedOrphaned.length > 0} +

Skipped orphaned: {skippedOrphaned.join(', ')}

+ {/if} +
    + {#each groupJobs as groupJob (groupJob.jobId)} +
  • + +
  • + {/each} +
+
+{/if} + +
+
+

Output{focusHostname ? ` — ${focusHostname}` : ''}

+ {#if jobState} + + {/if} +
+ + {#if progress} +
+
+ {progress.activity} + {progress.statusDescription ?? ''} +
+
+
+
+
+ {progress.percentComplete ?? 0}% + {progress.secondsRemaining != null ? ` · ~${progress.secondsRemaining}s remaining` : ''} +
+
+ {:else if running} +
Waiting for progress…
+ {/if} + +
+ {#if outputLines.length === 0} + + {job || groupJobs.length > 0 ? '—' : 'Run the script to see live progress and output.'} + + {:else} + {#each outputLines as line (line.seq)} +
{line.text}
+ {/each} + {/if} +
+
+ diff --git a/tests/Agent.Tests/ScriptFileFetcherTests.cs b/tests/Agent.Tests/ScriptFileFetcherTests.cs new file mode 100644 index 0000000..4a6c216 --- /dev/null +++ b/tests/Agent.Tests/ScriptFileFetcherTests.cs @@ -0,0 +1,171 @@ +using System.Net; +using System.Text; +using Agent.PowerShell; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Xunit; + +namespace Agent.Tests; + +public class ScriptFileFetcherTests +{ + [Theory] + [InlineData("sub/file.txt", true)] + [InlineData("deep/er/tree.bin", true)] + [InlineData("../evil.txt", false)] + [InlineData("a/../../evil.txt", false)] + [InlineData("/rooted.txt", false)] + [InlineData("C:\\rooted.txt", false)] + public void SafeCombineRefusesEscapes(string relative, bool allowed) + { + var root = Path.Combine(Path.GetTempPath(), "fetcher-root"); + if (allowed) + { + var combined = ScriptFileFetcher.SafeCombine(root, relative); + Assert.StartsWith(Path.GetFullPath(root), combined); + } + else + { + Assert.Throws(() => ScriptFileFetcher.SafeCombine(root, relative)); + } + } + + [Fact] + public async Task DownloadsFilesAndDirectoriesAndHonorsContinueOnFailure() + { + using var server = new StaticServer(new Dictionary + { + ["/single.txt"] = "single-content", + ["/dir/a.txt"] = "alpha", + ["/dir/sub/b.txt"] = "beta", + }); + + var workDir = Path.Combine(Path.GetTempPath(), $"fetcher-test-{Guid.NewGuid():N}"); + try + { + var deliveries = new List + { + new("Config", Path.Combine(workDir, "config.txt"), false, false, + [new ScriptFileItem("", server.Url("/single.txt"))]), + new("Tools", Path.Combine(workDir, "tools"), true, false, + [ + new ScriptFileItem("a.txt", server.Url("/dir/a.txt")), + new ScriptFileItem("sub/b.txt", server.Url("/dir/sub/b.txt")), + ]), + // 404s, but continue-on-failure keeps the job alive. + new("Optional", Path.Combine(workDir, "optional.txt"), false, true, + [new ScriptFileItem("", server.Url("/missing.txt"))]), + }; + + var records = new List(); + var result = await ScriptFileFetcher.FetchAsync( + deliveries, path => path, records.Add, CancellationToken.None); + + Assert.Null(result.FailureMessage); + Assert.Equal("single-content", await File.ReadAllTextAsync(Path.Combine(workDir, "config.txt"))); + Assert.Equal("beta", await File.ReadAllTextAsync(Path.Combine(workDir, "tools", "sub", "b.txt"))); + + // Case-insensitive dictionary of FileInfo / DirectoryInfo. + var config = Assert.IsType(result.Files["CONFIG"]); + Assert.True(config.Exists); + var tools = Assert.IsType(result.Files["tools"]); + Assert.True(tools.Exists); + + // The failed optional entry still resolves (Exists = false) and warned. + var optional = Assert.IsType(result.Files["Optional"]); + Assert.False(optional.Exists); + Assert.Contains(records, r => r.Stream == OutputStreamKind.Warning && r.Text.Contains("Optional")); + } + finally + { + if (Directory.Exists(workDir)) + { + Directory.Delete(workDir, recursive: true); + } + } + } + + [Fact] + public async Task AFailedRequiredDeliveryFailsBeforeTheScriptRuns() + { + using var server = new StaticServer([]); + + var workDir = Path.Combine(Path.GetTempPath(), $"fetcher-test-{Guid.NewGuid():N}"); + var deliveries = new List + { + new("Required", Path.Combine(workDir, "required.txt"), false, false, + [new ScriptFileItem("", server.Url("/missing.txt"))]), + }; + + var result = await ScriptFileFetcher.FetchAsync( + deliveries, path => path, _ => { }, CancellationToken.None); + + Assert.NotNull(result.FailureMessage); + Assert.Contains("Required", result.FailureMessage); + } + + [Fact] + public async Task ServerSideResolutionErrorsRespectContinueOnFailure() + { + var deliveries = new List + { + new("Broken", Path.Combine(Path.GetTempPath(), "x.txt"), false, true, [], + Error: "no objects under prefix"), + }; + + var records = new List(); + var result = await ScriptFileFetcher.FetchAsync( + deliveries, path => path, records.Add, CancellationToken.None); + + Assert.Null(result.FailureMessage); + Assert.IsType(result.Files["Broken"]); + Assert.Contains(records, r => r.Stream == OutputStreamKind.Warning); + } + + /// Tiny loopback HTTP server for real download round-trips. + private sealed class StaticServer : IDisposable + { + private readonly HttpListener listener = new(); + private readonly string baseUrl; + + public StaticServer(Dictionary content) + { + var port = Random.Shared.Next(20000, 60000); + baseUrl = $"http://127.0.0.1:{port}"; + listener.Prefixes.Add(baseUrl + "/"); + listener.Start(); + _ = Task.Run(async () => + { + while (listener.IsListening) + { + HttpListenerContext context; + try + { + context = await listener.GetContextAsync(); + } + catch (Exception) + { + return; + } + + if (content.TryGetValue(context.Request.Url!.AbsolutePath, out var body)) + { + var bytes = Encoding.UTF8.GetBytes(body); + context.Response.StatusCode = 200; + await context.Response.OutputStream.WriteAsync(bytes); + } + else + { + context.Response.StatusCode = 404; + } + + context.Response.Close(); + } + }); + } + + public string Url(string path) => baseUrl + path; + + public void Dispose() => listener.Stop(); + } +} diff --git a/tests/Backend.Tests/BackendTestFixture.cs b/tests/Backend.Tests/BackendTestFixture.cs index 1057299..e5b5acd 100644 --- a/tests/Backend.Tests/BackendTestFixture.cs +++ b/tests/Backend.Tests/BackendTestFixture.cs @@ -24,6 +24,9 @@ public sealed class BackendTestFixture : WebApplicationFactory builder.UseSetting("NATS_ACCOUNT_PUBLIC_KEY", AccountKey.GetPublicKey()); builder.UseSetting("NATS_URL", string.Empty); builder.UseSetting("RATE_LIMIT_PER_MINUTE", "10000"); + // Tests drive schedule sweeps manually; the background worker would + // race them (fire-and-advance between seeding steps). + builder.UseSetting("SCHEDULE_WORKER", "0"); builder.UseEnvironment("Development"); } diff --git a/tests/Backend.Tests/InventoryReportCacheTests.cs b/tests/Backend.Tests/InventoryReportCacheTests.cs new file mode 100644 index 0000000..58d8a94 --- /dev/null +++ b/tests/Backend.Tests/InventoryReportCacheTests.cs @@ -0,0 +1,69 @@ +using Backend.Groups; +using Xunit; + +namespace Backend.Tests; + +public class InventoryReportCacheTests +{ + private const string MinimalReport = """ + { + "identity": { "clientId": "c1", "hostname": "PC-001", "partOfDomain": false }, + "os": { "caption": "Windows 11 Pro" }, + "cpu": {}, "memory": [], "totalPhysicalMemoryBytes": 0, + "disks": [], "volumes": [], "network": [], + "collectedUtc": "2026-08-08T00:00:00Z" + } + """; + + [Fact] + public void HitsOnlyWhileTheSnapshotTimestampMatches() + { + var cache = new InventoryReportCache(); + var t1 = DateTimeOffset.UtcNow; + + Assert.False(cache.TryGet("c1", t1, out _)); + + var stored = cache.Store("c1", t1, MinimalReport); + Assert.NotNull(stored); + Assert.True(cache.TryGet("c1", t1, out var hit)); + Assert.Equal("Windows 11 Pro", hit!.Os.Caption); + + // A newer snapshot timestamp invalidates the entry. + Assert.False(cache.TryGet("c1", t1.AddMinutes(15), out _)); + } + + [Fact] + public void CorruptJsonCachesAsNullInsteadOfReparsingForever() + { + var cache = new InventoryReportCache(); + var t1 = DateTimeOffset.UtcNow; + + Assert.Null(cache.Store("c1", t1, "{not json")); + Assert.True(cache.TryGet("c1", t1, out var report)); + Assert.Null(report); + } + + [Theory] + [InlineData(@"C:\temp\agent.msi", true)] + [InlineData("/opt/tools/archive.tar", true)] + [InlineData(@"%TEMP%\executer", false)] + [InlineData("/opt/tools/", false)] + [InlineData(@"C:\app-1.2", false)] // version-like dots are not extensions + [InlineData(@"C:\payload\v2.hotfix", true)] + public void DirectoryDestinationsRejectLeafFilePaths(string destination, bool looksLikeFile) + => Assert.Equal(looksLikeFile, Backend.Scripts.ScriptEndpoints.LooksLikeFilePath(destination)); + + [Fact] + public void PruneDropsDevicesThatNoLongerExist() + { + var cache = new InventoryReportCache(); + var t1 = DateTimeOffset.UtcNow; + cache.Store("alive", t1, MinimalReport); + cache.Store("gone", t1, MinimalReport); + + cache.Prune(new HashSet(StringComparer.Ordinal) { "alive" }); + + Assert.True(cache.TryGet("alive", t1, out _)); + Assert.False(cache.TryGet("gone", t1, out _)); + } +} diff --git a/tests/Backend.Tests/RoleTests.cs b/tests/Backend.Tests/RoleTests.cs index c94798d..08f7d91 100644 --- a/tests/Backend.Tests/RoleTests.cs +++ b/tests/Backend.Tests/RoleTests.cs @@ -176,6 +176,70 @@ public class AccessControlHttpTests(BackendTestFixture fixture) : IClassFixture< (await viewerClient.GetAsync("/api/admin/roles")).StatusCode); } + [Fact] + public async Task DefaultedPasswordForcesAResetBeforeAnySessionExists() + { + var seeded = await SeedLocalUserAsync("reset-admin", "admin-password", "Admin"); + await fixture.WithDbAsync(async db => + { + var user = await db.Users.SingleAsync(u => u.Id == seeded.Id); + user.MustChangePassword = true; + await db.SaveChangesAsync(); + }); + + using var client = fixture.CreateClient(); + + // Valid credentials produce no session — only the must-change signal. + var login = await client.PostAsJsonAsync( + "/api/auth/login", new { username = "reset-admin", password = "admin-password" }); + Assert.Equal(System.Net.HttpStatusCode.OK, login.StatusCode); + using (var body = JsonDocument.Parse(await login.Content.ReadAsStringAsync())) + { + Assert.False(body.RootElement.GetProperty("authenticated").GetBoolean()); + Assert.True(body.RootElement.GetProperty("mustChangePassword").GetBoolean()); + } + + Assert.Equal(System.Net.HttpStatusCode.Unauthorized, + (await client.GetAsync("/api/admin/roles")).StatusCode); + + // Wrong current password is refused. + Assert.Equal(System.Net.HttpStatusCode.Unauthorized, + (await client.PostAsJsonAsync("/api/auth/change-password", new + { + username = "reset-admin", + currentPassword = "wrong", + newPassword = "brand-new-password-1", + })).StatusCode); + + // The change signs the user in and clears the flag. + var change = await client.PostAsJsonAsync("/api/auth/change-password", new + { + username = "reset-admin", + currentPassword = "admin-password", + newPassword = "brand-new-password-1", + }); + Assert.Equal(System.Net.HttpStatusCode.OK, change.StatusCode); + using (var body = JsonDocument.Parse(await change.Content.ReadAsStringAsync())) + { + Assert.True(body.RootElement.GetProperty("authenticated").GetBoolean()); + Assert.Equal("Admin", body.RootElement.GetProperty("roleName").GetString()); + } + + Assert.Equal(System.Net.HttpStatusCode.OK, + (await client.GetAsync("/api/admin/roles")).StatusCode); + + // Subsequent sign-ins use the new password with no reset detour. + using var fresh = fixture.CreateClient(); + var relogin = await fresh.PostAsJsonAsync( + "/api/auth/login", new { username = "reset-admin", password = "brand-new-password-1" }); + Assert.Equal(System.Net.HttpStatusCode.OK, relogin.StatusCode); + using (var body = JsonDocument.Parse(await relogin.Content.ReadAsStringAsync())) + { + Assert.True(body.RootElement.GetProperty("authenticated").GetBoolean()); + Assert.False(body.RootElement.GetProperty("mustChangePassword").GetBoolean()); + } + } + private async Task SeedLocalUserAsync(string username, string password, string roleName) => await fixture.WithDbAsync(async db => { diff --git a/tests/Shared.Tests/RuleEvaluatorTests.cs b/tests/Shared.Tests/RuleEvaluatorTests.cs index b0dae4f..c4d6947 100644 --- a/tests/Shared.Tests/RuleEvaluatorTests.cs +++ b/tests/Shared.Tests/RuleEvaluatorTests.cs @@ -20,7 +20,7 @@ public class RuleEvaluatorTests memoryBytes, [new InventoryDisk("SSD", "S1", 1_000_000_000_000, "NVMe")], [new InventoryVolume("C:", "NTFS", 1_000_000_000_000, 500_000_000_000)], - [new InventoryNetworkAdapter("NIC", "00:11:22:33:44:55", ips ?? ["10.20.4.14"], [], ["10.20.0.1"], ["10.20.0.10"])], + [new InventoryNetworkAdapter("NIC", "00:11:22:33:44:55", ips ?? ["10.20.4.14"], [], ["10.20.0.1"], ["10.20.0.10"], InterfaceName: "eth0")], DateTimeOffset.UtcNow); private static DeviceFieldBag Bag( @@ -188,5 +188,64 @@ public class RuleEvaluatorTests Assert.True(RuleEvaluator.Matches(new RuleCondition("memory.totalGb", RuleOperator.GreaterOrEqual, "15"), bag)); Assert.True(RuleEvaluator.Matches(new RuleCondition("network.ipv4", RuleOperator.StartsWith, "10.20."), bag)); Assert.True(RuleEvaluator.Matches(new RuleCondition("os.caption", RuleOperator.Contains, "Windows 11"), bag)); + Assert.True(RuleEvaluator.Matches(new RuleCondition("network.interface", RuleOperator.Equals, "eth0"), bag)); + } + + [Theory] + [InlineData("10.20.0.0/16", true)] + [InlineData("10.20.4.0/24", true)] + // Host bits in the base address are tolerated (normalized to the network). + [InlineData("10.20.4.99/24", true)] + [InlineData("10.30.0.0/16", false)] + [InlineData("192.168.1.0/24, 10.20.0.0/16", true)] // any range in the list + [InlineData("10.20.4.14", true)] // bare IP means equality + [InlineData("10.20.4.15", false)] + [InlineData("not-a-cidr", false)] // invalid input never matches + [InlineData("10.20.4.0/33", false)] // invalid prefix never matches + public void InCidrMatchesAddressesAgainstRanges(string cidr, bool expected) + { + var condition = new RuleCondition("network.ipv4", RuleOperator.InCidr, cidr); + Assert.Equal(expected, RuleEvaluator.Matches(condition, Bag())); + } + + [Fact] + public void NotInCidrIsUniversalAcrossAllAddresses() + { + var multiHomed = Bag(inventory: Inventory(ips: ["10.20.4.14", "192.168.50.9"])); + + // One address inside the range → NotInCidr fails (must hold for ALL). + Assert.False(RuleEvaluator.Matches( + new RuleCondition("network.ipv4", RuleOperator.NotInCidr, "192.168.0.0/16"), multiHomed)); + Assert.True(RuleEvaluator.Matches( + new RuleCondition("network.ipv4", RuleOperator.NotInCidr, "172.16.0.0/12"), multiHomed)); + // And InCidr matches when ANY address is inside. + Assert.True(RuleEvaluator.Matches( + new RuleCondition("network.ipv4", RuleOperator.InCidr, "192.168.0.0/16"), multiHomed)); + } + + [Fact] + public void EnrollmentOsFallbackWorksBeforeTheFirstInventoryReport() + { + // No inventory yet — the device row's OS caption keeps platform + // groups (and the triggers scoped to them) working immediately. + var bag = DeviceFieldBag.Build( + "c1", "PC-001", DeviceStatus.Online, "2026.08.08.1319", null, inventory: null, + fallbackOsCaption: "Windows Server 2022 Datacenter", fallbackOsVersion: "10.0.20348"); + + Assert.True(RuleEvaluator.Matches(new RuleCondition("os.platform", RuleOperator.Equals, "windows"), bag)); + Assert.True(RuleEvaluator.Matches(new RuleCondition("os.caption", RuleOperator.Contains, "Server"), bag)); + Assert.False(bag.Has("memory.totalGb")); + } + + [Theory] + [InlineData("Windows Server 2022 Datacenter", "windows")] + [InlineData("Windows 11 Pro", "windows")] + [InlineData("Ubuntu 24.04.1 LTS", "linux")] + [InlineData("macOS 15.3", "macos")] + [InlineData("Debian GNU/Linux 12 (bookworm)", "linux")] + public void PlatformDerivesFromOsCaption(string caption, string platform) + { + var bag = Bag(inventory: Inventory(os: caption)); + Assert.True(RuleEvaluator.Matches(new RuleCondition("os.platform", RuleOperator.Equals, platform), bag)); } }