Compare commits

...

5 Commits

Author SHA1 Message Date
Joseph Doherty e77e209b8a docs(m4): fix bundle CLI example option names in transport design §13 (--output/--input, not --out/positional) 2026-06-16 20:37:51 -04:00
Joseph Doherty dd545281e6 docs(m4.3): reconcile CLI README + Component-CLI to registered commands/options (document bundle group; fix option drift) 2026-06-16 20:30:40 -04:00
Joseph Doherty 0780c2e49e docs(m4.4): clear stale deferred/no-op markers for shipped features (relay, bundle-import audit, M5 redaction, audit drill-in, Transport CLI, traceability)
- SiteCallAudit/ServiceCollectionExtensions.cs: drop "still deferred" note on relay; point to SiteCallAuditActor where it lives
- Transport/Import/BundleImporter.cs: update "Only LoadAsync implemented" to reflect all three phases shipped
- SiteRuntime/Scripts/AuditingDbCommand.cs: replace two M5-deferred redaction comments with accurate references to AuditLogOptions.PerTargetOverrides
- SiteRuntime/Scripts/ScriptRuntimeContext.cs: replace "M5 will layer redaction" note with accurate description of shipped redactor
- CentralUI/AuditLogPage.razor.cs: replace "Bundle C wires… no-op seam" with accurate description of HandleRowSelected implementation
- docs/plans/2026-05-24-transport-design.md §13: update from "CLI Deferred / not built in v1" to reflect shipped BundleCommands.cs; update Open Questions entry
- docs/plans/2026-05-24-transport.md: convert Out-of-Scope "Do NOT build CLI" reminder to a factual note that it shipped
- docs/plans/2026-05-24-transport.md.tasks.json: flip all 30 tasks from pending → done (entire Transport feature shipped)
2026-06-16 20:30:29 -04:00
Joseph Doherty 13605d3dfd docs(m4.1): reconcile Config-DB AuditLog schema + Commons (AuditEvent/ApiKey/SiteCall/NotificationType) to shipped code 2026-06-16 20:29:16 -04:00
Joseph Doherty c3b046457e docs(m4.2): reconcile InboundAPI (Bearer/audit-timing/type-validation), Security (cookie session, role names), Notification (Email-only, AuditKind vocab) to code 2026-06-16 20:27:43 -04:00
15 changed files with 464 additions and 189 deletions
+14 -10
View File
@@ -332,21 +332,25 @@ Import flows through the **same audited repository methods** the UI and CLI use,
---
## 13. CLI (Deferred)
## 13. CLI
The `ZB.MOM.WW.ScadaBridge.Transport` library is callable from both Razor pages and `ZB.MOM.WW.ScadaBridge.CLI`. CLI commands are **not** built in v1 but the design leaves a clean path:
The `ZB.MOM.WW.ScadaBridge.Transport` library is callable from both Razor pages and `ZB.MOM.WW.ScadaBridge.CLI`. CLI commands are implemented in `BundleCommands.cs` under the `bundle` sub-command group (note: shipped as `bundle` rather than `transport` to match the script-facing vocabulary):
```
scadabridge transport export \
scadabridge bundle export \
--templates Pump,Pump.WaterPump \
--shared-scripts PumpUtils \
--out bundle.scadabundle \
--passphrase-file /run/secrets/p
--output bundle.scadabundle \
--passphrase mypassphrase
scadabridge transport import bundle.scadabundle \
--passphrase-file /run/secrets/p \
--on-conflict overwrite|skip|rename \
--dry-run
scadabridge bundle preview \
--input bundle.scadabundle \
--passphrase mypassphrase
scadabridge bundle import \
--input bundle.scadabundle \
--passphrase mypassphrase \
--on-conflict overwrite|skip|rename
```
Same auth model via the Management API.
@@ -400,7 +404,7 @@ Same auth model via the Management API.
- **Site-scoped artifact transport** (Instances, Areas, bindings, DataConnections). Requires a name-mapping subsystem (source-env-site → target-env-site). Deferred until concrete demand.
- **Direct cluster-to-cluster pull** as an alternative to file handoff. Same `ZB.MOM.WW.ScadaBridge.Transport` library can back it; needs cross-env auth design.
- **Bundle signing** with an asymmetric keypair (separate from passphrase encryption) for stronger non-repudiation. Manifest content hash is sufficient for v1 tamper detection.
- **CLI commands** (`scadabridge transport export/import`). Shape pre-decided in §13; not built in v1.
- **CLI commands** (`scadabridge bundle export/preview/import`). Shipped in `BundleCommands.cs`; see §13.
- **Differential bundles** ("only what changed since last export"). YAGNI for v1.
---
+1 -1
View File
@@ -1660,6 +1660,6 @@ All must pass. Then proceed to Task 29 manual checklist against the docker clust
- Do NOT add a feature flag.
- Do NOT touch site-side projects (`ZB.MOM.WW.ScadaBridge.SiteRuntime` etc.).
- Do NOT add a stale-mark column on `Instance` — the existing `DeploymentService.CompareAsync` already detects this.
- Do NOT build CLI commands — those are deferred per design doc §13.
- CLI commands shipped as `scadabridge bundle export/preview/import` (see `BundleCommands.cs` and design doc §13 — originally deferred but subsequently built).
- Do NOT add bundle signing — content hash in manifest is sufficient for v1.
- Do NOT retain bundles server-side after export download or import apply.
+31 -31
View File
@@ -1,36 +1,36 @@
{
"planPath": "docs/plans/2026-05-24-transport.md",
"tasks": [
{"id": 7, "subject": "T0: Bundle DTOs in Commons", "status": "pending"},
{"id": 8, "subject": "T1: Transport interfaces", "status": "pending"},
{"id": 9, "subject": "T2: BundleImportId column on AuditLogEntry", "status": "pending"},
{"id": 10, "subject": "T3: EF migration AddBundleImportIdToAuditLog", "status": "pending", "blockedBy": [9]},
{"id": 11, "subject": "T4: IAuditCorrelationContext scoped service", "status": "pending"},
{"id": 12, "subject": "T5: AuditService reads correlation context", "status": "pending", "blockedBy": [9, 11]},
{"id": 13, "subject": "T6: ZB.MOM.WW.ScadaBridge.Transport project skeleton", "status": "pending"},
{"id": 14, "subject": "T7: TransportOptions", "status": "pending", "blockedBy": [13]},
{"id": 15, "subject": "T8: BundleSecretEncryptor (AES-256-GCM + PBKDF2)", "status": "pending", "blockedBy": [13]},
{"id": 16, "subject": "T9: ManifestBuilder + ManifestValidator", "status": "pending", "blockedBy": [13]},
{"id": 17, "subject": "T10: EntitySerializer + DTOs + secret carving", "status": "pending", "blockedBy": [13]},
{"id": 18, "subject": "T11: BundleSerializer (ZIP packer + reader)", "status": "pending", "blockedBy": [15, 16, 17]},
{"id": 19, "subject": "T12: DependencyResolver", "status": "pending", "blockedBy": [13]},
{"id": 20, "subject": "T13: BundleSessionStore", "status": "pending", "blockedBy": [13]},
{"id": 21, "subject": "T14: BundleExporter.ExportAsync", "status": "pending", "blockedBy": [18, 19]},
{"id": 22, "subject": "T15: BundleImporter.LoadAsync", "status": "pending", "blockedBy": [18, 20]},
{"id": 23, "subject": "T16: BundleImporter.PreviewAsync (diff engine)", "status": "pending", "blockedBy": [22]},
{"id": 24, "subject": "T17: BundleImporter.ApplyAsync (transactional)", "status": "pending", "blockedBy": [12, 23]},
{"id": 25, "subject": "T18: Host registration + appsettings binding", "status": "pending", "blockedBy": [24]},
{"id": 26, "subject": "T19: TreeView checkbox-selection mode", "status": "pending"},
{"id": 27, "subject": "T20: TemplateFolderTree wrapper + Templates.razor refactor", "status": "pending", "blockedBy": [26]},
{"id": 28, "subject": "T21: TransportExport.razor wizard", "status": "pending", "blockedBy": [21, 27]},
{"id": 29, "subject": "T22: TransportImport.razor wizard", "status": "pending", "blockedBy": [24, 27]},
{"id": 30, "subject": "T23: NavMenu Export/Import entries", "status": "pending", "blockedBy": [28, 29]},
{"id": 31, "subject": "T24: Audit log Bundle Import filter", "status": "pending", "blockedBy": [9]},
{"id": 32, "subject": "T25: Integration round-trip test", "status": "pending", "blockedBy": [24]},
{"id": 33, "subject": "T26: Integration conflict + rollback tests", "status": "pending", "blockedBy": [24]},
{"id": 34, "subject": "T27: Component-Transport.md design doc", "status": "pending"},
{"id": 35, "subject": "T28: README + cross-reference updates", "status": "pending"},
{"id": 36, "subject": "T29: Manual cluster verification checklist", "status": "pending", "blockedBy": [25, 29, 30, 31, 32, 33, 34, 35]}
{"id": 7, "subject": "T0: Bundle DTOs in Commons", "status": "done"},
{"id": 8, "subject": "T1: Transport interfaces", "status": "done"},
{"id": 9, "subject": "T2: BundleImportId column on AuditLogEntry", "status": "done"},
{"id": 10, "subject": "T3: EF migration AddBundleImportIdToAuditLog", "status": "done", "blockedBy": [9]},
{"id": 11, "subject": "T4: IAuditCorrelationContext scoped service", "status": "done"},
{"id": 12, "subject": "T5: AuditService reads correlation context", "status": "done", "blockedBy": [9, 11]},
{"id": 13, "subject": "T6: ZB.MOM.WW.ScadaBridge.Transport project skeleton", "status": "done"},
{"id": 14, "subject": "T7: TransportOptions", "status": "done", "blockedBy": [13]},
{"id": 15, "subject": "T8: BundleSecretEncryptor (AES-256-GCM + PBKDF2)", "status": "done", "blockedBy": [13]},
{"id": 16, "subject": "T9: ManifestBuilder + ManifestValidator", "status": "done", "blockedBy": [13]},
{"id": 17, "subject": "T10: EntitySerializer + DTOs + secret carving", "status": "done", "blockedBy": [13]},
{"id": 18, "subject": "T11: BundleSerializer (ZIP packer + reader)", "status": "done", "blockedBy": [15, 16, 17]},
{"id": 19, "subject": "T12: DependencyResolver", "status": "done", "blockedBy": [13]},
{"id": 20, "subject": "T13: BundleSessionStore", "status": "done", "blockedBy": [13]},
{"id": 21, "subject": "T14: BundleExporter.ExportAsync", "status": "done", "blockedBy": [18, 19]},
{"id": 22, "subject": "T15: BundleImporter.LoadAsync", "status": "done", "blockedBy": [18, 20]},
{"id": 23, "subject": "T16: BundleImporter.PreviewAsync (diff engine)", "status": "done", "blockedBy": [22]},
{"id": 24, "subject": "T17: BundleImporter.ApplyAsync (transactional)", "status": "done", "blockedBy": [12, 23]},
{"id": 25, "subject": "T18: Host registration + appsettings binding", "status": "done", "blockedBy": [24]},
{"id": 26, "subject": "T19: TreeView checkbox-selection mode", "status": "done"},
{"id": 27, "subject": "T20: TemplateFolderTree wrapper + Templates.razor refactor", "status": "done", "blockedBy": [26]},
{"id": 28, "subject": "T21: TransportExport.razor wizard", "status": "done", "blockedBy": [21, 27]},
{"id": 29, "subject": "T22: TransportImport.razor wizard", "status": "done", "blockedBy": [24, 27]},
{"id": 30, "subject": "T23: NavMenu Export/Import entries", "status": "done", "blockedBy": [28, 29]},
{"id": 31, "subject": "T24: Audit log Bundle Import filter", "status": "done", "blockedBy": [9]},
{"id": 32, "subject": "T25: Integration round-trip test", "status": "done", "blockedBy": [24]},
{"id": 33, "subject": "T26: Integration conflict + rollback tests", "status": "done", "blockedBy": [24]},
{"id": 34, "subject": "T27: Component-Transport.md design doc", "status": "done"},
{"id": 35, "subject": "T28: README + cross-reference updates", "status": "done"},
{"id": 36, "subject": "T29: Manual cluster verification checklist", "status": "done", "blockedBy": [25, 29, 30, 31, 32, 33, 34, 35]}
],
"lastUpdated": "2026-05-24T00:00:00Z"
"lastUpdated": "2026-06-16T00:00:00Z"
}
+36 -21
View File
@@ -62,17 +62,17 @@ scadabridge template create --name <name> [--description <desc>] [--parent-id <i
scadabridge template update --id <id> [--name <name>] [--description <desc>] [--parent-id <id>]
scadabridge template validate --id <id>
scadabridge template delete --id <id>
scadabridge template attribute add --template-id <id> --name <name> --data-type <type> [--value <value>] [--description <desc>] [--data-source <ref>] [--locked <bool>]
scadabridge template attribute update --id <id> [--name <name>] [--data-type <type>] [--value <value>] [--description <desc>] [--data-source <ref>] [--locked <bool>]
scadabridge template attribute add --template-id <id> --name <name> --data-type <type> [--value <value>] [--description <desc>] [--data-source <ref>] [--locked]
scadabridge template attribute update --id <id> [--name <name>] [--data-type <type>] [--value <value>] [--description <desc>] [--data-source <ref>] [--locked]
scadabridge template attribute delete --id <id>
scadabridge template alarm add --template-id <id> --name <name> --trigger-type <type> --priority <n> [--description <desc>] [--trigger-config <json>] [--locked <bool>]
scadabridge template alarm update --id <id> [--name <name>] [--trigger-type <type>] [--priority <n>] [--description <desc>] [--trigger-config <json>] [--locked <bool>]
scadabridge template alarm add --template-id <id> --name <name> --trigger-type <type> --priority <n> [--description <desc>] [--trigger-config <json>] [--locked]
scadabridge template alarm update --id <id> --name <name> --trigger-type <type> --priority <n> [--description <desc>] [--trigger-config <json>] [--locked]
scadabridge template alarm delete --id <id>
scadabridge template script add --template-id <id> --name <name> --code <code> --trigger-type <type> [--trigger-config <json>] [--locked <bool>] [--parameters <json>] [--return-def <json>]
scadabridge template script update --id <id> [--name <name>] [--code <code>] [--trigger-type <type>] [--trigger-config <json>] [--locked <bool>] [--parameters <json>] [--return-def <json>]
scadabridge template script add --template-id <id> --name <name> --code <code> --trigger-type <type> [--trigger-config <json>] [--locked] [--parameters <json>] [--return-def <json>]
scadabridge template script update --id <id> --name <name> --code <code> --trigger-type <type> [--trigger-config <json>] [--locked] [--parameters <json>] [--return-def <json>]
scadabridge template script delete --id <id>
scadabridge template composition add --template-id <id> --instance-name <name> --composed-template-id <id>
scadabridge template composition delete --template-id <id> --instance-name <name>
scadabridge template composition delete --id <id>
scadabridge template native-alarm-source add --template-id <id> --name <name> --connection <name> --source-ref <ref> [--filter <expr>] [--description <desc>] [--locked]
scadabridge template native-alarm-source list --template-id <id>
scadabridge template native-alarm-source remove --id <id>
@@ -165,8 +165,8 @@ scadabridge deploy status [--instance-id <id>] [--status <status>] [--page <n>]
```
scadabridge data-connection list [--site-id <id>]
scadabridge data-connection get --id <id>
scadabridge data-connection create --site-id <id> --name <name> --protocol <protocol> [--backup-config <json>] [--failover-retry-count <n>]
scadabridge data-connection update --id <id> [--name <name>] [--protocol <protocol>] [--backup-config <json>] [--failover-retry-count <n>]
scadabridge data-connection create --site-id <id> --name <name> --protocol <protocol> [--primary-config <json>] [--backup-config <json>] [--failover-retry-count <n>]
scadabridge data-connection update --id <id> --name <name> --protocol <protocol> [--primary-config <json>] [--backup-config <json>] [--failover-retry-count <n>]
scadabridge data-connection delete --id <id>
```
@@ -192,32 +192,36 @@ scadabridge notification create --name <name> --emails <comma-separated>
scadabridge notification update --id <id> [--name <name>] [--emails <comma-separated>]
scadabridge notification delete --id <id>
scadabridge notification smtp list
scadabridge notification smtp update --id <id> --server <host> --port <n> --auth-mode <mode> --from-address <email>
scadabridge notification smtp update --id <id> --server <host> --port <n> --auth-mode <mode> --from-address <email> [--tls-mode <mode>] [--credentials <value>]
```
### Security Commands
```
scadabridge security api-key list
scadabridge security api-key create --name <name>
scadabridge security api-key update --id <id> --enabled <bool>
scadabridge security api-key delete --id <id>
scadabridge security api-key create --name <name> --methods <comma-separated-method-names>
scadabridge security api-key update --key-id <id> --enabled <bool>
scadabridge security api-key set-methods --key-id <id> --methods <comma-separated-method-names>
scadabridge security api-key delete --key-id <id>
scadabridge security role-mapping list
scadabridge security role-mapping create --ldap-group <group> --role <role>
scadabridge security role-mapping update --id <id> [--ldap-group <group>] [--role <role>]
scadabridge security role-mapping delete --id <id>
scadabridge security scope-rule list [--mapping-id <id>]
scadabridge security scope-rule list --mapping-id <id>
scadabridge security scope-rule add --mapping-id <id> --site-id <id>
scadabridge security scope-rule delete --id <id>
```
### Audit Log Commands
### Configuration-Change Audit Commands
The `audit-config` group queries the configuration-change audit trail (the `IAuditService`
record of admin edits). `audit-log` is a deprecated alias that still works but emits a
warning; migrate scripts to `audit-config`.
```
scadabridge audit-log query [--user <username>] [--entity-type <type>] [--action <action>] [--from <date>] [--to <date>] [--page <n>] [--page-size <n>]
scadabridge audit-config query [--user <username>] [--entity-type <type>] [--action <action>] [--from <date>] [--to <date>] [--page <n>] [--page-size <n>]
```
The legacy `audit-log query` above targets the original configuration-change audit
(IAuditService) surface. The new centralized Audit Log component (#23) is exposed via
the `scadabridge audit` group below.
The new centralized Audit Log component (#23) is exposed via the `scadabridge audit` group below.
### Centralized Audit Commands
@@ -230,7 +234,7 @@ require the `OperationalAudit` permission; `audit export` additionally requires
exit code 2) on denial.
```
scadabridge audit query --since <t> [--until <t>] [--channel <c>] [--kind <k>] [--status <s>] [--site <s>] [--instance <i>] [--target <t>] [--actor <a>] [--correlation-id <id>] [--errors-only] [--page <n>] [--page-size <n>]
scadabridge audit query [--since <t>] [--until <t>] [--channel <c>] [--kind <k>] [--status <s>] [--site <s>] [--target <t>] [--actor <a>] [--correlation-id <id>] [--execution-id <id>] [--parent-execution-id <id>] [--errors-only] [--page-size <n>] [--all]
scadabridge audit export --since <t> --until <t> --format csv|jsonl|parquet --output <path> [--channel <c>] [--kind <k>] [--status <s>] [--site <s>] [--target <t>] [--actor <a>]
scadabridge audit verify-chain --month <YYYY-MM>
```
@@ -298,10 +302,21 @@ scadabridge db-connection delete --id <id>
scadabridge api-method list
scadabridge api-method get --id <id>
scadabridge api-method create --name <name> --script <code> [--timeout <seconds>] [--parameters <json>] [--return-def <json>]
scadabridge api-method update --id <id> [--script <code>] [--timeout <seconds>] [--parameters <json>] [--return-def <json>]
scadabridge api-method update --id <id> --script <code> [--timeout <seconds>] [--parameters <json>] [--return-def <json>]
scadabridge api-method delete --id <id>
```
### Bundle Commands (Transport #24)
```
scadabridge bundle export --output <path> [--passphrase <phrase>] [--all] [--include-dependencies] [--templates <names>] [--shared-scripts <names>] [--external-systems <names>] [--db-connections <names>] [--notification-lists <names>] [--smtp-configs <names>] [--api-methods <names>] [--source-environment <env>]
scadabridge bundle preview --input <path> [--passphrase <phrase>]
scadabridge bundle import --input <path> [--passphrase <phrase>] [--on-conflict skip|overwrite|rename]
```
Inbound API keys are not transported between environments — re-create them on the destination via CLI or UI.
Bundle commands use a 5-minute timeout.
The `--format json|table` option is recursive and accepted on every command above.
## Configuration
+9 -8
View File
@@ -47,8 +47,8 @@ Commons must define shared primitive and utility types used across multiple comp
- **`AuditKind` enum**: ApiCall, ApiCallCached, DbWrite, DbWriteCached, NotifySend, NotifyDeliver, InboundRequest, InboundAuthFailure, CachedSubmit, CachedResolve. Channel-specific event kind — the valid `Kind` values for each `AuditChannel` are listed in the Audit Log component design (`Component-AuditLog.md`).
- **`AuditStatus` enum**: Submitted, Forwarded, Attempted, Delivered, Failed, Parked, Discarded, Skipped. Lifecycle status of an audit event row; cached operations transit Submitted → Forwarded → Attempted → Delivered/Parked/Discarded. `Skipped` covers short-circuited (e.g. dry-run) actions that should still be audited.
- **`AuditForwardState` enum**: Pending, Forwarded, Reconciled. Site-local SQLite flag governing the telemetry/reconciliation loop (set on a row but never sent to central).
- **`AuditEvent`**: A record carrying every column of the central `AuditLog` row — `EventId` (GUID, idempotency key), `OccurredAtUtc`, `IngestedAtUtc`, `Channel` (`AuditChannel`), `Kind` (`AuditKind`), `CorrelationId`, `ExecutionId`, `ParentExecutionId`, `SourceSiteId`, `SourceNode`, `SourceInstanceId`, `SourceScript`, `Actor`, `Target`, `Status` (`AuditStatus`), `HttpStatus`, `DurationMs`, `ErrorMessage`, `ErrorDetail`, `RequestSummary`, `ResponseSummary`, `PayloadTruncated`, `Extra` — plus a site-only `ForwardState` (`AuditForwardState`) used by the site SQLite write-buffer's telemetry/reconciliation loop. `IngestedAtUtc` is unset at the site and stamped on central ingest. See `Component-AuditLog.md` for the persistence schema and ingest semantics.
- **`SiteCall`**: A record carrying the central `SiteCalls` operational-mirror row — `TrackedOperationId`, `SourceSiteId`, `SourceNode`, `Kind`, `Target`, `Status`, `RetryCount`, key timestamps, and provenance — fed by site `CachedCallTelemetry` and the periodic reconciliation pull.
- **`AuditEvent`** (`ZB.MOM.WW.Audit.AuditEvent` — external NuGet package, not a Commons entity class): The canonical, transport-agnostic audit record from the `ZB.MOM.WW.Audit` package that Commons references. Carries the 10 canonical fields: `EventId` (GUID, idempotency key), `OccurredAtUtc`, `Actor`, `Action` (format `"{channel}.{kind}"`), `Outcome` (`AuditOutcome`: `Success`/`Failure`/`Denied`), `Category` (channel name for ScadaBridge), `Target`, `SourceNode`, `CorrelationId`, and `DetailsJson` (JSON extension bag). All ScadaBridge-specific fields — `Channel`, `Kind`, `Status`, `ExecutionId`, `ParentExecutionId`, `SourceSiteId`, `SourceInstanceId`, `SourceScript`, `HttpStatus`, `DurationMs`, `ErrorMessage`, `ErrorDetail`, `RequestSummary`, `ResponseSummary`, `PayloadTruncated`, `Extra`, `IngestedAtUtc` — are carried in `DetailsJson` and are not top-level properties of `AuditEvent`. The `AuditChannel`, `AuditKind`, `AuditStatus`, and `AuditForwardState` enums defined in Commons (under `Types/Enums/`) describe the vocabulary encoded in `DetailsJson` and in the `AuditLogRow` computed columns. The site-local `ForwardState` (`AuditForwardState`) flag used by the telemetry/reconciliation loop is stored separately in the site SQLite `AuditLog` table. See `Component-AuditLog.md` for the persistence schema and ingest semantics.
- **`SiteCall`**: A record carrying the central `SiteCalls` operational-mirror row — `TrackedOperationId`, `Channel` (the trust-boundary channel, `ApiOutbound` or `DbOutbound`), `Target` (human-readable call target), `SourceSite` (site id), `SourceNode` (emitting node, nullable), `Status` (string form of `AuditStatus`; monotonic), `RetryCount`, `LastError`, `HttpStatus`, `CreatedAtUtc`, `UpdatedAtUtc`, `TerminalAtUtc`, `IngestedAtUtc` — fed by site `CachedCallTelemetry` and the periodic reconciliation pull.
Types defined here must be immutable and thread-safe.
@@ -81,12 +81,12 @@ Entity classes are organized by domain area:
- **Sites & Data Connections**: `Site`, `DataConnection`.
- **External Systems & Database Connections**: `ExternalSystemDefinition`, `ExternalSystemMethod`, `DatabaseConnectionDefinition`.
- **Notifications**: `NotificationList` (carries a `Type` field — `NotificationType` enum — selecting the list's notification type and its type-specific targets), `NotificationRecipient`, `SmtpConfiguration`, `Notification` (the durable central-queue row — see below).
- **Inbound API**: `ApiKey`, `ApiMethod`.
- **Inbound API**: `ApiMethod`. (`ApiKey` was a Commons POCO entity backed by the SQL Server `ApiKeys` table; it was retired — migration `RetireInboundApiKeyStore` dropped the table, and the `ApiKey` entity class was removed from Commons. Inbound API key management now goes through the `IInboundApiKeyAdmin` interface, backed by the `ZB.MOM.WW.Auth.ApiKeys` SQLite store.)
- **Security**: `LdapGroupMapping`, `SiteScopeRule`.
- **Deployment**: `DeploymentRecord`, `SystemArtifactDeploymentRecord`, `DeployedConfigSnapshot`.
- **Audit**: `AuditLogEntry` (configuration-change audit, owned by Configuration Database), `AuditEvent` (centralized Audit Log row, see REQ-COM-1), `SiteCall` (`SiteCalls` operational-mirror row).
- **Audit**: `AuditLogEntry` (configuration-change audit, owned by Configuration Database), `SiteCall` (`SiteCalls` operational-mirror row). (`AuditEvent` is `ZB.MOM.WW.Audit.AuditEvent` from the external NuGet package — not a Commons entity class file; see REQ-COM-1.)
The **`Notification`** entity is the persistence-ignorant POCO for a row of the central `Notifications` table — the durable notification queue owned by the Notification Outbox. It is a plain class with properties for `NotificationId` (GUID, the idempotency key), `Type` (`NotificationType` enum discriminator), `ListName`, `Subject`, `Body`, `TypeData` (a JSON string — the type-agnostic extensibility hook), `Status` (`NotificationStatus` enum), `RetryCount`, `LastError`, `ResolvedTargets`, the provenance fields `SourceSiteId` / `SourceInstanceId` / `SourceScript`, and the UTC timestamps `SiteEnqueuedAt`, `CreatedAt`, `LastAttemptAt`, `NextAttemptAt`, `DeliveredAt`. As with every entity class it has no EF dependency; the Configuration Database component supplies the Fluent API mapping, value conversions, and indexes. The `Type` and `Status` enums (`NotificationType`: `Email`, `Teams`, …; `NotificationStatus`: `Pending`, `Retrying`, `Delivered`, `Parked`, `Discarded`) are defined under `Types/Enums/` per REQ-COM-1.
The **`Notification`** entity is the persistence-ignorant POCO for a row of the central `Notifications` table — the durable notification queue owned by the Notification Outbox. It is a plain class with properties for `NotificationId` (GUID, the idempotency key), `Type` (`NotificationType` enum discriminator), `ListName`, `Subject`, `Body`, `TypeData` (a JSON string — the type-agnostic extensibility hook), `Status` (`NotificationStatus` enum), `RetryCount`, `LastError`, `ResolvedTargets`, the provenance fields `SourceSiteId` / `SourceInstanceId` / `SourceScript`, and the UTC timestamps `SiteEnqueuedAt`, `CreatedAt`, `LastAttemptAt`, `NextAttemptAt`, `DeliveredAt`. As with every entity class it has no EF dependency; the Configuration Database component supplies the Fluent API mapping, value conversions, and indexes. The `Type` and `Status` enums (`NotificationType`: `Email` — currently the only value; `Teams` and other channels are planned but not yet present in the enum; `NotificationStatus`: `Pending`, `Retrying`, `Delivered`, `Parked`, `Discarded`) are defined under `Types/Enums/` per REQ-COM-1.
### REQ-COM-4: Per-Component Repository Interfaces
@@ -95,7 +95,7 @@ Commons must define repository interfaces that consuming components use for data
- `ITemplateEngineRepository` — Templates, attributes, alarms, native alarm sources, scripts, compositions, template folders, instances, overrides, alarm overrides, native alarm source overrides, connection bindings, areas.
- `IDeploymentManagerRepository` — Deployment records, deployed configuration snapshots, system-wide artifact deployment records.
- `ISecurityRepository` — LDAP group mappings, site scoping rules.
- `IInboundApiRepository` — API keys, API method definitions.
- `IInboundApiRepository` — API method definitions. (API key operations were removed when the `ApiKeys` SQL table was retired; key management goes through `IInboundApiKeyAdmin`.)
- `IExternalSystemRepository` — External system definitions, method definitions, database connection definitions.
- `INotificationRepository` — Notification lists (including the `Type` field), recipients, SMTP configuration.
- `INotificationOutboxRepository` — The `Notifications` table: insert-if-not-exists ingest on `NotificationId`, due-row polling (`Pending` rows and `Retrying` rows past `NextAttemptAt`), status transitions, KPI aggregate queries, and the bulk delete of terminal rows used by the daily purge job.
@@ -254,14 +254,15 @@ ZB.MOM.WW.ScadaBridge.Commons/
│ │ # DatabaseConnectionDefinition
│ ├── Notifications/ # NotificationList, NotificationRecipient, SmtpConfiguration,
│ │ # Notification (central Notifications-table row)
│ ├── InboundApi/ # ApiKey, ApiMethod
│ ├── InboundApi/ # ApiMethod (ApiKey retired — see REQ-COM-3)
│ ├── Security/ # LdapGroupMapping, SiteScopeRule
│ ├── Deployment/ # DeploymentRecord, SystemArtifactDeploymentRecord,
│ │ # DeployedConfigSnapshot
│ ├── Scripts/ # SharedScript
│ └── Audit/ # AuditLogEntry (config-change audit),
│ # AuditEvent (centralized AuditLog row),
│ # SiteCall (SiteCalls operational mirror)
│ # Note: AuditEvent is ZB.MOM.WW.Audit.AuditEvent
│ # (external NuGet package), not a file here
├── Messages/ # REQ-COM-5: Cross-component message contracts, by concern
│ ├── Deployment/
│ ├── Lifecycle/
@@ -60,14 +60,50 @@ The configuration database stores all central system data, organized by domain a
- **Notifications**: The durable central notification queue owned by the Notification Outbox — one row per notification, the single source of audit truth. The schema is **type-agnostic** so it records any notification type the system supports (email today, Microsoft Teams and others later): a `Type` discriminator selects the type, and a `TypeData` JSON column (`nvarchar(max)`) carries any future per-type fields without a schema change. Columns: `NotificationId` (GUID, primary key — generated at the site, used as the idempotency key), `Type`, `ListName`, `Subject`, `Body`, `TypeData`, `Status`, `RetryCount`, `LastError`, `ResolvedTargets`, `SourceSiteId`, `SourceInstanceId`, `SourceScript`, `SiteEnqueuedAt`, `CreatedAt`, `LastAttemptAt`, `NextAttemptAt`, `DeliveredAt`. `Status` is a `NotificationStatus` enum stored with values `Pending`, `Retrying`, `Delivered`, `Parked`, `Discarded` (the site-local `Forwarding` state is never persisted centrally). Indexed on `Status` and `NextAttemptAt` for efficient dispatcher polling of due rows, and on `SourceSiteId` and `CreatedAt` for KPI computation and the Central UI query page. Terminal rows are removed by a daily purge job — see Scheduled Maintenance below. See Component-NotificationOutbox.md for the full lifecycle.
### Site Calls
- **SiteCalls**: The central audit table for cached site calls — `ExternalSystem.CachedCall()` and `Database.CachedWrite()` — owned by the Site Call Audit component and a sibling of the `Notifications` table. One row per cached operation. Columns: `TrackedOperationId` (GUID, primary key — generated site-side at call time, used as the idempotency key), `SourceSite`, `Kind` (a `TrackedOperationKind` enum stored with values `ExternalCall` / `DatabaseWrite`), `TargetSummary` (external system + method for an `ExternalCall`, database connection name for a `DatabaseWrite`), `Status` (a `TrackedOperationStatus` enum stored with values `Pending`, `Retrying`, `Delivered`, `Parked`, `Failed`, `Discarded`), `RetryCount`, `LastError`, `Provenance` (source instance / script), `CreatedAtUtc`, `UpdatedAtUtc`, `TerminalAtUtc`. The table is populated **only** by Site Call Audit telemetry and reconciliation pulls — sites are the source of truth and the row is an eventually-consistent mirror, never written by a central dispatcher. Ingestion is **insert-if-not-exists** keyed on `TrackedOperationId`, then **upsert-on-newer-status**; the lifecycle is monotonic, so at-least-once and out-of-order telemetry are harmless. Indexed on `Status` and `SourceSite` for KPI computation and the Central UI query page. Terminal rows are removed by a daily purge job — see Scheduled Maintenance below. See Component-SiteCallAudit.md for the full lifecycle.
- **SiteCalls**: The central audit table for cached site calls — `ExternalSystem.CachedCall()` and `Database.CachedWrite()` — owned by the Site Call Audit component and a sibling of the `Notifications` table. One row per cached operation. Columns: `TrackedOperationId` (`varchar(36)`, primary key — the GUID idempotency key stored in "D"-format string, matching the site SQLite and gRPC wire format), `Channel` (`varchar(32)` — `ApiOutbound` or `DbOutbound`; the trust-boundary channel that produced the call), `Target` (`varchar(256)` — human-readable target, e.g. `ERP.GetOrder` for an external call), `SourceSite` (`varchar(64)` — the site that submitted the cached call), `SourceNode` (`varchar(64)` NULL — cluster node that emitted the call; null for reconciled rows from retired nodes), `Status` (`varchar(32)` — `AuditStatus` enum name: `Submitted`, `Forwarded`, `Attempted`, `Delivered`, `Failed`, `Parked`, `Discarded`; lifecycle is monotonic), `RetryCount` (`int`), `LastError` (`nvarchar(1024)` NULL), `HttpStatus` (`int` NULL — last HTTP status code for API calls), `CreatedAtUtc` (`datetime2`), `UpdatedAtUtc` (`datetime2`), `TerminalAtUtc` (`datetime2` NULL), `IngestedAtUtc` (`datetime2` — central ingest timestamp). The table is populated **only** by Site Call Audit telemetry and reconciliation pulls — sites are the source of truth and the row is an eventually-consistent mirror, never written by a central dispatcher. Ingestion is **insert-if-not-exists** keyed on `TrackedOperationId`, then **upsert-on-newer-status**; the lifecycle is monotonic, so at-least-once and out-of-order telemetry are harmless. Indexes: `IX_SiteCalls_Source_Created (SourceSite, CreatedAtUtc DESC)` for per-site queries and `IX_SiteCalls_Status_Updated (Status, UpdatedAtUtc DESC)` for status-filtered views. Terminal rows are removed by a daily purge job — see Scheduled Maintenance below. See Component-SiteCallAudit.md for the full lifecycle.
### Audit Log
- **AuditLog**: The central, append-only audit table owned by the Audit Log component — one row per script-trust-boundary lifecycle event across all channels (outbound API calls, outbound DB writes/reads, notifications, and inbound API requests). Sibling of the `Notifications` and `SiteCalls` tables but distinct: `AuditLog` is the immutable history that observes the other subsystems, not an operational state store. Columns: `EventId` (`uniqueidentifier` primary key — generated at the originator, used as the idempotency key), `OccurredAtUtc` (`datetime2`), `IngestedAtUtc` (`datetime2`), `Channel` (`varchar(32)` — `ApiOutbound` / `DbOutbound` / `Notification` / `ApiInbound`), `Kind` (`varchar(32)` — channel-specific event kind), `CorrelationId` (`uniqueidentifier` NULL — `TrackedOperationId` for cached calls, `NotificationId` for notifications, request-id for inbound API), `SourceSiteId` (`varchar(64)` NULL), `SourceInstanceId` (`varchar(128)` NULL), `SourceScript` (`varchar(128)` NULL), `Actor` (`varchar(128)` NULL), `Target` (`varchar(256)` NULL), `Status` (`varchar(32)` — outcome of *this event*: `Success`, `TransientFailure`, `PermanentFailure`, `Enqueued`, `Retrying`, `Delivered`, `Parked`, `Discarded`), `HttpStatus` (`int` NULL), `DurationMs` (`int` NULL), `ErrorMessage` (`nvarchar(1024)` NULL), `ErrorDetail` (`nvarchar(max)` NULL), `RequestSummary` (`nvarchar(max)` NULL — truncated request payload, headers redacted), `ResponseSummary` (`nvarchar(max)` NULL — truncated response payload), `PayloadTruncated` (`bit`), `Extra` (`nvarchar(max)` NULL — channel-specific JSON for fields not promoted to columns). Indexes: `IX_AuditLog_OccurredAtUtc` (primary time-range index for global scans), `IX_AuditLog_Site_Occurred (SourceSiteId, OccurredAtUtc)` (per-site filters), `IX_AuditLog_CorrelationId (CorrelationId)` (drilldown from a single operation), `IX_AuditLog_Channel_Status_Occurred (Channel, Status, OccurredAtUtc)` (KPI / dashboard tiles), and `IX_AuditLog_Target_Occurred (Target, OccurredAtUtc)` ("what did we send to system X"). The primary key on `EventId` enforces idempotency — central ingest is `INSERT … WHERE NOT EXISTS`, so at-least-once telemetry and reconciliation retries collapse to a single row. **Monthly partitioning** on `OccurredAtUtc` from day one via partition function `pf_AuditLog_Month` and partition scheme `ps_AuditLog_Month`, with a filegroup-per-month rollover so that retention purge is a partition switch rather than a row-level delete. The partition-maintenance job that rolls the scheme forward and switches expired partitions is owned by the Audit Log component, not this component. The table is populated only by Audit Log writers (site telemetry, central direct-write, reconciliation pulls); central ingest is **insert-if-not-exists** keyed on `EventId`. See Component-AuditLog.md for the full lifecycle, payload-capture policy, and ingestion paths.
- **AuditLog**: The central, append-only audit table owned by the Audit Log component — one row per script-trust-boundary lifecycle event across all channels (outbound API calls, outbound DB writes/reads, notifications, and inbound API requests). Sibling of the `Notifications` and `SiteCalls` tables but distinct: `AuditLog` is the immutable history that observes the other subsystems, not an operational state store.
**Schema (post-C5 canonical collapse, migration `CollapseAuditLogToCanonical`):** The table stores the 10 canonical `ZB.MOM.WW.Audit.AuditEvent` fields directly as writable columns, plus six read-only server-side persisted computed columns derived from `DetailsJson` via `JSON_VALUE … PERSISTED`.
*Writable columns (the 10 canonical `AuditEvent` fields):*
- `EventId` (`uniqueidentifier NOT NULL`) — idempotency key; generated at the originator.
- `OccurredAtUtc` (`datetime2(7) NOT NULL`) — UTC timestamp when the audited action occurred at its source.
- `Actor` (`nvarchar(256)` NULL) — authenticated actor; null/empty for system/anon actions.
- `Action` (`varchar(64) NOT NULL`) — canonical action verb, format `"{channel}.{kind}"` (e.g. `ApiOutbound.ApiCall`).
- `Outcome` (`varchar(16) NOT NULL`) — normalized outcome: `Success`, `Failure`, or `Denied`.
- `Category` (`varchar(32) NOT NULL`) — canonical `Category` column; for ScadaBridge this equals the channel name (`ApiOutbound`, `DbOutbound`, `Notification`, `ApiInbound`). Mapped to the `AuditChannel` enum in EF as `Channel`.
- `Target` (`nvarchar(256)` NULL) — target of the action: external system name, DB connection name, notification list name, or inbound method name.
- `SourceNode` (`varchar(64)` NULL) — cluster node that emitted the event (e.g. `node-a`, `central-a`); null for reconciled rows from a retired node.
- `CorrelationId` (`uniqueidentifier` NULL) — links related audit rows (e.g. the cached-op lifecycle): `TrackedOperationId` for cached calls, `NotificationId` for notifications.
- `DetailsJson` (`nvarchar(max)` NULL) — JSON extension bag carrying all ScadaBridge domain fields (channel, kind, status, executionId, parentExecutionId, sourceSiteId, sourceInstanceId, sourceScript, httpStatus, durationMs, errorMessage, errorDetail, requestSummary, responseSummary, payloadTruncated, extra, ingestedAtUtc, and others).
*Persisted computed columns (read-only; derived from `DetailsJson` by SQL Server on INSERT):*
- `Kind` — `JSON_VALUE(DetailsJson,'$.kind')` PERSISTED — channel-specific event kind (e.g. `ApiCall`, `CachedSubmit`).
- `Status` — `JSON_VALUE(DetailsJson,'$.status')` PERSISTED — `AuditStatus` enum name for this event (e.g. `Submitted`, `Delivered`, `Parked`).
- `SourceSiteId` — `JSON_VALUE(DetailsJson,'$.sourceSiteId')` PERSISTED — site of origin; null for central-direct events.
- `ExecutionId` — `CAST(JSON_VALUE(DetailsJson,'$.executionId') AS uniqueidentifier)` PERSISTED — originating script execution / inbound request id.
- `ParentExecutionId` — `CAST(JSON_VALUE(DetailsJson,'$.parentExecutionId') AS uniqueidentifier)` PERSISTED — spawner's `ExecutionId`; null for top-level runs.
- `IngestedAtUtc` — `CAST(SWITCHOFFSET(CAST(JSON_VALUE(DetailsJson,'$.ingestedAtUtc') AS datetimeoffset), 0) AS datetime2(7))` — central ingest timestamp; **not** persisted (SQL Server rejects PERSISTED on the non-deterministic `SWITCHOFFSET` expression).
*Clustered primary key:* `(EventId, OccurredAtUtc)` — composite so the key is partition-aligned. `UX_AuditLog_EventId` (unique, non-aligned on `[PRIMARY]`) enforces global `EventId` uniqueness for `InsertIfNotExistsAsync` idempotency.
*Indexes* (all non-clustered, partition-aligned on `ps_AuditLog_Month(OccurredAtUtc)` except `UX_AuditLog_EventId`):
- `IX_AuditLog_OccurredAtUtc` (primary time-range index for global scans)
- `IX_AuditLog_Site_Occurred (SourceSiteId, OccurredAtUtc)` (per-site filters)
- `IX_AuditLog_CorrelationId (CorrelationId) WHERE CorrelationId IS NOT NULL` (drilldown from a single operation)
- `IX_AuditLog_Channel_Status_Occurred (Category, Status, OccurredAtUtc)` (KPI / dashboard tiles — note: column is `Category` in SQL, `Channel` in EF)
- `IX_AuditLog_Target_Occurred (Target, OccurredAtUtc) WHERE Target IS NOT NULL` ("what did we send to system X")
- `IX_AuditLog_Execution (ExecutionId)` — unfiltered (SQL Server forbids filtered indexes on computed columns)
- `IX_AuditLog_ParentExecution (ParentExecutionId)` — unfiltered
- `IX_AuditLog_Node_Occurred (SourceNode, OccurredAtUtc)` (per-node queries)
**Monthly partitioning** on `OccurredAtUtc` via partition function `pf_AuditLog_Month` and partition scheme `ps_AuditLog_Month`; retention purge is a partition switch, never a row-level delete. The table is populated only by Audit Log writers (site telemetry, central direct-write, reconciliation pulls); central ingest is **insert-if-not-exists** keyed on `EventId`. See Component-AuditLog.md for the full lifecycle, payload-capture policy, and ingestion paths.
### Inbound API
- **API Keys**: Key definitions (name/label, key value, enabled flag).
- **API Methods**: Method definitions (name, approved key references, parameter definitions, return value definitions, implementation script, timeout).
- **API Keys**: The `ApiKeys` SQL Server table was **retired** by migration `RetireInboundApiKeyStore`. Inbound API keys now live in the shared `ZB.MOM.WW.Auth.ApiKeys` SQLite store, not the configuration MS SQL database. The `IInboundApiRepository` no longer exposes any `ApiKey` operations; key management goes through `IInboundApiKeyAdmin` (Commons, `Interfaces/Security/`). The `ApprovedApiKeyIds` column on `ApiMethods` was removed at the same time — key-to-method scoping is now managed by the auth library.
- **API Methods**: Method definitions (name, parameter definitions, return value definitions, implementation script, timeout).
### Security
- **LDAP Group Mappings**: Mappings between LDAP group names and system roles (Admin, Design, Deployment).
+16 -11
View File
@@ -29,7 +29,7 @@ Central cluster only (active node). Not available at site clusters.
- **Enabled/Disabled Flag**: Keys can be disabled without deletion.
### Management
- Managed by users with the **Admin** role via the Central UI.
- Managed by users with the **Administrator** role via the Central UI.
- All key changes (create, enable/disable, delete) are audit logged.
## API Method Definition
@@ -48,7 +48,7 @@ Each API method definition includes:
- **Timeout**: Configurable per method. Defines the maximum time the method is allowed to execute (including any routed calls to sites) before returning a timeout error to the caller.
### Management
- Managed by users with the **Design** role via the Central UI.
- Managed by users with the **Designer** role via the Central UI.
- All method definition changes are audit logged.
## HTTP Contract
@@ -58,8 +58,12 @@ Each API method definition includes:
- Method names map directly to URL path segments (e.g., method "GetProductionReport" → `POST /api/GetProductionReport`).
- All calls are POST — these are RPC-style script invocations, not RESTful resource operations.
### API Key Header
- API key is passed via the `X-API-Key` HTTP header.
### Authentication Header
- The API key token (`sbk_<keyId>_<secret>`) is accepted from **either** of two headers:
- `Authorization: Bearer sbk_<keyId>_<secret>` — the preferred form.
- `X-API-Key: sbk_<keyId>_<secret>` — alternate form for callers that cannot set the Authorization header.
- When both headers are present, `Authorization` takes precedence.
- Both forms are processed by the same `IApiKeyVerifier` from the shared `ZB.MOM.WW.Auth.ApiKeys` library; the verifier strips the optional `Bearer ` prefix and performs the same peppered-HMAC constant-time verification regardless of which header was used.
### Request Format
- Content-Type: `application/json`.
@@ -130,7 +134,7 @@ API method scripts are compiled at central startup — all method definitions ar
- **Every request — success or failure — emits one `ApiInbound.Completed` row** to `ICentralAuditWriter` from request middleware before the HTTP response is flushed. The row captures the API key **name** (never the key material), remote IP, user-agent, response status, duration, and the request/response bodies. Bodies are captured in full up to `AuditLog:InboundMaxBytes` (default 1 MiB); `PayloadTruncated = 1` only when that ceiling is hit. Header redaction and per-target body redactors still apply (see Component-AuditLog.md, Payload Capture Policy). This supersedes the earlier failures-only stance: operational API traffic is now part of the centralized audit log, so configuration changes and call activity share a single retention/query surface.
- Script execution errors (500 responses) remain captured on the same `ApiInbound.Completed` row (response status + error fields) rather than emitting a separate failure-only event.
- **Fail-soft semantics.** The audit write is synchronous (inline before the response is flushed), but failures are caught: a write that throws is logged and increments `CentralAuditWriteFailures` (see Health Monitoring #11) and the request still returns its normal HTTP response. A failed audit append never turns a successful API call into an error returned to the caller.
- **Fail-soft semantics (fire-and-forget).** The audit write is **fire-and-forget** (`InboundAPI-018`): `WriteAsync` is called without `await` so the user-facing HTTP response is never blocked or delayed by the audit path. Asynchronous faults are observed via a `ContinueWith` continuation that logs at Warning and increments `CentralAuditWriteFailures` (see Health Monitoring #11) rather than being silently dropped. A failed audit append never turns a successful API call into an error returned to the caller.
- No rate limiting — this is a private API in a controlled industrial environment with a known set of callers. Misbehaving callers are handled operationally (disable the API key).
## Request Flow
@@ -216,12 +220,13 @@ Inbound API scripts **cannot** call shared scripts directly — shared scripts a
## Authentication Details
- API key is passed via the `X-API-Key` HTTP header.
- The API key token is accepted from **either** the `Authorization: Bearer <token>` header (preferred) **or** the `X-API-Key: <token>` header (alternate). `Authorization` takes precedence when both are present.
- The token format is `sbk_<keyId>_<secret>`. Both header forms are verified by the same `IApiKeyVerifier` from `ZB.MOM.WW.Auth.ApiKeys`.
- The system validates:
1. The key exists in the configuration database.
2. The key is enabled.
3. The key is in the approved list for the requested method.
- Failed authentication returns an appropriate HTTP error (401 Unauthorized or 403 Forbidden).
1. The token is well-formed and the key ID exists in the key store.
2. The key is enabled (not revoked).
3. The key's provisioned scopes include the requested method name (case-sensitive).
- Failed authentication returns an appropriate HTTP error (401 Unauthorized for invalid/missing credentials; 403 Forbidden for a valid key not approved for the method). For enumeration-safety, both "method not found" and "key not in scope" return 403 with an identical body.
## Error Handling
@@ -246,5 +251,5 @@ Inbound API scripts **cannot** call shared scripts directly — shared scripts a
- **External Systems**: Call the API with API keys.
- **Communication Layer**: API method scripts use this to reach sites.
- **Site Runtime (Instance Actors, Script Actors)**: Routed calls execute on site Instance Actors via their Script Actors.
- **Central UI**: Admin manages API keys; Design manages method definitions.
- **Central UI**: Administrator manages API keys; Designer manages method definitions.
- **Configuration Database (via IAuditService)**: Configuration changes are audited.
@@ -15,7 +15,7 @@ Central cluster only. The Notification Service manages definitions in the centra
### Definitions (Central)
- Store notification lists in the configuration database: list name, list **type**, and type-specific targets (e.g. recipients for an `Email` list).
- Store email server configuration (SMTP settings).
- Managed by users with the Design role.
- Managed by users with the Designer role.
- Notification lists and SMTP configuration are **not deployed to sites** — they exist centrally only. There is no deploy-to-sites artifact and no local SQLite copy.
### Delivery Adapters (Central)
@@ -87,7 +87,7 @@ Each `Deliver(...)` call returns one of `success | transient failure | permanent
- **Configuration Database (MS SQL)**: Stores notification list definitions (name, type, type-specific targets) and SMTP config.
- **Notification Outbox**: Invokes the delivery adapters supplied by this component and asks it to resolve notification lists at delivery time.
- **Security & Auth**: Design role manages notification lists.
- **Security & Auth**: Designer role manages notification lists.
- **Configuration Database (via IAuditService)**: Notification list changes are audit logged.
## Interactions
+23 -16
View File
@@ -13,7 +13,7 @@ Central cluster. Sites do not have user-facing interfaces and do not perform ind
- Authenticate users against LDAP/Active Directory using a direct LDAP/AD bind (username/password).
- Map LDAP group memberships to system roles.
- Enforce role-based access control on all API and UI operations.
- Support site-scoped permissions for the Deployment role.
- Support site-scoped permissions for the Deployer role.
## Authentication
@@ -39,7 +39,7 @@ Set in a local or docker-dev environment via the environment variable `ScadaBrid
- The JWT is embedded in an **authentication cookie** rather than being passed as a bearer token. This is the correct transport for Blazor Server, where persistent SignalR circuits do not carry Authorization headers — the browser automatically sends the cookie with every SignalR connection and HTTP request.
- The cookie is **HttpOnly** and **Secure** (requires HTTPS).
- On each request, the server extracts and validates the JWT from the cookie. All authorization decisions are made from the JWT claims without hitting the database.
- **JWT claims**: User display name, username, list of roles (Admin, Design, Deployment), and for site-scoped Deployment, the list of permitted site IDs.
- **JWT claims**: User display name, username, list of roles (`Administrator`, `Designer`, `Deployer`, `Viewer`), and for site-scoped Deployer, the list of permitted site IDs.
### Token Lifecycle
@@ -80,7 +80,7 @@ Set in a local or docker-dev environment via the environment variable `ScadaBrid
## Roles
### Admin
### Administrator
- **Scope**: System-wide (always).
- **Permissions**:
- Manage site definitions.
@@ -89,9 +89,9 @@ Set in a local or docker-dev environment via the environment variable `ScadaBrid
- Manage LDAP group-to-role mappings.
- Manage API keys (create, enable/disable, delete).
- System-level configuration.
- View audit logs.
- View and export audit logs.
### Design
### Designer
- **Scope**: System-wide (always).
- **Permissions**:
- Create, edit, delete templates (including attributes, alarms, scripts).
@@ -102,7 +102,7 @@ Set in a local or docker-dev environment via the environment variable `ScadaBrid
- Manage inbound API method definitions.
- Run on-demand validation (template flattening, script compilation).
### Deployment
### Deployer
- **Scope**: System-wide or site-scoped.
- **Permissions**:
- Create and manage instances (overrides, connection bindings, area assignment).
@@ -114,25 +114,32 @@ Set in a local or docker-dev environment via the environment variable `ScadaBrid
- Manage parked messages.
- Monitor and manage the Notification Outbox (retry and discard parked notifications).
- View site event logs.
- **Site scoping**: A user with site-scoped Deployment role can only perform these actions for instances at their permitted sites.
- **Site scoping**: A user with site-scoped Deployer role can only perform these actions for instances at their permitted sites.
### Viewer
- **Scope**: System-wide (always).
- **Permissions**:
- Read-only access to operational audit data (Audit Log, Notifications, Site Calls).
- Navigation to audit pages.
- Does not grant export or any mutating action.
## Multi-Role Support
- A user can hold **multiple roles simultaneously** by being a member of multiple LDAP groups.
- Roles are **independent** — there is no implied hierarchy between roles.
- For example, a user who is a member of both `SCADA-Designers` and `SCADA-Deploy-All` holds both the Design and Deployment roles, allowing them to author templates and also deploy configurations.
- For example, a user who is a member of both `SCADA-Designers` and `SCADA-Deploy-All` holds both the Designer and Deployer roles, allowing them to author templates and also deploy configurations.
## LDAP Group Mapping
- System administrators configure mappings between LDAP groups and roles.
- Examples:
- `SCADA-Admins` → Admin role
- `SCADA-Designers` → Design role
- `SCADA-Deploy-All` → Deployment role (all sites)
- `SCADA-Deploy-SiteA` → Deployment role (Site A only)
- `SCADA-Deploy-SiteB` → Deployment role (Site B only)
- `SCADA-Admins` → Administrator role
- `SCADA-Designers` → Designer role
- `SCADA-Deploy-All` → Deployer role (all sites)
- `SCADA-Deploy-SiteA` → Deployer role (Site A only)
- `SCADA-Deploy-SiteB` → Deployer role (Site B only)
- A user can be a member of multiple groups, granting multiple independent roles.
- Group mappings are stored in the configuration database and managed via the Central UI (Admin role).
- Group mappings are stored in the configuration database and managed via the Central UI (Administrator role).
## Permission Enforcement
@@ -149,8 +156,8 @@ Set in a local or docker-dev environment via the environment variable `ScadaBrid
## Interactions
- **Central UI**: All UI requests pass through authentication and authorization.
- **Template Engine**: Design role enforcement.
- **Deployment Manager**: Deployment role enforcement with site scoping.
- **Template Engine**: Designer role enforcement.
- **Deployment Manager**: Deployer role enforcement with site scoping.
- **All central components**: Role checks are a cross-cutting concern applied at the API layer.
- **Management Service**: The ManagementActor enforces role-based authorization on every incoming command using the authenticated user identity carried in the message envelope. The CLI authenticates users via the same LDAP bind mechanism and passes the user's identity (username, roles, permitted sites) in every request message. The ManagementActor applies the same role and site-scoping rules as the Central UI — no separate authentication path exists on the server side.
- **Transport (#24)**: Provides the `RequireDesign` policy (export) and `RequireAdmin` policy (import) enforced at both the Razor page layer and inside the `ZB.MOM.WW.ScadaBridge.Transport` service entrypoints.
+277 -70
View File
@@ -226,48 +226,62 @@ scadabridge --url <url> template attribute delete --id <int>
Add an alarm definition to a template.
```sh
scadabridge --url <url> template alarm add --template-id <int> --name <string> --trigger-attribute <string> --condition <string> --setpoint <string> [--severity <string>] [--notification-list <string>]
scadabridge --url <url> template alarm add --template-id <int> --name <string> --trigger-type <string> --priority <int> [--description <string>] [--trigger-config <json>] [--locked] [typed-setpoint-flags]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--template-id` | yes | Template ID |
| `--name` | yes | Alarm name |
| `--trigger-attribute` | yes | Attribute that triggers the alarm |
| `--condition` | yes | Trigger condition (e.g. `GreaterThan`, `LessThan`, `Equal`) |
| `--setpoint` | yes | Setpoint value |
| `--severity` | no | Alarm severity (default: `Warning`) |
| `--notification-list` | no | Notification list name to notify on alarm |
| `--trigger-type` | yes | Trigger type (e.g. `ValueMatch`, `RangeViolation`, `RateOfChange`, `HiLo`, `Expression`) |
| `--priority` | yes | Alarm priority (0–1000) |
| `--description` | no | Description |
| `--trigger-config` | no | Trigger configuration as a JSON string (overrides typed flags when both are supplied) |
| `--locked` | no | Lock the alarm in derived templates |
| `--attribute` | no | Attribute name the trigger watches (all trigger types except `Expression`) |
| `--match-value` | no | `ValueMatch`: value to compare against |
| `--not-equals` | no | `ValueMatch`: match when the value is NOT equal |
| `--min` | no | `RangeViolation`: minimum allowed value |
| `--max` | no | `RangeViolation`: maximum allowed value |
| `--threshold-per-second` | no | `RateOfChange`: rate threshold per second |
| `--window-seconds` | no | `RateOfChange`: sliding window in seconds |
| `--direction` | no | `RateOfChange`: direction (`rising`, `falling`, or `either`) |
| `--lolo` | no | `HiLo`: low-low setpoint |
| `--lo` | no | `HiLo`: low setpoint |
| `--hi` | no | `HiLo`: high setpoint |
| `--hihi` | no | `HiLo`: high-high setpoint |
| `--expression` | no | `Expression`: boolean trigger expression |
#### `template alarm update`
Update an alarm definition on a template.
Update an alarm definition on a template. An update **replaces** the whole entity — every
required field below must be supplied with its post-update value, even if unchanged.
```sh
scadabridge --url <url> template alarm update --template-id <int> --name <string> [--condition <string>] [--setpoint <string>] [--severity <string>] [--notification-list <string>]
scadabridge --url <url> template alarm update --id <int> --name <string> --trigger-type <string> --priority <int> [--description <string>] [--trigger-config <json>] [--locked]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--template-id` | yes | Template ID |
| `--name` | yes | Alarm name to update |
| `--condition` | no | Updated trigger condition |
| `--setpoint` | no | Updated setpoint value |
| `--severity` | no | Updated severity |
| `--notification-list` | no | Updated notification list name |
| `--id` | yes | Alarm ID |
| `--name` | yes | Alarm name |
| `--trigger-type` | yes | Trigger type |
| `--priority` | yes | Alarm priority (0–1000) |
| `--description` | no | Description |
| `--trigger-config` | no | Trigger configuration JSON |
| `--locked` | no | Lock the alarm in derived templates |
#### `template alarm delete`
Remove an alarm definition from a template.
```sh
scadabridge --url <url> template alarm delete --template-id <int> --name <string>
scadabridge --url <url> template alarm delete --id <int>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--template-id` | yes | Template ID |
| `--name` | yes | Alarm name to delete |
| `--id` | yes | Alarm ID |
#### `template native-alarm-source add`
@@ -309,60 +323,64 @@ scadabridge --url <url> template native-alarm-source remove --id <int>
Add a script to a template.
```sh
scadabridge --url <url> template script add --template-id <int> --name <string> --trigger-type <string> [--trigger-attribute <string>] [--interval <int>] --code <string>
scadabridge --url <url> template script add --template-id <int> --name <string> --trigger-type <string> --code <string> [--trigger-config <json>] [--locked] [--parameters <json>] [--return-def <json>]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--template-id` | yes | Template ID |
| `--name` | yes | Script name |
| `--trigger-type` | yes | Trigger type: `OnChange`, `Periodic`, `OnAlarm` |
| `--trigger-attribute` | no | Attribute name for `OnChange` trigger |
| `--interval` | no | Interval in milliseconds for `Periodic` trigger |
| `--code` | yes | Script source code (or `@filepath` to read from file) |
| `--trigger-type` | yes | Trigger type (e.g. `OnChange`, `Periodic`, `OnAlarm`) |
| `--code` | yes | Script source code |
| `--trigger-config` | no | Trigger configuration as a JSON string (e.g. interval, attribute name) |
| `--locked` | no | Lock the script in derived templates |
| `--parameters` | no | Parameter definitions JSON |
| `--return-def` | no | Return definition JSON |
#### `template script update`
Update a script on a template.
Update a script on a template. An update **replaces** the whole entity — every required
field below must be supplied with its post-update value, even if unchanged.
```sh
scadabridge --url <url> template script update --template-id <int> --name <string> [--trigger-type <string>] [--trigger-attribute <string>] [--interval <int>] [--code <string>]
scadabridge --url <url> template script update --id <int> --name <string> --trigger-type <string> --code <string> [--trigger-config <json>] [--locked] [--parameters <json>] [--return-def <json>]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--template-id` | yes | Template ID |
| `--name` | yes | Script name to update |
| `--trigger-type` | no | Updated trigger type |
| `--trigger-attribute` | no | Updated trigger attribute |
| `--interval` | no | Updated interval |
| `--code` | no | Updated script source code (or `@filepath`) |
| `--id` | yes | Script ID |
| `--name` | yes | Script name |
| `--trigger-type` | yes | Trigger type |
| `--code` | yes | Script source code |
| `--trigger-config` | no | Trigger configuration JSON |
| `--locked` | no | Lock the script in derived templates |
| `--parameters` | no | Parameter definitions JSON |
| `--return-def` | no | Return definition JSON |
#### `template script delete`
Remove a script from a template.
```sh
scadabridge --url <url> template script delete --template-id <int> --name <string>
scadabridge --url <url> template script delete --id <int>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--template-id` | yes | Template ID |
| `--name` | yes | Script name to delete |
| `--id` | yes | Script ID |
#### `template composition add`
Add a feature module composition to a template.
```sh
scadabridge --url <url> template composition add --template-id <int> --module-template-id <int> --instance-name <string>
scadabridge --url <url> template composition add --template-id <int> --composed-template-id <int> --instance-name <string>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--template-id` | yes | Target template ID |
| `--module-template-id` | yes | Feature module template ID to compose |
| `--composed-template-id` | yes | Feature module template ID to compose |
| `--instance-name` | yes | Instance name for the composed module (used in path-qualified addressing) |
#### `template composition delete`
@@ -508,6 +526,84 @@ scadabridge --url <url> instance set-bindings --id <int> --bindings <json>
| `--id` | yes | Instance ID |
| `--bindings` | yes | JSON array of `[attributeName, dataConnectionId]` pairs (e.g. `[["Speed",7],["Temperature",7]]`) |
#### `instance set-overrides`
Set attribute value overrides for an instance.
```sh
scadabridge --url <url> instance set-overrides --id <int> --overrides <json>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--id` | yes | Instance ID |
| `--overrides` | yes | JSON object of attribute name to value (e.g. `{"Speed": "100", "Mode": null}`); null clears an override |
#### `instance alarm-override set`
Set (upsert) an alarm override on an instance.
```sh
scadabridge --url <url> instance alarm-override set --instance-id <int> --alarm <string> [--trigger-config <json>] [--priority <int>]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--instance-id` | yes | Instance ID |
| `--alarm` | yes | Alarm canonical name (e.g. `TempLevels` or `Pump.TempSensor.Heat`) |
| `--trigger-config` | no | JSON override for TriggerConfiguration (HiLo: partial merge; others: whole-replace) |
| `--priority` | no | Priority override (0–1000) |
#### `instance alarm-override delete`
Remove an alarm override on an instance.
```sh
scadabridge --url <url> instance alarm-override delete --instance-id <int> --alarm <string>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--instance-id` | yes | Instance ID |
| `--alarm` | yes | Alarm canonical name |
#### `instance alarm-override list`
List all alarm overrides for an instance.
```sh
scadabridge --url <url> instance alarm-override list --instance-id <int>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--instance-id` | yes | Instance ID |
#### `instance set-area`
Reassign an instance to a different area (or clear its area assignment).
```sh
scadabridge --url <url> instance set-area --id <int> [--area-id <int>]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--id` | yes | Instance ID |
| `--area-id` | no | Area ID; omit to clear area assignment |
#### `instance diff`
Show the deployment diff between the currently deployed configuration and the current template state.
```sh
scadabridge --url <url> instance diff --id <int>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--id` | yes | Instance ID |
---
### `site` — Manage sites
@@ -537,7 +633,7 @@ scadabridge --url <url> site list
Register a new site.
```sh
scadabridge --url <url> site create --name <string> --identifier <string> [--description <string>]
scadabridge --url <url> site create --name <string> --identifier <string> [--description <string>] [--node-a-address <string>] [--node-b-address <string>] [--grpc-node-a-address <string>] [--grpc-node-b-address <string>]
```
| Option | Required | Description |
@@ -545,6 +641,29 @@ scadabridge --url <url> site create --name <string> --identifier <string> [--des
| `--name` | yes | Human-readable site name |
| `--identifier` | yes | Unique machine identifier used for cluster routing (e.g. `site-a`) |
| `--description` | no | Site description |
| `--node-a-address` | no | Akka.NET cluster address for Node A |
| `--node-b-address` | no | Akka.NET cluster address for Node B |
| `--grpc-node-a-address` | no | gRPC streaming address for Node A |
| `--grpc-node-b-address` | no | gRPC streaming address for Node B |
#### `site update`
Update an existing site. An update **replaces** the whole entity — every required field
below must be supplied with its post-update value, even if unchanged.
```sh
scadabridge --url <url> site update --id <int> --name <string> [--description <string>] [--node-a-address <string>] [--node-b-address <string>] [--grpc-node-a-address <string>] [--grpc-node-b-address <string>]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--id` | yes | Site ID |
| `--name` | yes | Human-readable site name |
| `--description` | no | Site description |
| `--node-a-address` | no | Akka.NET cluster address for Node A |
| `--node-b-address` | no | Akka.NET cluster address for Node B |
| `--grpc-node-a-address` | no | gRPC streaming address for Node A |
| `--grpc-node-b-address` | no | gRPC streaming address for Node B |
#### `site delete`
@@ -587,14 +706,14 @@ scadabridge --url <url> site area list --site-id <int>
Create an area within a site.
```sh
scadabridge --url <url> site area create --site-id <int> --name <string> [--parent-area-id <int>]
scadabridge --url <url> site area create --site-id <int> --name <string> [--parent-id <int>]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--site-id` | yes | Site ID |
| `--name` | yes | Area name |
| `--parent-area-id` | no | Parent area ID for nested areas |
| `--parent-id` | no | Parent area ID for nested areas |
#### `site area update`
@@ -885,17 +1004,18 @@ scadabridge --url <url> notification smtp list
Update the SMTP configuration.
```sh
scadabridge --url <url> notification smtp update --host <string> --port <int> --auth-type <string> [--username <string>] [--password <string>] [--from-address <string>]
scadabridge --url <url> notification smtp update --id <int> --server <string> --port <int> --auth-mode <string> --from-address <string> [--tls-mode <string>] [--credentials <string>]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--host` | yes | SMTP server hostname |
| `--id` | yes | SMTP config ID |
| `--server` | yes | SMTP server hostname |
| `--port` | yes | SMTP server port |
| `--auth-type` | yes | Authentication type: `OAuth2` or `Basic` |
| `--username` | no | SMTP username (for Basic auth) |
| `--password` | no | SMTP password (for Basic auth) |
| `--from-address` | no | Sender email address |
| `--auth-mode` | yes | Authentication mode (e.g. `OAuth2ClientCredentials`, `Basic`) |
| `--from-address` | yes | Sender email address |
| `--tls-mode` | no | TLS mode: `None`, `StartTLS`, or `SSL` (preserves existing if omitted) |
| `--credentials` | no | SMTP credentials — `username:password` for Basic, or client secret for OAuth2 (preserves existing if omitted) |
---
@@ -914,38 +1034,51 @@ scadabridge --url <url> security api-key list
Create a new inbound API key. The generated key value is returned in the response and not stored in plaintext — save it immediately.
```sh
scadabridge --url <url> security api-key create --name <string>
scadabridge --url <url> security api-key create --name <string> --methods <string>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--name` | yes | Descriptive label for the key |
| `--methods` | yes | Comma-separated API method names this key may call (e.g. `"MethodA,MethodB"`) |
#### `security api-key update`
Update an API key's name or enabled status.
Enable or disable an API key.
```sh
scadabridge --url <url> security api-key update --id <int> [--name <string>] [--enabled <bool>]
scadabridge --url <url> security api-key update --key-id <string> --enabled <bool>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--id` | yes | API key ID |
| `--name` | no | Updated label |
| `--enabled` | no | Enable or disable the key (`true` or `false`) |
| `--key-id` | yes | API key ID |
| `--enabled` | yes | Enable or disable the key (`true` or `false`) |
#### `security api-key set-methods`
Replace the method scopes on an existing API key.
```sh
scadabridge --url <url> security api-key set-methods --key-id <string> --methods <string>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--key-id` | yes | API key ID |
| `--methods` | yes | Comma-separated API method names (replaces the existing set) |
#### `security api-key delete`
Revoke and delete an API key.
```sh
scadabridge --url <url> security api-key delete --id <int>
scadabridge --url <url> security api-key delete --key-id <string>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--id` | yes | API key ID |
| `--key-id` | yes | API key ID |
#### `security role-mapping list`
@@ -997,27 +1130,27 @@ scadabridge --url <url> security role-mapping delete --id <int>
#### `security scope-rule list`
List all site scope rules for role mappings.
List all site scope rules for a role mapping.
```sh
scadabridge --url <url> security scope-rule list [--role-mapping-id <int>]
scadabridge --url <url> security scope-rule list --mapping-id <int>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--role-mapping-id` | no | Filter by role mapping ID |
| `--mapping-id` | yes | Role mapping ID |
#### `security scope-rule add`
Add a site scope rule to a role mapping, restricting it to a specific site.
```sh
scadabridge --url <url> security scope-rule add --role-mapping-id <int> --site-id <int>
scadabridge --url <url> security scope-rule add --mapping-id <int> --site-id <int>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--role-mapping-id` | yes | Role mapping ID |
| `--mapping-id` | yes | Role mapping ID |
| `--site-id` | yes | Site ID to scope the mapping to |
#### `security scope-rule delete`
@@ -1061,29 +1194,32 @@ scadabridge --url <url> health site --identifier <string>
Query the site event log for a specific site. Events are fetched remotely from the site's local SQLite store.
```sh
scadabridge --url <url> health event-log --site-identifier <string> [--from <datetime>] [--to <datetime>] [--search <string>] [--page <int>] [--page-size <int>]
scadabridge --url <url> health event-log --site <string> [--event-type <string>] [--severity <string>] [--keyword <string>] [--from <datetime>] [--to <datetime>] [--page <int>] [--page-size <int>] [--instance-name <string>]
```
| Option | Required | Default | Description |
|--------|----------|---------|-------------|
| `--site-identifier` | yes | — | Site identifier |
| `--site` | yes | — | Site identifier |
| `--event-type` | no | — | Filter by event type |
| `--severity` | no | — | Filter by severity |
| `--keyword` | no | — | Keyword search term |
| `--from` | no | — | Start timestamp in ISO 8601 format |
| `--to` | no | — | End timestamp in ISO 8601 format |
| `--search` | no | — | Keyword search term |
| `--page` | no | `1` | Page number |
| `--page-size` | no | `50` | Results per page |
| `--instance-name` | no | — | Filter by instance name |
#### `health parked-messages`
Query parked (dead-letter) messages at a specific site.
```sh
scadabridge --url <url> health parked-messages --site-identifier <string> [--page <int>] [--page-size <int>]
scadabridge --url <url> health parked-messages --site <string> [--page <int>] [--page-size <int>]
```
| Option | Required | Default | Description |
|--------|----------|---------|-------------|
| `--site-identifier` | yes | — | Site identifier |
| `--site` | yes | — | Site identifier |
| `--page` | no | `1` | Page number |
| `--page-size` | no | `50` | Results per page |
@@ -1162,6 +1298,8 @@ scadabridge --url <url> audit query [options]
| `--target` | no | — | Filter by target (external system, DB connection, notification list) |
| `--actor` | no | — | Filter by actor |
| `--correlation-id` | no | — | Filter by correlation ID |
| `--execution-id` | no | — | Filter by execution ID |
| `--parent-execution-id` | no | — | Filter by parent execution ID |
| `--errors-only` | no | `false` | Show only failed events (`status=Failed`; overrides `--status`) |
| `--page-size` | no | `100` | Events per page (1–1000) |
| `--all` | no | `false` | Fetch every page, following the keyset cursor |
@@ -1350,14 +1488,13 @@ scadabridge --url <url> db-connection get --id <int>
Create a new database connection definition.
```sh
scadabridge --url <url> db-connection create --name <string> --connection-string <string> [--provider <string>]
scadabridge --url <url> db-connection create --name <string> --connection-string <string>
```
| Option | Required | Description |
|--------|----------|-------------|
| `--name` | yes | Connection name |
| `--connection-string` | yes | Database connection string |
| `--provider` | no | Database provider (default: `SqlServer`) |
#### `db-connection update`
@@ -1415,14 +1552,16 @@ scadabridge --url <url> api-method get --id <int>
Create a new inbound API method.
```sh
scadabridge --url <url> api-method create --name <string> --code <string> [--description <string>]
scadabridge --url <url> api-method create --name <string> --script <string> [--timeout <int>] [--parameters <json>] [--return-def <json>]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--name` | yes | Method name (used as the URL path segment in `POST /api/{methodName}`) |
| `--code` | yes | Script source code implementing the method (or `@filepath` to read from file) |
| `--description` | no | Method description |
| Option | Required | Default | Description |
|--------|----------|---------|-------------|
| `--name` | yes | — | Method name (used as the URL path segment in `POST /api/{methodName}`) |
| `--script` | yes | — | Script source code implementing the method |
| `--timeout` | no | `30` | Timeout in seconds |
| `--parameters` | no | — | Parameter definitions JSON |
| `--return-def` | no | — | Return type definition JSON |
#### `api-method update`
@@ -1457,6 +1596,74 @@ scadabridge --url <url> api-method delete --id <int>
---
### `bundle` — Transport bundle export / preview / import
Export, preview, and import Transport (#24) bundles. Bundles carry templates, shared
scripts, external systems, database connections, notification lists, SMTP configurations,
and API methods between environments. Inbound API keys are **not** transported — recreate
them on the destination via the CLI or UI.
Bundle commands use a 5-minute timeout (larger payloads may be slow over WAN).
#### `bundle export`
Export selected entities to a `.scadabundle` file.
```sh
scadabridge --url <url> bundle export --output <path> [--passphrase <string>] [--all] [--include-dependencies] [entity-selectors]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--output` | yes | Output file path (e.g. `env-baseline.scadabundle`) |
| `--passphrase` | no | Encryption passphrase; omit to produce an unencrypted bundle |
| `--all` | no | Export every entity of every supported type (ignores per-type name flags) |
| `--include-dependencies` | no | Pull transitive dependencies (referenced shared scripts, parents, composed members) into the bundle |
| `--templates` | no | Comma-separated template names to include |
| `--shared-scripts` | no | Comma-separated shared-script names to include |
| `--external-systems` | no | Comma-separated external-system names to include |
| `--db-connections` | no | Comma-separated database-connection names to include |
| `--notification-lists` | no | Comma-separated notification-list names to include |
| `--smtp-configs` | no | Comma-separated SMTP host names to include |
| `--api-methods` | no | Comma-separated API-method names to include |
| `--source-environment` | no | `SourceEnvironment` value stamped into the bundle manifest (default: `cli`) |
**Example** — export two templates and all their dependencies:
```sh
scadabridge --url <url> bundle export --output baseline.scadabundle \
--templates "PumpTemplate,TankTemplate" --include-dependencies
```
#### `bundle preview`
Load a bundle and print the diff preview (Added / Modified / Unchanged per entity) without applying any changes.
```sh
scadabridge --url <url> bundle preview --input <path> [--passphrase <string>]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--input` | yes | Bundle file path (`.scadabundle`) |
| `--passphrase` | no | Passphrase for encrypted bundles |
#### `bundle import`
Load and apply a bundle with a single global conflict policy. Preview first with `bundle preview` to review the diff.
```sh
scadabridge --url <url> bundle import --input <path> [--passphrase <string>] [--on-conflict <policy>]
```
| Option | Required | Default | Description |
|--------|----------|---------|-------------|
| `--input` | yes | — | Bundle file path (`.scadabundle`) |
| `--passphrase` | no | — | Passphrase for encrypted bundles |
| `--on-conflict` | no | `overwrite` | Resolution policy for `Modified` rows: `skip`, `overwrite`, or `rename` |
---
## Architecture Notes
The CLI connects to the Central cluster using Akka.NET's `ClusterClient`. It does not join the cluster — it contacts the `ClusterClientReceptionist` on one of the configured Central nodes and sends commands to the `ManagementActor` at path `/user/management`.
@@ -13,9 +13,8 @@ namespace ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Audit;
/// wires up <c>AuditFilterBar</c> and <c>AuditResultsGrid</c>: the page owns the
/// active <see cref="AuditLogQueryFilter"/> and re-pushes a fresh instance to the
/// grid on every Apply (the grid uses reference identity as its "reload"
/// trigger). Row clicks land in <see cref="HandleRowSelected"/> — Bundle C wires
/// this to the drilldown drawer; for now it is a no-op seam so test stubs do
/// not error.
/// trigger). Row clicks land in <see cref="HandleRowSelected"/>, which pins
/// the selected row and opens the drilldown drawer.
///
/// <para>
/// Bundle D (M7-T10..T12) adds query-string drill-in parsing so other pages can
@@ -8,8 +8,8 @@ namespace ZB.MOM.WW.ScadaBridge.SiteCallAudit;
/// <remarks>
/// <para>
/// Binds <see cref="SiteCallAuditOptions"/> (stuck-call detection + KPI
/// windowing for the read-side query/KPI handlers). The reconciliation puller
/// and central→site Retry/Discard relay are still deferred to later follow-ups.
/// windowing for the read-side query/KPI handlers). The central→site
/// Retry/Discard relay is wired in <see cref="SiteCallAuditActor"/>.
/// </para>
/// <para>
/// The repository (<c>ISiteCallAuditRepository</c>) is registered by
@@ -463,8 +463,9 @@ internal sealed class AuditingDbCommand : DbCommand
}
// RequestSummary captures the SQL statement + parameter values by
// default per the alog.md M4 acceptance criteria (M5 will add
// per-connection redaction opt-in).
// default per the alog.md M4 acceptance criteria. Per-target SQL
// parameter redaction is configured via AuditLogOptions.PerTargetOverrides
// (RedactSqlParamsMatching) and applied at write time by the redactor.
string? requestSummary = BuildRequestSummary();
// Extra carries the op discriminator + row count per the vocabulary
@@ -509,7 +510,8 @@ internal sealed class AuditingDbCommand : DbCommand
/// <summary>
/// Compose a JSON request summary capturing the SQL statement and
/// parameter values. Parameter values are captured by default per the
/// M4 acceptance criteria — redaction is opt-in and deferred to M5.
/// M4 acceptance criteria; per-target SQL-parameter redaction is applied
/// at write time via <c>AuditLogOptions.PerTargetOverrides.RedactSqlParamsMatching</c>.
/// </summary>
private string? BuildRequestSummary()
{
@@ -520,8 +522,7 @@ internal sealed class AuditingDbCommand : DbCommand
}
// Hand-roll the JSON so we don't pull in System.Text.Json for a
// shape this small. Values are stringified with ToString() — fully
// structured serialisation arrives with the redaction work in M5.
// shape this small. Values are stringified with ToString().
var sb = new System.Text.StringBuilder(sql.Length + 64);
sb.Append("{\"sql\":");
AppendJsonString(sb, sql);
@@ -2013,8 +2013,9 @@ public class ScriptRuntimeContext
// null per Bundle B's pattern rather than fail the emission.
Guid? correlationId = Guid.TryParse(notificationId, out var parsed) ? parsed : (Guid?)null;
// M4 captures the request summary verbatim — {"subject": "...", "body": "..."}.
// M5 will layer redaction / payload-cap enforcement on top.
// Capture the request summary — {"subject": "...", "body": "..."}.
// Payload cap and per-target body redaction are applied at write
// time by the audit redactor (AuditLogOptions / PerTargetRedactionOverride).
var requestSummary = JsonSerializer.Serialize(new
{
subject = subject,
@@ -26,9 +26,8 @@ namespace ZB.MOM.WW.ScadaBridge.Transport.Import;
/// bundle envelope (manifest + content hash + decryption) and opens a
/// session; <see cref="PreviewAsync"/> diffs the bundle's DTOs against the
/// current target database; <see cref="ApplyAsync"/> writes the chosen
/// resolutions through the audited repositories. Only LoadAsync is
/// implemented in this slice — the other two are wired into DI now so
/// follow-up tasks can fill them in without churning the constructor.
/// resolutions through the audited repositories. All three phases are
/// fully implemented.
/// <para>
/// Audit-row responsibility: repository mutation methods in
/// <c>ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories</c> are thin EF wrappers