From 762bcd7b8dfd6b6ef4fef33b9a6cb398dc7b6b2e Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 16:29:27 -0500 Subject: [PATCH] feat(admin): #1078 headless POST /api/cluster/failover (key-gated, same service+audit) and unattended SCM-restart gate fix(install): #1075 worker identity gets read+execute (not Modify) on \pe; re-run replaces the old grant --- docs/Redundancy.md | 1 + docs/ServiceHosting.md | 2 +- docs/security.md | 4 + .../install/Install-ScriptWorkerIsolation.ps1 | 2 +- scripts/install/ScriptWorkerIsolation.psm1 | 12 ++- ...est-ScmRestartAfterClusterExit.Windows.ps1 | 33 +++++- .../tests/Test-ScriptWorkerIsolation.ps1 | 4 +- .../Api/ManualFailoverApiEndpoints.cs | 81 ++++++++++++++ src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs | 2 + .../Api/ManualFailoverApiEndpointsTests.cs | 100 ++++++++++++++++++ 10 files changed, 229 insertions(+), 12 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Api/ManualFailoverApiEndpoints.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Api/ManualFailoverApiEndpointsTests.cs diff --git a/docs/Redundancy.md b/docs/Redundancy.md index 50f69a94f..04b194e65 100644 --- a/docs/Redundancy.md +++ b/docs/Redundancy.md @@ -555,6 +555,7 @@ advertises `ServiceLevel` 250. OPC UA clients re-select. | Peer guard | Disabled, with the reason as its tooltip, when fewer than two Up driver members exist — with one node a "failover" is a shutdown. Re-evaluated inside the service against live state, so a stale page cannot bypass it. | | Confirmation | A dialog naming the node, and what follows (restart, ServiceLevel 250 moves, clients re-select). | | Audit | Written through the shared `ZB.MOM.WW.Audit.IAuditWriter` seam **before** the Leave — action `cluster.manual-failover`, actor, target. A *refused* failover changes nothing and writes nothing. | +| Headless trigger (#1078) | `POST /api/cluster/failover` on an **admin** node (`ManualFailoverApiEndpoints`) calls the same `IManualFailoverService.FailOverDriverPrimaryAsync` — same peer guard, same `cluster.manual-failover` audit (actor `rest-api`, or `rest-api:`). Auth is the `DeployApiEndpoints` model, not the `FleetAdmin` cookie policy (an unattended script cannot do an LDAP login): header `X-Api-Key` == **`Security:FailoverApiKey`**, fixed-time compare, a key **separate from `Security:DeployApiKey`**; unset ⇒ `503` (disabled), wrong/missing ⇒ `401`, no peer ⇒ `409` (nothing changed or audited), accepted ⇒ `202 { outcome, leavingNode }`. Acts on the Primary of the answering node's own mesh. Used by `scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1 -FailoverUrl … -FailoverApiKey …`. Treat the key as an Administrator credential. | Phase 6 of the mesh program (see [Per-cluster meshes (Phase 6)](#per-cluster-meshes-phase-6)) split the fleet into one 2-node mesh per application `Cluster`, so the button now acts on **this pair's own** diff --git a/docs/ServiceHosting.md b/docs/ServiceHosting.md index 510361e8a..550c7c906 100644 --- a/docs/ServiceHosting.md +++ b/docs/ServiceHosting.md @@ -114,7 +114,7 @@ dotnet muxer. See `docs/VirtualTags.md` §"Out-of-process runner". | Worker identity | A **disabled** anchor service `OtOpcUaScriptWorker` running as `NT SERVICE\OtOpcUaScriptWorker`, so the virtual account exists. It is never started. | | `Scripting:Worker:Identity` | With `NT SERVICE\OtOpcUaScriptWorker` set (by `-ConfigureHostService`, or in appsettings), the host starts every worker under a **restricted token** derived from its own: every privilege but `SeChangeNotifyPrivilege` removed, and restricting SIDs = the identity + `Everyone` + `BUILTIN\Users` + `RESTRICTED`. Every access the worker makes must pass for the host account **and** for that set. The token's default DACL is host + SYSTEM + identity; the worker is created suspended and put in its Job Object before it runs; `TEMP`/`TMP` point at its per-launch working directory (ACL: host + SYSTEM full, identity Modify); `DOTNET_EnableDiagnostics=0`. The host also adds the identity to its own window station and desktop DACL (enumerate/read, and create-window on the desktop), once per process. USER32 connects to them in its DllMain and the runtime imports USER32, so without the grant `coreclr.dll` fails to load (`ERROR_DLL_INIT_FAILED`, measured on windev). The grant lives on the session's kernel objects and ends with the session; nothing persistent changes. The logon SID, which those objects normally grant, is deliberately not a restricting SID: the host's process DACL gives it `PROCESS_VM_READ`. Windows cannot start an ad-hoc child process *as* a virtual account (only the SCM can, for a service), and a separate local user would need a stored password plus `SeAssignPrimaryTokenPrivilege` on the host account; a restricted copy of the host's own token needs neither. Startup refuses the key off Windows or when malformed. | | Pipe ACL | On Windows the worker pipe always carries an explicit, protected DACL: the host account and (with an identity) the worker identity, read/write, nobody else. No SYSTEM, no Administrators, no Everyone. The owner is the host token's owner, so the worker's `CurrentUserOnly` check of the server end still holds. | -| `PeCacheDir` | Created with a protected ACL: SYSTEM, Administrators and the host account full control, no Users. `pe\` grants the identity Modify — **unused since lmxopcua#1014**: the host now verifies, compiles and writes every entry and sends verified images over the pipe, so a worker no longer touches the directory (anything it could still drop in `pe\` fails the host's HMAC check; removing the grant is a follow-up). The HMAC key and `workers\` markers are host-only. | +| `PeCacheDir` | Created with a protected ACL: SYSTEM, Administrators and the host account full control, no Users. `pe\` grants the identity **read & execute only** (lmxopcua#1075; it was Modify until then): since lmxopcua#1014 the host verifies, compiles and writes every entry and sends verified images over the pipe, so a worker never writes there. Re-running the installer replaces the identity's explicit ACE on `pe\` (`Set-OtOpcUaExplicitAce` purges it before adding the new one), so an upgrade drops the old Modify grant with no manual step; `-Verify` reports `[MISSING]` on a box still carrying it. The HMAC key and `workers\` markers are host-only. | | Install folder | The identity is **denied** read and write on `` (inherited: ReadData/List, WriteData/AddFile, AppendData/AddSubdirectory, write attributes/EA, Delete, DeleteChild, ChangePermissions, TakeOwnership; Traverse/Execute, ReadAttributes and ReadPermissions stay so the loader reaches `script-worker\`). The worker cannot read `appsettings*.json`, logs or host binaries even where `Users` can. `script-worker\` grants it read + execute. | | Sensitive folders (`-DenyPaths`, lmxopcua#890) | The same inherited deny on every listed folder. **Name every folder outside `` that holds keys, secrets, stores, logs or backups**: the worker's restricting SIDs include `Everyone` and `BUILTIN\Users`, so anything Users can read is otherwise readable to it (and a data drive usually lets Users create files in subfolders, e.g. a certificate in `pki\trusted\certs`). Name the deployment folder around `` (one ACE covers `pki\`, `data\`, `logs\`, `backup\`, old `app.bak.*`) **and** `pki\` and `data\` themselves, so the deny holds even on a folder whose DACL does not inherit. Drive and share roots, `script-worker\` and the PE cache are refused; each folder must exist. The list is recorded under `HKLM\…\Services\OtOpcUaScriptWorker\Parameters` (`DenyPaths`): a re-run removes the deny from folders dropped from the list, and `-Uninstall` removes every recorded one without repeating `-DenyPaths`. After an apply the installer WARNs about any item under a denied folder whose DACL is protected and has no deny of its own (the inherited deny does not reach it); without `-DenyPaths` it WARNs about `pki`/`data`/`logs`/`backup`/`config`/`secrets` siblings of ``. Wonder layout: `-InstallRoot E:\ApiInstall\OtOpcUa\app -DenyPaths E:\ApiInstall\OtOpcUa,E:\ApiInstall\OtOpcUa\pki,E:\ApiInstall\OtOpcUa\data,C:\ProgramData\ZB\kek` plus, box-wide (lmxopcua#891), every other app folder under `E:\ApiInstall` and the staging folders `E:\psrem-stage`, `E:\psrem`; keep deploy backups (`.reg` exports, appsettings copies) in a folder with a protected SYSTEM + Administrators ACL. | | Firewall | Outbound **block** rule `OtOpcUa-ScriptWorker-BlockOutbound` on `script-worker\ZB.MOM.WW.OtOpcUa.ScriptWorker.exe`, every profile. It covers the self-contained apphost the Windows installs run. A framework-dependent worker runs under `dotnet.exe` and is not covered, so there the analyzer's `System.Net` ban is the only network control. | diff --git a/docs/security.md b/docs/security.md index 3ba21fc0d..ef83ba760 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1831,6 +1831,10 @@ Responses: `202 Accepted` (`{ outcome, deploymentId, revisionHash }`) when a dep **Outcome unknown (lmxopcua#949).** The trigger waits 10 s for the admin singleton. A slow compose (one gate run took 10.5 s) can outlast that and still create and apply the deployment, so a timeout is **not** reported as a failure: the id is pre-allocated before the ask and the response is `202 Accepted` with `{ "outcome": "OutcomeUnknown", "deploymentId": "", "message": "…" }` and `Location: /api/deployments/`. Poll that resource: `200` means the deployment exists (and carries exactly that id); `404` for a couple of minutes means it was not created and the trigger can be repeated (a repeat while the original compose is still running answers `409` naming the same id). Scripts must therefore check `outcome`, not just the 2xx status. The AdminUI Deployments page shows the same case as "could not be confirmed … may still be created", with the id. The admin singleton logs a Warning with the per-phase timings (`dispatch`, `in-flight-check`, `snapshot-begin+compose-lock`, `snapshot-read`, `validate`, `compose`, `save+commit`), timed from the singleton's receipt of the request, for any deploy slower than 3 s. Since lmxopcua#955 the compose reads under SNAPSHOT isolation (serialised against other composes by an app lock), not SERIALIZABLE: a concurrent AdminUI edit neither waits for a running deploy nor holds it, and the two can no longer deadlock (under SERIALIZABLE a cross-table edit made the deploy wait ~5 s per deadlock-monitor cycle or fail with "StartDeployment failed on the server"). An edit that commits after the deploy's snapshot is simply in the next deployment. Set the secret via `Security:DeployApiKey` (env `Security__DeployApiKey`) on admin nodes only; treat it like any deploy credential (rotate, keep out of source). +### Headless manual failover (`POST /api/cluster/failover`, lmxopcua#1078) + +Admin-role nodes also expose the cluster redundancy page's "Trigger failover" action to scripts (`ManualFailoverApiEndpoints`), calling the same `IManualFailoverService` (peer guard + `cluster.manual-failover` audit; see `docs/Redundancy.md` §"Manual failover"). Same shape as the deploy API: `AllowAnonymous` + a handler-checked `X-Api-Key` against **`Security:FailoverApiKey`** (env `Security__FailoverApiKey`), fixed-time, self-disabling (`503`) until set. It is deliberately a **different key from `Security:DeployApiKey`** — the page requires `FleetAdmin` because it restarts a production node, so a deploy credential must not grant it. `401` wrong/missing key, `409` no peer, `202` accepted. Optional `X-Actor` header is appended to the audit actor. Treat the key as an Administrator credential (rotate, never commit). + ### `/fleet/diagnostics` dials only known nodes (#973 / review A-1) The page used to feed `?node=` (or the typed host:port box) straight into an Akka `ActorSelection`, so any signed-in user could make the admin node open an outbound remoting association to an arbitrary `host:port`. The target now resolves server-side through `FleetDiagnosticsTargets.Resolve` against a closed set: **Up driver-role cluster members ∪ `Host:AkkaPort` of every enabled `ClusterNode`**. Anything else renders "Unknown node … no connection was attempted" and never reaches `IFleetDiagnosticsClient`; the value dialled is the canonical member string, not the caller's text. Peer nodes for the cluster-wide Faulted tile go through the same check. `FleetDiagnosticsClient` independently refuses any value that is not a plain `host:port` (`FleetDiagnosticsTargets.IsWellFormed`; `/`, `@`, whitespace, `?`, port outside 1..65535) before building the address. diff --git a/scripts/install/Install-ScriptWorkerIsolation.ps1 b/scripts/install/Install-ScriptWorkerIsolation.ps1 index 05f106439..3c9b41382 100644 --- a/scripts/install/Install-ScriptWorkerIsolation.ps1 +++ b/scripts/install/Install-ScriptWorkerIsolation.ps1 @@ -15,7 +15,7 @@ makes must pass for the host account AND that set. 2. PeCacheDir created; ACL replaced: protected, owner Administrators, SYSTEM + Administrators + the host account full control. No Users, no worker access (the HMAC key and launch markers live here). - 3. PeEntriesDir \pe, the worker identity gets Modify (workers compile and write HMAC'd entries). + 3. PeEntriesDir \pe, the worker identity gets read+execute only (the host writes entries since #1014; a re-run replaces an older Modify grant, #1075). 4. WorkerFolderAcl \script-worker, the worker identity gets read + execute. 5. InstallRootDeny , the worker identity is DENIED read and write (inherited): ReadData/List, WriteData/AddFile, AppendData/AddSubdirectory, WriteAttributes/EA, Delete, DeleteChild, diff --git a/scripts/install/ScriptWorkerIsolation.psm1 b/scripts/install/ScriptWorkerIsolation.psm1 index 5596c519e..529ee398d 100644 --- a/scripts/install/ScriptWorkerIsolation.psm1 +++ b/scripts/install/ScriptWorkerIsolation.psm1 @@ -72,7 +72,7 @@ function Get-OtOpcUaPeCacheSddl { The PeCacheDir root's security descriptor: owner Administrators, PROTECTED (no inherited Users/Everyone/ Authenticated Users), SYSTEM + Administrators + the host account full control (container + object inherit). The worker identity gets NOTHING here — the HMAC key (pe-cache.key) and the launch markers (workers\) stay - host-only; the worker's one writable place is the pe\ subfolder (Get-OtOpcUaPeEntriesAce). + host-only; the worker can only READ the pe\ subfolder (Get-OtOpcUaPeEntriesAce, #1075). #> param([Parameter(Mandatory)] [string]$HostSid) $aces = @( @@ -84,9 +84,11 @@ function Get-OtOpcUaPeCacheSddl { } function Get-OtOpcUaPeEntriesAce { - # pe\ : the worker compiles in-process (owner decision §14 #7) and writes HMAC'd entries here — Modify, inherited. + # pe\ : read and execute only, inherited (lmxopcua#1075). Since #1014 the host verifies, compiles and writes every entry and + # sends verified images over the pipe, so the worker never writes here. Set-OtOpcUaExplicitAce PURGES the identity's existing + # explicit ACEs before adding this one, so a re-run on a box installed with the old Modify grant replaces it (idempotent upgrade). param([Parameter(Mandatory)] [string]$WorkerSid) - Format-OtOpcUaAce -Type A -Flags 'OICI' -Mask $script:Modify -Sid $WorkerSid + Format-OtOpcUaAce -Type A -Flags 'OICI' -Mask $script:ReadAndExecute -Sid $WorkerSid } function Get-OtOpcUaScriptWorkerFolderAce { @@ -220,8 +222,8 @@ function Get-ScriptWorkerIsolationPlan { "create the PE cache directory and set its ACL (protected; SYSTEM, Administrators, host account full control; no Users; no worker access to the key or markers)" ` @{ Path = $cache; Sddl = (Get-OtOpcUaPeCacheSddl -HostSid $HostSid) })) $steps.Add((New-OtOpcUaPlanStep 'PeEntriesDir' $entries ` - "create the PE entries directory and grant the worker identity Modify (it compiles and writes HMAC'd entries)" ` - @{ Path = $entries; Ace = (Get-OtOpcUaPeEntriesAce -WorkerSid $workerSid); Sid = $workerSid; Mask = $script:Modify; Type = 'Allow' })) + "create the PE entries directory and grant the worker identity read+execute only (host-side signing since #1014; replaces an older Modify grant on re-run)" ` + @{ Path = $entries; Ace = (Get-OtOpcUaPeEntriesAce -WorkerSid $workerSid); Sid = $workerSid; Mask = $script:ReadAndExecute; Type = 'Allow' })) $steps.Add((New-OtOpcUaPlanStep 'WorkerFolderAcl' $workerFolder ` "grant the worker identity read+execute on its own binaries" ` @{ Path = $workerFolder; Ace = (Get-OtOpcUaScriptWorkerFolderAce -WorkerSid $workerSid); Sid = $workerSid; Mask = $script:ReadAndExecute; Type = 'Allow' })) diff --git a/scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1 b/scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1 index f45c3f50d..43c4cce85 100644 --- a/scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1 +++ b/scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1 @@ -27,7 +27,9 @@ node did not exit non-zero" when leg 2 fails. Triggers (-Trigger): - Failover (default) the script pauses and asks the operator to press "Trigger failover" on the AdminUI cluster + Failover (default) with -FailoverUrl + a key (-FailoverApiKey or env OTOPCUA_FAILOVER_API_KEY) the script POSTs the + headless failover endpoint (lmxopcua#1078, POST /api/cluster/failover on an admin node, key = + Security:FailoverApiKey) - unattended. Without them the script pauses and asks the operator to press "Trigger failover" on the AdminUI cluster redundancy page (/clusters/{id}/redundancy). Manual failover asks the driver PRIMARY to leave, so run this on the box hosting the current Primary of a two-node pair. Needs an interactive console. Command runs -TriggerCommand (a PowerShell script block, as text) that makes THIS node leave or be downed, e.g. a @@ -43,6 +45,14 @@ powershell -NoProfile -ExecutionPolicy Bypass -File scripts\install\tests\Test-ScmRestartAfterClusterExit.Windows.ps1 -KillControl pwsh -NoProfile -File ...\Test-ScmRestartAfterClusterExit.Windows.ps1 -Trigger Command -TriggerCommand '