Merge ops follow-ups: authenticated manual-failover endpoint for the unattended SCM restart check (#1078, Security:FailoverApiKey), worker pe\ cache grant narrowed to read & execute (#1075)
This commit is contained in:
@@ -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:<X-Actor header>`). 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**
|
||||
|
||||
@@ -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 `<InstallRoot>` (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 `<InstallRoot>` 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 `<InstallRoot>` (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 `<InstallRoot>`. 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. |
|
||||
|
||||
@@ -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": "<id>", "message": "…" }` and `Location: /api/deployments/<id>`. 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.
|
||||
|
||||
@@ -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 <PeCacheDir>\pe, the worker identity gets Modify (workers compile and write HMAC'd entries).
|
||||
3. PeEntriesDir <PeCacheDir>\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 <InstallRoot>\script-worker, the worker identity gets read + execute.
|
||||
5. InstallRootDeny <InstallRoot>, the worker identity is DENIED read and write (inherited): ReadData/List,
|
||||
WriteData/AddFile, AppendData/AddSubdirectory, WriteAttributes/EA, Delete, DeleteChild,
|
||||
|
||||
@@ -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' }))
|
||||
|
||||
@@ -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 '<script>'
|
||||
|
||||
.PARAMETER FailoverUrl
|
||||
Base URL of an admin node of THIS node's cluster (e.g. http://central-1:9200). With a key, -Trigger Failover calls
|
||||
POST <FailoverUrl>/api/cluster/failover instead of prompting; the call is audited as cluster.manual-failover with actor
|
||||
rest-api:Test-ScmRestartAfterClusterExit. HTTP 409 = no peer (refused, nothing changed) and the script exits 2.
|
||||
|
||||
.PARAMETER FailoverApiKey
|
||||
The value of Security:FailoverApiKey. Defaults to env OTOPCUA_FAILOVER_API_KEY. Never commit it.
|
||||
|
||||
.PARAMETER ServiceName
|
||||
The service under test (default OtOpcUaHost, as Install-Services.ps1 names it).
|
||||
|
||||
@@ -54,6 +64,8 @@ param(
|
||||
[string]$ServiceName = 'OtOpcUaHost',
|
||||
[ValidateSet('Failover', 'Command')][string]$Trigger = 'Failover',
|
||||
[string]$TriggerCommand,
|
||||
[string]$FailoverUrl,
|
||||
[string]$FailoverApiKey = $env:OTOPCUA_FAILOVER_API_KEY,
|
||||
[int]$TimeoutSeconds = 180,
|
||||
[switch]$SkipStopControl,
|
||||
[switch]$KillControl)
|
||||
@@ -65,7 +77,9 @@ if ($PSVersionTable.PSEdition -eq 'Core' -and -not $IsWindows) { Write-Host 'SKI
|
||||
$principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
|
||||
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Host 'run elevated'; exit 2 }
|
||||
if ($Trigger -eq 'Command' -and [string]::IsNullOrWhiteSpace($TriggerCommand)) { Write-Host '-Trigger Command needs -TriggerCommand'; exit 2 }
|
||||
if ($Trigger -eq 'Failover' -and -not [Environment]::UserInteractive) { Write-Host '-Trigger Failover needs an interactive console (use -Trigger Command)'; exit 2 }
|
||||
$useEndpoint = $Trigger -eq 'Failover' -and $FailoverUrl -and $FailoverApiKey
|
||||
if ($Trigger -eq 'Failover' -and ($FailoverUrl -xor $FailoverApiKey)) { Write-Host '-FailoverUrl and a key (-FailoverApiKey / OTOPCUA_FAILOVER_API_KEY) must be given together'; exit 2 }
|
||||
if ($Trigger -eq 'Failover' -and -not $useEndpoint -and -not [Environment]::UserInteractive) { Write-Host '-Trigger Failover needs an interactive console, or -FailoverUrl + a key (or use -Trigger Command)'; exit 2 }
|
||||
|
||||
$svc = Get-CimInstance Win32_Service -Filter "Name='$ServiceName'"
|
||||
if (-not $svc) { Write-Host "service $ServiceName is not installed"; exit 2 }
|
||||
@@ -124,7 +138,20 @@ try {
|
||||
$before = Get-ServicePid
|
||||
$proc = Watch-ServiceProcess $before
|
||||
$since = (Get-Date).AddSeconds(-1)
|
||||
if ($Trigger -eq 'Failover') {
|
||||
if ($useEndpoint) {
|
||||
$uri = $FailoverUrl.TrimEnd('/') + '/api/cluster/failover'
|
||||
Write-Host " POST $uri"
|
||||
try {
|
||||
$resp = Invoke-RestMethod -Method Post -Uri $uri -Headers @{ 'X-Api-Key' = $FailoverApiKey; 'X-Actor' = 'Test-ScmRestartAfterClusterExit' } -TimeoutSec 30
|
||||
Write-Host " failover accepted; leaving node: $($resp.leavingNode)"
|
||||
}
|
||||
catch {
|
||||
$code = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { 0 }
|
||||
Write-Host " failover endpoint failed (HTTP $code): $($_.Exception.Message)"
|
||||
exit 2
|
||||
}
|
||||
}
|
||||
elseif ($Trigger -eq 'Failover') {
|
||||
Write-Host ' Press "Trigger failover" on the AdminUI cluster redundancy page for THIS node''s cluster (this node must be the'
|
||||
Write-Host ' driver Primary), then press Enter here.'
|
||||
$null = Read-Host
|
||||
|
||||
@@ -58,8 +58,8 @@ Assert ($sysSddl -eq 'O:BAG:SYD:PAI(A;OICI;0x1f01ff;;;SY)(A;OICI;0x1f01ff;;;BA)'
|
||||
|
||||
$pe = $byId['PeEntriesDir'].Data
|
||||
Assert ($pe.Path -eq "$cache\pe" -or $pe.Path -eq "$cache/pe") "entries dir is <PeCacheDir>\pe ($($pe.Path))"
|
||||
Assert ($pe.Ace -eq "(A;OICI;0x1301bf;;;$workerSid)") "worker gets Modify on pe\ ($($pe.Ace))"
|
||||
Assert ($pe.Type -eq 'Allow' -and $pe.Mask -eq 0x1301BF -and $pe.Sid -eq $workerSid) 'pe\ ACE data matches its SDDL'
|
||||
Assert ($pe.Ace -eq "(A;OICI;0x1200a9;;;$workerSid)") "worker gets read+execute only on pe\ ($($pe.Ace))"
|
||||
Assert ($pe.Type -eq 'Allow' -and $pe.Mask -eq 0x1200A9 -and $pe.Sid -eq $workerSid) 'pe\ ACE data matches its SDDL'
|
||||
|
||||
$wf = $byId['WorkerFolderAcl'].Data
|
||||
Assert ($wf.Ace -eq "(A;OICI;0x1200a9;;;$workerSid)") "worker gets read+execute on script-worker\ ($($wf.Ace))"
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.ControlPlane.Redundancy;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Headless trigger for the manual failover the cluster redundancy page's "Trigger failover" button
|
||||
/// performs (lmxopcua#1078), so scripted gates such as
|
||||
/// <c>scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1</c> can run unattended.
|
||||
/// It calls the same <see cref="IManualFailoverService.FailOverDriverPrimaryAsync"/> — peer guard and the
|
||||
/// <c>cluster.manual-failover</c> audit event included — and adds no failover logic of its own.
|
||||
/// <para>
|
||||
/// Auth follows <see cref="DeployApiEndpoints"/>: a configured secret (<c>Security:FailoverApiKey</c>,
|
||||
/// a key SEPARATE from the deploy key so a deploy credential cannot bounce the Primary) checked from
|
||||
/// <c>X-Api-Key</c> in fixed time; the endpoint self-disables (503) until the key is set. The page's
|
||||
/// <c>FleetAdmin</c> policy needs an interactive LDAP login, which an unattended script has no way to
|
||||
/// perform, so holding this key is the Administrator-equivalent grant. The audit actor is
|
||||
/// <c>rest-api</c> (or <c>rest-api:<X-Actor></c> when the optional header is sent).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static class ManualFailoverApiEndpoints
|
||||
{
|
||||
/// <summary>Configuration key holding the failover API secret.</summary>
|
||||
public const string ConfigKey = "Security:FailoverApiKey";
|
||||
|
||||
/// <summary>Optional header naming who/what is triggering (recorded in the audit actor).</summary>
|
||||
public const string ActorHeader = "X-Actor";
|
||||
|
||||
/// <summary>Maps <c>POST /api/cluster/failover</c>. Acts on the Primary of THIS node's own mesh.</summary>
|
||||
/// <param name="app">The endpoint route builder.</param>
|
||||
/// <param name="config">Application configuration (read for the failover API key).</param>
|
||||
/// <returns>The same <paramref name="app"/> for chaining.</returns>
|
||||
public static IEndpointRouteBuilder MapOtOpcUaManualFailoverApi(this IEndpointRouteBuilder app, IConfiguration config)
|
||||
{
|
||||
var configuredKey = config[ConfigKey];
|
||||
|
||||
app.MapPost("/api/cluster/failover", (HttpContext http, IManualFailoverService failover) =>
|
||||
HandleAsync(
|
||||
configuredKey,
|
||||
http.Request.Headers[DeployApiEndpoints.ApiKeyHeader].ToString(),
|
||||
http.Request.Headers[ActorHeader].ToString(),
|
||||
failover))
|
||||
.AllowAnonymous() // gated by the API key, not the cookie auth fallback
|
||||
.DisableAntiforgery() // machine endpoint, not a browser form post
|
||||
.WithName("ManualFailover");
|
||||
return app;
|
||||
}
|
||||
|
||||
/// <summary>The endpoint's decision logic, separated from routing so it is unit-testable.</summary>
|
||||
/// <param name="configuredKey">The configured secret; empty disables the endpoint.</param>
|
||||
/// <param name="providedKey">The caller's <c>X-Api-Key</c>.</param>
|
||||
/// <param name="actorHeader">The caller's optional <c>X-Actor</c>.</param>
|
||||
/// <param name="failover">The manual-failover service the UI button also calls.</param>
|
||||
/// <returns>503 when disabled, 401 on a wrong key, 409 when refused (no peer), else 202 naming the leaving node.</returns>
|
||||
public static async Task<IResult> HandleAsync(
|
||||
string? configuredKey, string? providedKey, string? actorHeader, IManualFailoverService failover)
|
||||
{
|
||||
if (string.IsNullOrEmpty(configuredKey))
|
||||
return Results.Problem(
|
||||
$"Manual failover API is disabled. Set {ConfigKey} to enable it.",
|
||||
statusCode: StatusCodes.Status503ServiceUnavailable);
|
||||
|
||||
if (!DeployApiEndpoints.IsAuthorized(providedKey, configuredKey))
|
||||
return Results.Unauthorized();
|
||||
|
||||
var actor = string.IsNullOrWhiteSpace(actorHeader) ? "rest-api" : $"rest-api:{actorHeader.Trim()}";
|
||||
var target = await failover.FailOverDriverPrimaryAsync(actor);
|
||||
return target is null
|
||||
? Results.Problem("Failover refused: no driver peer is available to take over.",
|
||||
statusCode: StatusCodes.Status409Conflict)
|
||||
: Results.Accepted(value: new FailoverResponse("Accepted", target));
|
||||
}
|
||||
|
||||
/// <summary>Response body for an accepted failover.</summary>
|
||||
/// <param name="Outcome">Always <c>Accepted</c>.</param>
|
||||
/// <param name="LeavingNode">The address of the Primary asked to leave the cluster.</param>
|
||||
public sealed record FailoverResponse(string Outcome, string LeavingNode);
|
||||
}
|
||||
@@ -818,6 +818,8 @@ if (hasAdmin)
|
||||
app.MapOtOpcUaHubs();
|
||||
// Headless deploy trigger for CI/scripts (API-key gated; disabled until Security:DeployApiKey set).
|
||||
app.MapOtOpcUaDeployApi(app.Configuration);
|
||||
// Headless manual failover (#1078; API-key gated; disabled until Security:FailoverApiKey set).
|
||||
app.MapOtOpcUaManualFailoverApi(app.Configuration);
|
||||
}
|
||||
|
||||
// Mesh gRPC ingress: the LocalDb passive sync endpoint, the ConfigServe artifact + central
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.Api;
|
||||
using ZB.MOM.WW.OtOpcUa.ControlPlane.Redundancy;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Api;
|
||||
|
||||
/// <summary>lmxopcua#1078: the headless failover trigger is key-gated and dispatches the same service call as the UI button.</summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class ManualFailoverApiEndpointsTests
|
||||
{
|
||||
private sealed class FakeFailover(string? target) : IManualFailoverService
|
||||
{
|
||||
public List<string> Actors { get; } = [];
|
||||
public ManualFailoverSnapshot GetSnapshot() => new(null, []);
|
||||
public Task<string?> FailOverDriverPrimaryAsync(string actor) { Actors.Add(actor); return Task.FromResult(target); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unconfigured_key_disables_the_endpoint_and_never_dispatches()
|
||||
{
|
||||
var fake = new FakeFailover("akka://n1");
|
||||
var r = await ManualFailoverApiEndpoints.HandleAsync(null, "anything", null, fake);
|
||||
r.ShouldBeOfType<ProblemHttpResult>().StatusCode.ShouldBe(503);
|
||||
fake.Actors.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData("wrong")]
|
||||
public async Task Missing_or_wrong_key_is_unauthorized_and_never_dispatches(string? provided)
|
||||
{
|
||||
var fake = new FakeFailover("akka://n1");
|
||||
var r = await ManualFailoverApiEndpoints.HandleAsync("secret", provided, null, fake);
|
||||
r.ShouldBeOfType<UnauthorizedHttpResult>();
|
||||
fake.Actors.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_deploy_key_is_not_a_failover_credential()
|
||||
{
|
||||
// Distinct config keys: a deploy credential must not bounce the Primary.
|
||||
ManualFailoverApiEndpoints.ConfigKey.ShouldNotBe(DeployApiEndpoints.ConfigKey);
|
||||
var fake = new FakeFailover("akka://n1");
|
||||
var r = await ManualFailoverApiEndpoints.HandleAsync("failover-key", "deploy-key", null, fake);
|
||||
r.ShouldBeOfType<UnauthorizedHttpResult>();
|
||||
fake.Actors.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Valid_key_dispatches_the_service_call_once_and_names_the_leaving_node()
|
||||
{
|
||||
var fake = new FakeFailover("akka.tcp://sys@host:4053");
|
||||
var r = await ManualFailoverApiEndpoints.HandleAsync("secret", "secret", null, fake);
|
||||
var accepted = r.ShouldBeOfType<Accepted<ManualFailoverApiEndpoints.FailoverResponse>>();
|
||||
accepted.Value!.LeavingNode.ShouldBe("akka.tcp://sys@host:4053");
|
||||
fake.Actors.ShouldBe(["rest-api"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Actor_header_is_recorded_for_attribution()
|
||||
{
|
||||
var fake = new FakeFailover("akka://n1");
|
||||
await ManualFailoverApiEndpoints.HandleAsync("secret", "secret", " gate-run ", fake);
|
||||
fake.Actors.ShouldBe(["rest-api:gate-run"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_refused_failover_is_409_not_success()
|
||||
{
|
||||
var fake = new FakeFailover(null);
|
||||
var r = await ManualFailoverApiEndpoints.HandleAsync("secret", "secret", null, fake);
|
||||
r.ShouldBeOfType<ProblemHttpResult>().StatusCode.ShouldBe(409);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Route_is_post_only_and_gated_in_the_handler_not_by_the_cookie_policy()
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder();
|
||||
builder.Services.AddSingleton<IManualFailoverService>(new FakeFailover(null));
|
||||
var app = builder.Build();
|
||||
var config = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?> { [ManualFailoverApiEndpoints.ConfigKey] = "k" }).Build();
|
||||
app.MapOtOpcUaManualFailoverApi(config);
|
||||
|
||||
var e = ((IEndpointRouteBuilder)app).DataSources.SelectMany(d => d.Endpoints).OfType<RouteEndpoint>()
|
||||
.Single(x => x.Metadata.GetMetadata<IEndpointNameMetadata>()?.EndpointName == "ManualFailover");
|
||||
e.RoutePattern.RawText.ShouldBe("/api/cluster/failover");
|
||||
e.Metadata.GetMetadata<IHttpMethodMetadata>()!.HttpMethods.ShouldBe(["POST"]);
|
||||
e.Metadata.GetMetadata<IAllowAnonymous>().ShouldNotBeNull();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user