Compare commits

...

7 Commits

Author SHA1 Message Date
Joseph Doherty 3eb370d4ea refactor(adminui): explicit discard on fire-and-forget audit + Untrust not-found test (review)
v2-ci / build (push) Failing after 49s
v2-ci / unit-tests (tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests) (push) Has been skipped
2026-06-19 00:45:10 -04:00
Joseph Doherty 3ee0099fae refactor(adminui): omit error key on success cert-audit rows + assert OccurredAtUtc (review) 2026-06-19 00:38:41 -04:00
Joseph Doherty 23d45efcfd feat(adminui): audit cert Trust/Untrust/Delete to ConfigAuditLog 2026-06-19 00:36:54 -04:00
Joseph Doherty de6ce147fc fix(runtime): drop OpcUaProbeResult in redundancy-topic subscribers (no dead-letter) 2026-06-19 00:32:03 -04:00
Joseph Doherty 084d73ea2b feat(adminui): IAuditWriter adapter + cert-action audit-event factory 2026-06-19 00:31:37 -04:00
Joseph Doherty 21c881161a docs(plan): implementation plan + tasks for cert-audit + probe dead-letter tidy 2026-06-19 00:26:30 -04:00
Joseph Doherty e8c75cc38f docs(plan): design for cert-action audit logging + OpcUaProbeResult dead-letter tidy 2026-06-19 00:23:32 -04:00
16 changed files with 1053 additions and 20 deletions
@@ -0,0 +1,161 @@
# Cert-action audit logging + `OpcUaProbeResult` dead-letter tidy — Design
**Date:** 2026-06-19
**Status:** Approved (brainstorming)
**Branch:** `feat/cert-audit-and-probe-tidy` (off master `40e8a23e`)
Two independent, self-contained backlog items, batched into one branch.
- **Item 1 — Cert-action audit logging** (`stillpending.md` §A.7 deferred follow-up): the
meaty one. Standard complexity.
- **Item 2 — `OpcUaProbeResult` dead-letter tidy** (Phase-4 final-integration-review
follow-up (i)): trivial actor hygiene.
Hard guardrails (both): **no EF migration, no Commons/proto/interface change, no bUnit.**
Stage by explicit path; never stage the never-stage files (`sql_login.txt`,
`Host/pki/`, `docker-dev/docker-compose.yml`, `pending.md`, `current.md`,
`stillpending.md`). No `--no-verify`, no force-push. Finish = merge to master + push.
---
## Background: H2 was reclassified, then this was chosen
The session began on the "within-timestamp tie-cluster paging (#400)" follow-up — found
**already shipped** (`2e6c6d3a`/`0f929ae6`, 2026-06-17); reconciled the stale `pending.md`
banners. Then surveyed the backlog: the only genuinely-OPEN §A item, **H2 (OPC UA
`HistoryUpdate` service)**, was reclassified **infra-gated/DEFERRED** (no historian backend
can durably insert/replace/delete — `IHistorianDataSource` is read-only and the Wonderware
sidecar has no update RPC; same boundary as H5b). The two remaining actionable, in-repo,
non-infra items are the two below.
---
## Item 1 — Cert-action audit logging
### Problem
When a FleetAdmin **Trusts / Untrusts / Deletes** a peer certificate
(`Certificates.razor` → `CertificateStoreManager`), nothing is written to the audit DB.
Today only certificate *validation* is logged (to Serilog). These are security-relevant
mutations and should leave a durable audit trail.
### Key discovery that shapes the design
OtOpcUa has **no live structured `AuditEvent` emit sites yet**. The `Security/AuditActor`
helper is explicitly forward-looking ("tested and ready so future emit sites pick up the
correct Actor automatically"), and `IAuditWriter` is **not** registered as an injectable
DI service anywhere. But the persistence path exists end-to-end:
- `AuditWriterActor` (an **AdminRole cluster singleton**, `ControlPlane/Audit/`) implements
`IAuditWriter` (from the external `ZB.MOM.WW.Audit` package), batches `AuditEvent`s, and
bulk-inserts into the existing **`ConfigAuditLog`** table (filtered-unique-index dedup on
`EventId`).
- AdminUI already reaches an AdminRole singleton from the `ActorRegistry`:
`AdminOperationsClient` does `registry.Get<AdminOperationsActorKey>()`. Same pattern works
for `AuditWriterActorKey`.
So this is the **first** structured emit site — exactly what the infra was built for. The
`ConfigAuditLog` table and `AuditWriterActor` already exist ⇒ **no EF migration, no Commons
change.**
### Components
1. **`ActorAuditWriter : IAuditWriter`** — *new*, `AdminUI/Audit/ActorAuditWriter.cs`.
Holds the `AuditWriterActorKey` singleton-proxy `IActorRef` (resolved from
`ActorRegistry`, mirroring `AdminOperationsClient`); `WriteAsync(evt, ct)` does
`_proxy.Tell(evt)` and returns `Task.CompletedTask` (best-effort, non-blocking — the
actor owns batching/dedup/flush). Registered `AddSingleton<IAuditWriter, ActorAuditWriter>()`
in the AdminUI DI extension.
2. **`CertAuditEvents.Build(action, store, thumbprint, actor, success, error)` → `AuditEvent`**
— *new*, `AdminUI/Audit/CertAuditEvents.cs`. Pure static factory:
- `Category = "Certificate"`, `Action ∈ {Trust, Untrust, Delete}`
- `SourceNode = thumbprint`
- `DetailsJson` = compact JSON `{ "store": …, "thumbprint": …, "error": …? }`
- `Outcome` = Success / Failure (from `success`)
- `Actor = actor`, fresh `EventId`, `OccurredAtUtc = DateTimeOffset.UtcNow`
Pure ⇒ fully unit-testable; the implementer confirms the exact `AuditEvent` required /
optional fields + the `AuditOutcome` enum member names against the `ZB.MOM.WW.Audit`
package.
3. **`CertificateStoreManager`** — *modify*. Audit at the **choke point** (the thing that
performs the mutation; already has a unit-test class — far more testable than the razor,
which has no bUnit). Each public method gains the actor string and emits the event from
the `CertActionResult` it already computes:
- `Trust(string thumbprint, string actor)`
- `Untrust(string thumbprint, string actor)`
- `Delete(string store, string thumbprint, string actor)`
Production ctor gains `IAuditWriter _audit`; the internal test ctor defaults it to a
null/fake writer so existing tests compile. Each method calls
`_audit.WriteAsync(CertAuditEvents.Build(...))` (non-blocking) — including the
not-found / invalid-thumbprint **failure** paths (audited with `Outcome = Failure`).
4. **`Certificates.razor`** — *modify*. Pass the authenticated principal name into the
manager calls: `authState.User.Identity?.Name ?? "system"` (already fetched at the
FleetAdmin re-check, ~line 185). Sourcing the actor from `AuthenticationState` (not the
scoped `IAuditActorAccessor`/HttpContext) avoids the Blazor-Server HttpContext-null
pitfall over the SignalR circuit.
### Data flow
```
FleetAdmin clicks Trust
→ Certificates.razor RequestAction (FleetAdmin re-checked)
→ CertManager.Trust(thumbprint, actor)
→ filesystem move (rejected → trusted) [unchanged]
→ CertAuditEvents.Build(Trust, store, thumbprint, actor, success, error)
→ IAuditWriter.WriteAsync(evt) (= ActorAuditWriter → proxy.Tell)
→ AuditWriterActor batches → bulk insert → ConfigAuditLog
```
Both success and failure are audited (Outcome reflects `result.Success`).
### Testing (xUnit + Shouldly; no bUnit)
- `CertAuditEventsTests` — factory output for trust/untrust/delete × success/failure:
Category, Action, SourceNode, Outcome, DetailsJson shape.
- Extend `CertificateStoreManagerTests` — inject a recording fake `IAuditWriter`; assert
exactly one event per action with the correct Action + Outcome, including the not-found
failure path.
- `ActorAuditWriterTests` — a `TestKit` probe registered under `AuditWriterActorKey`
receives the Tell'd `AuditEvent`.
- Razor wiring proven by `dotnet build` + a live docker-dev `/run` (login disabled on the
local rig — agent drives it; deploy, perform a Trust/Untrust on the Certificates page,
confirm a new `ConfigAuditLog` row).
### Classification: **standard** (additive DI + first structured emit path; multi-file).
---
## Item 2 — `OpcUaProbeResult` dead-letter tidy
### Problem
`DriverHostActor`, `HistorianAdapterActor`, `ScriptedAlarmHostActor` subscribe the
redundancy-state topic (for state changes) but have **no** handler for the co-published
`PeerOpcUaProbeActor.OpcUaProbeResult`, so each INFO-dead-letters that message (benign,
capped at 10 then 5-min-suppressed, but noisy).
### Change
Add `Receive<PeerOpcUaProbeActor.OpcUaProbeResult>(_ => { })` to each of the three actors —
the exact intentional-drop pattern already used by `PeerProbeSupervisor.cs:69` and
`OpcUaPublishActor` (which actually consumes it). ~3 lines + a one-line doc comment each.
The implementer confirms each actor's topic subscription before adding the drop.
### Testing
A dead-letter probe test (`EventStream` / `AllDeadLetters`) asserting that an
`OpcUaProbeResult` published to the redundancy topic produces **no** dead-letter for each
actor — mirrors the existing Phase-B dead-letter-probe test idiom.
### Classification: **trivial → small** (mechanical drop handler + one guard test).
---
## Execution
Subagent-driven (this session). Item 1 and Item 2 touch **disjoint** files ⇒ their
implementers can be dispatched concurrently. Item 1 gets spec + code review (standard);
Item 2 gets a code review (small). Final integration review before finish. Finish = merge
to master + push.
@@ -0,0 +1,336 @@
# Cert-action audit logging + `OpcUaProbeResult` dead-letter tidy — Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers-extended-cc:subagent-driven-development to implement this plan task-by-task.
**Goal:** Record certificate Trust/Untrust/Delete actions to the `ConfigAuditLog` DB table
via the existing `IAuditWriter`/`AuditWriterActor` path (the first live structured audit
emit site), and silence the benign `OpcUaProbeResult` dead-letters in three Runtime actors.
**Architecture:** Item 1 adds an `ActorAuditWriter : IAuditWriter` AdminUI adapter (Tells the
`AuditWriterActorKey` cluster-singleton proxy, mirroring `AdminOperationsClient`), a pure
`CertAuditEvents` factory, and audits at the `CertificateStoreManager` choke point. Item 2
adds an intentional-drop `Receive<…OpcUaProbeResult>(_ => {})` to three actors (the
`PeerProbeSupervisor.cs:69` idiom). No EF migration, no Commons/proto/interface change, no bUnit.
**Tech Stack:** .NET 10, Akka.NET (Akka.Hosting `ActorRegistry`), Blazor Server (AdminUI),
EF Core (`ConfigAuditLog` — table already exists), `ZB.MOM.WW.Audit` package
(`IAuditWriter`/`AuditEvent`), xUnit + Shouldly, Akka.TestKit.
**Design:** `docs/plans/2026-06-19-cert-audit-and-probe-deadletter-tidy-design.md`
**Branch:** `feat/cert-audit-and-probe-tidy` (off master `40e8a23e`; design committed `e8c75cc3`)
**Standing guardrails:** stage by explicit path (never `git add .`); never stage
`sql_login.txt`, `Host/pki/`, `docker-dev/docker-compose.yml`, `pending.md`, `current.md`,
`stillpending.md`. No `--no-verify`, no force-push. `dangerouslyDisableSandbox: true` for
build/test/rig. Finish = merge to master + push.
**Dependency graph:** `{T1 ∥ T3} → T2 → T4`. T1 (AdminUI cert-audit core) and T3 (Runtime
actor drops) touch disjoint projects ⇒ dispatch their implementers concurrently. T2 depends
on T1 (uses `CertAuditEvents` + `IAuditWriter`). T4 is the final gate.
---
### Task 0 (do this once, before T1/T2): Confirm the `AuditEvent` / `IAuditWriter` / `AuditOutcome` shape
Not a code task — a **read** the T1/T2 implementer MUST do first so the factory matches the
real package type (it lives in the external `ZB.MOM.WW.Audit` assembly, not this repo).
- Go-to-definition / decompile `ZB.MOM.WW.Audit.AuditEvent`, `IAuditWriter`,
and the `Outcome` enum type. Confirm: exact property names + whether it's a record with a
primary ctor or settable inits; the `Outcome` enum member names (the design assumes
`Success` / `Failure` — verify); the `CorrelationId` property type (Guid? / a CorrelationId
struct / nullable).
- Ground truth for how the existing code populates it:
`src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Audit/AuditWriterActor.cs:97-107` reads
`EventId, OccurredAtUtc, Actor, Category, Action, SourceNode, DetailsJson, CorrelationId,
Outcome`. Mirror those names exactly.
- If any assumed field/name differs, adjust the T1 factory code below accordingly (the
shape is the contract; the literal property names must match the package).
---
### Task 1: Cert-audit core — `ActorAuditWriter` + `CertAuditEvents` factory + DI + unit tests
**Classification:** standard
**Estimated implement time:** ~5 min
**Parallelizable with:** Task 3
**Files:**
- Create: `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Audit/ActorAuditWriter.cs`
- Create: `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Audit/CertAuditEvents.cs`
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/EndpointRouteBuilderExtensions.cs` (register `IAuditWriter` near line 55)
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Audit/CertAuditEventsTests.cs`
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Audit/ActorAuditWriterTests.cs`
**Step 1 — Write `CertAuditEventsTests` (failing).** Cover trust/untrust/delete × success/failure:
- `Build("Trust", "trusted", thumb, "alice", success: true, error: null)` ⇒ `Category=="Certificate"`,
`Action=="Trust"`, `SourceNode==thumb`, `Actor=="alice"`, `Outcome` is the success member,
`DetailsJson` contains the store + thumbprint, `EventId != Guid.Empty`.
- A failure case (`success: false, error: "certificate not found in rejected"`) ⇒ `Outcome` is the
failure member and `DetailsJson` includes the error text.
Use Shouldly. (Assert `DetailsJson` by `ShouldContain` substrings, not exact JSON, to stay robust.)
**Step 2 — Write `CertAuditEvents`:**
```csharp
using System.Text.Json;
using ZB.MOM.WW.Audit; // confirm namespace in Task 0
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Audit;
/// <summary>
/// Pure factory for the canonical <see cref="AuditEvent"/> emitted on a certificate-store
/// mutation (Trust / Untrust / Delete). Separated from <c>CertificateStoreManager</c> so the
/// event shape is unit-testable without a filesystem or an actor system.
/// </summary>
public static class CertAuditEvents
{
/// <summary>The audit category for all certificate-store actions.</summary>
public const string Category = "Certificate";
/// <summary>Builds the audit event for one certificate action and outcome.</summary>
/// <param name="action">The action verb: <c>Trust</c> / <c>Untrust</c> / <c>Delete</c>.</param>
/// <param name="store">The PKI sub-store acted on (e.g. <c>trusted</c> / <c>rejected</c>).</param>
/// <param name="thumbprint">The certificate thumbprint.</param>
/// <param name="actor">The authenticated principal performing the action.</param>
/// <param name="success">Whether the action succeeded.</param>
/// <param name="error">The failure message when <paramref name="success"/> is false; otherwise null.</param>
/// <returns>A canonical audit event ready for <see cref="IAuditWriter.WriteAsync"/>.</returns>
public static AuditEvent Build(
string action, string store, string thumbprint, string actor, bool success, string? error)
{
var details = JsonSerializer.Serialize(new
{
store,
thumbprint,
error = success ? null : error,
});
return new AuditEvent
{
EventId = Guid.NewGuid(),
OccurredAtUtc = DateTimeOffset.UtcNow,
Actor = actor,
Category = Category,
Action = action,
SourceNode = thumbprint,
DetailsJson = details,
// CorrelationId / Outcome property types per Task 0. Outcome member names assumed
// Success / Failure — confirm and adjust.
Outcome = success ? AuditOutcome.Success : AuditOutcome.Failure,
};
}
}
```
(Adjust property/enum names to the real package per Task 0. If `AuditEvent` uses a positional
record ctor instead of init-setters, switch to the ctor form.)
**Step 3 — Write `ActorAuditWriterTests` (failing).** Use Akka.TestKit: register a `TestProbe`
in an `ActorRegistry` under `AuditWriterActorKey`, construct `ActorAuditWriter(registry)`, call
`WriteAsync(evt)`, assert the probe `ExpectMsg<AuditEvent>()` equal to `evt`. (Mirror how other
AdminUI TestKit tests build an `ActorRegistry` + register a key — search the AdminUI.Tests project.)
**Step 4 — Write `ActorAuditWriter`** (copy the `AdminOperationsClient` resolve idiom):
```csharp
using Akka.Actor;
using Akka.Hosting;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.OtOpcUa.ControlPlane; // AuditWriterActorKey
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Audit;
/// <summary>
/// <see cref="IAuditWriter"/> backed by the <c>AuditWriterActor</c> cluster singleton registered
/// in <c>AddOtOpcUaControlPlane</c>. Resolves the singleton proxy from <see cref="ActorRegistry"/>
/// at construction (mirroring <c>AdminOperationsClient</c>); <see cref="WriteAsync"/> is a
/// best-effort, non-blocking <c>Tell</c> — the actor owns batching, dedup, and flush.
/// </summary>
public sealed class ActorAuditWriter : IAuditWriter
{
private readonly IActorRef _proxy;
/// <summary>Initializes a new instance resolving the audit-writer singleton proxy.</summary>
/// <param name="registry">The actor registry to resolve the audit-writer singleton proxy.</param>
public ActorAuditWriter(ActorRegistry registry) => _proxy = registry.Get<AuditWriterActorKey>();
/// <inheritdoc />
public Task WriteAsync(AuditEvent evt, CancellationToken ct = default)
{
_proxy.Tell(evt);
return Task.CompletedTask;
}
}
```
(Confirm the exact `IAuditWriter.WriteAsync` signature in Task 0 and match it.)
**Step 5 — Register in DI.** In `EndpointRouteBuilderExtensions.cs`, next to
`services.AddSingleton<Certificates.CertificateStoreManager>();` (line ~55):
```csharp
services.AddSingleton<ZB.MOM.WW.Audit.IAuditWriter, Audit.ActorAuditWriter>();
```
(Confirm `ActorRegistry` is resolvable in this method's host — it is, Akka.Hosting registers it
as a singleton; `AdminOperationsClient` proves the pattern works in AdminUI.)
**Step 6 — Run tests + build:**
`dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests --filter "FullyQualifiedName~Audit"` → green.
**Step 7 — Commit** (stage by path):
`git add src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Audit/ src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/EndpointRouteBuilderExtensions.cs tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Audit/`
then `git commit -m "feat(adminui): IAuditWriter adapter + cert-action audit-event factory"`.
---
### Task 2: Wire audit into `CertificateStoreManager` + `Certificates.razor` + extend manager tests
**Classification:** standard
**Estimated implement time:** ~5 min
**Parallelizable with:** none (depends on Task 1)
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Certificates/CertificateStoreManager.cs`
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Certificates.razor:194-205`
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Certificates/CertificateStoreManagerTests.cs`
**Step 1 — Extend `CertificateStoreManagerTests` (failing).** Add a recording fake `IAuditWriter`:
```csharp
private sealed class RecordingAuditWriter : ZB.MOM.WW.Audit.IAuditWriter
{
public List<ZB.MOM.WW.Audit.AuditEvent> Events { get; } = new();
public Task WriteAsync(ZB.MOM.WW.Audit.AuditEvent evt, CancellationToken ct = default)
{ Events.Add(evt); return Task.CompletedTask; }
}
```
Change the test ctor to build `_audit = new RecordingAuditWriter();` and
`_sut = new CertificateStoreManager(_root, _audit);`. Add tests:
- `Trust_success_writes_one_success_audit_event` — seed a rejected cert, `Trust(thumb, "alice")`,
assert `_audit.Events` has one event with `Action=="Trust"`, success outcome, `SourceNode==thumb`.
- `Delete_not_found_writes_one_failure_audit_event` — `Delete("trusted", unknownThumb, "bob")`,
assert one event, failure outcome.
- Confirm the existing (no-audit-arg) assertions still pass via the defaulted test ctor.
**Step 2 — Modify `CertificateStoreManager`:**
- Add field `private readonly IAuditWriter _audit;`.
- Production ctor: `public CertificateStoreManager(IConfiguration config, IAuditWriter audit)` —
set `_audit = audit;` (and keep the pki-root read).
- Internal test ctor: `internal CertificateStoreManager(string pkiRoot, IAuditWriter? audit = null)`
→ `_audit = audit ?? NullAuditWriter`. (Use a tiny private no-op `IAuditWriter` if the package
has no Null impl — confirm in Task 0.)
- Add the actor param to the three public methods and emit after computing the result:
```csharp
public CertActionResult Trust(string thumbprint, string actor)
{
var r = Move("rejected", "trusted", thumbprint);
Audit("Trust", "rejected→trusted", thumbprint, actor, r);
return r;
}
// Untrust(thumbprint, actor) → Move("trusted","rejected",…) + Audit("Untrust", "trusted→rejected", …)
// Delete(store, thumbprint, actor) → existing body + Audit("Delete", store, …, r) at each return
private void Audit(string action, string store, string thumbprint, string actor, CertActionResult r)
=> _audit.WriteAsync(CertAuditEvents.Build(action, store, thumbprint, actor, r.Success, r.Error));
```
Ensure **every** return path of `Delete` (invalid store, invalid thumbprint, not-found, success,
IO failure) is audited — simplest is to compute the `CertActionResult` into a local, `Audit(...)`,
then return it. Keep `_audit.WriteAsync(...)` fire-and-forget (returns a completed task).
**Step 3 — Modify `Certificates.razor` `ConfirmAction` (line 194):** capture the actor and thread it:
```csharp
var actor = authState.User.Identity?.Name ?? "system";
var result = p.Verb switch
{
"trust" => CertManager.Trust(p.Thumbprint, actor),
"untrust" => CertManager.Untrust(p.Thumbprint, actor),
"delete" => p.Kind switch
{
StoreKind.Trusted => CertManager.Delete("trusted", p.Thumbprint, actor),
StoreKind.Rejected => CertManager.Delete("rejected", p.Thumbprint, actor),
_ => CertActionResult.Fail($"cannot delete from {p.Kind}"),
},
_ => CertActionResult.Fail("unknown action"),
};
```
(`authState` is already in scope from the FleetAdmin re-check at line 185.)
**Step 4 — Test + build:**
`dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests --filter "FullyQualifiedName~CertificateStoreManager"` → green;
`dotnet build src/Server/ZB.MOM.WW.OtOpcUa.AdminUI` → 0 errors (proves the razor compiles).
**Step 5 — Commit:**
`git add src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Certificates/CertificateStoreManager.cs src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Certificates.razor tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Certificates/CertificateStoreManagerTests.cs`
then `git commit -m "feat(adminui): audit cert Trust/Untrust/Delete to ConfigAuditLog"`.
---
### Task 3: `OpcUaProbeResult` dead-letter tidy — three actor drop handlers + guard test
**Classification:** small
**Estimated implement time:** ~4 min
**Parallelizable with:** Task 1
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs` (handler region ~line 482+)
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/HistorianAdapterActor.cs` (ctor handlers ~line 86)
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs` (ctor handlers ~line 172)
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/…` (new guard test; place beside the existing dead-letter-probe test — find it via `rg "AllDeadLetters" tests`)
**Step 1 — Write the guard test (failing without the fix).** For at least `DriverHostActor`
(the most-trafficked), subscribe a probe to `AllDeadLetters` on the EventStream, spin up the
actor with its redundancy-topic subscription, publish a `PeerOpcUaProbeActor.OpcUaProbeResult`
to the `RedundancyStateTopic`, and assert **no** `DeadLetter` wrapping an `OpcUaProbeResult`.
(Mirror the Phase-B `AllDeadLetters`-probe idiom already in Runtime.Tests.) A combined test
covering all three is fine if the harness makes that easy; otherwise the `DriverHostActor`
case is the required guard and the other two are covered by inspection + build.
**Step 2 — Add the drop to each actor.** Each already subscribes the redundancy-state topic in
`PreStart` and imports `Akka.Cluster.Tools.PublishSubscribe`. Add, next to the existing
`RedundancyStateChanged` / `SubscribeAck` handlers:
```csharp
// The redundancy-state topic also carries OpcUaProbeResult (published by OpcUaPublishActor's
// peer-probes). We don't consume it here — drop it so it doesn't dead-letter. Matches
// PeerProbeSupervisor / OpcUaPublishActor. (intentional no-op)
Receive<ZB.MOM.WW.OtOpcUa.Runtime.Health.PeerOpcUaProbeActor.OpcUaProbeResult>(_ => { });
```
- `HistorianAdapterActor`: add in the ctor near `Receive<SubscribeAck>(_ => { });` (~line 87).
- `ScriptedAlarmHostActor`: add in the ctor near the other `Receive<…>` registrations (~line 172).
- `DriverHostActor`: add in the steady-state behaviour where `Receive<…>` handlers are registered
(the `Receive<RedundancyStateChanged>` handler — confirm it exists in each behaviour that is
active while subscribed; add the drop wherever `RedundancyStateChanged` is handled so the probe
result is dropped in the same behaviour(s)).
**Note:** if `DriverHostActor` uses `Become`/multiple behaviours, add the drop to every behaviour
that handles `RedundancyStateChanged`, else the probe still dead-letters in the others.
**Step 3 — Test + build:**
`dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests --filter "FullyQualifiedName~ProbeResult"` → green;
`dotnet build src/Server/ZB.MOM.WW.OtOpcUa.Runtime` → 0 errors.
**Step 4 — Commit:**
`git add src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/HistorianAdapterActor.cs src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/`
then `git commit -m "fix(runtime): drop OpcUaProbeResult in redundancy-topic subscribers (no dead-letter)"`.
---
### Task 4: Reconcile + full build/test + live `/run` + finish
**Classification:** standard (verification + integration review + finish)
**Estimated implement time:** ~5 min + live run
**Parallelizable with:** none (depends on T1, T2, T3)
**Step 1 — Full build + solution test:**
`dotnet build ZB.MOM.WW.OtOpcUa.slnx` → 0 errors;
`dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests` → green.
**Step 2 — Final integration review** (code-reviewer subagent over `git diff master..HEAD`):
confirm no Commons/proto/EF change, audit emitted on all cert paths (incl. failures), the
`AuditEvent` shape matches the package, the drop handler is in every behaviour that subscribes
the topic, and tests genuinely fail without the fix.
**Step 3 — Live `/run` (agent-driven; docker-dev login is disabled).** Rebuild both central
nodes to the branch (`docker compose -f docker-dev/docker-compose.yml up -d --build central-1
central-2`); open the AdminUI Certificates page (`http://localhost:9200`), perform a Trust or
Untrust (or seed a rejected cert first), and confirm a new `ConfigAuditLog` row exists
(query the shared SQL `10.100.0.35,14330` ConfigDb: principal = the dev admin user,
EventType = `Certificate:Trust`, Outcome = success). Confirm server logs show **no**
`OpcUaProbeResult` dead-letter on either node. Capture the evidence.
**Step 4 — Finish.** `git checkout master && git merge --ff-only feat/cert-audit-and-probe-tidy`
(fast-forward; the branch is linear off master), then `git push`. Delete the feature branch.
Update `pending.md`/`stillpending.md` (on-disk, never-staged) to record both items shipped.
@@ -0,0 +1,11 @@
{
"planPath": "docs/plans/2026-06-19-cert-audit-and-probe-deadletter-tidy.md",
"executionState": "IN_PROGRESS",
"tasks": [
{"id": 1, "subject": "Task 1: Cert-audit core — ActorAuditWriter + CertAuditEvents factory + DI + unit tests", "classification": "standard", "status": "pending", "parallelizableWith": [3]},
{"id": 2, "subject": "Task 2: Wire audit into CertificateStoreManager + Certificates.razor + extend manager tests", "classification": "standard", "status": "pending", "blockedBy": [1]},
{"id": 3, "subject": "Task 3: OpcUaProbeResult dead-letter tidy — three actor drop handlers + guard test", "classification": "small", "status": "pending", "parallelizableWith": [1]},
{"id": 4, "subject": "Task 4: Reconcile + full build/test + live /run + finish (merge + push)", "classification": "standard", "status": "pending", "blockedBy": [1, 2, 3]}
],
"lastUpdated": "2026-06-19"
}
@@ -0,0 +1,39 @@
using Akka.Actor;
using Akka.Hosting;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.OtOpcUa.ControlPlane;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Audit;
/// <summary>
/// AdminUI-side <see cref="IAuditWriter" /> adapter. Forwards canonical
/// <see cref="AuditEvent" />s to the ControlPlane <see cref="AuditWriterActorKey" /> cluster
/// singleton (resolved from <see cref="ActorRegistry" /> at construction, mirroring
/// <c>AdminOperationsClient</c>), which batches and persists them to <c>ConfigAuditLog</c>.
/// Emission is fire-and-forget via <c>Tell</c>: best-effort and never blocks or throws to the
/// caller, matching the audit-writer contract.
/// </summary>
public sealed class ActorAuditWriter : IAuditWriter
{
private readonly IActorRef _proxy;
/// <summary>Initializes a new instance of the <see cref="ActorAuditWriter" /> class.</summary>
/// <param name="registry">The actor registry used to resolve the AuditWriter singleton proxy.</param>
public ActorAuditWriter(ActorRegistry registry)
{
_proxy = registry.Get<AuditWriterActorKey>();
}
/// <summary>
/// Forwards the event to the AuditWriter singleton via <c>Tell</c> and returns immediately.
/// The actual persistence happens asynchronously on the actor's next flush.
/// </summary>
/// <param name="evt">The canonical audit event to persist.</param>
/// <param name="ct">Unused — enqueue is synchronous and non-blocking.</param>
/// <returns>A completed task.</returns>
public Task WriteAsync(AuditEvent evt, CancellationToken ct = default)
{
_proxy.Tell(evt);
return Task.CompletedTask;
}
}
@@ -0,0 +1,55 @@
using System.Text.Json;
using ZB.MOM.WW.Audit;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Audit;
/// <summary>
/// Pure factory that maps a certificate-store action (Trust / Untrust / Delete of a peer
/// certificate) into a canonical <see cref="AuditEvent" /> for persistence via the shared
/// <see cref="IAuditWriter" /> seam. No side effects: callers build the event then hand it to
/// the writer.
/// </summary>
public static class CertAuditEvents
{
/// <summary>The audit <see cref="AuditEvent.Category" /> stamped onto every certificate event.</summary>
public const string Category = "Certificate";
/// <summary>
/// Builds a canonical <see cref="AuditEvent" /> describing a certificate-store action.
/// </summary>
/// <param name="action">The action verb — e.g. <c>Trust</c>, <c>Untrust</c>, or <c>Delete</c>.
/// Stamped onto <see cref="AuditEvent.Action" />.</param>
/// <param name="store">The certificate store the action targeted (carried in the details payload).</param>
/// <param name="thumbprint">The subject certificate's thumbprint; stamped onto
/// <see cref="AuditEvent.SourceNode" /> and echoed in the details payload.</param>
/// <param name="actor">The identity that performed the action; stamped onto
/// <see cref="AuditEvent.Actor" />.</param>
/// <param name="success"><see langword="true" /> if the action succeeded (Outcome
/// <see cref="AuditOutcome.Success" />); otherwise <see langword="false" /> (Outcome
/// <see cref="AuditOutcome.Failure" />).</param>
/// <param name="error">On failure, the error text carried in the details payload; ignored on
/// success (the <c>error</c> field is omitted from the details payload entirely).</param>
/// <returns>A fully populated <see cref="AuditEvent" /> with a fresh <see cref="AuditEvent.EventId" />
/// and <see cref="AuditEvent.OccurredAtUtc" /> set to now (UTC).</returns>
public static AuditEvent Build(
string action, string store, string thumbprint, string actor, bool success, string? error)
{
// On success the error field is omitted entirely (not serialized as null) so the common
// success-path audit row carries no dead "error" key.
var detailsJson = JsonSerializer.Serialize(success
? (object)new { store, thumbprint }
: new { store, thumbprint, error });
return new AuditEvent
{
EventId = Guid.NewGuid(),
OccurredAtUtc = DateTimeOffset.UtcNow,
Actor = actor,
Action = action,
Category = Category,
SourceNode = thumbprint,
Outcome = success ? AuditOutcome.Success : AuditOutcome.Failure,
DetailsJson = detailsJson,
};
}
}
@@ -1,6 +1,8 @@
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.Configuration;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Audit;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Certificates;
@@ -25,31 +27,61 @@ public sealed class CertificateStoreManager
new(StringComparer.OrdinalIgnoreCase) { "trusted", "rejected" };
private readonly string _pkiRoot;
private readonly IAuditWriter _audit;
/// <summary>Production ctor — reads <c>OpcUa:PkiStoreRoot</c> (default <c>pki</c>).</summary>
/// <param name="config">App configuration.</param>
public CertificateStoreManager(IConfiguration config)
=> _pkiRoot = config.GetValue<string?>("OpcUa:PkiStoreRoot") ?? "pki";
/// <param name="audit">The audit writer that persists Trust/Untrust/Delete actions to <c>ConfigAuditLog</c>.</param>
public CertificateStoreManager(IConfiguration config, IAuditWriter audit)
{
_pkiRoot = config.GetValue<string?>("OpcUa:PkiStoreRoot") ?? "pki";
_audit = audit;
}
/// <summary>Test ctor — explicit PKI root.</summary>
/// <param name="pkiRoot">The PKI store root directory.</param>
internal CertificateStoreManager(string pkiRoot) => _pkiRoot = pkiRoot;
/// <param name="audit">Optional audit writer; defaults to a no-op writer when omitted.</param>
internal CertificateStoreManager(string pkiRoot, IAuditWriter? audit = null)
{
_pkiRoot = pkiRoot;
_audit = audit ?? NoOpAuditWriter.Instance;
}
/// <summary>Moves a rejected peer cert into the trusted store.</summary>
/// <param name="thumbprint">The cert thumbprint.</param>
/// <param name="actor">The identity performing the action; recorded in the audit log.</param>
/// <returns>The action result.</returns>
public CertActionResult Trust(string thumbprint) => Move("rejected", "trusted", thumbprint);
public CertActionResult Trust(string thumbprint, string actor)
{
var r = Move("rejected", "trusted", thumbprint);
Audit("Trust", "rejected→trusted", thumbprint, actor, r);
return r;
}
/// <summary>Moves a trusted peer cert back into the rejected store.</summary>
/// <param name="thumbprint">The cert thumbprint.</param>
/// <param name="actor">The identity performing the action; recorded in the audit log.</param>
/// <returns>The action result.</returns>
public CertActionResult Untrust(string thumbprint) => Move("trusted", "rejected", thumbprint);
public CertActionResult Untrust(string thumbprint, string actor)
{
var r = Move("trusted", "rejected", thumbprint);
Audit("Untrust", "trusted→rejected", thumbprint, actor, r);
return r;
}
/// <summary>Deletes a cert from the named mutable store (<c>trusted</c> or <c>rejected</c>).</summary>
/// <param name="store">The store name.</param>
/// <param name="thumbprint">The cert thumbprint.</param>
/// <param name="actor">The identity performing the action; recorded in the audit log.</param>
/// <returns>The action result.</returns>
public CertActionResult Delete(string store, string thumbprint)
public CertActionResult Delete(string store, string thumbprint, string actor)
{
var r = DeleteCore(store, thumbprint);
Audit("Delete", store, thumbprint, actor, r);
return r;
}
private CertActionResult DeleteCore(string store, string thumbprint)
{
if (!MutableStores.Contains(store)) return CertActionResult.Fail($"unknown store '{store}'");
if (!IsValidThumbprint(thumbprint)) return CertActionResult.Fail("invalid thumbprint");
@@ -66,6 +98,12 @@ public sealed class CertificateStoreManager
}
}
// Fire-and-forget: the writer enqueues synchronously and returns a completed task, so the
// store mutation stays synchronous. Every return path (success + every failure) is audited
// because Trust/Untrust/Delete each route their single result through here.
private void Audit(string action, string store, string thumbprint, string actor, CertActionResult r)
=> _ = _audit.WriteAsync(CertAuditEvents.Build(action, store, thumbprint, actor, r.Success, r.Error));
private CertActionResult Move(string fromSub, string toSub, string thumbprint)
{
if (!IsValidThumbprint(thumbprint)) return CertActionResult.Fail("invalid thumbprint");
@@ -191,14 +191,15 @@ else
return;
}
var actor = authState.User.Identity?.Name ?? "system";
var result = p.Verb switch
{
"trust" => CertManager.Trust(p.Thumbprint),
"untrust" => CertManager.Untrust(p.Thumbprint),
"trust" => CertManager.Trust(p.Thumbprint, actor),
"untrust" => CertManager.Untrust(p.Thumbprint, actor),
"delete" => p.Kind switch
{
StoreKind.Trusted => CertManager.Delete("trusted", p.Thumbprint),
StoreKind.Rejected => CertManager.Delete("rejected", p.Thumbprint),
StoreKind.Trusted => CertManager.Delete("trusted", p.Thumbprint, actor),
StoreKind.Rejected => CertManager.Delete("rejected", p.Thumbprint, actor),
_ => CertActionResult.Fail($"cannot delete from {p.Kind}"),
},
_ => CertActionResult.Fail("unknown action"),
@@ -54,6 +54,9 @@ public static class EndpointRouteBuilderExtensions
// Certificate-store actions (trust/untrust/delete) for the /certificates page.
services.AddSingleton<Certificates.CertificateStoreManager>();
// Structured audit-event sink: forwards AuditEvents to the ControlPlane AuditWriter singleton.
services.AddSingleton<ZB.MOM.WW.Audit.IAuditWriter, Audit.ActorAuditWriter>();
return services;
}
}
@@ -488,6 +488,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
Receive<RouteNodeWrite>(HandleRouteNodeWrite);
Receive<RouteNativeAlarmAck>(HandleRouteNativeAlarmAck);
Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
// The redundancy-state topic also carries OpcUaProbeResult (OpcUaPublishActor peer-probes).
// We don't consume it here — drop it so it doesn't dead-letter (matches PeerProbeSupervisor).
Receive<ZB.MOM.WW.OtOpcUa.Runtime.Health.PeerOpcUaProbeActor.OpcUaProbeResult>(_ => { });
Receive<SubscribeAck>(_ => { /* PubSub ack */ });
}
@@ -513,6 +516,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
Receive<RouteNodeWrite>(HandleRouteNodeWrite);
Receive<RouteNativeAlarmAck>(HandleRouteNativeAlarmAck);
Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
// The redundancy-state topic also carries OpcUaProbeResult (OpcUaPublishActor peer-probes).
// We don't consume it here — drop it so it doesn't dead-letter (matches PeerProbeSupervisor).
Receive<ZB.MOM.WW.OtOpcUa.Runtime.Health.PeerOpcUaProbeActor.OpcUaProbeResult>(_ => { });
Receive<SubscribeAck>(_ => { /* PubSub ack */ });
}
@@ -759,6 +765,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
Receive<RestartDriver>(HandleRestartDriver);
Receive<ReconnectDriver>(HandleReconnectDriver);
Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
// The redundancy-state topic also carries OpcUaProbeResult (OpcUaPublishActor peer-probes).
// We don't consume it here — drop it so it doesn't dead-letter (matches PeerProbeSupervisor).
Receive<ZB.MOM.WW.OtOpcUa.Runtime.Health.PeerOpcUaProbeActor.OpcUaProbeResult>(_ => { });
// An inbound operator write can't be serviced while the config DB is unreachable — fast-fail so the
// node-manager's bounded Ask gets an immediate clear status instead of dead-lettering into a timeout.
Receive<RouteNodeWrite>(_ =>
@@ -84,6 +84,9 @@ public sealed class HistorianAdapterActor : ReceiveActor
// cache this node's role so the historize gate can scope the durable sink enqueue to the Primary.
// The PubSub Subscribe acks (redundancy-state + alerts) are acked back to Self (no-op below).
Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
// The redundancy-state topic also carries OpcUaProbeResult (OpcUaPublishActor peer-probes).
// We don't consume it here — drop it so it doesn't dead-letter (matches PeerProbeSupervisor).
Receive<ZB.MOM.WW.OtOpcUa.Runtime.Health.PeerOpcUaProbeActor.OpcUaProbeResult>(_ => { });
Receive<SubscribeAck>(_ => { });
}
@@ -190,6 +190,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
// A LoadAsync cancelled by PostStop's _cts pipes back this marker. The actor is stopping, so
// there's nothing to do — swallow it quietly (no Warning, no dead letter).
Receive<AlarmsLoadCanceled>(_ => { });
// The redundancy-state topic also carries OpcUaProbeResult (OpcUaPublishActor peer-probes).
// We don't consume it here — drop it so it doesn't dead-letter (matches PeerProbeSupervisor).
Receive<ZB.MOM.WW.OtOpcUa.Runtime.Health.PeerOpcUaProbeActor.OpcUaProbeResult>(_ => { });
// DPS Subscribe (PreStart) acks back here once the mediator has registered Self on the topic.
// No-op — the subscription is live the moment the ack arrives; we only need to keep it off the
// dead-letter log. Matches OpcUaPublishActor / DriverHostActor's SubscribeAck convention.
@@ -0,0 +1,44 @@
using Akka.Hosting;
using Akka.TestKit.Xunit2;
using Shouldly;
using Xunit;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Audit;
using ZB.MOM.WW.OtOpcUa.ControlPlane;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Audit;
/// <summary>
/// Unit tests for <see cref="ActorAuditWriter" />, the AdminUI-side <see cref="IAuditWriter" />
/// adapter that forwards canonical audit events to the cluster-singleton
/// <see cref="AuditWriterActorKey" /> proxy resolved from the <see cref="ActorRegistry" />.
/// </summary>
public sealed class ActorAuditWriterTests : TestKit
{
/// <summary>WriteAsync forwards the event verbatim to the registered AuditWriter singleton.</summary>
[Fact]
public async Task WriteAsync_tells_the_registered_singleton()
{
var probe = CreateTestProbe("audit-writer");
var registry = new ActorRegistry();
registry.Register<AuditWriterActorKey>(probe.Ref);
var writer = new ActorAuditWriter(registry);
var evt = new AuditEvent
{
EventId = Guid.NewGuid(),
OccurredAtUtc = DateTimeOffset.UtcNow,
Actor = "alice",
Action = "Trust",
Category = "Certificate",
SourceNode = "AABBCC",
Outcome = AuditOutcome.Success,
DetailsJson = "{}",
};
await writer.WriteAsync(evt);
var received = probe.ExpectMsg<AuditEvent>(TimeSpan.FromSeconds(3));
received.ShouldBe(evt);
}
}
@@ -0,0 +1,110 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Audit;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Audit;
/// <summary>
/// Unit tests for <see cref="CertAuditEvents" />, the pure factory that maps a certificate
/// trust/untrust/delete action into a canonical <see cref="AuditEvent" />.
/// </summary>
public sealed class CertAuditEventsTests
{
private const string Thumb = "AABBCCDDEEFF00112233445566778899AABBCCDD";
/// <summary>A successful Trust maps Category/Action/SourceNode/Actor and Success, with the
/// thumbprint carried in the details payload.</summary>
[Fact]
public void Build_trust_success_maps_core_fields()
{
var evt = CertAuditEvents.Build("Trust", "rejected→trusted", Thumb, "alice", success: true, error: null);
evt.Category.ShouldBe("Certificate");
evt.Action.ShouldBe("Trust");
evt.SourceNode.ShouldBe(Thumb);
evt.Actor.ShouldBe("alice");
evt.Outcome.ShouldBe(AuditOutcome.Success);
evt.EventId.ShouldNotBe(Guid.Empty);
evt.OccurredAtUtc.ShouldBeGreaterThan(DateTimeOffset.UtcNow.AddSeconds(-5));
evt.DetailsJson.ShouldNotBeNull();
evt.DetailsJson!.ShouldContain(Thumb);
}
/// <summary>A successful Untrust carries the Untrust action and Success outcome.</summary>
[Fact]
public void Build_untrust_success_maps_action_and_outcome()
{
var evt = CertAuditEvents.Build("Untrust", "trusted", Thumb, "bob", success: true, error: null);
evt.Action.ShouldBe("Untrust");
evt.Outcome.ShouldBe(AuditOutcome.Success);
evt.DetailsJson!.ShouldContain(Thumb);
}
/// <summary>A successful Delete carries the Delete action and Success outcome.</summary>
[Fact]
public void Build_delete_success_maps_action_and_outcome()
{
var evt = CertAuditEvents.Build("Delete", "rejected", Thumb, "carol", success: true, error: null);
evt.Action.ShouldBe("Delete");
evt.Outcome.ShouldBe(AuditOutcome.Success);
}
/// <summary>A failed Trust maps the Failure outcome and surfaces the error text in the details
/// payload.</summary>
[Fact]
public void Build_trust_failure_maps_failure_and_carries_error()
{
var evt = CertAuditEvents.Build(
"Trust", "rejected", Thumb, "alice", success: false, error: "certificate not found in rejected");
evt.Action.ShouldBe("Trust");
evt.Outcome.ShouldBe(AuditOutcome.Failure);
evt.DetailsJson!.ShouldContain("certificate not found in rejected");
}
/// <summary>A failed Delete maps the Failure outcome.</summary>
[Fact]
public void Build_delete_failure_maps_failure()
{
var evt = CertAuditEvents.Build(
"Delete", "rejected", Thumb, "dave", success: false, error: "delete failed: access denied");
evt.Action.ShouldBe("Delete");
evt.Outcome.ShouldBe(AuditOutcome.Failure);
evt.DetailsJson!.ShouldContain("delete failed: access denied");
}
/// <summary>A failed Untrust maps the Failure outcome.</summary>
[Fact]
public void Build_untrust_failure_maps_failure()
{
var evt = CertAuditEvents.Build(
"Untrust", "trusted", Thumb, "erin", success: false, error: "store write failed");
evt.Action.ShouldBe("Untrust");
evt.Outcome.ShouldBe(AuditOutcome.Failure);
evt.DetailsJson!.ShouldContain("store write failed");
}
/// <summary>On success the error text AND the error key are omitted from the details payload.</summary>
[Fact]
public void Build_success_omits_error_text()
{
var evt = CertAuditEvents.Build("Trust", "rejected", Thumb, "alice", success: true, error: "ignored");
evt.DetailsJson!.ShouldNotContain("ignored");
evt.DetailsJson!.ShouldNotContain("error");
}
/// <summary>The public Category constant matches the value stamped onto built events.</summary>
[Fact]
public void Category_constant_matches_built_event()
{
CertAuditEvents.Category.ShouldBe("Certificate");
CertAuditEvents.Build("Trust", "s", Thumb, "a", success: true, error: null).Category
.ShouldBe(CertAuditEvents.Category);
}
}
@@ -9,12 +9,27 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Certificates;
public sealed class CertificateStoreManagerTests : IDisposable
{
private readonly string _root;
private readonly RecordingAuditWriter _audit;
private readonly CertificateStoreManager _sut;
public CertificateStoreManagerTests()
{
_root = Path.Combine(Path.GetTempPath(), $"pki-test-{Guid.NewGuid():N}");
_sut = new CertificateStoreManager(_root);
_audit = new RecordingAuditWriter();
_sut = new CertificateStoreManager(_root, _audit);
}
// ── Recording audit-writer fake ───────────────────────────────────────────
private sealed class RecordingAuditWriter : ZB.MOM.WW.Audit.IAuditWriter
{
public List<ZB.MOM.WW.Audit.AuditEvent> Events { get; } = new();
public Task WriteAsync(ZB.MOM.WW.Audit.AuditEvent evt, CancellationToken ct = default)
{
Events.Add(evt);
return Task.CompletedTask;
}
}
public void Dispose()
@@ -84,7 +99,7 @@ public sealed class CertificateStoreManagerTests : IDisposable
var rejectedCerts = Path.Combine(_root, "rejected", "certs");
var tp = SeedCert(rejectedCerts, "TestClient1");
var result = _sut.Trust(tp);
var result = _sut.Trust(tp, "tester");
result.Success.ShouldBeTrue(result.Error);
ThumbprintExistsInDir(rejectedCerts, tp).ShouldBeFalse("cert should have left rejected");
@@ -97,7 +112,7 @@ public sealed class CertificateStoreManagerTests : IDisposable
var trustedCerts = Path.Combine(_root, "trusted", "certs");
var tp = SeedCert(trustedCerts, "TestClient2");
var result = _sut.Untrust(tp);
var result = _sut.Untrust(tp, "tester");
result.Success.ShouldBeTrue(result.Error);
ThumbprintExistsInDir(trustedCerts, tp).ShouldBeFalse("cert should have left trusted");
@@ -110,7 +125,7 @@ public sealed class CertificateStoreManagerTests : IDisposable
var rejectedCerts = Path.Combine(_root, "rejected", "certs");
var tp = SeedCert(rejectedCerts, "TestClient3");
var result = _sut.Delete("rejected", tp);
var result = _sut.Delete("rejected", tp, "tester");
result.Success.ShouldBeTrue(result.Error);
ThumbprintExistsInDir(rejectedCerts, tp).ShouldBeFalse("cert should be gone from rejected");
@@ -122,7 +137,7 @@ public sealed class CertificateStoreManagerTests : IDisposable
var trustedCerts = Path.Combine(_root, "trusted", "certs");
var tp = SeedCert(trustedCerts, "TestClient4");
var result = _sut.Delete("trusted", tp);
var result = _sut.Delete("trusted", tp, "tester");
result.Success.ShouldBeTrue(result.Error);
ThumbprintExistsInDir(trustedCerts, tp).ShouldBeFalse("cert should be gone from trusted");
@@ -133,7 +148,7 @@ public sealed class CertificateStoreManagerTests : IDisposable
{
var tp = new string('A', 40);
var result = _sut.Trust(tp);
var result = _sut.Trust(tp, "tester");
result.Success.ShouldBeFalse();
CertCountInDir(Path.Combine(_root, "trusted", "certs")).ShouldBe(0);
@@ -142,7 +157,7 @@ public sealed class CertificateStoreManagerTests : IDisposable
[Fact]
public void Trust_PathTraversalThumbprint_Rejected()
{
var result = _sut.Trust("../../x");
var result = _sut.Trust("../../x", "tester");
result.Success.ShouldBeFalse();
result.Error.ShouldNotBeNull();
@@ -158,7 +173,7 @@ public sealed class CertificateStoreManagerTests : IDisposable
var ownCerts = Path.Combine(_root, "own", "certs");
var tp = SeedCert(ownCerts, "OwnCert");
var result = _sut.Delete("own", tp);
var result = _sut.Delete("own", tp, "tester");
result.Success.ShouldBeFalse();
result.Error.ShouldNotBeNull();
@@ -178,7 +193,7 @@ public sealed class CertificateStoreManagerTests : IDisposable
var srcFile = Directory.GetFiles(rejectedCerts).Single();
File.Copy(srcFile, Path.Combine(trustedCerts, Path.GetFileName(srcFile)));
var result = _sut.Trust(tp);
var result = _sut.Trust(tp, "tester");
result.Success.ShouldBeTrue(result.Error);
ThumbprintExistsInDir(rejectedCerts, tp).ShouldBeFalse("source (rejected) should no longer have it");
@@ -188,9 +203,104 @@ public sealed class CertificateStoreManagerTests : IDisposable
[Fact]
public void Trust_NullOrEmptyThumbprint_Fails()
{
var result = _sut.Trust("");
var result = _sut.Trust("", "tester");
result.Success.ShouldBeFalse();
result.Error.ShouldNotBeNull();
}
// ── Audit tests ───────────────────────────────────────────────────────────
[Fact]
public void Trust_success_writes_one_success_audit_event()
{
var rejectedCerts = Path.Combine(_root, "rejected", "certs");
var tp = SeedCert(rejectedCerts, "AuditTrust");
var result = _sut.Trust(tp, "alice");
result.Success.ShouldBeTrue(result.Error);
var evt = _audit.Events.ShouldHaveSingleItem();
evt.Action.ShouldBe("Trust");
evt.Outcome.ShouldBe(ZB.MOM.WW.Audit.AuditOutcome.Success);
evt.SourceNode.ShouldBe(tp);
evt.Actor.ShouldBe("alice");
}
[Fact]
public void Untrust_success_writes_one_success_audit_event()
{
var trustedCerts = Path.Combine(_root, "trusted", "certs");
var tp = SeedCert(trustedCerts, "AuditUntrust");
var result = _sut.Untrust(tp, "alice");
result.Success.ShouldBeTrue(result.Error);
var evt = _audit.Events.ShouldHaveSingleItem();
evt.Action.ShouldBe("Untrust");
evt.Outcome.ShouldBe(ZB.MOM.WW.Audit.AuditOutcome.Success);
evt.SourceNode.ShouldBe(tp);
evt.Actor.ShouldBe("alice");
}
[Fact]
public void Delete_success_writes_one_success_audit_event()
{
var rejectedCerts = Path.Combine(_root, "rejected", "certs");
var tp = SeedCert(rejectedCerts, "AuditDelete");
var result = _sut.Delete("rejected", tp, "alice");
result.Success.ShouldBeTrue(result.Error);
var evt = _audit.Events.ShouldHaveSingleItem();
evt.Action.ShouldBe("Delete");
evt.Outcome.ShouldBe(ZB.MOM.WW.Audit.AuditOutcome.Success);
evt.SourceNode.ShouldBe(tp);
evt.Actor.ShouldBe("alice");
}
[Fact]
public void Delete_not_found_writes_one_failure_audit_event()
{
var absent = new string('0', 40);
var result = _sut.Delete("trusted", absent, "bob");
result.Success.ShouldBeFalse();
var evt = _audit.Events.ShouldHaveSingleItem();
evt.Action.ShouldBe("Delete");
evt.Outcome.ShouldBe(ZB.MOM.WW.Audit.AuditOutcome.Failure);
evt.SourceNode.ShouldBe(absent);
evt.Actor.ShouldBe("bob");
}
[Fact]
public void Trust_not_found_writes_one_failure_audit_event()
{
var absent = new string('0', 40);
var result = _sut.Trust(absent, "bob");
result.Success.ShouldBeFalse();
var evt = _audit.Events.ShouldHaveSingleItem();
evt.Action.ShouldBe("Trust");
evt.Outcome.ShouldBe(ZB.MOM.WW.Audit.AuditOutcome.Failure);
evt.SourceNode.ShouldBe(absent);
evt.Actor.ShouldBe("bob");
}
[Fact]
public void Untrust_not_found_writes_one_failure_audit_event()
{
var absent = new string('0', 40);
var result = _sut.Untrust(absent, "erin");
result.Success.ShouldBeFalse();
var evt = _audit.Events.ShouldHaveSingleItem();
evt.Action.ShouldBe("Untrust");
evt.Outcome.ShouldBe(ZB.MOM.WW.Audit.AuditOutcome.Failure);
evt.SourceNode.ShouldBe(absent);
evt.Actor.ShouldBe("erin");
}
}
@@ -12,6 +12,10 @@
<PackageReference Include="Shouldly"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory"/>
<PackageReference Include="Microsoft.NET.Test.Sdk"/>
<!-- Akka.TestKit.Xunit2 ties this project to xunit v2 (TestKit isn't ported to v3 yet);
used by the IAuditWriter adapter test to register a TestProbe in an ActorRegistry. -->
<PackageReference Include="Akka.Hosting"/>
<PackageReference Include="Akka.TestKit.Xunit2"/>
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -0,0 +1,106 @@
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Event;
using Microsoft.EntityFrameworkCore;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Health;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// Guard test: verifies that a <see cref="PeerOpcUaProbeActor.OpcUaProbeResult"/> published on the
/// <c>redundancy-state</c> DistributedPubSub topic does NOT produce a dead-letter in
/// <see cref="DriverHostActor"/>.
///
/// <para>
/// Background: <see cref="DriverHostActor"/> subscribes the <c>redundancy-state</c> topic so
/// <see cref="ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy.RedundancyStateChanged"/> snapshots
/// land and cache the node's role. The SAME topic also carries
/// <see cref="PeerOpcUaProbeActor.OpcUaProbeResult"/> messages (published by
/// <see cref="OpcUaPublishActor"/> peer-probes) which <see cref="DriverHostActor"/> does not
/// consume. Without an explicit drop handler the actor logs an unhandled-message warning and
/// the message becomes a dead-letter — noisy but benign. The fix adds an intentional-drop
/// <c>Receive</c> in every behaviour (<c>Steady</c>, <c>Applying</c>, <c>Stale</c>), mirroring
/// <see cref="PeerProbeSupervisor"/>.
/// </para>
///
/// <para>
/// The test uses <see cref="DriverHostActor"/>'s <c>Stale</c> path (bootstrapped with a
/// throwing DB factory) because it requires no deployment artifact or apply round-trip, making
/// the harness minimal while still exercising the subscription and the message-dispatch fix.
/// The Stale behaviour is one of the three that was patched; <c>Steady</c> and <c>Applying</c>
/// are covered by inspection + build (all three use the same <c>Receive</c> registration
/// pattern, so a compile-time pass on the Runtime project is the correctness gate for those).
/// </para>
/// </summary>
public sealed class DriverHostActorProbeResultDropTests : RuntimeActorTestBase
{
private static readonly NodeId TestNode = NodeId.Parse("probe-drop-test");
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(5);
/// <summary>
/// A <see cref="PeerOpcUaProbeActor.OpcUaProbeResult"/> published on the redundancy-state
/// topic must NOT produce an <see cref="AllDeadLetters"/> event on the
/// <see cref="ActorSystem.EventStream"/> after the fix.
/// </summary>
[Fact]
public void ProbeResult_on_redundancy_topic_does_not_dead_letter_in_DriverHostActor()
{
// Wire a dead-letter probe that ONLY passes through messages carrying an OpcUaProbeResult
// payload. Everything else (SubscribeAck, health-poll noise, etc.) is ignored so the probe
// mailbox is precise and ExpectNoMsg is race-free.
var deadLetterProbe = CreateTestProbe();
deadLetterProbe.IgnoreMessages(
m => m is not AllDeadLetters { Message: PeerOpcUaProbeActor.OpcUaProbeResult });
Sys.EventStream.Subscribe(deadLetterProbe.Ref, typeof(AllDeadLetters));
// Spin up the actor in Stale state (ThrowingDbFactory ⇒ Bootstrap's catch ⇒ Become(Stale)).
// Stale subscribes the redundancy-state topic in PreStart, so it will receive the probe
// message once the subscription is established.
var actor = Sys.ActorOf(DriverHostActor.Props(
new ThrowingDbFactory(), TestNode, CreateTestProbe().Ref,
localRoles: new HashSet<string> { "driver" }));
// Wait until the actor has subscribed to the redundancy-state topic. We do this by having a
// test probe subscribe to the same topic and waiting for its ack: once BOTH subscriptions are
// registered the mediator will fan-out any subsequent Publish to both subscribers. This avoids
// a fixed sleep and is the same barrier DriverHostActorNativeAlarmTests uses for the alerts topic.
var barrierProbe = CreateTestProbe();
DistributedPubSub.Get(Sys).Mediator.Tell(
new Subscribe(OpcUaPublishActor.RedundancyStateTopic, barrierProbe.Ref),
barrierProbe.Ref);
barrierProbe.ExpectMsg<SubscribeAck>(Timeout);
// Publish an OpcUaProbeResult to the redundancy-state topic. The mediator fans it out to
// every subscriber — including the DriverHostActor — so it lands on the actor's mailbox.
DistributedPubSub.Get(Sys).Mediator.Tell(
new Publish(OpcUaPublishActor.RedundancyStateTopic,
new PeerOpcUaProbeActor.OpcUaProbeResult(TestNode, Ok: true)));
// BARRIER: send a synchronous RouteNodeWrite (which Stale handles synchronously with an
// immediate fast-fail reply) and await its response. Once the reply arrives, the actor has
// drained its mailbox past the OpcUaProbeResult message, so any dead-letter from an unhandled
// OpcUaProbeResult would already be on the EventStream before we assert.
var asker = CreateTestProbe();
actor.Tell(new DriverHostActor.RouteNodeWrite("eq-x/speed", 0.0), asker.Ref);
asker.ExpectMsg<DriverHostActor.NodeWriteResult>(Timeout);
// Assert no dead-letter carrying an OpcUaProbeResult was published.
deadLetterProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
}
/// <summary>An <see cref="IDbContextFactory{TContext}"/> whose <c>CreateDbContext</c> always throws,
/// driving <see cref="DriverHostActor"/>'s bootstrap into the <c>catch</c> ⇒ <c>Become(Stale)</c>
/// path (the same stub used in <c>DriverHostActorWriteRoutingTests.Stale_host_fast_fails_route_node_write</c>).</summary>
private sealed class ThrowingDbFactory : IDbContextFactory<OtOpcUaConfigDbContext>
{
/// <inheritdoc />
public OtOpcUaConfigDbContext CreateDbContext() =>
throw new InvalidOperationException("config DB unreachable (test stub)");
}
}