Compare commits
61 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a1156960b9 | |||
| 5539ec8542 | |||
| 73e54e252d | |||
| 70d959bd9b | |||
| 0c5b796e2e | |||
| 47dc9d865f | |||
| 4f757e3c0c | |||
| 2f0ee4c961 | |||
| 0859d47f75 | |||
| 7ea8358c06 | |||
| a5944bbe5d | |||
| 04bce3ff9f | |||
| 9572045787 | |||
| 7e1af37eb1 | |||
| 05009d7370 | |||
| f4dc11bae4 | |||
| c3b466e13d | |||
| 792e3f9445 | |||
| ae281d06bb | |||
| 3ca2799c90 | |||
| 459a88b3e7 | |||
| 437ab65fc1 | |||
| 679562e5ed | |||
| dbf550da8b | |||
| 3965a7741e | |||
| abb2cfb84b | |||
| 4e0d8ccfed | |||
| a935aa8b7c | |||
| 9912389fa1 | |||
| f1129b969d | |||
| c51b6f9ce4 | |||
| e39972357b | |||
| 9ad17e2964 | |||
| ef0a883a81 | |||
| 62ba5e9487 | |||
| 136614be94 | |||
| a912bffad5 | |||
| 9bdb899774 | |||
| e5c704de69 | |||
| 4e520f9c0c | |||
| 2eb81379e4 | |||
| ddd5721082 | |||
| 3775f6bf3b | |||
| cdfad420bb | |||
| 330e665f6b | |||
| 5e01ad9c22 | |||
| 77a9108673 | |||
| 192607ab8c | |||
| ba82afe669 | |||
| fe7d1ce1ec | |||
| b8a6695612 | |||
| 6f9188bc8d | |||
| a276f46f81 | |||
| 572b268d81 | |||
| 4c093a64fa | |||
| f47bbaea95 | |||
| c463b49f46 | |||
| 87f86503ef | |||
| e912ef960c | |||
| c4e7ddea70 | |||
| 6bfa4fe884 |
@@ -147,3 +147,8 @@ generated-scratch/
|
|||||||
|
|
||||||
# Keep empty directories with .gitkeep files when needed
|
# Keep empty directories with .gitkeep files when needed
|
||||||
!.gitkeep
|
!.gitkeep
|
||||||
|
|
||||||
|
# Documentation review artifacts (CommentChecker output)
|
||||||
|
*-docs-issues.md
|
||||||
|
*-docs-fixed.md
|
||||||
|
*-docs-final.md
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ When source code changes, build and test the affected component before reporting
|
|||||||
## Design Sources To Consult Before Non-Trivial Changes
|
## Design Sources To Consult Before Non-Trivial Changes
|
||||||
|
|
||||||
- `gateway.md` — top-level architecture, command/event surface, IPC envelope, STA thread model, fault handling.
|
- `gateway.md` — top-level architecture, command/event surface, IPC envelope, STA thread model, fault handling.
|
||||||
- `glauth.md` — local LDAP server (GLAuth on `localhost:3893`, base DN `dc=lmxopcua,dc=local`) used for dev authn. Pre-provisioned users (`admin/admin123`, `readonly/readonly123`, etc.) and the role→capability mapping live there.
|
- `glauth.md` — local LDAP server (GLAuth on `localhost:3893`, base DN `dc=zb,dc=local`) used for dev authn. Pre-provisioned users (`admin/admin123`, `readonly/readonly123`, etc.) and the role→capability mapping live there.
|
||||||
- `docs/DesignDecisions.md` — v1 choices (MXAccess COM target `LMXProxyServerClass` from `C:\Program Files (x86)\ArchestrA\Framework\Bin\ArchestrA.MXAccess.dll`, API-key-in-SQLite auth, fail-fast event backpressure, etc.).
|
- `docs/DesignDecisions.md` — v1 choices (MXAccess COM target `LMXProxyServerClass` from `C:\Program Files (x86)\ArchestrA\Framework\Bin\ArchestrA.MXAccess.dll`, API-key-in-SQLite auth, fail-fast event backpressure, etc.).
|
||||||
- `docs/GatewayProcessDesign.md`, `docs/MxAccessWorkerInstanceDesign.md`, `docs/WorkerFrameProtocol.md`, `docs/WorkerProcessLauncher.md` — detailed component designs.
|
- `docs/GatewayProcessDesign.md`, `docs/MxAccessWorkerInstanceDesign.md`, `docs/WorkerFrameProtocol.md`, `docs/WorkerProcessLauncher.md` — detailed component designs.
|
||||||
- `docs/GatewayConfiguration.md` — full `MxGateway:*` options bound by `GatewayOptions` and validated at startup by `GatewayOptionsValidator`.
|
- `docs/GatewayConfiguration.md` — full `MxGateway:*` options bound by `GatewayOptions` and validated at startup by `GatewayOptionsValidator`.
|
||||||
|
|||||||
@@ -107,6 +107,7 @@ public sealed class MxGatewayClientOptions
|
|||||||
public required string ApiKey { get; init; }
|
public required string ApiKey { get; init; }
|
||||||
public bool UseTls { get; init; }
|
public bool UseTls { get; init; }
|
||||||
public string? CaCertificatePath { get; init; }
|
public string? CaCertificatePath { get; init; }
|
||||||
|
public bool RequireCertificateValidation { get; init; }
|
||||||
public string? ServerNameOverride { get; init; }
|
public string? ServerNameOverride { get; init; }
|
||||||
public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(10);
|
public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(10);
|
||||||
public TimeSpan DefaultCallTimeout { get; init; } = TimeSpan.FromSeconds(30);
|
public TimeSpan DefaultCallTimeout { get; init; } = TimeSpan.FromSeconds(30);
|
||||||
@@ -124,6 +125,24 @@ or subscription changes because those calls can partially succeed in MXAccess.
|
|||||||
API key may be loaded from `MXGATEWAY_API_KEY` by the CLI, not implicitly by the
|
API key may be loaded from `MXGATEWAY_API_KEY` by the CLI, not implicitly by the
|
||||||
library constructor unless a helper explicitly says it does that.
|
library constructor unless a helper explicitly says it does that.
|
||||||
|
|
||||||
|
### TLS trust posture
|
||||||
|
|
||||||
|
The gateway can serve a self-signed certificate it generates itself (it has no
|
||||||
|
PKI). To make that usable, TLS is **lenient by default**: when `UseTls` is set
|
||||||
|
and `CaCertificatePath` is empty, `CreateHttpHandler` installs a
|
||||||
|
`RemoteCertificateValidationCallback` that returns `true`, so the gateway's
|
||||||
|
self-signed certificate is accepted without verification.
|
||||||
|
|
||||||
|
To verify the gateway instead:
|
||||||
|
|
||||||
|
- set `CaCertificatePath` to pin a CA — validated via a `CustomRootTrust`
|
||||||
|
`X509Chain` against that root, and the callback additionally rejects a
|
||||||
|
hostname/SAN mismatch (`RemoteCertificateNameMismatch`); or
|
||||||
|
- set `RequireCertificateValidation` to `true` to keep the default OS/system-trust
|
||||||
|
verification on a connection with no pinned CA.
|
||||||
|
|
||||||
|
Pinning a CA always wins over the lenient default.
|
||||||
|
|
||||||
## Auth Interceptor
|
## Auth Interceptor
|
||||||
|
|
||||||
Use a gRPC call credentials/interceptor layer to attach:
|
Use a gRPC call credentials/interceptor layer to attach:
|
||||||
|
|||||||
@@ -287,6 +287,17 @@ Use TLS options for a secured gateway:
|
|||||||
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- smoke --endpoint https://ZB.MOM.WW.MxGateway.example.local:5001 --tls --ca-file C:\certs\mxgateway-ca.pem --server-name ZB.MOM.WW.MxGateway.example.local --api-key-env MXGATEWAY_API_KEY --item Area001.Pump001.Speed --json
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- smoke --endpoint https://ZB.MOM.WW.MxGateway.example.local:5001 --tls --ca-file C:\certs\mxgateway-ca.pem --server-name ZB.MOM.WW.MxGateway.example.local --api-key-env MXGATEWAY_API_KEY --item Area001.Pump001.Speed --json
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### TLS trust
|
||||||
|
|
||||||
|
The gateway can auto-generate its own self-signed certificate (it has no PKI), so
|
||||||
|
the client is **lenient by default**: a TLS connection (`UseTls` / `--tls`) with
|
||||||
|
no pinned CA accepts whatever certificate the gateway presents. To verify
|
||||||
|
instead, pin a CA with `CaCertificatePath` / `--ca-file` (this path also enforces
|
||||||
|
the certificate hostname/SAN match), or set `RequireCertificateValidation` to
|
||||||
|
force OS/system-trust verification without pinning. Use `ServerNameOverride` /
|
||||||
|
`--server-name` when the dialed host differs from the certificate SAN. See
|
||||||
|
[Gateway Configuration](../../docs/GatewayConfiguration.md#automatic-self-signed-certificate).
|
||||||
|
|
||||||
## Integration Checks
|
## Integration Checks
|
||||||
|
|
||||||
Run live checks only when a gateway and MXAccess-backed worker are available:
|
Run live checks only when a gateway and MXAccess-backed worker are available:
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ internal sealed class CliArguments
|
|||||||
|
|
||||||
/// <summary>Returns whether the named flag was present in the arguments.</summary>
|
/// <summary>Returns whether the named flag was present in the arguments.</summary>
|
||||||
/// <param name="name">The flag name (without '--' prefix).</param>
|
/// <param name="name">The flag name (without '--' prefix).</param>
|
||||||
|
/// <returns>True if the flag was present; otherwise false.</returns>
|
||||||
public bool HasFlag(string name)
|
public bool HasFlag(string name)
|
||||||
{
|
{
|
||||||
return _flags.Contains(name);
|
return _flags.Contains(name);
|
||||||
@@ -51,6 +52,7 @@ internal sealed class CliArguments
|
|||||||
|
|
||||||
/// <summary>Returns the value for a named argument, or <c>null</c> if absent.</summary>
|
/// <summary>Returns the value for a named argument, or <c>null</c> if absent.</summary>
|
||||||
/// <param name="name">The argument name (without '--' prefix).</param>
|
/// <param name="name">The argument name (without '--' prefix).</param>
|
||||||
|
/// <returns>The argument value, or null if the argument was not provided.</returns>
|
||||||
public string? GetOptional(string name)
|
public string? GetOptional(string name)
|
||||||
{
|
{
|
||||||
return _values.TryGetValue(name, out string? value)
|
return _values.TryGetValue(name, out string? value)
|
||||||
@@ -60,6 +62,7 @@ internal sealed class CliArguments
|
|||||||
|
|
||||||
/// <summary>Returns the value for a required named argument, or throws if absent.</summary>
|
/// <summary>Returns the value for a required named argument, or throws if absent.</summary>
|
||||||
/// <param name="name">The argument name (without '--' prefix).</param>
|
/// <param name="name">The argument name (without '--' prefix).</param>
|
||||||
|
/// <returns>The argument value.</returns>
|
||||||
public string GetRequired(string name)
|
public string GetRequired(string name)
|
||||||
{
|
{
|
||||||
string? value = GetOptional(name);
|
string? value = GetOptional(name);
|
||||||
@@ -74,6 +77,7 @@ internal sealed class CliArguments
|
|||||||
/// <summary>Parses and returns an int32 argument, or the default value if absent.</summary>
|
/// <summary>Parses and returns an int32 argument, or the default value if absent.</summary>
|
||||||
/// <param name="name">The argument name (without '--' prefix).</param>
|
/// <param name="name">The argument name (without '--' prefix).</param>
|
||||||
/// <param name="defaultValue">The default value if the argument is absent; if <c>null</c>, the argument is required.</param>
|
/// <param name="defaultValue">The default value if the argument is absent; if <c>null</c>, the argument is required.</param>
|
||||||
|
/// <returns>The parsed int32 value, or the default if absent.</returns>
|
||||||
public int GetInt32(string name, int? defaultValue = null)
|
public int GetInt32(string name, int? defaultValue = null)
|
||||||
{
|
{
|
||||||
string? value = GetOptional(name);
|
string? value = GetOptional(name);
|
||||||
@@ -93,6 +97,7 @@ internal sealed class CliArguments
|
|||||||
/// <summary>Parses and returns a uint32 argument, or the default value if absent.</summary>
|
/// <summary>Parses and returns a uint32 argument, or the default value if absent.</summary>
|
||||||
/// <param name="name">The argument name (without '--' prefix).</param>
|
/// <param name="name">The argument name (without '--' prefix).</param>
|
||||||
/// <param name="defaultValue">The default value if the argument is absent.</param>
|
/// <param name="defaultValue">The default value if the argument is absent.</param>
|
||||||
|
/// <returns>The parsed uint32 value, or the default if absent.</returns>
|
||||||
public uint GetUInt32(string name, uint defaultValue)
|
public uint GetUInt32(string name, uint defaultValue)
|
||||||
{
|
{
|
||||||
string? value = GetOptional(name);
|
string? value = GetOptional(name);
|
||||||
@@ -104,6 +109,7 @@ internal sealed class CliArguments
|
|||||||
/// <summary>Parses and returns a uint64 argument, or the default value if absent.</summary>
|
/// <summary>Parses and returns a uint64 argument, or the default value if absent.</summary>
|
||||||
/// <param name="name">The argument name (without '--' prefix).</param>
|
/// <param name="name">The argument name (without '--' prefix).</param>
|
||||||
/// <param name="defaultValue">The default value if the argument is absent.</param>
|
/// <param name="defaultValue">The default value if the argument is absent.</param>
|
||||||
|
/// <returns>The parsed uint64 value, or the default if absent.</returns>
|
||||||
public ulong GetUInt64(string name, ulong defaultValue)
|
public ulong GetUInt64(string name, ulong defaultValue)
|
||||||
{
|
{
|
||||||
string? value = GetOptional(name);
|
string? value = GetOptional(name);
|
||||||
@@ -115,6 +121,7 @@ internal sealed class CliArguments
|
|||||||
/// <summary>Parses and returns a TimeSpan argument, or the default value if absent. Supports "ms", "s", and standard TimeSpan format.</summary>
|
/// <summary>Parses and returns a TimeSpan argument, or the default value if absent. Supports "ms", "s", and standard TimeSpan format.</summary>
|
||||||
/// <param name="name">The argument name (without '--' prefix).</param>
|
/// <param name="name">The argument name (without '--' prefix).</param>
|
||||||
/// <param name="defaultValue">The default value if the argument is absent.</param>
|
/// <param name="defaultValue">The default value if the argument is absent.</param>
|
||||||
|
/// <returns>The parsed TimeSpan value, or the default if absent.</returns>
|
||||||
public TimeSpan GetDuration(string name, TimeSpan defaultValue)
|
public TimeSpan GetDuration(string name, TimeSpan defaultValue)
|
||||||
{
|
{
|
||||||
string? value = GetOptional(name);
|
string? value = GetOptional(name);
|
||||||
|
|||||||
@@ -100,7 +100,8 @@ internal sealed class MxGatewayCliClientAdapter : IMxGatewayCliClient
|
|||||||
return _galaxyClient.Value.WatchDeployEventsRawAsync(request, cancellationToken);
|
return _galaxyClient.Value.WatchDeployEventsRawAsync(request, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <summary>Disposes the galaxy client (if created) and the underlying gateway client.</summary>
|
||||||
|
/// <returns>A value task that completes when both clients are disposed.</returns>
|
||||||
public async ValueTask DisposeAsync()
|
public async ValueTask DisposeAsync()
|
||||||
{
|
{
|
||||||
if (_galaxyClient.IsValueCreated)
|
if (_galaxyClient.IsValueCreated)
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ internal static class MxGatewayCliSecretRedactor
|
|||||||
/// <summary>Replaces occurrences of the API key in the value with a redacted placeholder.</summary>
|
/// <summary>Replaces occurrences of the API key in the value with a redacted placeholder.</summary>
|
||||||
/// <param name="value">The message text to redact.</param>
|
/// <param name="value">The message text to redact.</param>
|
||||||
/// <param name="apiKey">The API key to remove; no redaction if null or empty.</param>
|
/// <param name="apiKey">The API key to remove; no redaction if null or empty.</param>
|
||||||
|
/// <returns>The message text with any API key occurrence replaced by <c>[redacted]</c>.</returns>
|
||||||
public static string Redact(string value, string? apiKey)
|
public static string Redact(string value, string? apiKey)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(apiKey))
|
if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(apiKey))
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ public static class MxGatewayClientCli
|
|||||||
/// <param name="args">Command-line arguments (command name followed by options).</param>
|
/// <param name="args">Command-line arguments (command name followed by options).</param>
|
||||||
/// <param name="standardOutput">TextWriter for command output.</param>
|
/// <param name="standardOutput">TextWriter for command output.</param>
|
||||||
/// <param name="standardError">TextWriter for error messages.</param>
|
/// <param name="standardError">TextWriter for error messages.</param>
|
||||||
|
/// <returns>The process exit code (0 for success, 1 for error).</returns>
|
||||||
public static int Run(
|
public static int Run(
|
||||||
string[] args,
|
string[] args,
|
||||||
TextWriter standardOutput,
|
TextWriter standardOutput,
|
||||||
@@ -38,6 +39,7 @@ public static class MxGatewayClientCli
|
|||||||
/// <param name="standardError">TextWriter for error messages.</param>
|
/// <param name="standardError">TextWriter for error messages.</param>
|
||||||
/// <param name="clientFactory">Optional factory to create the gateway client; defaults to MxGatewayClient.Create.</param>
|
/// <param name="clientFactory">Optional factory to create the gateway client; defaults to MxGatewayClient.Create.</param>
|
||||||
/// <param name="standardInput">Optional TextReader for batch-mode stdin; defaults to <see cref="Console.In"/>.</param>
|
/// <param name="standardInput">Optional TextReader for batch-mode stdin; defaults to <see cref="Console.In"/>.</param>
|
||||||
|
/// <returns>A task that resolves to the process exit code (0 for success, 1 for error).</returns>
|
||||||
public static Task<int> RunAsync(
|
public static Task<int> RunAsync(
|
||||||
string[] args,
|
string[] args,
|
||||||
TextWriter standardOutput,
|
TextWriter standardOutput,
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ public sealed class BrowseChildrenSmokeTests
|
|||||||
/// Verifies that BrowseChildren returns a non-zero cache sequence and
|
/// Verifies that BrowseChildren returns a non-zero cache sequence and
|
||||||
/// a consistent children/child-has-children count from a live gateway.
|
/// a consistent children/child-has-children count from a live gateway.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact(Skip = "Set MXGATEWAY_API_KEY and MXGATEWAY_ENDPOINT to enable.")]
|
[Fact(Skip = "Set MXGATEWAY_API_KEY and MXGATEWAY_ENDPOINT to enable.")]
|
||||||
public async Task BrowseChildren_LiveGateway_ReturnsRootsWithCacheSequence()
|
public async Task BrowseChildren_LiveGateway_ReturnsRootsWithCacheSequence()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -8,14 +8,10 @@ namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed class FakeGalaxyRepositoryTransport(MxGatewayClientOptions options) : IGalaxyRepositoryClientTransport
|
internal sealed class FakeGalaxyRepositoryTransport(MxGatewayClientOptions options) : IGalaxyRepositoryClientTransport
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Gets the gateway client options.
|
|
||||||
/// </summary>
|
|
||||||
public MxGatewayClientOptions Options { get; } = options;
|
public MxGatewayClientOptions Options { get; } = options;
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Gets the raw gRPC client; always null for the fake.
|
|
||||||
/// </summary>
|
|
||||||
public GalaxyRepository.GalaxyRepositoryClient? RawClient => null;
|
public GalaxyRepository.GalaxyRepositoryClient? RawClient => null;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -66,11 +62,7 @@ internal sealed class FakeGalaxyRepositoryTransport(MxGatewayClientOptions optio
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public Queue<Exception> DiscoverHierarchyExceptions { get; } = new();
|
public Queue<Exception> DiscoverHierarchyExceptions { get; } = new();
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Records the request and either throws a queued exception or returns the configured reply.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request">The TestConnectionRequest to process.</param>
|
|
||||||
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
|
||||||
public Task<TestConnectionReply> TestConnectionAsync(
|
public Task<TestConnectionReply> TestConnectionAsync(
|
||||||
TestConnectionRequest request,
|
TestConnectionRequest request,
|
||||||
CallOptions callOptions)
|
CallOptions callOptions)
|
||||||
@@ -84,11 +76,7 @@ internal sealed class FakeGalaxyRepositoryTransport(MxGatewayClientOptions optio
|
|||||||
return Task.FromResult(TestConnectionReply);
|
return Task.FromResult(TestConnectionReply);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Records the request and either throws a queued exception or returns the configured reply.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request">The GetLastDeployTimeRequest to process.</param>
|
|
||||||
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
|
||||||
public Task<GetLastDeployTimeReply> GetLastDeployTimeAsync(
|
public Task<GetLastDeployTimeReply> GetLastDeployTimeAsync(
|
||||||
GetLastDeployTimeRequest request,
|
GetLastDeployTimeRequest request,
|
||||||
CallOptions callOptions)
|
CallOptions callOptions)
|
||||||
@@ -102,11 +90,7 @@ internal sealed class FakeGalaxyRepositoryTransport(MxGatewayClientOptions optio
|
|||||||
return Task.FromResult(GetLastDeployTimeReply);
|
return Task.FromResult(GetLastDeployTimeReply);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Records the request and either throws a queued exception or returns the configured reply.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request">The DiscoverHierarchyRequest to process.</param>
|
|
||||||
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
|
||||||
public Task<DiscoverHierarchyReply> DiscoverHierarchyAsync(
|
public Task<DiscoverHierarchyReply> DiscoverHierarchyAsync(
|
||||||
DiscoverHierarchyRequest request,
|
DiscoverHierarchyRequest request,
|
||||||
CallOptions callOptions)
|
CallOptions callOptions)
|
||||||
@@ -135,11 +119,7 @@ internal sealed class FakeGalaxyRepositoryTransport(MxGatewayClientOptions optio
|
|||||||
/// <summary>Queue of exceptions to throw from BrowseChildren; dequeued in FIFO order.</summary>
|
/// <summary>Queue of exceptions to throw from BrowseChildren; dequeued in FIFO order.</summary>
|
||||||
public Queue<Exception> BrowseChildrenExceptions { get; } = new();
|
public Queue<Exception> BrowseChildrenExceptions { get; } = new();
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Records the request and either throws a queued exception or returns the configured reply.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request">The BrowseChildrenRequest to process.</param>
|
|
||||||
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
|
||||||
public Task<BrowseChildrenReply> BrowseChildrenAsync(
|
public Task<BrowseChildrenReply> BrowseChildrenAsync(
|
||||||
BrowseChildrenRequest request,
|
BrowseChildrenRequest request,
|
||||||
CallOptions callOptions)
|
CallOptions callOptions)
|
||||||
@@ -177,11 +157,7 @@ internal sealed class FakeGalaxyRepositoryTransport(MxGatewayClientOptions optio
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public Func<CancellationToken, Task>? WatchDeployEventsBeforeYield { get; set; }
|
public Func<CancellationToken, Task>? WatchDeployEventsBeforeYield { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Records the request and streams events, checking for queued exceptions and calling WatchDeployEventsBeforeYield before each event.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request">The WatchDeployEventsRequest to process.</param>
|
|
||||||
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
|
||||||
public async IAsyncEnumerable<DeployEvent> WatchDeployEventsAsync(
|
public async IAsyncEnumerable<DeployEvent> WatchDeployEventsAsync(
|
||||||
WatchDeployEventsRequest request,
|
WatchDeployEventsRequest request,
|
||||||
CallOptions callOptions)
|
CallOptions callOptions)
|
||||||
|
|||||||
@@ -11,14 +11,10 @@ internal sealed class FakeGatewayTransport(MxGatewayClientOptions options) : IMx
|
|||||||
private readonly Queue<MxCommandReply> _invokeReplies = new();
|
private readonly Queue<MxCommandReply> _invokeReplies = new();
|
||||||
private readonly List<MxEvent> _events = [];
|
private readonly List<MxEvent> _events = [];
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Gets the gateway client options.
|
|
||||||
/// </summary>
|
|
||||||
public MxGatewayClientOptions Options { get; } = options;
|
public MxGatewayClientOptions Options { get; } = options;
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Gets null, since this is a test fake without a real gRPC client.
|
|
||||||
/// </summary>
|
|
||||||
public MxAccessGateway.MxAccessGatewayClient? RawClient => null;
|
public MxAccessGateway.MxAccessGatewayClient? RawClient => null;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -102,11 +98,7 @@ internal sealed class FakeGatewayTransport(MxGatewayClientOptions options) : IMx
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public Queue<Exception> InvokeExceptions { get; } = new();
|
public Queue<Exception> InvokeExceptions { get; } = new();
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Verifies that the OpenSessionAsync call is recorded and returns the configured reply.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request">The OpenSessionRequest to process.</param>
|
|
||||||
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
|
||||||
public Task<OpenSessionReply> OpenSessionAsync(
|
public Task<OpenSessionReply> OpenSessionAsync(
|
||||||
OpenSessionRequest request,
|
OpenSessionRequest request,
|
||||||
CallOptions callOptions)
|
CallOptions callOptions)
|
||||||
@@ -120,11 +112,7 @@ internal sealed class FakeGatewayTransport(MxGatewayClientOptions options) : IMx
|
|||||||
return Task.FromResult(OpenSessionReply);
|
return Task.FromResult(OpenSessionReply);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Verifies that the CloseSessionAsync call is recorded and returns the configured reply.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request">The CloseSessionRequest to process.</param>
|
|
||||||
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
|
||||||
public Task<CloseSessionReply> CloseSessionAsync(
|
public Task<CloseSessionReply> CloseSessionAsync(
|
||||||
CloseSessionRequest request,
|
CloseSessionRequest request,
|
||||||
CallOptions callOptions)
|
CallOptions callOptions)
|
||||||
@@ -138,11 +126,7 @@ internal sealed class FakeGatewayTransport(MxGatewayClientOptions options) : IMx
|
|||||||
return Task.FromResult(CloseSessionReply);
|
return Task.FromResult(CloseSessionReply);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Verifies that the InvokeAsync call is recorded and returns the next enqueued reply.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request">The MxCommandRequest to process.</param>
|
|
||||||
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
|
||||||
public Task<MxCommandReply> InvokeAsync(
|
public Task<MxCommandReply> InvokeAsync(
|
||||||
MxCommandRequest request,
|
MxCommandRequest request,
|
||||||
CallOptions callOptions)
|
CallOptions callOptions)
|
||||||
@@ -156,11 +140,7 @@ internal sealed class FakeGatewayTransport(MxGatewayClientOptions options) : IMx
|
|||||||
return Task.FromResult(_invokeReplies.Dequeue());
|
return Task.FromResult(_invokeReplies.Dequeue());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Verifies that the StreamEventsAsync call is recorded and yields all enqueued events.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request">The StreamEventsRequest to process.</param>
|
|
||||||
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
|
||||||
public async IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
public async IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
||||||
StreamEventsRequest request,
|
StreamEventsRequest request,
|
||||||
CallOptions callOptions)
|
CallOptions callOptions)
|
||||||
@@ -193,11 +173,7 @@ internal sealed class FakeGatewayTransport(MxGatewayClientOptions options) : IMx
|
|||||||
_events.Add(gatewayEvent);
|
_events.Add(gatewayEvent);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Records the acknowledge call and returns the next enqueued reply (or default).
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request">The acknowledge alarm request.</param>
|
|
||||||
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
|
||||||
public Task<AcknowledgeAlarmReply> AcknowledgeAlarmAsync(
|
public Task<AcknowledgeAlarmReply> AcknowledgeAlarmAsync(
|
||||||
AcknowledgeAlarmRequest request,
|
AcknowledgeAlarmRequest request,
|
||||||
CallOptions callOptions)
|
CallOptions callOptions)
|
||||||
@@ -218,11 +194,7 @@ internal sealed class FakeGatewayTransport(MxGatewayClientOptions options) : IMx
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Records the query call and yields each enqueued snapshot.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request">The query active alarms request.</param>
|
|
||||||
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
|
||||||
public async IAsyncEnumerable<ActiveAlarmSnapshot> QueryActiveAlarmsAsync(
|
public async IAsyncEnumerable<ActiveAlarmSnapshot> QueryActiveAlarmsAsync(
|
||||||
QueryActiveAlarmsRequest request,
|
QueryActiveAlarmsRequest request,
|
||||||
CallOptions callOptions)
|
CallOptions callOptions)
|
||||||
@@ -251,11 +223,7 @@ internal sealed class FakeGatewayTransport(MxGatewayClientOptions options) : IMx
|
|||||||
_activeAlarmSnapshots.Add(snapshot);
|
_activeAlarmSnapshots.Add(snapshot);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Records the stream-alarms call and yields each enqueued feed message.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request">The stream alarms request.</param>
|
|
||||||
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
|
||||||
public async IAsyncEnumerable<AlarmFeedMessage> StreamAlarmsAsync(
|
public async IAsyncEnumerable<AlarmFeedMessage> StreamAlarmsAsync(
|
||||||
StreamAlarmsRequest request,
|
StreamAlarmsRequest request,
|
||||||
CallOptions callOptions)
|
CallOptions callOptions)
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that TestConnectionAsync attaches the API key in request metadata and returns the Ok flag.
|
/// Verifies that TestConnectionAsync attaches the API key in request metadata and returns the Ok flag.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task TestConnectionAsync_AttachesApiKeyMetadataAndReturnsOkFlag()
|
public async Task TestConnectionAsync_AttachesApiKeyMetadataAndReturnsOkFlag()
|
||||||
{
|
{
|
||||||
@@ -27,6 +28,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that TestConnectionAsync returns false when the server reports NotOk.
|
/// Verifies that TestConnectionAsync returns false when the server reports NotOk.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task TestConnectionAsync_ReturnsFalseWhenServerReportsNotOk()
|
public async Task TestConnectionAsync_ReturnsFalseWhenServerReportsNotOk()
|
||||||
{
|
{
|
||||||
@@ -42,6 +44,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that GetLastDeployTimeAsync returns null when the server reports not present.
|
/// Verifies that GetLastDeployTimeAsync returns null when the server reports not present.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task GetLastDeployTimeAsync_ReturnsNullWhenNotPresent()
|
public async Task GetLastDeployTimeAsync_ReturnsNullWhenNotPresent()
|
||||||
{
|
{
|
||||||
@@ -58,6 +61,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that GetLastDeployTimeAsync returns the timestamp when the server reports it present.
|
/// Verifies that GetLastDeployTimeAsync returns the timestamp when the server reports it present.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task GetLastDeployTimeAsync_ReturnsTimestampWhenPresent()
|
public async Task GetLastDeployTimeAsync_ReturnsTimestampWhenPresent()
|
||||||
{
|
{
|
||||||
@@ -79,6 +83,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that DiscoverHierarchyAsync returns the objects from the server reply.
|
/// Verifies that DiscoverHierarchyAsync returns the objects from the server reply.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task DiscoverHierarchyAsync_ReturnsObjectsFromReply()
|
public async Task DiscoverHierarchyAsync_ReturnsObjectsFromReply()
|
||||||
{
|
{
|
||||||
@@ -141,6 +146,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that DiscoverHierarchyAsync propagates cancellation tokens to the transport.
|
/// Verifies that DiscoverHierarchyAsync propagates cancellation tokens to the transport.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task DiscoverHierarchyAsync_PropagatesCancellationToTransport()
|
public async Task DiscoverHierarchyAsync_PropagatesCancellationToTransport()
|
||||||
{
|
{
|
||||||
@@ -161,6 +167,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that TestConnectionAsync retries on transient gRPC failures.
|
/// Verifies that TestConnectionAsync retries on transient gRPC failures.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task DiscoverHierarchyAsync_WithRepeatedPageToken_ThrowsProtocolError()
|
public async Task DiscoverHierarchyAsync_WithRepeatedPageToken_ThrowsProtocolError()
|
||||||
{
|
{
|
||||||
@@ -184,6 +191,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that DiscoverHierarchyAsync maps typed filter options correctly to the request.
|
/// Verifies that DiscoverHierarchyAsync maps typed filter options correctly to the request.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task DiscoverHierarchyAsync_WithOptions_MapsTypedFilters()
|
public async Task DiscoverHierarchyAsync_WithOptions_MapsTypedFilters()
|
||||||
{
|
{
|
||||||
@@ -218,6 +226,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that TestConnectionAsync retries on transient gRPC failures.
|
/// Verifies that TestConnectionAsync retries on transient gRPC failures.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task TestConnectionAsync_RetriesOnTransientGrpcFailure()
|
public async Task TestConnectionAsync_RetriesOnTransientGrpcFailure()
|
||||||
{
|
{
|
||||||
@@ -235,6 +244,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that DiscoverHierarchyAsync retries on transient gRPC failures.
|
/// Verifies that DiscoverHierarchyAsync retries on transient gRPC failures.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task DiscoverHierarchyAsync_RetriesOnTransientGrpcFailure()
|
public async Task DiscoverHierarchyAsync_RetriesOnTransientGrpcFailure()
|
||||||
{
|
{
|
||||||
@@ -251,6 +261,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that WatchDeployEventsAsync delivers the bootstrap event.
|
/// Verifies that WatchDeployEventsAsync delivers the bootstrap event.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task WatchDeployEventsAsync_DeliversBootstrapEvent()
|
public async Task WatchDeployEventsAsync_DeliversBootstrapEvent()
|
||||||
{
|
{
|
||||||
@@ -287,6 +298,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that WatchDeployEventsAsync delivers multiple events in order.
|
/// Verifies that WatchDeployEventsAsync delivers multiple events in order.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task WatchDeployEventsAsync_DeliversMultipleEventsInOrder()
|
public async Task WatchDeployEventsAsync_DeliversMultipleEventsInOrder()
|
||||||
{
|
{
|
||||||
@@ -325,6 +337,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that WatchDeployEventsAsync stops iteration cleanly when cancelled.
|
/// Verifies that WatchDeployEventsAsync stops iteration cleanly when cancelled.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task WatchDeployEventsAsync_CancellationStopsIterationCleanly()
|
public async Task WatchDeployEventsAsync_CancellationStopsIterationCleanly()
|
||||||
{
|
{
|
||||||
@@ -369,6 +382,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that WatchDeployEventsAsync throws ObjectDisposedException after the client is disposed.
|
/// Verifies that WatchDeployEventsAsync throws ObjectDisposedException after the client is disposed.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task WatchDeployEventsAsync_ThrowsAfterDisposal()
|
public async Task WatchDeployEventsAsync_ThrowsAfterDisposal()
|
||||||
{
|
{
|
||||||
@@ -384,6 +398,7 @@ public sealed class GalaxyRepositoryClientTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that TestConnectionAsync throws ObjectDisposedException after the client is disposed.
|
/// Verifies that TestConnectionAsync throws ObjectDisposedException after the client is disposed.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task TestConnectionAsync_ThrowsAfterDisposal()
|
public async Task TestConnectionAsync_ThrowsAfterDisposal()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ public sealed class LazyBrowseNodeTests
|
|||||||
/// Verifies that calling BrowseAsync with no parent returns the root nodes
|
/// Verifies that calling BrowseAsync with no parent returns the root nodes
|
||||||
/// from the first BrowseChildren reply and surfaces the per-child has-children hint.
|
/// from the first BrowseChildren reply and surfaces the per-child has-children hint.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Browse_NoParent_ReturnsRoots()
|
public async Task Browse_NoParent_ReturnsRoots()
|
||||||
{
|
{
|
||||||
@@ -36,6 +37,7 @@ public sealed class LazyBrowseNodeTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that ExpandAsync populates Children and marks the node expanded after one RPC.
|
/// Verifies that ExpandAsync populates Children and marks the node expanded after one RPC.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Expand_PopulatesChildrenAndMarksExpanded()
|
public async Task Expand_PopulatesChildrenAndMarksExpanded()
|
||||||
{
|
{
|
||||||
@@ -62,6 +64,7 @@ public sealed class LazyBrowseNodeTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that a second ExpandAsync call is a no-op and issues no additional RPC.
|
/// Verifies that a second ExpandAsync call is a no-op and issues no additional RPC.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Expand_CalledTwice_NoSecondRpc()
|
public async Task Expand_CalledTwice_NoSecondRpc()
|
||||||
{
|
{
|
||||||
@@ -86,6 +89,7 @@ public sealed class LazyBrowseNodeTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that an RPC failure (NotFound) during expand is wrapped in MxGatewayException.
|
/// Verifies that an RPC failure (NotFound) during expand is wrapped in MxGatewayException.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Expand_UnknownParent_ThrowsMxGatewayException()
|
public async Task Expand_UnknownParent_ThrowsMxGatewayException()
|
||||||
{
|
{
|
||||||
@@ -113,6 +117,7 @@ public sealed class LazyBrowseNodeTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that ExpandAsync drains multi-page sibling replies and forwards the page token.
|
/// Verifies that ExpandAsync drains multi-page sibling replies and forwards the page token.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Expand_MultiPageSiblings_GathersAllPages()
|
public async Task Expand_MultiPageSiblings_GathersAllPages()
|
||||||
{
|
{
|
||||||
@@ -147,6 +152,7 @@ public sealed class LazyBrowseNodeTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that ten concurrent ExpandAsync calls issue exactly one RPC, not ten.
|
/// Verifies that ten concurrent ExpandAsync calls issue exactly one RPC, not ten.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Expand_CalledConcurrently_OnlyFiresOneRpc()
|
public async Task Expand_CalledConcurrently_OnlyFiresOneRpc()
|
||||||
{
|
{
|
||||||
@@ -178,6 +184,7 @@ public sealed class LazyBrowseNodeTests
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that BrowseChildrenOptions filter fields are forwarded to the BrowseChildren request.
|
/// Verifies that BrowseChildrenOptions filter fields are forwarded to the BrowseChildren request.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Browse_WithFilter_ForwardsToRequest()
|
public async Task Browse_WithFilter_ForwardsToRequest()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
|||||||
public sealed class MxGatewayClientAlarmsTests
|
public sealed class MxGatewayClientAlarmsTests
|
||||||
{
|
{
|
||||||
/// <summary>AcknowledgeAlarmAsync records request and returns reply.</summary>
|
/// <summary>AcknowledgeAlarmAsync records request and returns reply.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task AcknowledgeAlarmAsync_RecordsRequestShapeAndReturnsReply()
|
public async Task AcknowledgeAlarmAsync_RecordsRequestShapeAndReturnsReply()
|
||||||
{
|
{
|
||||||
@@ -48,6 +49,7 @@ public sealed class MxGatewayClientAlarmsTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>AcknowledgeAlarmAsync honors cancellation.</summary>
|
/// <summary>AcknowledgeAlarmAsync honors cancellation.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task AcknowledgeAlarmAsync_HonorsCancellation()
|
public async Task AcknowledgeAlarmAsync_HonorsCancellation()
|
||||||
{
|
{
|
||||||
@@ -72,6 +74,7 @@ public sealed class MxGatewayClientAlarmsTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>AcknowledgeAlarmAsync maps unauthenticated RPC exception to typed exception.</summary>
|
/// <summary>AcknowledgeAlarmAsync maps unauthenticated RPC exception to typed exception.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task AcknowledgeAlarmAsync_MapsUnauthenticated_RpcException_ToTypedException()
|
public async Task AcknowledgeAlarmAsync_MapsUnauthenticated_RpcException_ToTypedException()
|
||||||
{
|
{
|
||||||
@@ -97,6 +100,7 @@ public sealed class MxGatewayClientAlarmsTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>QueryActiveAlarmsAsync streams enqueued snapshots.</summary>
|
/// <summary>QueryActiveAlarmsAsync streams enqueued snapshots.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task QueryActiveAlarmsAsync_StreamsEnqueuedSnapshots()
|
public async Task QueryActiveAlarmsAsync_StreamsEnqueuedSnapshots()
|
||||||
{
|
{
|
||||||
@@ -122,6 +126,7 @@ public sealed class MxGatewayClientAlarmsTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>QueryActiveAlarmsAsync passes filter prefix.</summary>
|
/// <summary>QueryActiveAlarmsAsync passes filter prefix.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task QueryActiveAlarmsAsync_PassesFilterPrefix()
|
public async Task QueryActiveAlarmsAsync_PassesFilterPrefix()
|
||||||
{
|
{
|
||||||
@@ -142,6 +147,7 @@ public sealed class MxGatewayClientAlarmsTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>QueryActiveAlarmsAsync honors cancellation during enumeration.</summary>
|
/// <summary>QueryActiveAlarmsAsync honors cancellation during enumeration.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task QueryActiveAlarmsAsync_HonorsCancellationDuringEnumeration()
|
public async Task QueryActiveAlarmsAsync_HonorsCancellationDuringEnumeration()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that the version command with --json flag prints JSON protocol versions.</summary>
|
/// <summary>Verifies that the version command with --json flag prints JSON protocol versions.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_VersionJson_PrintsJsonProtocolVersions()
|
public async Task RunAsync_VersionJson_PrintsJsonProtocolVersions()
|
||||||
{
|
{
|
||||||
@@ -38,6 +39,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that the write command builds a write request and prints JSON reply.</summary>
|
/// <summary>Verifies that the write command builds a write request and prints JSON reply.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_Write_BuildsWriteCommandAndPrintsJsonReply()
|
public async Task RunAsync_Write_BuildsWriteCommandAndPrintsJsonReply()
|
||||||
{
|
{
|
||||||
@@ -83,6 +85,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that error output redacts sensitive API key values.</summary>
|
/// <summary>Verifies that error output redacts sensitive API key values.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_ErrorOutput_RedactsApiKey()
|
public async Task RunAsync_ErrorOutput_RedactsApiKey()
|
||||||
{
|
{
|
||||||
@@ -107,6 +110,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that stream-events with max-events limit stops output in non-JSON format.</summary>
|
/// <summary>Verifies that stream-events with max-events limit stops output in non-JSON format.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_StreamEvents_WithMaxEventsStopsNonJsonOutput()
|
public async Task RunAsync_StreamEvents_WithMaxEventsStopsNonJsonOutput()
|
||||||
{
|
{
|
||||||
@@ -149,6 +153,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
|
|
||||||
|
|
||||||
/// <summary>Verifies that stream-alarms with --max-events stops output and distinguishes payload cases.</summary>
|
/// <summary>Verifies that stream-alarms with --max-events stops output and distinguishes payload cases.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_StreamAlarms_WithMaxEventsStopsAndDistinguishesPayloadCases()
|
public async Task RunAsync_StreamAlarms_WithMaxEventsStopsAndDistinguishesPayloadCases()
|
||||||
{
|
{
|
||||||
@@ -188,6 +193,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that acknowledge-alarm builds a request and prints the JSON reply.</summary>
|
/// <summary>Verifies that acknowledge-alarm builds a request and prints the JSON reply.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_AcknowledgeAlarm_BuildsRequestAndPrintsJsonReply()
|
public async Task RunAsync_AcknowledgeAlarm_BuildsRequestAndPrintsJsonReply()
|
||||||
{
|
{
|
||||||
@@ -230,6 +236,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that smoke command closes opened session when a command fails.</summary>
|
/// <summary>Verifies that smoke command closes opened session when a command fails.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_Smoke_WhenCommandFails_ClosesOpenedSession()
|
public async Task RunAsync_Smoke_WhenCommandFails_ClosesOpenedSession()
|
||||||
{
|
{
|
||||||
@@ -261,6 +268,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that galaxy-test-connection command prints JSON reply.</summary>
|
/// <summary>Verifies that galaxy-test-connection command prints JSON reply.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_GalaxyTestConnection_PrintsJsonReply()
|
public async Task RunAsync_GalaxyTestConnection_PrintsJsonReply()
|
||||||
{
|
{
|
||||||
@@ -291,6 +299,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that galaxy-discover command prints hierarchy summary.</summary>
|
/// <summary>Verifies that galaxy-discover command prints hierarchy summary.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_GalaxyDiscover_PrintsHierarchySummary()
|
public async Task RunAsync_GalaxyDiscover_PrintsHierarchySummary()
|
||||||
{
|
{
|
||||||
@@ -361,6 +370,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that galaxy-watch command prints text output for deploy events.</summary>
|
/// <summary>Verifies that galaxy-watch command prints text output for deploy events.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_GalaxyWatch_PrintsTextOutputForEvents()
|
public async Task RunAsync_GalaxyWatch_PrintsTextOutputForEvents()
|
||||||
{
|
{
|
||||||
@@ -415,6 +425,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that galaxy-watch with --json emits one JSON object per event.</summary>
|
/// <summary>Verifies that galaxy-watch with --json emits one JSON object per event.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_GalaxyWatch_JsonEmitsOneObjectPerEvent()
|
public async Task RunAsync_GalaxyWatch_JsonEmitsOneObjectPerEvent()
|
||||||
{
|
{
|
||||||
@@ -450,6 +461,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that batch mode dispatches a single version command and emits the EOR sentinel.</summary>
|
/// <summary>Verifies that batch mode dispatches a single version command and emits the EOR sentinel.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_Batch_DispatchesVersionAndWritesEndOfRecord()
|
public async Task RunAsync_Batch_DispatchesVersionAndWritesEndOfRecord()
|
||||||
{
|
{
|
||||||
@@ -476,6 +488,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that batch mode routes per-command errors to stdout as JSON between EOR markers.</summary>
|
/// <summary>Verifies that batch mode routes per-command errors to stdout as JSON between EOR markers.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_Batch_WritesErrorsToStdoutAsJson()
|
public async Task RunAsync_Batch_WritesErrorsToStdoutAsJson()
|
||||||
{
|
{
|
||||||
@@ -520,6 +533,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
/// against exit code 0.
|
/// against exit code 0.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="command">The alarm subcommand to validate (e.g. "stream-alarms", "acknowledge-alarm").</param>
|
/// <param name="command">The alarm subcommand to validate (e.g. "stream-alarms", "acknowledge-alarm").</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("stream-alarms")]
|
[InlineData("stream-alarms")]
|
||||||
[InlineData("acknowledge-alarm")]
|
[InlineData("acknowledge-alarm")]
|
||||||
@@ -574,6 +588,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
/// against a zero server handle. The fix must fail loudly with a
|
/// against a zero server handle. The fix must fail loudly with a
|
||||||
/// descriptive <see cref="MxGatewayException"/>.
|
/// descriptive <see cref="MxGatewayException"/>.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_BenchReadBulk_WhenRegisterReplyMissingTypedPayload_FailsLoudly()
|
public async Task RunAsync_BenchReadBulk_WhenRegisterReplyMissingTypedPayload_FailsLoudly()
|
||||||
{
|
{
|
||||||
@@ -624,6 +639,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
/// kept spinning until <c>--duration-seconds</c> elapsed. After the fix
|
/// kept spinning until <c>--duration-seconds</c> elapsed. After the fix
|
||||||
/// the bench must exit promptly when the supplied token cancels.
|
/// the bench must exit promptly when the supplied token cancels.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RunAsync_BenchReadBulk_WhenSteadyStateLoopReceivesCancellation_ExitsPromptly()
|
public async Task RunAsync_BenchReadBulk_WhenSteadyStateLoopReceivesCancellation_ExitsPromptly()
|
||||||
{
|
{
|
||||||
@@ -718,6 +734,7 @@ public sealed class MxGatewayClientCliTests
|
|||||||
/// to ~49.7 days. The fix must reject negatives with a clear error.
|
/// to ~49.7 days. The fix must reject negatives with a clear error.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="command">The bulk-read subcommand to validate (e.g. "read-bulk", "bench-read-bulk").</param>
|
/// <param name="command">The bulk-read subcommand to validate (e.g. "read-bulk", "bench-read-bulk").</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("read-bulk")]
|
[InlineData("read-bulk")]
|
||||||
[InlineData("bench-read-bulk")]
|
[InlineData("bench-read-bulk")]
|
||||||
@@ -880,7 +897,8 @@ public sealed class MxGatewayClientCliTests
|
|||||||
/// <summary>Optional per-call handler that overrides queue-based behaviour.</summary>
|
/// <summary>Optional per-call handler that overrides queue-based behaviour.</summary>
|
||||||
public Func<MxCommandRequest, CancellationToken, Task<MxCommandReply>>? InvokeHandler { get; init; }
|
public Func<MxCommandRequest, CancellationToken, Task<MxCommandReply>>? InvokeHandler { get; init; }
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <summary>Releases resources held by the fake CLI client.</summary>
|
||||||
|
/// <returns>A completed value task.</returns>
|
||||||
public ValueTask DisposeAsync()
|
public ValueTask DisposeAsync()
|
||||||
{
|
{
|
||||||
return ValueTask.CompletedTask;
|
return ValueTask.CompletedTask;
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
|||||||
public sealed class MxGatewayClientSessionTests
|
public sealed class MxGatewayClientSessionTests
|
||||||
{
|
{
|
||||||
/// <summary>Verifies that open session attaches API key metadata and cancellation token.</summary>
|
/// <summary>Verifies that open session attaches API key metadata and cancellation token.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task OpenSessionRawAsync_AttachesApiKeyMetadataAndCancellation()
|
public async Task OpenSessionRawAsync_AttachesApiKeyMetadataAndCancellation()
|
||||||
{
|
{
|
||||||
@@ -22,6 +23,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that open session returns a session with the raw open reply.</summary>
|
/// <summary>Verifies that open session returns a session with the raw open reply.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task OpenSessionAsync_ReturnsSessionWithRawOpenReply()
|
public async Task OpenSessionAsync_ReturnsSessionWithRawOpenReply()
|
||||||
{
|
{
|
||||||
@@ -37,6 +39,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that register builds a register command and returns server handle.</summary>
|
/// <summary>Verifies that register builds a register command and returns server handle.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RegisterAsync_BuildsRegisterCommandAndReturnsServerHandle()
|
public async Task RegisterAsync_BuildsRegisterCommandAndReturnsServerHandle()
|
||||||
{
|
{
|
||||||
@@ -62,6 +65,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that add item 2 builds a command with the specified context.</summary>
|
/// <summary>Verifies that add item 2 builds a command with the specified context.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task AddItem2Async_BuildsAddItem2CommandWithContext()
|
public async Task AddItem2Async_BuildsAddItem2CommandWithContext()
|
||||||
{
|
{
|
||||||
@@ -87,6 +91,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that write raw builds a write command with the raw value.</summary>
|
/// <summary>Verifies that write raw builds a write command with the raw value.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task WriteRawAsync_BuildsWriteCommandWithRawValue()
|
public async Task WriteRawAsync_BuildsWriteCommandWithRawValue()
|
||||||
{
|
{
|
||||||
@@ -118,6 +123,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that write 2 raw builds a write 2 command with value and timestamp.</summary>
|
/// <summary>Verifies that write 2 raw builds a write 2 command with value and timestamp.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Write2RawAsync_BuildsWrite2CommandWithValueAndTimestamp()
|
public async Task Write2RawAsync_BuildsWrite2CommandWithValueAndTimestamp()
|
||||||
{
|
{
|
||||||
@@ -146,6 +152,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that subscribe bulk builds one command and returns per-item results.</summary>
|
/// <summary>Verifies that subscribe bulk builds one command and returns per-item results.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task SubscribeBulkAsync_BuildsOneBulkCommandAndReturnsPerItemResults()
|
public async Task SubscribeBulkAsync_BuildsOneBulkCommandAndReturnsPerItemResults()
|
||||||
{
|
{
|
||||||
@@ -185,6 +192,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that stream events yields events in the order received from the gateway.</summary>
|
/// <summary>Verifies that stream events yields events in the order received from the gateway.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task StreamEventsAsync_YieldsEventsInGatewayOrder()
|
public async Task StreamEventsAsync_YieldsEventsInGatewayOrder()
|
||||||
{
|
{
|
||||||
@@ -216,6 +224,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that close is explicit and idempotent.</summary>
|
/// <summary>Verifies that close is explicit and idempotent.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task CloseAsync_IsExplicitAndIdempotent()
|
public async Task CloseAsync_IsExplicitAndIdempotent()
|
||||||
{
|
{
|
||||||
@@ -232,6 +241,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that invoke retries safe diagnostic commands on transient RPC failure.</summary>
|
/// <summary>Verifies that invoke retries safe diagnostic commands on transient RPC failure.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task InvokeAsync_RetriesSafeDiagnosticCommandOnTransientGrpcFailure()
|
public async Task InvokeAsync_RetriesSafeDiagnosticCommandOnTransientGrpcFailure()
|
||||||
{
|
{
|
||||||
@@ -256,6 +266,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that open session does not retry on transient RPC failure.</summary>
|
/// <summary>Verifies that open session does not retry on transient RPC failure.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task OpenSessionAsync_DoesNotRetryTransientGrpcFailure()
|
public async Task OpenSessionAsync_DoesNotRetryTransientGrpcFailure()
|
||||||
{
|
{
|
||||||
@@ -269,6 +280,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that invoke does not retry write commands on transient RPC failure.</summary>
|
/// <summary>Verifies that invoke does not retry write commands on transient RPC failure.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task InvokeAsync_DoesNotRetryWriteCommand()
|
public async Task InvokeAsync_DoesNotRetryWriteCommand()
|
||||||
{
|
{
|
||||||
@@ -284,6 +296,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that invoke helpers pass cancellation token to the transport.</summary>
|
/// <summary>Verifies that invoke helpers pass cancellation token to the transport.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task InvokeHelpers_PassCancellationTokenToTransport()
|
public async Task InvokeHelpers_PassCancellationTokenToTransport()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Security;
|
||||||
|
using ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
|
public sealed class MxGatewayClientTlsHandlerTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that when TLS is used with no pinned CA and RequireCertificateValidation is false (default),
|
||||||
|
/// the handler installs an accept-all callback so the gateway's self-signed cert is trusted.
|
||||||
|
/// The callback must return true regardless of chain errors.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void Handler_SkipsVerification_WhenTlsAndNoCaPinned()
|
||||||
|
{
|
||||||
|
MxGatewayClientOptions options = new()
|
||||||
|
{
|
||||||
|
Endpoint = new Uri("https://localhost:5120"),
|
||||||
|
ApiKey = "k",
|
||||||
|
UseTls = true,
|
||||||
|
};
|
||||||
|
using SocketsHttpHandler handler = MxGatewayClient.CreateHttpHandlerForTests(options);
|
||||||
|
Assert.NotNull(handler.SslOptions.RemoteCertificateValidationCallback);
|
||||||
|
Assert.True(handler.SslOptions.RemoteCertificateValidationCallback!(null!, null!, null, SslPolicyErrors.RemoteCertificateChainErrors));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that when RequireCertificateValidation is true, the callback is left null
|
||||||
|
/// so the OS trust store performs validation.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void Handler_KeepsDefaultVerification_WhenRequireCertificateValidation()
|
||||||
|
{
|
||||||
|
MxGatewayClientOptions options = new()
|
||||||
|
{
|
||||||
|
Endpoint = new Uri("https://localhost:5120"),
|
||||||
|
ApiKey = "k",
|
||||||
|
UseTls = true,
|
||||||
|
RequireCertificateValidation = true,
|
||||||
|
};
|
||||||
|
using SocketsHttpHandler handler = MxGatewayClient.CreateHttpHandlerForTests(options);
|
||||||
|
Assert.Null(handler.SslOptions.RemoteCertificateValidationCallback);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class GalaxyRepositoryClientTlsHandlerTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that when TLS is used with no pinned CA and RequireCertificateValidation is false (default),
|
||||||
|
/// the Galaxy client handler installs an accept-all callback so the gateway's self-signed cert is trusted.
|
||||||
|
/// The callback must return true regardless of chain errors.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void Handler_SkipsVerification_WhenTlsAndNoCaPinned()
|
||||||
|
{
|
||||||
|
MxGatewayClientOptions options = new()
|
||||||
|
{
|
||||||
|
Endpoint = new Uri("https://localhost:5120"),
|
||||||
|
ApiKey = "k",
|
||||||
|
UseTls = true,
|
||||||
|
};
|
||||||
|
using SocketsHttpHandler handler = GalaxyRepositoryClient.CreateHttpHandlerForTests(options);
|
||||||
|
Assert.NotNull(handler.SslOptions.RemoteCertificateValidationCallback);
|
||||||
|
Assert.True(handler.SslOptions.RemoteCertificateValidationCallback!(null!, null!, null, SslPolicyErrors.RemoteCertificateChainErrors));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that when RequireCertificateValidation is true, the Galaxy client callback is left null
|
||||||
|
/// so the OS trust store performs validation.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void Handler_KeepsDefaultVerification_WhenRequireCertificateValidation()
|
||||||
|
{
|
||||||
|
MxGatewayClientOptions options = new()
|
||||||
|
{
|
||||||
|
Endpoint = new Uri("https://localhost:5120"),
|
||||||
|
ApiKey = "k",
|
||||||
|
UseTls = true,
|
||||||
|
RequireCertificateValidation = true,
|
||||||
|
};
|
||||||
|
using SocketsHttpHandler handler = GalaxyRepositoryClient.CreateHttpHandlerForTests(options);
|
||||||
|
Assert.Null(handler.SslOptions.RemoteCertificateValidationCallback);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
|||||||
public sealed class MxGatewayGeneratedContractTests
|
public sealed class MxGatewayGeneratedContractTests
|
||||||
{
|
{
|
||||||
/// <summary>Verifies that the generated gRPC client can be instantiated from the client factory.</summary>
|
/// <summary>Verifies that the generated gRPC client can be instantiated from the client factory.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task GeneratedGrpcClient_CanBeConstructedFromClientFactory()
|
public async Task GeneratedGrpcClient_CanBeConstructedFromClientFactory()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -337,6 +337,9 @@ public sealed class GalaxyRepositoryClient : IAsyncDisposable
|
|||||||
cancellationToken);
|
cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Builds a <see cref="BrowseChildrenRequest"/> from the provided options.</summary>
|
||||||
|
/// <param name="options">Browse children options to convert.</param>
|
||||||
|
/// <returns>The constructed request message.</returns>
|
||||||
internal static BrowseChildrenRequest BuildBrowseChildrenRequest(BrowseChildrenOptions options)
|
internal static BrowseChildrenRequest BuildBrowseChildrenRequest(BrowseChildrenOptions options)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(options);
|
ArgumentNullException.ThrowIfNull(options);
|
||||||
@@ -424,6 +427,7 @@ public sealed class GalaxyRepositoryClient : IAsyncDisposable
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Closes the gRPC channel and releases resources.
|
/// Closes the gRPC channel and releases resources.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous dispose operation.</returns>
|
||||||
public ValueTask DisposeAsync()
|
public ValueTask DisposeAsync()
|
||||||
{
|
{
|
||||||
if (_disposed)
|
if (_disposed)
|
||||||
@@ -490,7 +494,13 @@ public sealed class GalaxyRepositoryClient : IAsyncDisposable
|
|||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static HttpMessageHandler CreateHttpHandler(MxGatewayClientOptions options)
|
private static HttpMessageHandler CreateHttpHandler(MxGatewayClientOptions options) =>
|
||||||
|
CreateHttpHandlerForTests(options);
|
||||||
|
|
||||||
|
/// <summary>Creates an <see cref="HttpMessageHandler"/> configured from the provided options for test use.</summary>
|
||||||
|
/// <param name="options">Client options used to configure TLS and timeouts.</param>
|
||||||
|
/// <returns>The configured HTTP message handler.</returns>
|
||||||
|
internal static SocketsHttpHandler CreateHttpHandlerForTests(MxGatewayClientOptions options)
|
||||||
{
|
{
|
||||||
SocketsHttpHandler handler = new()
|
SocketsHttpHandler handler = new()
|
||||||
{
|
{
|
||||||
@@ -510,6 +520,11 @@ public sealed class GalaxyRepositoryClient : IAsyncDisposable
|
|||||||
X509Certificate2 trustedRoot = X509CertificateLoader.LoadCertificateFromFile(options.CaCertificatePath);
|
X509Certificate2 trustedRoot = X509CertificateLoader.LoadCertificateFromFile(options.CaCertificatePath);
|
||||||
handler.SslOptions.RemoteCertificateValidationCallback = (_, certificate, chain, errors) =>
|
handler.SslOptions.RemoteCertificateValidationCallback = (_, certificate, chain, errors) =>
|
||||||
{
|
{
|
||||||
|
if ((errors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if (certificate is null)
|
if (certificate is null)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
@@ -525,6 +540,10 @@ public sealed class GalaxyRepositoryClient : IAsyncDisposable
|
|||||||
return customChain.Build(certificateToValidate);
|
return customChain.Build(certificateToValidate);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
else if (!options.RequireCertificateValidation)
|
||||||
|
{
|
||||||
|
handler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return handler;
|
return handler;
|
||||||
|
|||||||
@@ -10,9 +10,7 @@ internal sealed class GrpcGalaxyRepositoryClientTransport(
|
|||||||
MxGatewayClientOptions options,
|
MxGatewayClientOptions options,
|
||||||
GalaxyRepository.GalaxyRepositoryClient rawClient) : IGalaxyRepositoryClientTransport
|
GalaxyRepository.GalaxyRepositoryClient rawClient) : IGalaxyRepositoryClientTransport
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Gets the gateway client options.
|
|
||||||
/// </summary>
|
|
||||||
public MxGatewayClientOptions Options { get; } = options;
|
public MxGatewayClientOptions Options { get; } = options;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -91,7 +89,11 @@ internal sealed class GrpcGalaxyRepositoryClientTransport(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <summary>Streams deploy events from the Galaxy Repository, using an explicit cancellation token that overrides the call options token when provided.</summary>
|
||||||
|
/// <param name="request">The watch deploy events request.</param>
|
||||||
|
/// <param name="callOptions">Call options for the underlying gRPC call.</param>
|
||||||
|
/// <param name="cancellationToken">Optional cancellation token; takes precedence over the token in <paramref name="callOptions"/> when cancellable.</param>
|
||||||
|
/// <returns>An async enumerable of deploy events.</returns>
|
||||||
public async IAsyncEnumerable<DeployEvent> WatchDeployEventsAsync(
|
public async IAsyncEnumerable<DeployEvent> WatchDeployEventsAsync(
|
||||||
WatchDeployEventsRequest request,
|
WatchDeployEventsRequest request,
|
||||||
CallOptions callOptions,
|
CallOptions callOptions,
|
||||||
|
|||||||
@@ -10,9 +10,7 @@ internal sealed class GrpcMxGatewayClientTransport(
|
|||||||
MxGatewayClientOptions options,
|
MxGatewayClientOptions options,
|
||||||
MxAccessGateway.MxAccessGatewayClient rawClient) : IMxGatewayClientTransport
|
MxAccessGateway.MxAccessGatewayClient rawClient) : IMxGatewayClientTransport
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Gets the gateway client options.
|
|
||||||
/// </summary>
|
|
||||||
public MxGatewayClientOptions Options { get; } = options;
|
public MxGatewayClientOptions Options { get; } = options;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -74,7 +72,11 @@ internal sealed class GrpcMxGatewayClientTransport(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <summary>Streams MXAccess events from the gateway, forwarding an explicit cancellation token to the stream reader.</summary>
|
||||||
|
/// <param name="request">The stream events request.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options.</param>
|
||||||
|
/// <param name="cancellationToken">Token to cancel the streaming enumeration.</param>
|
||||||
|
/// <returns>An async enumerable of MXAccess events.</returns>
|
||||||
public async IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
public async IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
||||||
StreamEventsRequest request,
|
StreamEventsRequest request,
|
||||||
CallOptions callOptions,
|
CallOptions callOptions,
|
||||||
@@ -133,7 +135,11 @@ internal sealed class GrpcMxGatewayClientTransport(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <summary>Queries active alarms from the gateway, forwarding an explicit cancellation token to the stream reader.</summary>
|
||||||
|
/// <param name="request">The query active alarms request.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options.</param>
|
||||||
|
/// <param name="cancellationToken">Token to cancel the streaming enumeration.</param>
|
||||||
|
/// <returns>An async enumerable of active alarm snapshots.</returns>
|
||||||
public async IAsyncEnumerable<ActiveAlarmSnapshot> QueryActiveAlarmsAsync(
|
public async IAsyncEnumerable<ActiveAlarmSnapshot> QueryActiveAlarmsAsync(
|
||||||
QueryActiveAlarmsRequest request,
|
QueryActiveAlarmsRequest request,
|
||||||
CallOptions callOptions,
|
CallOptions callOptions,
|
||||||
@@ -175,7 +181,11 @@ internal sealed class GrpcMxGatewayClientTransport(
|
|||||||
return QueryActiveAlarmsAsync(request, callOptions);
|
return QueryActiveAlarmsAsync(request, callOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <summary>Streams alarm feed messages from the gateway, forwarding an explicit cancellation token to the stream reader.</summary>
|
||||||
|
/// <param name="request">The stream alarms request.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options.</param>
|
||||||
|
/// <param name="cancellationToken">Token to cancel the streaming enumeration.</param>
|
||||||
|
/// <returns>An async enumerable of alarm feed messages.</returns>
|
||||||
public async IAsyncEnumerable<AlarmFeedMessage> StreamAlarmsAsync(
|
public async IAsyncEnumerable<AlarmFeedMessage> StreamAlarmsAsync(
|
||||||
StreamAlarmsRequest request,
|
StreamAlarmsRequest request,
|
||||||
CallOptions callOptions,
|
CallOptions callOptions,
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ internal interface IGalaxyRepositoryClientTransport
|
|||||||
/// <summary>Tests the connection to the Galaxy Repository server.</summary>
|
/// <summary>Tests the connection to the Galaxy Repository server.</summary>
|
||||||
/// <param name="request">The test connection request.</param>
|
/// <param name="request">The test connection request.</param>
|
||||||
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
||||||
|
/// <returns>A task that resolves to the test connection reply.</returns>
|
||||||
Task<TestConnectionReply> TestConnectionAsync(
|
Task<TestConnectionReply> TestConnectionAsync(
|
||||||
TestConnectionRequest request,
|
TestConnectionRequest request,
|
||||||
CallOptions callOptions);
|
CallOptions callOptions);
|
||||||
@@ -22,6 +23,7 @@ internal interface IGalaxyRepositoryClientTransport
|
|||||||
/// <summary>Gets the last deploy time from the Galaxy Repository server.</summary>
|
/// <summary>Gets the last deploy time from the Galaxy Repository server.</summary>
|
||||||
/// <param name="request">The get last deploy time request.</param>
|
/// <param name="request">The get last deploy time request.</param>
|
||||||
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
||||||
|
/// <returns>A task that resolves to the last deploy time reply.</returns>
|
||||||
Task<GetLastDeployTimeReply> GetLastDeployTimeAsync(
|
Task<GetLastDeployTimeReply> GetLastDeployTimeAsync(
|
||||||
GetLastDeployTimeRequest request,
|
GetLastDeployTimeRequest request,
|
||||||
CallOptions callOptions);
|
CallOptions callOptions);
|
||||||
@@ -29,6 +31,7 @@ internal interface IGalaxyRepositoryClientTransport
|
|||||||
/// <summary>Discovers the object hierarchy in the Galaxy Repository.</summary>
|
/// <summary>Discovers the object hierarchy in the Galaxy Repository.</summary>
|
||||||
/// <param name="request">The discover hierarchy request.</param>
|
/// <param name="request">The discover hierarchy request.</param>
|
||||||
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
||||||
|
/// <returns>A task that resolves to the hierarchy discovery reply.</returns>
|
||||||
Task<DiscoverHierarchyReply> DiscoverHierarchyAsync(
|
Task<DiscoverHierarchyReply> DiscoverHierarchyAsync(
|
||||||
DiscoverHierarchyRequest request,
|
DiscoverHierarchyRequest request,
|
||||||
CallOptions callOptions);
|
CallOptions callOptions);
|
||||||
@@ -36,6 +39,7 @@ internal interface IGalaxyRepositoryClientTransport
|
|||||||
/// <summary>Returns direct children of a parent in the Galaxy hierarchy.</summary>
|
/// <summary>Returns direct children of a parent in the Galaxy hierarchy.</summary>
|
||||||
/// <param name="request">The browse children request.</param>
|
/// <param name="request">The browse children request.</param>
|
||||||
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
||||||
|
/// <returns>A task that resolves to the browse children reply.</returns>
|
||||||
Task<BrowseChildrenReply> BrowseChildrenAsync(
|
Task<BrowseChildrenReply> BrowseChildrenAsync(
|
||||||
BrowseChildrenRequest request,
|
BrowseChildrenRequest request,
|
||||||
CallOptions callOptions);
|
CallOptions callOptions);
|
||||||
@@ -43,6 +47,7 @@ internal interface IGalaxyRepositoryClientTransport
|
|||||||
/// <summary>Watches for deployment events from the Galaxy Repository server.</summary>
|
/// <summary>Watches for deployment events from the Galaxy Repository server.</summary>
|
||||||
/// <param name="request">The watch deploy events request.</param>
|
/// <param name="request">The watch deploy events request.</param>
|
||||||
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
||||||
|
/// <returns>An async enumerable of deploy events.</returns>
|
||||||
IAsyncEnumerable<DeployEvent> WatchDeployEventsAsync(
|
IAsyncEnumerable<DeployEvent> WatchDeployEventsAsync(
|
||||||
WatchDeployEventsRequest request,
|
WatchDeployEventsRequest request,
|
||||||
CallOptions callOptions);
|
CallOptions callOptions);
|
||||||
|
|||||||
@@ -16,6 +16,11 @@ public sealed class LazyBrowseNode
|
|||||||
private readonly SemaphoreSlim _expandLock = new(1, 1);
|
private readonly SemaphoreSlim _expandLock = new(1, 1);
|
||||||
private bool _isExpanded;
|
private bool _isExpanded;
|
||||||
|
|
||||||
|
/// <summary>Initializes a new instance of <see cref="LazyBrowseNode"/>.</summary>
|
||||||
|
/// <param name="client">The repository client used to fetch children.</param>
|
||||||
|
/// <param name="object">The underlying Galaxy object for this node.</param>
|
||||||
|
/// <param name="hasChildrenHint">True when the server reports the node has at least one matching descendant.</param>
|
||||||
|
/// <param name="options">Options controlling child browse behavior.</param>
|
||||||
internal LazyBrowseNode(
|
internal LazyBrowseNode(
|
||||||
GalaxyRepositoryClient client,
|
GalaxyRepositoryClient client,
|
||||||
GalaxyObject @object,
|
GalaxyObject @object,
|
||||||
@@ -49,6 +54,7 @@ public sealed class LazyBrowseNode
|
|||||||
/// (after the first completes) return immediately.
|
/// (after the first completes) return immediately.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
/// <param name="cancellationToken">Token to observe for cancellation.</param>
|
/// <param name="cancellationToken">Token to observe for cancellation.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
public async Task ExpandAsync(CancellationToken cancellationToken = default)
|
public async Task ExpandAsync(CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
if (_isExpanded)
|
if (_isExpanded)
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ public static class MxCommandReplyExtensions
|
|||||||
{
|
{
|
||||||
/// <summary>Validates that the reply has a successful protocol status (Ok or MxAccessFailure), throwing a gateway exception if not.</summary>
|
/// <summary>Validates that the reply has a successful protocol status (Ok or MxAccessFailure), throwing a gateway exception if not.</summary>
|
||||||
/// <param name="reply">The command reply to check.</param>
|
/// <param name="reply">The command reply to check.</param>
|
||||||
|
/// <returns>The same <paramref name="reply"/> for fluent chaining when validation passes.</returns>
|
||||||
public static MxCommandReply EnsureProtocolSuccess(this MxCommandReply reply)
|
public static MxCommandReply EnsureProtocolSuccess(this MxCommandReply reply)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(reply);
|
ArgumentNullException.ThrowIfNull(reply);
|
||||||
@@ -24,6 +25,7 @@ public static class MxCommandReplyExtensions
|
|||||||
|
|
||||||
/// <summary>Validates that the reply indicates MXAccess success (no HResult or status failures), throwing MxAccessException if not.</summary>
|
/// <summary>Validates that the reply indicates MXAccess success (no HResult or status failures), throwing MxAccessException if not.</summary>
|
||||||
/// <param name="reply">The command reply to check.</param>
|
/// <param name="reply">The command reply to check.</param>
|
||||||
|
/// <returns>The same <paramref name="reply"/> for fluent chaining when validation passes.</returns>
|
||||||
public static MxCommandReply EnsureMxAccessSuccess(this MxCommandReply reply)
|
public static MxCommandReply EnsureMxAccessSuccess(this MxCommandReply reply)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(reply);
|
ArgumentNullException.ThrowIfNull(reply);
|
||||||
|
|||||||
@@ -249,6 +249,7 @@ public sealed class MxGatewayClient : IAsyncDisposable
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Disposes the client and releases all resources.
|
/// Disposes the client and releases all resources.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous dispose operation.</returns>
|
||||||
public ValueTask DisposeAsync()
|
public ValueTask DisposeAsync()
|
||||||
{
|
{
|
||||||
if (_disposed)
|
if (_disposed)
|
||||||
@@ -315,7 +316,13 @@ public sealed class MxGatewayClient : IAsyncDisposable
|
|||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static HttpMessageHandler CreateHttpHandler(MxGatewayClientOptions options)
|
private static HttpMessageHandler CreateHttpHandler(MxGatewayClientOptions options) =>
|
||||||
|
CreateHttpHandlerForTests(options);
|
||||||
|
|
||||||
|
/// <summary>Creates an <see cref="HttpMessageHandler"/> configured from the provided options for test use.</summary>
|
||||||
|
/// <param name="options">Client options used to configure TLS and timeouts.</param>
|
||||||
|
/// <returns>The configured HTTP message handler.</returns>
|
||||||
|
internal static SocketsHttpHandler CreateHttpHandlerForTests(MxGatewayClientOptions options)
|
||||||
{
|
{
|
||||||
SocketsHttpHandler handler = new()
|
SocketsHttpHandler handler = new()
|
||||||
{
|
{
|
||||||
@@ -335,6 +342,11 @@ public sealed class MxGatewayClient : IAsyncDisposable
|
|||||||
X509Certificate2 trustedRoot = X509CertificateLoader.LoadCertificateFromFile(options.CaCertificatePath);
|
X509Certificate2 trustedRoot = X509CertificateLoader.LoadCertificateFromFile(options.CaCertificatePath);
|
||||||
handler.SslOptions.RemoteCertificateValidationCallback = (_, certificate, chain, errors) =>
|
handler.SslOptions.RemoteCertificateValidationCallback = (_, certificate, chain, errors) =>
|
||||||
{
|
{
|
||||||
|
if ((errors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if (certificate is null)
|
if (certificate is null)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
@@ -350,6 +362,10 @@ public sealed class MxGatewayClient : IAsyncDisposable
|
|||||||
return customChain.Build(certificateToValidate);
|
return customChain.Build(certificateToValidate);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
else if (!options.RequireCertificateValidation)
|
||||||
|
{
|
||||||
|
handler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return handler;
|
return handler;
|
||||||
|
|||||||
@@ -27,6 +27,14 @@ public sealed class MxGatewayClientOptions
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public string? CaCertificatePath { get; init; }
|
public string? CaCertificatePath { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// When true, TLS connections without a pinned <see cref="CaCertificatePath"/>
|
||||||
|
/// use the OS trust store. When false (default), the gateway certificate is
|
||||||
|
/// accepted without verification — appropriate for this internal tool's
|
||||||
|
/// auto-generated self-signed certificate. Pinning a CA always verifies.
|
||||||
|
/// </summary>
|
||||||
|
public bool RequireCertificateValidation { get; init; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the server name override for SNI during TLS handshake.
|
/// Gets the server name override for SNI during TLS handshake.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ internal static class MxGatewayClientRetryPolicy
|
|||||||
/// <summary>Creates a Polly ResiliencePipeline that retries transient gRPC failures with exponential backoff.</summary>
|
/// <summary>Creates a Polly ResiliencePipeline that retries transient gRPC failures with exponential backoff.</summary>
|
||||||
/// <param name="options">Retry configuration (max attempts, delay bounds, jitter).</param>
|
/// <param name="options">Retry configuration (max attempts, delay bounds, jitter).</param>
|
||||||
/// <param name="logger">Optional logger for retry diagnostics.</param>
|
/// <param name="logger">Optional logger for retry diagnostics.</param>
|
||||||
|
/// <returns>A configured <see cref="ResiliencePipeline"/> with exponential-backoff retry.</returns>
|
||||||
public static ResiliencePipeline Create(
|
public static ResiliencePipeline Create(
|
||||||
MxGatewayClientRetryOptions options,
|
MxGatewayClientRetryOptions options,
|
||||||
ILogger? logger)
|
ILogger? logger)
|
||||||
@@ -42,6 +43,7 @@ internal static class MxGatewayClientRetryPolicy
|
|||||||
|
|
||||||
/// <summary>Returns whether a command kind is eligible for automatic retry on transient failures.</summary>
|
/// <summary>Returns whether a command kind is eligible for automatic retry on transient failures.</summary>
|
||||||
/// <param name="kind">The command kind to check.</param>
|
/// <param name="kind">The command kind to check.</param>
|
||||||
|
/// <returns><see langword="true"/> if the command kind is safe to retry; otherwise <see langword="false"/>.</returns>
|
||||||
public static bool IsRetryableCommand(MxCommandKind kind)
|
public static bool IsRetryableCommand(MxCommandKind kind)
|
||||||
{
|
{
|
||||||
return kind is MxCommandKind.Ping
|
return kind is MxCommandKind.Ping
|
||||||
|
|||||||
@@ -211,6 +211,7 @@ public sealed class MxGatewaySession : IAsyncDisposable
|
|||||||
/// <param name="serverHandle">The ServerHandle from register.</param>
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
||||||
/// <param name="cancellationToken">Cancellation token.</param>
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
public async Task AdviseAsync(
|
public async Task AdviseAsync(
|
||||||
int serverHandle,
|
int serverHandle,
|
||||||
int itemHandle,
|
int itemHandle,
|
||||||
@@ -252,6 +253,7 @@ public sealed class MxGatewaySession : IAsyncDisposable
|
|||||||
/// <param name="serverHandle">The ServerHandle from register.</param>
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
||||||
/// <param name="cancellationToken">Cancellation token.</param>
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
public async Task UnAdviseAsync(
|
public async Task UnAdviseAsync(
|
||||||
int serverHandle,
|
int serverHandle,
|
||||||
int itemHandle,
|
int itemHandle,
|
||||||
@@ -293,6 +295,7 @@ public sealed class MxGatewaySession : IAsyncDisposable
|
|||||||
/// <param name="serverHandle">The ServerHandle from register.</param>
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
||||||
/// <param name="cancellationToken">Cancellation token.</param>
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
public async Task RemoveItemAsync(
|
public async Task RemoveItemAsync(
|
||||||
int serverHandle,
|
int serverHandle,
|
||||||
int itemHandle,
|
int itemHandle,
|
||||||
@@ -675,6 +678,7 @@ public sealed class MxGatewaySession : IAsyncDisposable
|
|||||||
/// <param name="value">The value to write.</param>
|
/// <param name="value">The value to write.</param>
|
||||||
/// <param name="userId">User ID context for the write.</param>
|
/// <param name="userId">User ID context for the write.</param>
|
||||||
/// <param name="cancellationToken">Cancellation token.</param>
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
public async Task WriteAsync(
|
public async Task WriteAsync(
|
||||||
int serverHandle,
|
int serverHandle,
|
||||||
int itemHandle,
|
int itemHandle,
|
||||||
@@ -729,6 +733,7 @@ public sealed class MxGatewaySession : IAsyncDisposable
|
|||||||
/// <param name="timestampValue">The timestamp to write with the value.</param>
|
/// <param name="timestampValue">The timestamp to write with the value.</param>
|
||||||
/// <param name="userId">User ID context for the write.</param>
|
/// <param name="userId">User ID context for the write.</param>
|
||||||
/// <param name="cancellationToken">Cancellation token.</param>
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
public async Task Write2Async(
|
public async Task Write2Async(
|
||||||
int serverHandle,
|
int serverHandle,
|
||||||
int itemHandle,
|
int itemHandle,
|
||||||
@@ -821,6 +826,7 @@ public sealed class MxGatewaySession : IAsyncDisposable
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Closes the session and releases resources.
|
/// Closes the session and releases resources.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
public async ValueTask DisposeAsync()
|
public async ValueTask DisposeAsync()
|
||||||
{
|
{
|
||||||
await CloseAsync().ConfigureAwait(false);
|
await CloseAsync().ConfigureAwait(false);
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ public static class MxStatusProxyExtensions
|
|||||||
{
|
{
|
||||||
/// <summary>Returns whether the status indicates success (success flag set and category is Ok).</summary>
|
/// <summary>Returns whether the status indicates success (success flag set and category is Ok).</summary>
|
||||||
/// <param name="status">The status to check.</param>
|
/// <param name="status">The status to check.</param>
|
||||||
|
/// <returns><c>true</c> if the status is successful; <c>false</c> otherwise.</returns>
|
||||||
public static bool IsSuccess(this MxStatusProxy status)
|
public static bool IsSuccess(this MxStatusProxy status)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(status);
|
ArgumentNullException.ThrowIfNull(status);
|
||||||
@@ -17,6 +18,7 @@ public static class MxStatusProxyExtensions
|
|||||||
|
|
||||||
/// <summary>Returns a formatted summary of the status for diagnostic output.</summary>
|
/// <summary>Returns a formatted summary of the status for diagnostic output.</summary>
|
||||||
/// <param name="status">The status to summarize.</param>
|
/// <param name="status">The status to summarize.</param>
|
||||||
|
/// <returns>A human-readable string combining category, source, detail, and diagnostic text.</returns>
|
||||||
public static string ToDiagnosticSummary(this MxStatusProxy status)
|
public static string ToDiagnosticSummary(this MxStatusProxy status)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(status);
|
ArgumentNullException.ThrowIfNull(status);
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a boolean value to an MxValue with MxDataType.Boolean.
|
/// Converts a boolean value to an MxValue with MxDataType.Boolean.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="value">Scalar boolean value to wrap.</param>
|
/// <param name="value">Scalar boolean value to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Boolean</c>.</returns>
|
||||||
public static MxValue ToMxValue(this bool value)
|
public static MxValue ToMxValue(this bool value)
|
||||||
{
|
{
|
||||||
return new MxValue
|
return new MxValue
|
||||||
@@ -28,6 +29,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a 32-bit integer value to an MxValue with MxDataType.Integer.
|
/// Converts a 32-bit integer value to an MxValue with MxDataType.Integer.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="value">32-bit integer value to wrap.</param>
|
/// <param name="value">32-bit integer value to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Integer</c>.</returns>
|
||||||
public static MxValue ToMxValue(this int value)
|
public static MxValue ToMxValue(this int value)
|
||||||
{
|
{
|
||||||
return new MxValue
|
return new MxValue
|
||||||
@@ -42,6 +44,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a 64-bit integer value to an MxValue with MxDataType.Integer.
|
/// Converts a 64-bit integer value to an MxValue with MxDataType.Integer.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="value">64-bit integer value to wrap.</param>
|
/// <param name="value">64-bit integer value to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Integer</c>.</returns>
|
||||||
public static MxValue ToMxValue(this long value)
|
public static MxValue ToMxValue(this long value)
|
||||||
{
|
{
|
||||||
return new MxValue
|
return new MxValue
|
||||||
@@ -56,6 +59,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a single-precision floating-point value to an MxValue with MxDataType.Float.
|
/// Converts a single-precision floating-point value to an MxValue with MxDataType.Float.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="value">Single-precision floating-point value to wrap.</param>
|
/// <param name="value">Single-precision floating-point value to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Float</c>.</returns>
|
||||||
public static MxValue ToMxValue(this float value)
|
public static MxValue ToMxValue(this float value)
|
||||||
{
|
{
|
||||||
return new MxValue
|
return new MxValue
|
||||||
@@ -70,6 +74,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a double-precision floating-point value to an MxValue with MxDataType.Double.
|
/// Converts a double-precision floating-point value to an MxValue with MxDataType.Double.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="value">Double-precision floating-point value to wrap.</param>
|
/// <param name="value">Double-precision floating-point value to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Double</c>.</returns>
|
||||||
public static MxValue ToMxValue(this double value)
|
public static MxValue ToMxValue(this double value)
|
||||||
{
|
{
|
||||||
return new MxValue
|
return new MxValue
|
||||||
@@ -84,6 +89,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a string value to an MxValue with MxDataType.String.
|
/// Converts a string value to an MxValue with MxDataType.String.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="value">String value to wrap.</param>
|
/// <param name="value">String value to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.String</c>.</returns>
|
||||||
public static MxValue ToMxValue(this string value)
|
public static MxValue ToMxValue(this string value)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(value);
|
ArgumentNullException.ThrowIfNull(value);
|
||||||
@@ -100,6 +106,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a DateTimeOffset value to an MxValue with MxDataType.Time.
|
/// Converts a DateTimeOffset value to an MxValue with MxDataType.Time.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="value">DateTimeOffset value to wrap.</param>
|
/// <param name="value">DateTimeOffset value to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Time</c>.</returns>
|
||||||
public static MxValue ToMxValue(this DateTimeOffset value)
|
public static MxValue ToMxValue(this DateTimeOffset value)
|
||||||
{
|
{
|
||||||
return new MxValue
|
return new MxValue
|
||||||
@@ -114,6 +121,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a DateTime value to an MxValue with MxDataType.Time.
|
/// Converts a DateTime value to an MxValue with MxDataType.Time.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="value">DateTime value to wrap.</param>
|
/// <param name="value">DateTime value to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Time</c>.</returns>
|
||||||
public static MxValue ToMxValue(this DateTime value)
|
public static MxValue ToMxValue(this DateTime value)
|
||||||
{
|
{
|
||||||
return new DateTimeOffset(
|
return new DateTimeOffset(
|
||||||
@@ -127,6 +135,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a boolean array to an MxValue with MxDataType.Boolean.
|
/// Converts a boolean array to an MxValue with MxDataType.Boolean.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="values">Array of boolean values to wrap.</param>
|
/// <param name="values">Array of boolean values to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Boolean</c> and an array payload.</returns>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<bool> values)
|
public static MxValue ToMxValue(this IReadOnlyList<bool> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -145,6 +154,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a 32-bit integer array to an MxValue with MxDataType.Integer.
|
/// Converts a 32-bit integer array to an MxValue with MxDataType.Integer.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="values">Array of 32-bit integer values to wrap.</param>
|
/// <param name="values">Array of 32-bit integer values to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Integer</c> and an array payload.</returns>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<int> values)
|
public static MxValue ToMxValue(this IReadOnlyList<int> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -163,6 +173,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a 64-bit integer array to an MxValue with MxDataType.Integer.
|
/// Converts a 64-bit integer array to an MxValue with MxDataType.Integer.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="values">Array of 64-bit integer values to wrap.</param>
|
/// <param name="values">Array of 64-bit integer values to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Integer</c> and an array payload.</returns>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<long> values)
|
public static MxValue ToMxValue(this IReadOnlyList<long> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -181,6 +192,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a single-precision floating-point array to an MxValue with MxDataType.Float.
|
/// Converts a single-precision floating-point array to an MxValue with MxDataType.Float.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="values">Array of single-precision floating-point values to wrap.</param>
|
/// <param name="values">Array of single-precision floating-point values to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Float</c> and an array payload.</returns>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<float> values)
|
public static MxValue ToMxValue(this IReadOnlyList<float> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -199,6 +211,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a double-precision floating-point array to an MxValue with MxDataType.Double.
|
/// Converts a double-precision floating-point array to an MxValue with MxDataType.Double.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="values">Array of double-precision floating-point values to wrap.</param>
|
/// <param name="values">Array of double-precision floating-point values to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Double</c> and an array payload.</returns>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<double> values)
|
public static MxValue ToMxValue(this IReadOnlyList<double> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -217,6 +230,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a string array to an MxValue with MxDataType.String.
|
/// Converts a string array to an MxValue with MxDataType.String.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="values">Array of string values to wrap.</param>
|
/// <param name="values">Array of string values to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.String</c> and an array payload.</returns>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<string> values)
|
public static MxValue ToMxValue(this IReadOnlyList<string> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -235,6 +249,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts a DateTimeOffset array to an MxValue with MxDataType.Time.
|
/// Converts a DateTimeOffset array to an MxValue with MxDataType.Time.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="values">Array of DateTimeOffset values to wrap.</param>
|
/// <param name="values">Array of DateTimeOffset values to wrap.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Time</c> and an array payload.</returns>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<DateTimeOffset> values)
|
public static MxValue ToMxValue(this IReadOnlyList<DateTimeOffset> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -253,6 +268,7 @@ public static class MxValueExtensions
|
|||||||
/// Gets the projection kind (field name) of the given MxValue's current oneof value.
|
/// Gets the projection kind (field name) of the given MxValue's current oneof value.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="value">The MxValue whose oneof projection kind is returned.</param>
|
/// <param name="value">The MxValue whose oneof projection kind is returned.</param>
|
||||||
|
/// <returns>The JSON field name of the active oneof case, or <c>"nullValue"</c>/<c>"unspecified"</c> for null/unset values.</returns>
|
||||||
public static string GetProjectionKind(this MxValue value)
|
public static string GetProjectionKind(this MxValue value)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(value);
|
ArgumentNullException.ThrowIfNull(value);
|
||||||
@@ -276,6 +292,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts an MxValue to a CLR object; returns the boxed value or null for null MxValues.
|
/// Converts an MxValue to a CLR object; returns the boxed value or null for null MxValues.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="value">The MxValue to convert.</param>
|
/// <param name="value">The MxValue to convert.</param>
|
||||||
|
/// <returns>The boxed CLR value, or null if the MxValue represents a null.</returns>
|
||||||
public static object? ToClrValue(this MxValue value)
|
public static object? ToClrValue(this MxValue value)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(value);
|
ArgumentNullException.ThrowIfNull(value);
|
||||||
@@ -299,6 +316,7 @@ public static class MxValueExtensions
|
|||||||
/// Converts an MxArray to a CLR array; returns null if the array does not have a known element type.
|
/// Converts an MxArray to a CLR array; returns null if the array does not have a known element type.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="array">The MxArray to convert.</param>
|
/// <param name="array">The MxArray to convert.</param>
|
||||||
|
/// <returns>A CLR array of the appropriate element type, or null for unknown element types.</returns>
|
||||||
public static object? ToClrArrayValue(this MxArray array)
|
public static object? ToClrArrayValue(this MxArray array)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(array);
|
ArgumentNullException.ThrowIfNull(array);
|
||||||
@@ -328,6 +346,7 @@ public static class MxValueExtensions
|
|||||||
/// <param name="variantType">Variant type string (e.g., "VT_BSTR").</param>
|
/// <param name="variantType">Variant type string (e.g., "VT_BSTR").</param>
|
||||||
/// <param name="rawDiagnostic">Diagnostic string describing the raw value.</param>
|
/// <param name="rawDiagnostic">Diagnostic string describing the raw value.</param>
|
||||||
/// <param name="rawDataType">Optional MXAccess data type override.</param>
|
/// <param name="rawDataType">Optional MXAccess data type override.</param>
|
||||||
|
/// <returns>An <see cref="MxValue"/> with <c>MxDataType.Unknown</c> and the raw byte payload.</returns>
|
||||||
public static MxValue ToRawMxValue(
|
public static MxValue ToRawMxValue(
|
||||||
byte[] value,
|
byte[] value,
|
||||||
string variantType,
|
string variantType,
|
||||||
|
|||||||
@@ -27,4 +27,10 @@
|
|||||||
<None Include="..\README.md" Pack="true" PackagePath="\" />
|
<None Include="..\README.md" Pack="true" PackagePath="\" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||||
|
<_Parameter1>ZB.MOM.WW.MxGateway.Client.Tests</_Parameter1>
|
||||||
|
</AssemblyAttribute>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -104,6 +104,23 @@ Support:
|
|||||||
- `credentials.NewClientTLSFromFile`,
|
- `credentials.NewClientTLSFromFile`,
|
||||||
- custom `tls.Config` for advanced callers.
|
- custom `tls.Config` for advanced callers.
|
||||||
|
|
||||||
|
### Trust posture
|
||||||
|
|
||||||
|
The gateway can serve a self-signed certificate it generates itself (it has no
|
||||||
|
PKI). To make that usable, TLS is **lenient by default**: when `Plaintext` is
|
||||||
|
`false` and no `CACertFile`/`TLSConfig`/`TransportCredentials` is supplied,
|
||||||
|
`buildCredentials` dials with `tls.Config{InsecureSkipVerify: true}` (carrying
|
||||||
|
`ServerNameOverride` as the SNI when set), so the gateway's self-signed
|
||||||
|
certificate is accepted without verification.
|
||||||
|
|
||||||
|
To verify the gateway instead:
|
||||||
|
|
||||||
|
- set `CACertFile` to pin a CA (full verification against that root), or
|
||||||
|
- set `RequireCertificateValidation: true` to verify against the OS/system trust
|
||||||
|
roots without pinning.
|
||||||
|
|
||||||
|
Pinning a CA always wins over the lenient default.
|
||||||
|
|
||||||
## Streaming
|
## Streaming
|
||||||
|
|
||||||
`Events(ctx)` should return a receive channel of:
|
`Events(ctx)` should return a receive channel of:
|
||||||
|
|||||||
@@ -75,6 +75,14 @@ client, err := mxgateway.Dial(ctx, mxgateway.Options{
|
|||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The gateway can auto-generate its own self-signed certificate (it has no PKI), so
|
||||||
|
the client is **lenient by default**: a TLS connection (`Plaintext: false`) with
|
||||||
|
no `CACertFile`/`TLSConfig` accepts whatever certificate the gateway presents
|
||||||
|
(`InsecureSkipVerify`, with `ServerNameOverride` as the SNI when set). To verify
|
||||||
|
instead, set `CACertFile` to pin a CA, or set `RequireCertificateValidation:
|
||||||
|
true` to verify against the OS/system trust roots without pinning. See
|
||||||
|
[Gateway Configuration](../../docs/GatewayConfiguration.md#automatic-self-signed-certificate).
|
||||||
|
|
||||||
`Client.OpenSession` returns a `Session` with helpers for `Register`,
|
`Client.OpenSession` returns a `Session` with helpers for `Register`,
|
||||||
`AddItem`, `AddItem2`, `Advise`, `Write`, `Events`, and `Close`. Prefer
|
`AddItem`, `AddItem2`, `Advise`, `Write`, `Events`, and `Close`. Prefer
|
||||||
`SubscribeEvents` or `SubscribeEventsAfter` for long-running streams because the
|
`SubscribeEvents` or `SubscribeEventsAfter` for long-running streams because the
|
||||||
|
|||||||
@@ -222,10 +222,22 @@ func resolveTransportCredentials(opts Options) (credentials.TransportCredentials
|
|||||||
return credentials.NewTLS(cfg), nil
|
return credentials.NewTLS(cfg), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return credentials.NewTLS(&tls.Config{
|
return credentials.NewTLS(tlsConfigForOptions(opts)), nil
|
||||||
MinVersion: tls.VersionTLS12,
|
}
|
||||||
ServerName: opts.ServerNameOverride,
|
|
||||||
}), nil
|
// tlsConfigForOptions returns the *tls.Config for the no-CA, no-custom-config TLS path.
|
||||||
|
// It returns nil when the caller should use a different credentials path (CA file or custom TLSConfig).
|
||||||
|
// Exposed as an internal helper so unit tests can assert the InsecureSkipVerify posture.
|
||||||
|
func tlsConfigForOptions(opts Options) *tls.Config {
|
||||||
|
// CA file and custom TLSConfig take their own paths in resolveTransportCredentials.
|
||||||
|
if opts.CACertFile != "" || opts.TLSConfig != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &tls.Config{
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
ServerName: opts.ServerNameOverride,
|
||||||
|
InsecureSkipVerify: !opts.RequireCertificateValidation, //nolint:gosec // internal tool; self-signed gateway cert expected; opt-in strict via RequireCertificateValidation
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// OpenSessionOptions describes fields used to create an OpenSessionRequest.
|
// OpenSessionOptions describes fields used to create an OpenSessionRequest.
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package mxgateway
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// tlsConfigFromOptions is the internal helper under test.
|
||||||
|
// It extracts the *tls.Config from the no-CA TLS path of resolveTransportCredentials.
|
||||||
|
// We exercise it directly to avoid needing a real dial target.
|
||||||
|
|
||||||
|
func TestTLSInsecureSkipVerify_DefaultTrue(t *testing.T) {
|
||||||
|
cfg := tlsConfigForOptions(Options{
|
||||||
|
Endpoint: "localhost:5120",
|
||||||
|
})
|
||||||
|
if cfg == nil {
|
||||||
|
t.Fatal("expected non-nil tls.Config")
|
||||||
|
}
|
||||||
|
if !cfg.InsecureSkipVerify {
|
||||||
|
t.Error("InsecureSkipVerify should be true by default when no CA is pinned")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTLSInsecureSkipVerify_FalseWhenRequireCertificateValidation(t *testing.T) {
|
||||||
|
cfg := tlsConfigForOptions(Options{
|
||||||
|
Endpoint: "localhost:5120",
|
||||||
|
RequireCertificateValidation: true,
|
||||||
|
})
|
||||||
|
if cfg == nil {
|
||||||
|
t.Fatal("expected non-nil tls.Config")
|
||||||
|
}
|
||||||
|
if cfg.InsecureSkipVerify {
|
||||||
|
t.Error("InsecureSkipVerify should be false when RequireCertificateValidation is true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTLSInsecureSkipVerify_FalseWhenCACertFileSet(t *testing.T) {
|
||||||
|
// When a CA file is pinned, the CA-verification path is taken instead.
|
||||||
|
// tlsConfigForOptions should return nil (the CA path does not use our helper).
|
||||||
|
cfg := tlsConfigForOptions(Options{
|
||||||
|
Endpoint: "localhost:5120",
|
||||||
|
CACertFile: "/some/ca.pem",
|
||||||
|
})
|
||||||
|
if cfg != nil {
|
||||||
|
t.Error("expected nil tls.Config when CACertFile is set (CA path taken)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTLSInsecureSkipVerify_FalseWhenCustomTLSConfig(t *testing.T) {
|
||||||
|
// When TLSConfig is supplied explicitly, our default skip-verify must not overwrite it.
|
||||||
|
custom := &tls.Config{MinVersion: tls.VersionTLS13}
|
||||||
|
cfg := tlsConfigForOptions(Options{
|
||||||
|
Endpoint: "localhost:5120",
|
||||||
|
TLSConfig: custom,
|
||||||
|
})
|
||||||
|
if cfg != nil {
|
||||||
|
t.Error("expected nil tls.Config when TLSConfig is already set (custom config path taken)")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,6 +34,10 @@ type Options struct {
|
|||||||
TransportCredentials credentials.TransportCredentials
|
TransportCredentials credentials.TransportCredentials
|
||||||
// DialOptions are appended to the gRPC dial options after the defaults.
|
// DialOptions are appended to the gRPC dial options after the defaults.
|
||||||
DialOptions []grpc.DialOption
|
DialOptions []grpc.DialOption
|
||||||
|
// RequireCertificateValidation forces TLS certificate verification even when
|
||||||
|
// no CACertFile is pinned. Default false: the gateway's self-signed cert is
|
||||||
|
// accepted without verification (internal-tool posture).
|
||||||
|
RequireCertificateValidation bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// BrowseChildrenOptions configures lazy Galaxy hierarchy walks performed by
|
// BrowseChildrenOptions configures lazy Galaxy hierarchy walks performed by
|
||||||
|
|||||||
@@ -112,6 +112,23 @@ Support:
|
|||||||
- custom CA certificate file,
|
- custom CA certificate file,
|
||||||
- server name override for test environments.
|
- server name override for test environments.
|
||||||
|
|
||||||
|
### Trust posture
|
||||||
|
|
||||||
|
The gateway can serve a self-signed certificate it generates itself (it has no
|
||||||
|
PKI). To make that usable, TLS is **lenient by default**: when the channel is not
|
||||||
|
plaintext and no `caCertificatePath` is set, the client builds
|
||||||
|
`GrpcSslContexts.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)`
|
||||||
|
(grpc-netty-shaded), so the gateway's self-signed certificate is accepted without
|
||||||
|
verification.
|
||||||
|
|
||||||
|
To verify the gateway instead:
|
||||||
|
|
||||||
|
- set `caCertificatePath` to pin a CA (full verification against that root), or
|
||||||
|
- set `requireCertificateValidation` to `true` to verify against the JVM trust
|
||||||
|
store without pinning.
|
||||||
|
|
||||||
|
Pinning a CA always wins over the lenient default.
|
||||||
|
|
||||||
## Streaming
|
## Streaming
|
||||||
|
|
||||||
Support both:
|
Support both:
|
||||||
|
|||||||
@@ -57,6 +57,16 @@ try (MxGatewayClient client = MxGatewayClient.connect(options);
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The gateway can auto-generate its own self-signed certificate (it has no PKI), so
|
||||||
|
the client is **lenient by default**: a TLS connection (`plaintext(false)`) with
|
||||||
|
no `caCertificatePath` accepts whatever certificate the gateway presents (via
|
||||||
|
grpc-netty-shaded's `InsecureTrustManagerFactory`). To verify instead, set
|
||||||
|
`caCertificatePath` to pin a CA, or set `requireCertificateValidation(true)` to
|
||||||
|
verify against the JVM trust store without pinning. Use `serverNameOverride` /
|
||||||
|
`--server-name-override` when the dialed host differs from the certificate SAN.
|
||||||
|
See
|
||||||
|
[Gateway Configuration](../../docs/GatewayConfiguration.md#automatic-self-signed-certificate).
|
||||||
|
|
||||||
Use `rawBlockingStub`, `rawFutureStub`, `rawAsyncStub`, `openSessionRaw`,
|
Use `rawBlockingStub`, `rawFutureStub`, `rawAsyncStub`, `openSessionRaw`,
|
||||||
`closeSessionRaw`, `invoke`, and raw session helper methods when tests need the
|
`closeSessionRaw`, `invoke`, and raw session helper methods when tests need the
|
||||||
underlying protobuf messages. `MxGatewayCommandException` and
|
underlying protobuf messages. `MxGatewayCommandException` and
|
||||||
|
|||||||
@@ -9,6 +9,10 @@ pluginManagement {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'
|
||||||
|
}
|
||||||
|
|
||||||
dependencyResolutionManagement {
|
dependencyResolutionManagement {
|
||||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||||
repositories {
|
repositories {
|
||||||
|
|||||||
+22
@@ -384,6 +384,15 @@ public final class MxGatewayClient implements AutoCloseable {
|
|||||||
} catch (SSLException error) {
|
} catch (SSLException error) {
|
||||||
throw new MxGatewayException("failed to configure gateway TLS", error);
|
throw new MxGatewayException("failed to configure gateway TLS", error);
|
||||||
}
|
}
|
||||||
|
} else if (!options.requireCertificateValidation()) {
|
||||||
|
try {
|
||||||
|
builder.sslContext(GrpcSslContexts.forClient()
|
||||||
|
.trustManager(io.grpc.netty.shaded.io.netty.handler.ssl.util
|
||||||
|
.InsecureTrustManagerFactory.INSTANCE)
|
||||||
|
.build());
|
||||||
|
} catch (SSLException error) {
|
||||||
|
throw new MxGatewayException("failed to configure lenient gateway TLS", error);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
builder.useTransportSecurity();
|
builder.useTransportSecurity();
|
||||||
}
|
}
|
||||||
@@ -393,6 +402,19 @@ public final class MxGatewayClient implements AutoCloseable {
|
|||||||
return builder.build();
|
return builder.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Package-visible test seam — creates a raw {@link ManagedChannel} from the
|
||||||
|
* given options without attaching auth interceptors. Used by TLS fixture
|
||||||
|
* tests to verify channel construction behaviour without a full
|
||||||
|
* {@link MxGatewayClient} wrapper.
|
||||||
|
*
|
||||||
|
* @param options the client options
|
||||||
|
* @return a new {@link ManagedChannel}
|
||||||
|
*/
|
||||||
|
static ManagedChannel createChannelForTests(MxGatewayClientOptions options) {
|
||||||
|
return createChannel(options);
|
||||||
|
}
|
||||||
|
|
||||||
private <T extends io.grpc.stub.AbstractStub<T>> T withDeadline(T stub) {
|
private <T extends io.grpc.stub.AbstractStub<T>> T withDeadline(T stub) {
|
||||||
if (options.callTimeout().isNegative()) {
|
if (options.callTimeout().isNegative()) {
|
||||||
return stub;
|
return stub;
|
||||||
|
|||||||
+32
@@ -20,6 +20,7 @@ public final class MxGatewayClientOptions {
|
|||||||
private final String apiKey;
|
private final String apiKey;
|
||||||
private final boolean plaintext;
|
private final boolean plaintext;
|
||||||
private final Path caCertificatePath;
|
private final Path caCertificatePath;
|
||||||
|
private final boolean requireCertificateValidation;
|
||||||
private final String serverNameOverride;
|
private final String serverNameOverride;
|
||||||
private final Duration connectTimeout;
|
private final Duration connectTimeout;
|
||||||
private final Duration callTimeout;
|
private final Duration callTimeout;
|
||||||
@@ -31,6 +32,7 @@ public final class MxGatewayClientOptions {
|
|||||||
apiKey = builder.apiKey == null ? "" : builder.apiKey;
|
apiKey = builder.apiKey == null ? "" : builder.apiKey;
|
||||||
plaintext = builder.plaintext;
|
plaintext = builder.plaintext;
|
||||||
caCertificatePath = builder.caCertificatePath;
|
caCertificatePath = builder.caCertificatePath;
|
||||||
|
requireCertificateValidation = builder.requireCertificateValidation;
|
||||||
serverNameOverride = builder.serverNameOverride == null ? "" : builder.serverNameOverride;
|
serverNameOverride = builder.serverNameOverride == null ? "" : builder.serverNameOverride;
|
||||||
connectTimeout = builder.connectTimeout == null ? DEFAULT_CONNECT_TIMEOUT : builder.connectTimeout;
|
connectTimeout = builder.connectTimeout == null ? DEFAULT_CONNECT_TIMEOUT : builder.connectTimeout;
|
||||||
callTimeout = builder.callTimeout == null ? DEFAULT_CALL_TIMEOUT : builder.callTimeout;
|
callTimeout = builder.callTimeout == null ? DEFAULT_CALL_TIMEOUT : builder.callTimeout;
|
||||||
@@ -95,6 +97,18 @@ public final class MxGatewayClientOptions {
|
|||||||
return caCertificatePath;
|
return caCertificatePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns whether TLS certificate verification is required even when no CA is pinned.
|
||||||
|
* When {@code false} (default), the gateway's self-signed certificate is accepted
|
||||||
|
* without verification. When {@code true}, the OS trust store is used.
|
||||||
|
* Pinning a CA via {@link #caCertificatePath()} always verifies regardless of this flag.
|
||||||
|
*
|
||||||
|
* @return {@code true} if strict certificate verification is required
|
||||||
|
*/
|
||||||
|
public boolean requireCertificateValidation() {
|
||||||
|
return requireCertificateValidation;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the TLS server-name override, or an empty string when none was supplied.
|
* Returns the TLS server-name override, or an empty string when none was supplied.
|
||||||
*
|
*
|
||||||
@@ -148,6 +162,8 @@ public final class MxGatewayClientOptions {
|
|||||||
+ plaintext
|
+ plaintext
|
||||||
+ ", caCertificatePath="
|
+ ", caCertificatePath="
|
||||||
+ caCertificatePath
|
+ caCertificatePath
|
||||||
|
+ ", requireCertificateValidation="
|
||||||
|
+ requireCertificateValidation
|
||||||
+ ", serverNameOverride='"
|
+ ", serverNameOverride='"
|
||||||
+ serverNameOverride
|
+ serverNameOverride
|
||||||
+ '\''
|
+ '\''
|
||||||
@@ -177,6 +193,7 @@ public final class MxGatewayClientOptions {
|
|||||||
private String apiKey;
|
private String apiKey;
|
||||||
private boolean plaintext;
|
private boolean plaintext;
|
||||||
private Path caCertificatePath;
|
private Path caCertificatePath;
|
||||||
|
private boolean requireCertificateValidation;
|
||||||
private String serverNameOverride;
|
private String serverNameOverride;
|
||||||
private Duration connectTimeout;
|
private Duration connectTimeout;
|
||||||
private Duration callTimeout;
|
private Duration callTimeout;
|
||||||
@@ -230,6 +247,21 @@ public final class MxGatewayClientOptions {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When {@code true}, TLS connections without a pinned CA use the OS trust store
|
||||||
|
* and will reject the gateway's self-signed certificate. When {@code false}
|
||||||
|
* (default), the gateway certificate is accepted without verification —
|
||||||
|
* appropriate for this internal tool's auto-generated self-signed certificate.
|
||||||
|
* Pinning a CA via {@link #caCertificatePath(Path)} always verifies.
|
||||||
|
*
|
||||||
|
* @param value {@code true} to require certificate validation, {@code false} to accept any cert
|
||||||
|
* @return this builder
|
||||||
|
*/
|
||||||
|
public Builder requireCertificateValidation(boolean value) {
|
||||||
|
requireCertificateValidation = value;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Overrides the TLS server name used during the handshake.
|
* Overrides the TLS server name used during the handshake.
|
||||||
*
|
*
|
||||||
|
|||||||
+198
@@ -0,0 +1,198 @@
|
|||||||
|
package com.zb.mom.ww.mxgateway.client;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import io.grpc.ManagedChannel;
|
||||||
|
import io.grpc.Server;
|
||||||
|
import io.grpc.StatusRuntimeException;
|
||||||
|
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
|
||||||
|
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
|
||||||
|
import io.grpc.stub.StreamObserver;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.security.KeyStore;
|
||||||
|
import java.security.PrivateKey;
|
||||||
|
import java.security.cert.Certificate;
|
||||||
|
import java.security.cert.X509Certificate;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import javax.net.ssl.SSLException;
|
||||||
|
import mxaccess_gateway.v1.MxAccessGatewayGrpc;
|
||||||
|
import mxaccess_gateway.v1.MxaccessGateway.OpenSessionReply;
|
||||||
|
import mxaccess_gateway.v1.MxaccessGateway.OpenSessionRequest;
|
||||||
|
import mxaccess_gateway.v1.MxaccessGateway.ProtocolStatus;
|
||||||
|
import mxaccess_gateway.v1.MxaccessGateway.ProtocolStatusCode;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifies that the Java client connects to a Netty TLS server with a
|
||||||
|
* self-signed certificate when no CA is pinned (lenient default), and that
|
||||||
|
* setting {@code requireCertificateValidation(true)} causes a TLS failure.
|
||||||
|
*
|
||||||
|
* <p>A self-signed certificate is generated using {@code keytool} (always
|
||||||
|
* available in the JDK) to avoid dependencies on internal JDK APIs or
|
||||||
|
* BouncyCastle, and so the test works on all JDK versions used by the project.
|
||||||
|
*/
|
||||||
|
final class MxGatewayClientTlsTests {
|
||||||
|
|
||||||
|
private Server server;
|
||||||
|
private int port;
|
||||||
|
private File certPemFile;
|
||||||
|
private File keyPemFile;
|
||||||
|
private File keystoreFile;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void startTlsServer() throws Exception {
|
||||||
|
keystoreFile = File.createTempFile("gw-test-ks", ".p12");
|
||||||
|
certPemFile = File.createTempFile("gw-test-cert", ".pem");
|
||||||
|
keyPemFile = File.createTempFile("gw-test-key", ".pem");
|
||||||
|
|
||||||
|
// keytool refuses to write to a pre-existing (even empty) file; delete it first.
|
||||||
|
keystoreFile.delete();
|
||||||
|
|
||||||
|
// Use keytool to generate a self-signed PKCS12 keystore.
|
||||||
|
String keytool = ProcessHandle.current().info().command()
|
||||||
|
.map(cmd -> cmd.replace("java", "keytool"))
|
||||||
|
.orElse("keytool");
|
||||||
|
// Fall back to just "keytool" on PATH if the resolved path doesn't exist.
|
||||||
|
if (!new File(keytool).exists()) {
|
||||||
|
keytool = "keytool";
|
||||||
|
}
|
||||||
|
Process p = new ProcessBuilder(
|
||||||
|
keytool,
|
||||||
|
"-genkeypair",
|
||||||
|
"-alias", "server",
|
||||||
|
"-keyalg", "RSA",
|
||||||
|
"-keysize", "2048",
|
||||||
|
"-sigalg", "SHA256withRSA",
|
||||||
|
"-validity", "1",
|
||||||
|
"-dname", "CN=localhost",
|
||||||
|
"-storetype", "PKCS12",
|
||||||
|
"-storepass", "changeit",
|
||||||
|
"-keypass", "changeit",
|
||||||
|
"-keystore", keystoreFile.getAbsolutePath())
|
||||||
|
.redirectErrorStream(true)
|
||||||
|
.start();
|
||||||
|
int exit = p.waitFor();
|
||||||
|
if (exit != 0) {
|
||||||
|
String out = new String(p.getInputStream().readAllBytes());
|
||||||
|
throw new IllegalStateException("keytool failed (exit " + exit + "): " + out);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Export cert and private key from the PKCS12 keystore to PEM files.
|
||||||
|
KeyStore ks = KeyStore.getInstance("PKCS12");
|
||||||
|
try (var is = Files.newInputStream(keystoreFile.toPath())) {
|
||||||
|
ks.load(is, "changeit".toCharArray());
|
||||||
|
}
|
||||||
|
X509Certificate cert = (X509Certificate) ks.getCertificate("server");
|
||||||
|
PrivateKey privateKey = (PrivateKey) ks.getKey("server", "changeit".toCharArray());
|
||||||
|
|
||||||
|
try (FileOutputStream out = new FileOutputStream(certPemFile)) {
|
||||||
|
out.write("-----BEGIN CERTIFICATE-----\n".getBytes());
|
||||||
|
out.write(Base64.getMimeEncoder(64, new byte[]{'\n'}).encode(cert.getEncoded()));
|
||||||
|
out.write("\n-----END CERTIFICATE-----\n".getBytes());
|
||||||
|
}
|
||||||
|
try (FileOutputStream out = new FileOutputStream(keyPemFile)) {
|
||||||
|
out.write("-----BEGIN PRIVATE KEY-----\n".getBytes());
|
||||||
|
out.write(Base64.getMimeEncoder(64, new byte[]{'\n'}).encode(privateKey.getEncoded()));
|
||||||
|
out.write("\n-----END PRIVATE KEY-----\n".getBytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
server = NettyServerBuilder
|
||||||
|
.forAddress(new InetSocketAddress("127.0.0.1", 0))
|
||||||
|
.sslContext(GrpcSslContexts.forServer(certPemFile, keyPemFile).build())
|
||||||
|
.addService(new MinimalGatewayService())
|
||||||
|
.build()
|
||||||
|
.start();
|
||||||
|
port = server.getPort();
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void stopTlsServer() throws InterruptedException {
|
||||||
|
if (server != null) {
|
||||||
|
server.shutdown();
|
||||||
|
server.awaitTermination(5, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
if (certPemFile != null) {
|
||||||
|
certPemFile.delete();
|
||||||
|
}
|
||||||
|
if (keyPemFile != null) {
|
||||||
|
keyPemFile.delete();
|
||||||
|
}
|
||||||
|
if (keystoreFile != null) {
|
||||||
|
keystoreFile.delete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void connectsToSelfSignedServer_WhenRequireCertificateValidationIsFalse() throws SSLException {
|
||||||
|
// Default options — requireCertificateValidation defaults to false.
|
||||||
|
MxGatewayClientOptions options = MxGatewayClientOptions.builder()
|
||||||
|
.endpoint("127.0.0.1:" + port)
|
||||||
|
.apiKey("test-key")
|
||||||
|
.connectTimeout(Duration.ofSeconds(5))
|
||||||
|
.callTimeout(Duration.ofSeconds(5))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
ManagedChannel channel = MxGatewayClient.createChannelForTests(options);
|
||||||
|
try {
|
||||||
|
MxAccessGatewayGrpc.MxAccessGatewayBlockingStub stub =
|
||||||
|
MxAccessGatewayGrpc.newBlockingStub(channel);
|
||||||
|
OpenSessionReply reply = stub.openSession(
|
||||||
|
OpenSessionRequest.newBuilder()
|
||||||
|
.setClientSessionName("tls-test")
|
||||||
|
.build());
|
||||||
|
assertTrue(reply.getProtocolStatus().getCode()
|
||||||
|
== ProtocolStatusCode.PROTOCOL_STATUS_CODE_OK);
|
||||||
|
} finally {
|
||||||
|
channel.shutdownNow();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void failsToConnect_WhenRequireCertificateValidationIsTrue() throws SSLException {
|
||||||
|
MxGatewayClientOptions options = MxGatewayClientOptions.builder()
|
||||||
|
.endpoint("127.0.0.1:" + port)
|
||||||
|
.apiKey("test-key")
|
||||||
|
.requireCertificateValidation(true)
|
||||||
|
.connectTimeout(Duration.ofSeconds(5))
|
||||||
|
.callTimeout(Duration.ofSeconds(5))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
ManagedChannel channel = MxGatewayClient.createChannelForTests(options);
|
||||||
|
try {
|
||||||
|
MxAccessGatewayGrpc.MxAccessGatewayBlockingStub stub =
|
||||||
|
MxAccessGatewayGrpc.newBlockingStub(channel);
|
||||||
|
assertThrows(StatusRuntimeException.class, () ->
|
||||||
|
stub.openSession(OpenSessionRequest.newBuilder()
|
||||||
|
.setClientSessionName("tls-strict-test")
|
||||||
|
.build()));
|
||||||
|
} finally {
|
||||||
|
channel.shutdownNow();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Minimal gateway stub that succeeds any OpenSession call. */
|
||||||
|
private static final class MinimalGatewayService
|
||||||
|
extends MxAccessGatewayGrpc.MxAccessGatewayImplBase {
|
||||||
|
@Override
|
||||||
|
public void openSession(
|
||||||
|
OpenSessionRequest request,
|
||||||
|
StreamObserver<OpenSessionReply> responseObserver) {
|
||||||
|
responseObserver.onNext(OpenSessionReply.newBuilder()
|
||||||
|
.setSessionId("tls-test-session")
|
||||||
|
.setProtocolStatus(ProtocolStatus.newBuilder()
|
||||||
|
.setCode(ProtocolStatusCode.PROTOCOL_STATUS_CODE_OK)
|
||||||
|
.build())
|
||||||
|
.build());
|
||||||
|
responseObserver.onCompleted();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -112,6 +112,28 @@ Support:
|
|||||||
- TLS channel with default roots,
|
- TLS channel with default roots,
|
||||||
- custom root certificate file.
|
- custom root certificate file.
|
||||||
|
|
||||||
|
### Trust posture (trust-on-first-use)
|
||||||
|
|
||||||
|
The gateway can serve a self-signed certificate it generates itself (it has no
|
||||||
|
PKI). grpc-python exposes no per-channel skip-verify hook, so the client cannot
|
||||||
|
"accept any certificate" the way the other clients do. Instead, when the channel
|
||||||
|
is not plaintext and neither `ca_file` nor `require_certificate_validation` is
|
||||||
|
set, the TLS default is **trust-on-first-use**: the client fetches the server's
|
||||||
|
presented certificate once via `ssl.get_server_certificate` (an unverified
|
||||||
|
probe), pins it as the channel's only trust root, and — because the generated
|
||||||
|
certificate always carries a `localhost` SAN — defaults
|
||||||
|
`grpc.ssl_target_name_override` to `localhost` when no `server_name_override` was
|
||||||
|
supplied (tolerating dial-by-IP or a hostname mismatch). A failed probe is
|
||||||
|
surfaced as a transport error naming the endpoint.
|
||||||
|
|
||||||
|
To verify the gateway instead:
|
||||||
|
|
||||||
|
- set `ca_file` to verify against a specific CA, or
|
||||||
|
- set `require_certificate_validation=True` to verify against the system trust
|
||||||
|
roots.
|
||||||
|
|
||||||
|
Both bypass the TOFU path.
|
||||||
|
|
||||||
## Streaming
|
## Streaming
|
||||||
|
|
||||||
Expose `stream_events` as an async iterator. Canceling the task should cancel
|
Expose `stream_events` as an async iterator. Canceling the task should cancel
|
||||||
|
|||||||
@@ -230,6 +230,17 @@ The client supports plaintext channels for local development, TLS with system
|
|||||||
roots, TLS with a custom `ca_file`, and an optional test server name override.
|
roots, TLS with a custom `ca_file`, and an optional test server name override.
|
||||||
API keys are redacted from option repr output and CLI error output.
|
API keys are redacted from option repr output and CLI error output.
|
||||||
|
|
||||||
|
The gateway can auto-generate its own self-signed certificate (it has no PKI).
|
||||||
|
grpc-python has no per-channel skip-verify, so the lenient TLS default is
|
||||||
|
**trust-on-first-use**: with no `ca_file` and `require_certificate_validation`
|
||||||
|
left `False`, the client fetches the gateway's presented certificate once
|
||||||
|
(unverified) and pins it for the channel, defaulting the SNI/target-name override
|
||||||
|
to `localhost` (the generated certificate always carries a `localhost` SAN) when
|
||||||
|
none was supplied. To verify instead, pass `ca_file` to verify against a specific
|
||||||
|
CA, or set `require_certificate_validation=True` to verify against the system
|
||||||
|
trust roots. See
|
||||||
|
[Gateway Configuration](../../docs/GatewayConfiguration.md#automatic-self-signed-certificate).
|
||||||
|
|
||||||
## CLI
|
## CLI
|
||||||
|
|
||||||
The CLI emits deterministic JSON for automation:
|
The CLI emits deterministic JSON for automation:
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ssl
|
||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -9,6 +10,7 @@ from pathlib import Path
|
|||||||
import grpc
|
import grpc
|
||||||
|
|
||||||
from .auth import REDACTED, ApiKey
|
from .auth import REDACTED, ApiKey
|
||||||
|
from .errors import MxGatewayTransportError
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -19,6 +21,7 @@ class ClientOptions:
|
|||||||
api_key: str | ApiKey | None = None
|
api_key: str | ApiKey | None = None
|
||||||
plaintext: bool = False
|
plaintext: bool = False
|
||||||
ca_file: str | None = None
|
ca_file: str | None = None
|
||||||
|
require_certificate_validation: bool = False
|
||||||
server_name_override: str | None = None
|
server_name_override: str | None = None
|
||||||
call_timeout: float | None = 30.0
|
call_timeout: float | None = 30.0
|
||||||
stream_timeout: float | None = None
|
stream_timeout: float | None = None
|
||||||
@@ -45,6 +48,7 @@ class ClientOptions:
|
|||||||
f"{type(self).__name__}(endpoint={self.endpoint!r}, "
|
f"{type(self).__name__}(endpoint={self.endpoint!r}, "
|
||||||
f"api_key={api_key!r}, plaintext={self.plaintext!r}, "
|
f"api_key={api_key!r}, plaintext={self.plaintext!r}, "
|
||||||
f"ca_file={self.ca_file!r}, "
|
f"ca_file={self.ca_file!r}, "
|
||||||
|
f"require_certificate_validation={self.require_certificate_validation!r}, "
|
||||||
f"server_name_override={self.server_name_override!r}, "
|
f"server_name_override={self.server_name_override!r}, "
|
||||||
f"call_timeout={self.call_timeout!r}, "
|
f"call_timeout={self.call_timeout!r}, "
|
||||||
f"stream_timeout={self.stream_timeout!r}, "
|
f"stream_timeout={self.stream_timeout!r}, "
|
||||||
@@ -69,8 +73,34 @@ class BrowseChildrenOptions:
|
|||||||
historized_only: bool = False
|
historized_only: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
def _split_authority(endpoint: str) -> tuple[str, int]:
|
||||||
|
"""Split a gRPC target (optionally scheme-prefixed) into (host, port).
|
||||||
|
|
||||||
|
Handles bracketed IPv6 literals (e.g. ``[::1]:5120`` or bare ``[::1]``),
|
||||||
|
returning the host without brackets so it is safe to pass to
|
||||||
|
``ssl.get_server_certificate``.
|
||||||
|
"""
|
||||||
|
target = endpoint.split("://", 1)[-1]
|
||||||
|
if target.startswith("["):
|
||||||
|
# Bracketed IPv6: "[::1]:5120" or "[::1]"
|
||||||
|
bracket_end = target.find("]")
|
||||||
|
host = target[1:bracket_end] # strip surrounding brackets
|
||||||
|
remainder = target[bracket_end + 1 :] # ":5120" or ""
|
||||||
|
port_str = remainder.lstrip(":")
|
||||||
|
return (host, int(port_str) if port_str else 443)
|
||||||
|
host, _, port = target.rpartition(":")
|
||||||
|
return (host or "localhost", int(port) if port else 443)
|
||||||
|
|
||||||
|
|
||||||
def create_channel(options: ClientOptions) -> grpc.aio.Channel:
|
def create_channel(options: ClientOptions) -> grpc.aio.Channel:
|
||||||
"""Create a plaintext or TLS `grpc.aio` channel from client options."""
|
"""Create a plaintext or TLS `grpc.aio` channel from client options.
|
||||||
|
|
||||||
|
The TLS default is lenient: grpc-python has no per-channel skip-verify, so
|
||||||
|
the server's presented certificate is fetched once (unverified) and pinned
|
||||||
|
as the channel's only trust root (trust-on-first-use). Set
|
||||||
|
`require_certificate_validation=True` to force system-trust verification, or
|
||||||
|
pass `ca_file` to verify against a specific CA — both bypass the TOFU path.
|
||||||
|
"""
|
||||||
|
|
||||||
channel_options: list[tuple[str, str | int]] = [
|
channel_options: list[tuple[str, str | int]] = [
|
||||||
("grpc.max_receive_message_length", options.max_grpc_message_bytes),
|
("grpc.max_receive_message_length", options.max_grpc_message_bytes),
|
||||||
@@ -82,11 +112,28 @@ def create_channel(options: ClientOptions) -> grpc.aio.Channel:
|
|||||||
if options.plaintext:
|
if options.plaintext:
|
||||||
return grpc.aio.insecure_channel(options.endpoint, options=channel_options)
|
return grpc.aio.insecure_channel(options.endpoint, options=channel_options)
|
||||||
|
|
||||||
root_certificates = None
|
|
||||||
if options.ca_file:
|
if options.ca_file:
|
||||||
root_certificates = Path(options.ca_file).read_bytes()
|
root_certificates = Path(options.ca_file).read_bytes()
|
||||||
|
credentials = grpc.ssl_channel_credentials(root_certificates=root_certificates)
|
||||||
|
elif options.require_certificate_validation:
|
||||||
|
credentials = grpc.ssl_channel_credentials()
|
||||||
|
else:
|
||||||
|
# Lenient default: grpc-python has no per-channel skip-verify, so fetch the
|
||||||
|
# server's certificate (unverified) and pin it for this channel (TOFU).
|
||||||
|
host, port = _split_authority(options.endpoint)
|
||||||
|
try:
|
||||||
|
presented = ssl.get_server_certificate((host, port))
|
||||||
|
except OSError as error:
|
||||||
|
raise MxGatewayTransportError(
|
||||||
|
f"failed to fetch TLS certificate from {options.endpoint}: {error}"
|
||||||
|
) from error
|
||||||
|
credentials = grpc.ssl_channel_credentials(root_certificates=presented.encode("ascii"))
|
||||||
|
# The gateway self-signed cert always carries a "localhost" SAN, so default
|
||||||
|
# the SNI/target-name override to it when none was supplied, tolerating
|
||||||
|
# dial-by-IP or hostname mismatch.
|
||||||
|
if not options.server_name_override:
|
||||||
|
channel_options.append(("grpc.ssl_target_name_override", "localhost"))
|
||||||
|
|
||||||
credentials = grpc.ssl_channel_credentials(root_certificates=root_certificates)
|
|
||||||
return grpc.aio.secure_channel(
|
return grpc.aio.secure_channel(
|
||||||
options.endpoint,
|
options.endpoint,
|
||||||
credentials,
|
credentials,
|
||||||
|
|||||||
@@ -72,27 +72,83 @@ def test_create_channel_uses_plaintext_channel(monkeypatch: pytest.MonkeyPatch)
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def test_create_channel_uses_tls_channel(monkeypatch: pytest.MonkeyPatch) -> None:
|
def test_create_channel_uses_tls_channel_tofu_default(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
calls: list[tuple[str, object, object]] = []
|
"""Default TLS (no ca_file, no require_certificate_validation) uses TOFU:
|
||||||
|
fetches the server cert unverified, pins it as root_certificates, and adds
|
||||||
|
grpc.ssl_target_name_override = "localhost" automatically.
|
||||||
|
"""
|
||||||
|
_DUMMY_PEM = "-----BEGIN CERTIFICATE-----\nZmFrZQ==\n-----END CERTIFICATE-----\n"
|
||||||
|
get_cert_calls: list[tuple[str, int]] = []
|
||||||
|
|
||||||
def fake_credentials(*, root_certificates: object) -> str:
|
def fake_get_server_certificate(addr: tuple[str, int]) -> str:
|
||||||
assert root_certificates is None
|
get_cert_calls.append(addr)
|
||||||
|
return _DUMMY_PEM
|
||||||
|
|
||||||
|
cred_calls: list[object] = []
|
||||||
|
|
||||||
|
def fake_credentials(*, root_certificates: object = None) -> str:
|
||||||
|
cred_calls.append(root_certificates)
|
||||||
return "creds"
|
return "creds"
|
||||||
|
|
||||||
|
channel_calls: list[tuple[str, object, object]] = []
|
||||||
|
|
||||||
def fake_secure_channel(endpoint: str, credentials: object, *, options: object) -> str:
|
def fake_secure_channel(endpoint: str, credentials: object, *, options: object) -> str:
|
||||||
calls.append((endpoint, credentials, options))
|
channel_calls.append((endpoint, credentials, options))
|
||||||
return "tls-channel"
|
return "tls-channel"
|
||||||
|
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(options_module.ssl, "get_server_certificate", fake_get_server_certificate)
|
||||||
options_module.grpc,
|
monkeypatch.setattr(options_module.grpc, "ssl_channel_credentials", fake_credentials)
|
||||||
"ssl_channel_credentials",
|
monkeypatch.setattr(options_module.grpc.aio, "secure_channel", fake_secure_channel)
|
||||||
fake_credentials,
|
|
||||||
|
channel = create_channel(
|
||||||
|
ClientOptions(endpoint="gateway.example:5001"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
assert channel == "tls-channel"
|
||||||
|
# TOFU: should have fetched the cert from the server (host, port)
|
||||||
|
assert get_cert_calls == [("gateway.example", 5001)]
|
||||||
|
# Pinned the fetched PEM bytes as root_certificates
|
||||||
|
assert cred_calls == [_DUMMY_PEM.encode("ascii")]
|
||||||
|
# Auto-injected localhost override (no server_name_override supplied)
|
||||||
|
assert channel_calls == [
|
||||||
|
(
|
||||||
|
"gateway.example:5001",
|
||||||
|
"creds",
|
||||||
|
[
|
||||||
|
("grpc.max_receive_message_length", 16 * 1024 * 1024),
|
||||||
|
("grpc.max_send_message_length", 16 * 1024 * 1024),
|
||||||
|
("grpc.ssl_target_name_override", "localhost"),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_channel_uses_tls_channel_tofu_respects_server_name_override(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
"""When server_name_override is set, TOFU still runs but does NOT add the
|
||||||
|
auto-localhost override (the explicit override is already in channel_options).
|
||||||
|
"""
|
||||||
|
_DUMMY_PEM = "-----BEGIN CERTIFICATE-----\nZmFrZQ==\n-----END CERTIFICATE-----\n"
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
options_module.grpc.aio,
|
options_module.ssl,
|
||||||
"secure_channel",
|
"get_server_certificate",
|
||||||
fake_secure_channel,
|
lambda addr: _DUMMY_PEM,
|
||||||
)
|
)
|
||||||
|
cred_calls: list[object] = []
|
||||||
|
|
||||||
|
def fake_credentials(*, root_certificates: object = None) -> str:
|
||||||
|
cred_calls.append(root_certificates)
|
||||||
|
return "creds"
|
||||||
|
|
||||||
|
channel_calls: list[tuple[str, object, object]] = []
|
||||||
|
|
||||||
|
def fake_secure_channel(endpoint: str, credentials: object, *, options: object) -> str:
|
||||||
|
channel_calls.append((endpoint, credentials, options))
|
||||||
|
return "tls-channel"
|
||||||
|
|
||||||
|
monkeypatch.setattr(options_module.grpc, "ssl_channel_credentials", fake_credentials)
|
||||||
|
monkeypatch.setattr(options_module.grpc.aio, "secure_channel", fake_secure_channel)
|
||||||
|
|
||||||
channel = create_channel(
|
channel = create_channel(
|
||||||
ClientOptions(
|
ClientOptions(
|
||||||
@@ -102,14 +158,121 @@ def test_create_channel_uses_tls_channel(monkeypatch: pytest.MonkeyPatch) -> Non
|
|||||||
)
|
)
|
||||||
|
|
||||||
assert channel == "tls-channel"
|
assert channel == "tls-channel"
|
||||||
assert calls == [
|
assert cred_calls == [_DUMMY_PEM.encode("ascii")]
|
||||||
(
|
assert channel_calls == [
|
||||||
"gateway.example:5001",
|
(
|
||||||
"creds",
|
"gateway.example:5001",
|
||||||
[
|
"creds",
|
||||||
("grpc.max_receive_message_length", 16 * 1024 * 1024),
|
[
|
||||||
("grpc.max_send_message_length", 16 * 1024 * 1024),
|
("grpc.max_receive_message_length", 16 * 1024 * 1024),
|
||||||
("grpc.ssl_target_name_override", "gateway.test"),
|
("grpc.max_send_message_length", 16 * 1024 * 1024),
|
||||||
],
|
# Explicit override from ClientOptions — not the auto-localhost one
|
||||||
),
|
("grpc.ssl_target_name_override", "gateway.test"),
|
||||||
]
|
],
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_channel_uses_tls_channel_require_cert_validation(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
"""require_certificate_validation=True uses system trust (no TOFU, no root_certificates)."""
|
||||||
|
get_cert_called = False
|
||||||
|
|
||||||
|
def fake_get_server_certificate(addr: object) -> str: # pragma: no cover
|
||||||
|
nonlocal get_cert_called
|
||||||
|
get_cert_called = True
|
||||||
|
return "SHOULD_NOT_BE_CALLED"
|
||||||
|
|
||||||
|
cred_calls: list[object] = []
|
||||||
|
|
||||||
|
def fake_credentials(**kwargs: object) -> str:
|
||||||
|
cred_calls.append(kwargs)
|
||||||
|
return "creds"
|
||||||
|
|
||||||
|
channel_calls: list[tuple[str, object, object]] = []
|
||||||
|
|
||||||
|
def fake_secure_channel(endpoint: str, credentials: object, *, options: object) -> str:
|
||||||
|
channel_calls.append((endpoint, credentials, options))
|
||||||
|
return "tls-channel"
|
||||||
|
|
||||||
|
monkeypatch.setattr(options_module.ssl, "get_server_certificate", fake_get_server_certificate)
|
||||||
|
monkeypatch.setattr(options_module.grpc, "ssl_channel_credentials", fake_credentials)
|
||||||
|
monkeypatch.setattr(options_module.grpc.aio, "secure_channel", fake_secure_channel)
|
||||||
|
|
||||||
|
channel = create_channel(
|
||||||
|
ClientOptions(
|
||||||
|
endpoint="gateway.example:5001",
|
||||||
|
require_certificate_validation=True,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert channel == "tls-channel"
|
||||||
|
# Must NOT call TOFU prefetch
|
||||||
|
assert not get_cert_called
|
||||||
|
# ssl_channel_credentials() called with NO keyword args (system trust)
|
||||||
|
assert cred_calls == [{}]
|
||||||
|
assert channel_calls == [
|
||||||
|
(
|
||||||
|
"gateway.example:5001",
|
||||||
|
"creds",
|
||||||
|
[
|
||||||
|
("grpc.max_receive_message_length", 16 * 1024 * 1024),
|
||||||
|
("grpc.max_send_message_length", 16 * 1024 * 1024),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_channel_uses_tls_channel_ca_file(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
tmp_path: pytest.TempPathFactory,
|
||||||
|
) -> None:
|
||||||
|
"""ca_file path: reads the PEM file, passes bytes as root_certificates, skips TOFU."""
|
||||||
|
ca_pem = b"-----BEGIN CERTIFICATE-----\nY2FkYXRh\n-----END CERTIFICATE-----\n"
|
||||||
|
ca_file = tmp_path / "ca.pem"
|
||||||
|
ca_file.write_bytes(ca_pem)
|
||||||
|
|
||||||
|
get_cert_called = False
|
||||||
|
|
||||||
|
def fake_get_server_certificate(addr: object) -> str: # pragma: no cover
|
||||||
|
nonlocal get_cert_called
|
||||||
|
get_cert_called = True
|
||||||
|
return "SHOULD_NOT_BE_CALLED"
|
||||||
|
|
||||||
|
cred_calls: list[object] = []
|
||||||
|
|
||||||
|
def fake_credentials(*, root_certificates: object = None) -> str:
|
||||||
|
cred_calls.append(root_certificates)
|
||||||
|
return "creds"
|
||||||
|
|
||||||
|
channel_calls: list[tuple[str, object, object]] = []
|
||||||
|
|
||||||
|
def fake_secure_channel(endpoint: str, credentials: object, *, options: object) -> str:
|
||||||
|
channel_calls.append((endpoint, credentials, options))
|
||||||
|
return "tls-channel"
|
||||||
|
|
||||||
|
monkeypatch.setattr(options_module.ssl, "get_server_certificate", fake_get_server_certificate)
|
||||||
|
monkeypatch.setattr(options_module.grpc, "ssl_channel_credentials", fake_credentials)
|
||||||
|
monkeypatch.setattr(options_module.grpc.aio, "secure_channel", fake_secure_channel)
|
||||||
|
|
||||||
|
channel = create_channel(
|
||||||
|
ClientOptions(
|
||||||
|
endpoint="gateway.example:5001",
|
||||||
|
ca_file=str(ca_file),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert channel == "tls-channel"
|
||||||
|
assert not get_cert_called
|
||||||
|
assert cred_calls == [ca_pem]
|
||||||
|
assert channel_calls == [
|
||||||
|
(
|
||||||
|
"gateway.example:5001",
|
||||||
|
"creds",
|
||||||
|
[
|
||||||
|
("grpc.max_receive_message_length", 16 * 1024 * 1024),
|
||||||
|
("grpc.max_send_message_length", 16 * 1024 * 1024),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
"""TLS behaviour tests for ``create_channel``.
|
||||||
|
|
||||||
|
These spin up a real loopback ``grpc.aio`` server with a freshly generated
|
||||||
|
self-signed certificate (carrying a ``localhost`` SAN, mirroring the gateway's
|
||||||
|
auto-generated cert) and assert the lenient TOFU default lets a client connect
|
||||||
|
without any CA configured.
|
||||||
|
|
||||||
|
Marked ``tls`` and skipped unless ``MXGATEWAY_RUN_TLS_TESTS=1`` because loopback
|
||||||
|
TLS handshakes can be timing-flaky on shared CI runners. This mirrors how the
|
||||||
|
suite gates anything that depends on real sockets rather than fakes.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import grpc
|
||||||
|
import pytest
|
||||||
|
import pytest_asyncio
|
||||||
|
|
||||||
|
from zb_mom_ww_mxgateway import ClientOptions
|
||||||
|
from zb_mom_ww_mxgateway.errors import MxGatewayTransportError
|
||||||
|
from zb_mom_ww_mxgateway.generated import mxaccess_gateway_pb2 as pb
|
||||||
|
from zb_mom_ww_mxgateway.generated import mxaccess_gateway_pb2_grpc as pb_grpc
|
||||||
|
from zb_mom_ww_mxgateway.options import create_channel
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.tls
|
||||||
|
|
||||||
|
_RUN_TLS_TESTS = os.environ.get("MXGATEWAY_RUN_TLS_TESTS") == "1"
|
||||||
|
_OPENSSL = shutil.which("openssl")
|
||||||
|
|
||||||
|
requires_tls = pytest.mark.skipif(
|
||||||
|
not _RUN_TLS_TESTS,
|
||||||
|
reason="set MXGATEWAY_RUN_TLS_TESTS=1 to run loopback TLS tests",
|
||||||
|
)
|
||||||
|
requires_openssl = pytest.mark.skipif(
|
||||||
|
_OPENSSL is None,
|
||||||
|
reason="openssl CLI is required to generate a self-signed test certificate",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _generate_self_signed_cert(directory: Path) -> tuple[Path, Path]:
|
||||||
|
"""Generate a self-signed cert/key pair with a ``localhost`` SAN."""
|
||||||
|
key_path = directory / "server.key"
|
||||||
|
cert_path = directory / "server.crt"
|
||||||
|
subprocess.run(
|
||||||
|
[
|
||||||
|
str(_OPENSSL),
|
||||||
|
"req",
|
||||||
|
"-x509",
|
||||||
|
"-newkey",
|
||||||
|
"rsa:2048",
|
||||||
|
"-nodes",
|
||||||
|
"-keyout",
|
||||||
|
str(key_path),
|
||||||
|
"-out",
|
||||||
|
str(cert_path),
|
||||||
|
"-days",
|
||||||
|
"1",
|
||||||
|
"-subj",
|
||||||
|
"/CN=mxgateway-test",
|
||||||
|
"-addext",
|
||||||
|
"subjectAltName=DNS:localhost,IP:127.0.0.1",
|
||||||
|
],
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
)
|
||||||
|
return cert_path, key_path
|
||||||
|
|
||||||
|
|
||||||
|
def _free_port() -> int:
|
||||||
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||||
|
sock.bind(("127.0.0.1", 0))
|
||||||
|
return int(sock.getsockname()[1])
|
||||||
|
|
||||||
|
|
||||||
|
class _StaticGatewayServicer(pb_grpc.MxAccessGatewayServicer):
|
||||||
|
"""Minimal servicer answering ``OpenSession`` with a fixed session id."""
|
||||||
|
|
||||||
|
async def OpenSession( # noqa: N802 - generated gRPC method name
|
||||||
|
self, request: pb.OpenSessionRequest, context: object
|
||||||
|
) -> pb.OpenSessionReply:
|
||||||
|
return pb.OpenSessionReply(session_id="tls-session-1")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest_asyncio.fixture
|
||||||
|
async def tls_server() -> AsyncIterator[int]:
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
cert_path, key_path = _generate_self_signed_cert(Path(tmp))
|
||||||
|
credentials = grpc.ssl_server_credentials(
|
||||||
|
[(key_path.read_bytes(), cert_path.read_bytes())]
|
||||||
|
)
|
||||||
|
server = grpc.aio.server()
|
||||||
|
pb_grpc.add_MxAccessGatewayServicer_to_server(_StaticGatewayServicer(), server)
|
||||||
|
port = _free_port()
|
||||||
|
server.add_secure_port(f"127.0.0.1:{port}", credentials)
|
||||||
|
await server.start()
|
||||||
|
try:
|
||||||
|
yield port
|
||||||
|
finally:
|
||||||
|
await server.stop(grace=None)
|
||||||
|
|
||||||
|
|
||||||
|
@requires_tls
|
||||||
|
@requires_openssl
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_default_tls_connects_via_tofu(tls_server: int) -> None:
|
||||||
|
"""Default TLS options (no CA) connect by pinning the presented cert."""
|
||||||
|
options = ClientOptions(
|
||||||
|
endpoint=f"127.0.0.1:{tls_server}",
|
||||||
|
api_key="mxgw_test_secret",
|
||||||
|
)
|
||||||
|
channel = create_channel(options)
|
||||||
|
try:
|
||||||
|
stub = pb_grpc.MxAccessGatewayStub(channel)
|
||||||
|
reply = await stub.OpenSession(pb.OpenSessionRequest(), timeout=10)
|
||||||
|
assert reply.session_id == "tls-session-1"
|
||||||
|
finally:
|
||||||
|
await channel.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_authority_parses_host_and_port() -> None:
|
||||||
|
from zb_mom_ww_mxgateway.options import _split_authority
|
||||||
|
|
||||||
|
assert _split_authority("https://10.0.0.5:5120") == ("10.0.0.5", 5120)
|
||||||
|
assert _split_authority("localhost:5120") == ("localhost", 5120)
|
||||||
|
assert _split_authority(":5120") == ("localhost", 5120)
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_authority_strips_ipv6_brackets() -> None:
|
||||||
|
from zb_mom_ww_mxgateway.options import _split_authority
|
||||||
|
|
||||||
|
# Bracketed IPv6 with port — brackets must be removed for ssl.get_server_certificate
|
||||||
|
assert _split_authority("[::1]:5120") == ("::1", 5120)
|
||||||
|
# Bare bracketed IPv6 (no port) — default port 443
|
||||||
|
assert _split_authority("[::1]") == ("::1", 443)
|
||||||
|
# Scheme-prefixed bracketed IPv6
|
||||||
|
assert _split_authority("grpc://[::1]:5120") == ("::1", 5120)
|
||||||
|
|
||||||
|
|
||||||
|
def test_tofu_connect_failure_raises_transport_error() -> None:
|
||||||
|
"""A failed cert pre-fetch surfaces the client's transport error type."""
|
||||||
|
options = ClientOptions(endpoint=f"127.0.0.1:{_free_port()}")
|
||||||
|
with pytest.raises(MxGatewayTransportError) as excinfo:
|
||||||
|
create_channel(options)
|
||||||
|
assert options.endpoint in str(excinfo.value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_require_certificate_validation_uses_system_trust() -> None:
|
||||||
|
"""``require_certificate_validation`` must not attempt a TOFU pre-fetch."""
|
||||||
|
# Pointing at a closed port: with system-trust the channel is created lazily
|
||||||
|
# (no eager pre-fetch), so create_channel must succeed without connecting.
|
||||||
|
options = ClientOptions(
|
||||||
|
endpoint=f"127.0.0.1:{_free_port()}",
|
||||||
|
require_certificate_validation=True,
|
||||||
|
)
|
||||||
|
channel = create_channel(options)
|
||||||
|
assert isinstance(channel, grpc.aio.Channel)
|
||||||
@@ -76,6 +76,19 @@ types.
|
|||||||
cargo run -p mxgw-cli -- smoke --endpoint https://mxgateway.example.local:5001 --tls --ca-file C:\certs\mxgateway-ca.pem --server-name-override mxgateway.example.local --api-key-env MXGATEWAY_API_KEY --item TestChildObject.TestInt --json
|
cargo run -p mxgw-cli -- smoke --endpoint https://mxgateway.example.local:5001 --tls --ca-file C:\certs\mxgateway-ca.pem --server-name-override mxgateway.example.local --api-key-env MXGATEWAY_API_KEY --item TestChildObject.TestInt --json
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### TLS trust (pin-only)
|
||||||
|
|
||||||
|
The gateway can auto-generate its own self-signed certificate (it has no PKI).
|
||||||
|
Unlike the other clients, the Rust client is **not** lenient: tonic 0.13.1
|
||||||
|
exposes no public hook to inject a custom certificate verifier, so TLS over Rust
|
||||||
|
is pin-only. A TLS connection requires either `--ca-file` /
|
||||||
|
`ClientOptions::with_ca_file(...)` to pin a CA (export the gateway's self-signed
|
||||||
|
certificate and pin it), or `--require-certificate-validation` /
|
||||||
|
`with_require_certificate_validation(true)` to verify against the system trust
|
||||||
|
roots. TLS with neither set fails `connect` with a clear, actionable error rather
|
||||||
|
than accepting the certificate. See
|
||||||
|
[Gateway Configuration](../../docs/GatewayConfiguration.md#automatic-self-signed-certificate).
|
||||||
|
|
||||||
## Library Surface
|
## Library Surface
|
||||||
|
|
||||||
`ClientOptions` configures endpoint, API key, plaintext or TLS transport,
|
`ClientOptions` configures endpoint, API key, plaintext or TLS transport,
|
||||||
|
|||||||
@@ -189,6 +189,25 @@ Support:
|
|||||||
- custom CA file,
|
- custom CA file,
|
||||||
- domain override.
|
- domain override.
|
||||||
|
|
||||||
|
### Trust posture (pin-only)
|
||||||
|
|
||||||
|
The gateway can serve a self-signed certificate it generates itself (it has no
|
||||||
|
PKI). Rust is the **exception** to the lenient-by-default posture the other
|
||||||
|
clients use: tonic 0.13.1 exposes no public hook to inject a custom certificate
|
||||||
|
verifier, so the Rust client cannot accept an arbitrary certificate. TLS over the
|
||||||
|
Rust client is therefore **pin-only** — it requires either:
|
||||||
|
|
||||||
|
- `ClientOptions::with_ca_file(...)` to pin a CA (the supported path for the
|
||||||
|
gateway's self-signed certificate; export the certificate and pin it), or
|
||||||
|
- `ClientOptions::with_require_certificate_validation(true)` to verify against the
|
||||||
|
system trust roots.
|
||||||
|
|
||||||
|
With TLS enabled (`with_plaintext(false)`), no pinned CA, and certificate
|
||||||
|
validation not required, `GatewayClient::connect` rejects the connection with a
|
||||||
|
clear, actionable error pointing at `with_ca_file` /
|
||||||
|
`require_certificate_validation` rather than silently accepting the certificate.
|
||||||
|
The CLI exposes `--ca-file` and `--require-certificate-validation`.
|
||||||
|
|
||||||
## Streaming
|
## Streaming
|
||||||
|
|
||||||
Expose event streams as a `Stream<Item = Result<MxEvent, Error>>`. Dropping the
|
Expose event streams as a `Stream<Item = Result<MxEvent, Error>>`. Dropping the
|
||||||
|
|||||||
@@ -426,6 +426,11 @@ struct ConnectionArgs {
|
|||||||
ca_file: Option<PathBuf>,
|
ca_file: Option<PathBuf>,
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
server_name_override: Option<String>,
|
server_name_override: Option<String>,
|
||||||
|
/// Verify the server certificate against the system trust roots even
|
||||||
|
/// without a pinned CA. The Rust client's default is to require a CA
|
||||||
|
/// file (see `--ca-file`); set this flag to use system roots instead.
|
||||||
|
#[arg(long)]
|
||||||
|
require_certificate_validation: bool,
|
||||||
#[arg(long, default_value_t = 10)]
|
#[arg(long, default_value_t = 10)]
|
||||||
connect_timeout_seconds: u64,
|
connect_timeout_seconds: u64,
|
||||||
#[arg(long, default_value_t = 30)]
|
#[arg(long, default_value_t = 30)]
|
||||||
@@ -453,6 +458,9 @@ impl ConnectionArgs {
|
|||||||
if let Some(server_name_override) = &self.server_name_override {
|
if let Some(server_name_override) = &self.server_name_override {
|
||||||
options = options.with_server_name_override(server_name_override);
|
options = options.with_server_name_override(server_name_override);
|
||||||
}
|
}
|
||||||
|
if self.require_certificate_validation {
|
||||||
|
options = options.with_require_certificate_validation(true);
|
||||||
|
}
|
||||||
|
|
||||||
options
|
options
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,10 +6,8 @@
|
|||||||
//! code should prefer [`GatewayClient::open_session`] and the [`Session`]
|
//! code should prefer [`GatewayClient::open_session`] and the [`Session`]
|
||||||
//! handle it returns, rather than the `*_raw` methods.
|
//! handle it returns, rather than the `*_raw` methods.
|
||||||
|
|
||||||
use std::fs;
|
|
||||||
|
|
||||||
use tonic::codegen::InterceptedService;
|
use tonic::codegen::InterceptedService;
|
||||||
use tonic::transport::{Certificate, Channel, ClientTlsConfig};
|
use tonic::transport::Channel;
|
||||||
use tonic::Request;
|
use tonic::Request;
|
||||||
|
|
||||||
use crate::auth::AuthInterceptor;
|
use crate::auth::AuthInterceptor;
|
||||||
@@ -21,7 +19,7 @@ use crate::generated::mxaccess_gateway::v1::{
|
|||||||
OpenSessionReply, OpenSessionRequest, QueryActiveAlarmsRequest, StreamAlarmsRequest,
|
OpenSessionReply, OpenSessionRequest, QueryActiveAlarmsRequest, StreamAlarmsRequest,
|
||||||
StreamEventsRequest,
|
StreamEventsRequest,
|
||||||
};
|
};
|
||||||
use crate::options::ClientOptions;
|
use crate::options::{build_tls_config, ClientOptions};
|
||||||
use crate::session::Session;
|
use crate::session::Session;
|
||||||
|
|
||||||
/// Generated gateway client wrapped in the auth interceptor that
|
/// Generated gateway client wrapped in the auth interceptor that
|
||||||
@@ -78,18 +76,7 @@ impl GatewayClient {
|
|||||||
})?;
|
})?;
|
||||||
endpoint = endpoint.connect_timeout(options.connect_timeout());
|
endpoint = endpoint.connect_timeout(options.connect_timeout());
|
||||||
|
|
||||||
if !options.plaintext() {
|
if let Some(tls) = build_tls_config(&options)? {
|
||||||
let mut tls = ClientTlsConfig::new();
|
|
||||||
if let Some(server_name) = options.server_name_override() {
|
|
||||||
tls = tls.domain_name(server_name.to_owned());
|
|
||||||
}
|
|
||||||
if let Some(ca_file) = options.ca_file() {
|
|
||||||
let certificate = fs::read(ca_file).map_err(|source| Error::InvalidEndpoint {
|
|
||||||
endpoint: options.endpoint().to_owned(),
|
|
||||||
detail: format!("failed to read CA file {}: {source}", ca_file.display()),
|
|
||||||
})?;
|
|
||||||
tls = tls.ca_certificate(Certificate::from_pem(certificate));
|
|
||||||
}
|
|
||||||
endpoint = endpoint.tls_config(tls)?;
|
endpoint = endpoint.tls_config(tls)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,13 +6,12 @@
|
|||||||
//! re-exported through [`crate::generated::galaxy_repository::v1`].
|
//! re-exported through [`crate::generated::galaxy_repository::v1`].
|
||||||
|
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::fs;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use prost_types::Timestamp;
|
use prost_types::Timestamp;
|
||||||
use tokio::sync::Mutex as AsyncMutex;
|
use tokio::sync::Mutex as AsyncMutex;
|
||||||
use tonic::codegen::InterceptedService;
|
use tonic::codegen::InterceptedService;
|
||||||
use tonic::transport::{Certificate, Channel, ClientTlsConfig};
|
use tonic::transport::Channel;
|
||||||
use tonic::Request;
|
use tonic::Request;
|
||||||
|
|
||||||
use crate::auth::AuthInterceptor;
|
use crate::auth::AuthInterceptor;
|
||||||
@@ -23,7 +22,7 @@ use crate::generated::galaxy_repository::v1::{
|
|||||||
DiscoverHierarchyRequest, GalaxyObject, GetLastDeployTimeRequest, TestConnectionRequest,
|
DiscoverHierarchyRequest, GalaxyObject, GetLastDeployTimeRequest, TestConnectionRequest,
|
||||||
WatchDeployEventsRequest,
|
WatchDeployEventsRequest,
|
||||||
};
|
};
|
||||||
use crate::options::ClientOptions;
|
use crate::options::{build_tls_config, ClientOptions};
|
||||||
|
|
||||||
const DISCOVER_HIERARCHY_PAGE_SIZE: i32 = 5000;
|
const DISCOVER_HIERARCHY_PAGE_SIZE: i32 = 5000;
|
||||||
const BROWSE_CHILDREN_PAGE_SIZE: i32 = 500;
|
const BROWSE_CHILDREN_PAGE_SIZE: i32 = 500;
|
||||||
@@ -183,18 +182,7 @@ impl GalaxyClient {
|
|||||||
})?;
|
})?;
|
||||||
endpoint = endpoint.connect_timeout(options.connect_timeout());
|
endpoint = endpoint.connect_timeout(options.connect_timeout());
|
||||||
|
|
||||||
if !options.plaintext() {
|
if let Some(tls) = build_tls_config(&options)? {
|
||||||
let mut tls = ClientTlsConfig::new();
|
|
||||||
if let Some(server_name) = options.server_name_override() {
|
|
||||||
tls = tls.domain_name(server_name.to_owned());
|
|
||||||
}
|
|
||||||
if let Some(ca_file) = options.ca_file() {
|
|
||||||
let certificate = fs::read(ca_file).map_err(|source| Error::InvalidEndpoint {
|
|
||||||
endpoint: options.endpoint().to_owned(),
|
|
||||||
detail: format!("failed to read CA file {}: {source}", ca_file.display()),
|
|
||||||
})?;
|
|
||||||
tls = tls.ca_certificate(Certificate::from_pem(certificate));
|
|
||||||
}
|
|
||||||
endpoint = endpoint.tls_config(tls)?;
|
endpoint = endpoint.tls_config(tls)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,14 @@
|
|||||||
//! chain of `with_*` setters; the `Debug` impl redacts the API key.
|
//! chain of `with_*` setters; the `Debug` impl redacts the API key.
|
||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
use std::fs;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use tonic::transport::{Certificate, ClientTlsConfig};
|
||||||
|
|
||||||
use crate::auth::ApiKey;
|
use crate::auth::ApiKey;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
const DEFAULT_MAX_GRPC_MESSAGE_BYTES: usize = 16 * 1024 * 1024;
|
const DEFAULT_MAX_GRPC_MESSAGE_BYTES: usize = 16 * 1024 * 1024;
|
||||||
|
|
||||||
@@ -22,6 +26,7 @@ pub struct ClientOptions {
|
|||||||
api_key: Option<ApiKey>,
|
api_key: Option<ApiKey>,
|
||||||
plaintext: bool,
|
plaintext: bool,
|
||||||
ca_file: Option<PathBuf>,
|
ca_file: Option<PathBuf>,
|
||||||
|
require_certificate_validation: bool,
|
||||||
server_name_override: Option<String>,
|
server_name_override: Option<String>,
|
||||||
connect_timeout: Duration,
|
connect_timeout: Duration,
|
||||||
call_timeout: Duration,
|
call_timeout: Duration,
|
||||||
@@ -38,6 +43,7 @@ impl ClientOptions {
|
|||||||
api_key: None,
|
api_key: None,
|
||||||
plaintext: true,
|
plaintext: true,
|
||||||
ca_file: None,
|
ca_file: None,
|
||||||
|
require_certificate_validation: false,
|
||||||
server_name_override: None,
|
server_name_override: None,
|
||||||
connect_timeout: Duration::from_secs(10),
|
connect_timeout: Duration::from_secs(10),
|
||||||
call_timeout: Duration::from_secs(30),
|
call_timeout: Duration::from_secs(30),
|
||||||
@@ -67,6 +73,22 @@ impl ClientOptions {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Require TLS certificate verification even without a pinned CA. Default
|
||||||
|
/// false: the gateway's self-signed certificate is accepted (internal-tool
|
||||||
|
/// posture). Setting a CA file always verifies.
|
||||||
|
///
|
||||||
|
/// Note for Rust: tonic 0.13's `ClientTlsConfig` exposes no hook for a
|
||||||
|
/// custom rustls verifier, so the Rust client cannot accept an arbitrary
|
||||||
|
/// self-signed certificate the way the other clients do. With the default
|
||||||
|
/// (false) and no pinned CA, [`crate::client::GatewayClient::connect`]
|
||||||
|
/// rejects the TLS connection and asks for a CA file. Either pin a CA via
|
||||||
|
/// [`ClientOptions::with_ca_file`] (the supported lenient path on Rust) or
|
||||||
|
/// set this `true` to verify against the system trust roots.
|
||||||
|
pub fn with_require_certificate_validation(mut self, require: bool) -> Self {
|
||||||
|
self.require_certificate_validation = require;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Override the SNI/server name used during the TLS handshake. Useful
|
/// Override the SNI/server name used during the TLS handshake. Useful
|
||||||
/// when the dial-target host name does not match the certificate.
|
/// when the dial-target host name does not match the certificate.
|
||||||
pub fn with_server_name_override(mut self, server_name_override: impl Into<String>) -> Self {
|
pub fn with_server_name_override(mut self, server_name_override: impl Into<String>) -> Self {
|
||||||
@@ -121,6 +143,12 @@ impl ClientOptions {
|
|||||||
self.ca_file.as_ref()
|
self.ca_file.as_ref()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether TLS certificate verification is required even without a pinned
|
||||||
|
/// CA. See [`ClientOptions::with_require_certificate_validation`].
|
||||||
|
pub fn require_certificate_validation(&self) -> bool {
|
||||||
|
self.require_certificate_validation
|
||||||
|
}
|
||||||
|
|
||||||
/// Optional SNI / server-name override for TLS handshakes.
|
/// Optional SNI / server-name override for TLS handshakes.
|
||||||
pub fn server_name_override(&self) -> Option<&str> {
|
pub fn server_name_override(&self) -> Option<&str> {
|
||||||
self.server_name_override.as_deref()
|
self.server_name_override.as_deref()
|
||||||
@@ -147,6 +175,68 @@ impl ClientOptions {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Build the [`ClientTlsConfig`] for a non-plaintext connection described by
|
||||||
|
/// `options`, applying the lenient-default guard that is the **Rust
|
||||||
|
/// pin-only exception**.
|
||||||
|
///
|
||||||
|
/// Returns `Ok(None)` when `options.plaintext()` is `true` (no TLS needed).
|
||||||
|
/// Returns `Ok(Some(tls))` when a valid TLS config can be assembled.
|
||||||
|
/// Returns `Err(Error::InvalidEndpoint)` when TLS is requested but no pinned
|
||||||
|
/// CA was provided and `require_certificate_validation` is `false`.
|
||||||
|
///
|
||||||
|
/// # Why this guard exists
|
||||||
|
///
|
||||||
|
/// `tonic` 0.13's `ClientTlsConfig` builds its rustls verifier inside a
|
||||||
|
/// crate-private connector and exposes no hook for a custom
|
||||||
|
/// `ServerCertVerifier`. The Rust client therefore cannot accept an arbitrary
|
||||||
|
/// self-signed certificate the way the other language clients do. Rather than
|
||||||
|
/// silently falling back to system-root verification (which always fails
|
||||||
|
/// against a self-signed gateway certificate), we reject the configuration
|
||||||
|
/// early with an actionable error.
|
||||||
|
pub(crate) fn build_tls_config(options: &ClientOptions) -> Result<Option<ClientTlsConfig>, Error> {
|
||||||
|
if options.plaintext() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut tls = ClientTlsConfig::new();
|
||||||
|
if let Some(server_name) = options.server_name_override() {
|
||||||
|
tls = tls.domain_name(server_name.to_owned());
|
||||||
|
}
|
||||||
|
if let Some(ca_file) = options.ca_file() {
|
||||||
|
let certificate = fs::read(ca_file).map_err(|source| Error::InvalidEndpoint {
|
||||||
|
endpoint: options.endpoint().to_owned(),
|
||||||
|
detail: format!("failed to read CA file {}: {source}", ca_file.display()),
|
||||||
|
})?;
|
||||||
|
tls = tls.ca_certificate(Certificate::from_pem(certificate));
|
||||||
|
} else if !options.require_certificate_validation() {
|
||||||
|
// Lenient-default fallback (Rust pin-only exception): tonic
|
||||||
|
// 0.13's `ClientTlsConfig` builds its rustls verifier inside a
|
||||||
|
// crate-private connector and exposes no hook for a custom
|
||||||
|
// `ServerCertVerifier`, so — unlike the other clients — the
|
||||||
|
// Rust client cannot accept an arbitrary self-signed cert. Pin
|
||||||
|
// the gateway's CA instead, or opt into strict verification
|
||||||
|
// against the system trust roots. We reject here rather than
|
||||||
|
// silently verifying against system roots (which would fail a
|
||||||
|
// self-signed gateway with a confusing handshake error).
|
||||||
|
//
|
||||||
|
// Note: a server-name override affects SNI (the hostname sent
|
||||||
|
// in the TLS ClientHello) but does NOT pin trust. Overriding
|
||||||
|
// the server name alone does not bypass certificate validation.
|
||||||
|
return Err(Error::InvalidEndpoint {
|
||||||
|
endpoint: options.endpoint().to_owned(),
|
||||||
|
detail: "TLS requested without a pinned CA. The Rust client cannot accept an \
|
||||||
|
arbitrary self-signed certificate (tonic 0.13 exposes no custom \
|
||||||
|
rustls verifier). Pin the gateway certificate with \
|
||||||
|
ClientOptions::with_ca_file, or call \
|
||||||
|
ClientOptions::with_require_certificate_validation(true) to verify \
|
||||||
|
against the system trust roots. Note: a server-name override \
|
||||||
|
affects SNI but does not pin trust."
|
||||||
|
.to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(Some(tls))
|
||||||
|
}
|
||||||
|
|
||||||
impl Default for ClientOptions {
|
impl Default for ClientOptions {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self::new("http://127.0.0.1:5000")
|
Self::new("http://127.0.0.1:5000")
|
||||||
@@ -161,6 +251,10 @@ impl fmt::Debug for ClientOptions {
|
|||||||
.field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
|
.field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
|
||||||
.field("plaintext", &self.plaintext)
|
.field("plaintext", &self.plaintext)
|
||||||
.field("ca_file", &self.ca_file)
|
.field("ca_file", &self.ca_file)
|
||||||
|
.field(
|
||||||
|
"require_certificate_validation",
|
||||||
|
&self.require_certificate_validation,
|
||||||
|
)
|
||||||
.field("server_name_override", &self.server_name_override)
|
.field("server_name_override", &self.server_name_override)
|
||||||
.field("connect_timeout", &self.connect_timeout)
|
.field("connect_timeout", &self.connect_timeout)
|
||||||
.field("call_timeout", &self.call_timeout)
|
.field("call_timeout", &self.call_timeout)
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
//! TLS posture coverage for the Rust client.
|
||||||
|
//!
|
||||||
|
//! tonic 0.13.1's `ClientTlsConfig` exposes no hook for a custom rustls
|
||||||
|
//! `ServerCertVerifier` (the verifier is built internally inside the
|
||||||
|
//! crate-private `TlsConnector`), so the Rust client cannot implement the
|
||||||
|
//! "accept any server certificate" lenient default the other clients use.
|
||||||
|
//! Rust is therefore the documented **pin-only exception**: TLS without a
|
||||||
|
//! pinned CA is rejected up front with a clear, actionable error, and
|
||||||
|
//! supplying a CA file is the supported path. These tests pin that contract.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use zb_mom_ww_mxgateway_client::{ClientOptions, Error, GalaxyClient, GatewayClient};
|
||||||
|
|
||||||
|
/// Drive `connect` to its error without requiring `GatewayClient: Debug`
|
||||||
|
/// (the success arm is dropped explicitly so `unwrap_err` is unnecessary).
|
||||||
|
async fn connect_err(options: ClientOptions) -> Error {
|
||||||
|
match GatewayClient::connect(options).await {
|
||||||
|
Ok(_client) => panic!("connect unexpectedly succeeded against a dead TLS address"),
|
||||||
|
Err(error) => error,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tls_without_ca_is_rejected_with_actionable_error_by_default() {
|
||||||
|
let options = ClientOptions::new("https://127.0.0.1:1")
|
||||||
|
.with_plaintext(false)
|
||||||
|
.with_connect_timeout(Duration::from_millis(200));
|
||||||
|
|
||||||
|
let error = connect_err(options).await;
|
||||||
|
|
||||||
|
let Error::InvalidEndpoint { detail, .. } = error else {
|
||||||
|
panic!("expected InvalidEndpoint, got {error:?}");
|
||||||
|
};
|
||||||
|
// The message must point the caller at the supported remedy (pin a CA)
|
||||||
|
// and name the opt-in escape hatch.
|
||||||
|
assert!(
|
||||||
|
detail.contains("ca_file") || detail.contains("CA"),
|
||||||
|
"error should instruct the user to pass a CA file: {detail}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
detail.contains("require_certificate_validation"),
|
||||||
|
"error should mention the require_certificate_validation opt-in: {detail}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tls_with_require_certificate_validation_does_not_short_circuit() {
|
||||||
|
// With strict verification opted in, the no-CA guard must not fire; the
|
||||||
|
// connect attempt instead proceeds to the transport (and fails to reach
|
||||||
|
// the dead address) rather than returning the "CA required" guard error.
|
||||||
|
let options = ClientOptions::new("https://127.0.0.1:1")
|
||||||
|
.with_plaintext(false)
|
||||||
|
.with_require_certificate_validation(true)
|
||||||
|
.with_connect_timeout(Duration::from_millis(200));
|
||||||
|
|
||||||
|
let error = connect_err(options).await;
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
!matches!(&error, Error::InvalidEndpoint { detail, .. }
|
||||||
|
if detail.contains("require_certificate_validation")),
|
||||||
|
"strict verification must bypass the no-CA guard, got {error:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tls_with_ca_file_is_permitted_and_proceeds_past_the_guard() {
|
||||||
|
// Pinning a CA is the supported TLS path: the no-CA guard must not fire.
|
||||||
|
// We hand it a readable PEM file; construction proceeds past the guard
|
||||||
|
// and only fails later at the transport (dead address / handshake).
|
||||||
|
let ca_path = std::env::temp_dir().join("mxgw-rust-tls-ca-fixture.pem");
|
||||||
|
std::fs::write(&ca_path, SELF_SIGNED_CA_PEM).unwrap();
|
||||||
|
|
||||||
|
let options = ClientOptions::new("https://127.0.0.1:1")
|
||||||
|
.with_plaintext(false)
|
||||||
|
.with_ca_file(&ca_path)
|
||||||
|
.with_connect_timeout(Duration::from_millis(200));
|
||||||
|
|
||||||
|
let error = connect_err(options).await;
|
||||||
|
|
||||||
|
let _ = std::fs::remove_file(&ca_path);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
!matches!(&error, Error::InvalidEndpoint { detail, .. }
|
||||||
|
if detail.contains("require_certificate_validation")),
|
||||||
|
"pinning a CA must bypass the no-CA guard, got {error:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drive `GalaxyClient::connect` to its error (mirrors `connect_err` above).
|
||||||
|
async fn galaxy_connect_err(options: ClientOptions) -> Error {
|
||||||
|
match GalaxyClient::connect(options).await {
|
||||||
|
Ok(_client) => {
|
||||||
|
panic!("GalaxyClient::connect unexpectedly succeeded against a dead TLS address")
|
||||||
|
}
|
||||||
|
Err(error) => error,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn galaxy_tls_without_ca_is_rejected_with_actionable_error_by_default() {
|
||||||
|
// GalaxyClient::connect must apply the same TLS guard as GatewayClient —
|
||||||
|
// TLS without a pinned CA (and without require_certificate_validation)
|
||||||
|
// returns a clear, actionable InvalidEndpoint error.
|
||||||
|
let options = ClientOptions::new("https://127.0.0.1:1")
|
||||||
|
.with_plaintext(false)
|
||||||
|
.with_connect_timeout(Duration::from_millis(200));
|
||||||
|
|
||||||
|
let error = galaxy_connect_err(options).await;
|
||||||
|
|
||||||
|
let Error::InvalidEndpoint { detail, .. } = error else {
|
||||||
|
panic!("expected InvalidEndpoint, got {error:?}");
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
detail.contains("ca_file") || detail.contains("CA"),
|
||||||
|
"error should instruct the user to pass a CA file: {detail}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
detail.contains("require_certificate_validation"),
|
||||||
|
"error should mention the require_certificate_validation opt-in: {detail}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A throwaway self-signed CA certificate (PEM). Only needs to parse as a
|
||||||
|
/// PEM trust root so the CA-pinning path is exercised past the guard.
|
||||||
|
const SELF_SIGNED_CA_PEM: &str = "-----BEGIN CERTIFICATE-----
|
||||||
|
MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAw
|
||||||
|
DgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlow
|
||||||
|
EjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d
|
||||||
|
7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B
|
||||||
|
5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggr
|
||||||
|
BgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1
|
||||||
|
NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/l
|
||||||
|
Wf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc
|
||||||
|
6MF9+Yw1Yy0t
|
||||||
|
-----END CERTIFICATE-----
|
||||||
|
";
|
||||||
@@ -51,6 +51,19 @@ The shared inputs are:
|
|||||||
The commands in the matrix use `MXGATEWAY_API_KEY` through each CLI's
|
The commands in the matrix use `MXGATEWAY_API_KEY` through each CLI's
|
||||||
`api-key-env` flag. They must not embed bearer tokens or raw API keys.
|
`api-key-env` flag. They must not embed bearer tokens or raw API keys.
|
||||||
|
|
||||||
|
### TLS variant
|
||||||
|
|
||||||
|
The matrix runs over plaintext (`h2c`) by default. A TLS variant exists but stays
|
||||||
|
a manual/opt-in run, consistent with the gate above, because it needs the gateway
|
||||||
|
started with an HTTPS endpoint (an `https://` `MXGATEWAY_ENDPOINT`) and each CLI
|
||||||
|
switched to its TLS flag (`--tls` / `-tls` / `--plaintext=false` /
|
||||||
|
`plaintext=False`). The clients are lenient by default and accept the gateway's
|
||||||
|
auto-generated self-signed certificate without extra trust setup, except the Rust
|
||||||
|
CLI, which is pin-only and needs `--ca-file` or `--require-certificate-validation`
|
||||||
|
(and Python uses trust-on-first-use). See
|
||||||
|
[Gateway Configuration — Automatic self-signed certificate](./GatewayConfiguration.md#automatic-self-signed-certificate)
|
||||||
|
and each client README for the per-client TLS flags.
|
||||||
|
|
||||||
## JSON Comparison
|
## JSON Comparison
|
||||||
|
|
||||||
Every command in the matrix requests JSON output. A runner can compare the
|
Every command in the matrix requests JSON output. A runner can compare the
|
||||||
|
|||||||
@@ -375,6 +375,42 @@ deployment-heavy box, multiply per-session SQL connections, and complicate the
|
|||||||
cold-start path. Wire-side laziness solves the actual pain (oversized gRPC
|
cold-start path. Wire-side laziness solves the actual pain (oversized gRPC
|
||||||
replies and a heavy DOM) without disturbing the materialization model.
|
replies and a heavy DOM) without disturbing the materialization model.
|
||||||
|
|
||||||
|
## TLS Auto-Certificate and Lenient Client Trust
|
||||||
|
|
||||||
|
Decision: when a Kestrel `https://` endpoint is configured without a certificate
|
||||||
|
of its own (and no `Kestrel:Certificates:Default` is set), the gateway generates
|
||||||
|
and persists a self-signed certificate rather than failing to start. Clients
|
||||||
|
connecting over TLS without a pinned CA accept whatever certificate the server
|
||||||
|
presents by default; pinning a CA restores full verification.
|
||||||
|
|
||||||
|
Rationale: `mxaccessgw` is an internal tool with no PKI to issue or distribute
|
||||||
|
certificates. The prior behavior — an `https` endpoint with no certificate
|
||||||
|
fails at startup with Kestrel's opaque "no server certificate was specified"
|
||||||
|
error — pushed operators toward plaintext (`h2c`), exposing the API key and
|
||||||
|
request payloads on the wire. Auto-generating a long-lived, persisted, reused
|
||||||
|
certificate lets TLS "just work" with zero certificate management, while the
|
||||||
|
lenient client default means clients connect to that self-signed certificate
|
||||||
|
without a manual trust step. Both choices are deliberate, not oversights:
|
||||||
|
strict-by-default would force PKI work this tool does not warrant. Plaintext-only
|
||||||
|
deployments are untouched — no certificate or key material is written for them —
|
||||||
|
and an operator who supplies a real certificate transparently overrides the
|
||||||
|
generated one.
|
||||||
|
|
||||||
|
Two clients diverge from "accept any certificate" because their gRPC stacks lack
|
||||||
|
a per-channel skip-verify hook:
|
||||||
|
|
||||||
|
- Python uses trust-on-first-use: it fetches the server's presented certificate
|
||||||
|
over a separate unverified probe and pins it for the channel, and defaults the
|
||||||
|
SNI/target-name override to `localhost` (the generated certificate always
|
||||||
|
carries a `localhost` SAN).
|
||||||
|
- Rust is pin-only: tonic exposes no public hook to inject a custom certificate
|
||||||
|
verifier, so TLS over Rust requires either a pinned CA or an explicit opt-in to
|
||||||
|
system-trust verification; otherwise connecting returns a clear, actionable
|
||||||
|
error.
|
||||||
|
|
||||||
|
See [Gateway Configuration — Automatic self-signed certificate](./GatewayConfiguration.md#automatic-self-signed-certificate)
|
||||||
|
and the per-client READMEs for the as-built behavior.
|
||||||
|
|
||||||
## Later Revisit Items
|
## Later Revisit Items
|
||||||
|
|
||||||
These are explicit post-v1 revisit items, not open blockers:
|
These are explicit post-v1 revisit items, not open blockers:
|
||||||
|
|||||||
@@ -229,6 +229,185 @@ behavior.
|
|||||||
The alarm monitor is independent of client sessions: `AcknowledgeAlarm` and
|
The alarm monitor is independent of client sessions: `AcknowledgeAlarm` and
|
||||||
`StreamAlarms` are session-less RPCs served by the monitor.
|
`StreamAlarms` are session-less RPCs served by the monitor.
|
||||||
|
|
||||||
|
## Host Endpoints and Transport Security (Kestrel)
|
||||||
|
|
||||||
|
The listening endpoints are **not** part of the `MxGateway` section. The gateway
|
||||||
|
uses the stock ASP.NET Core host (`WebApplication.CreateBuilder`) with no
|
||||||
|
`ConfigureKestrel` call in code, so endpoints come entirely from the standard
|
||||||
|
`Kestrel` configuration section. On the deployed hosts these values are supplied
|
||||||
|
as NSSM environment variables (`Kestrel__Endpoints__...`), not from
|
||||||
|
`appsettings.json`.
|
||||||
|
|
||||||
|
Two named endpoints are bound:
|
||||||
|
|
||||||
|
| Endpoint name | Purpose | Protocol requirement |
|
||||||
|
|---|---|---|
|
||||||
|
| `Http` | Public gRPC API (sessions, invoke, events, Galaxy browse) | HTTP/2 |
|
||||||
|
| `Dashboard` | Blazor dashboard and SignalR hubs | HTTP/1.1 (HTTP/2 optional) |
|
||||||
|
|
||||||
|
Both endpoints share one routing pipeline; the names only select which TCP port
|
||||||
|
serves which traffic. The gRPC endpoint must negotiate **HTTP/2**, which drives
|
||||||
|
the protocol settings below.
|
||||||
|
|
||||||
|
### Plaintext (current deployments)
|
||||||
|
|
||||||
|
Both running hosts (`10.100.0.48` and `wonder-app-vd03`) serve the gRPC port in
|
||||||
|
**cleartext HTTP/2 (`h2c`)**. Because cleartext HTTP/2 has no ALPN to negotiate
|
||||||
|
the protocol, the gRPC endpoint must be pinned to `Http2` with prior knowledge:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Kestrel__Endpoints__Http__Url=http://0.0.0.0:5120
|
||||||
|
Kestrel__Endpoints__Http__Protocols=Http2
|
||||||
|
Kestrel__Endpoints__Dashboard__Url=http://0.0.0.0:5130
|
||||||
|
```
|
||||||
|
|
||||||
|
In this mode all client↔gateway traffic — including the
|
||||||
|
`authorization: Bearer mxgw_...` API key and any `WriteSecured` / `AuthenticateUser`
|
||||||
|
payloads — crosses the network **unencrypted**. This is acceptable only on a
|
||||||
|
trusted/isolated network segment. Prefer TLS for anything else.
|
||||||
|
|
||||||
|
### TLS
|
||||||
|
|
||||||
|
To encrypt the gRPC channel, give the `Http` endpoint an `https://` URL and a
|
||||||
|
certificate. Over TLS, ALPN negotiates HTTP/2, so the explicit `Protocols=Http2`
|
||||||
|
pin is no longer required (the default `Http1AndHttp2` works for gRPC over TLS).
|
||||||
|
|
||||||
|
`appsettings.json` form:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"Kestrel": {
|
||||||
|
"Endpoints": {
|
||||||
|
"Http": {
|
||||||
|
"Url": "https://0.0.0.0:5120",
|
||||||
|
"Certificate": {
|
||||||
|
"Path": "C:\\ProgramData\\MxGateway\\certs\\gateway.pfx",
|
||||||
|
"Password": "<pfx-password>"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Dashboard": {
|
||||||
|
"Url": "https://0.0.0.0:5130",
|
||||||
|
"Certificate": {
|
||||||
|
"Path": "C:\\ProgramData\\MxGateway\\certs\\gateway.pfx",
|
||||||
|
"Password": "<pfx-password>"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Equivalent NSSM environment-variable form (how config is delivered on the hosts —
|
||||||
|
see [server deploy mechanics in the project notes]):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Kestrel__Endpoints__Http__Url=https://0.0.0.0:5120
|
||||||
|
Kestrel__Endpoints__Http__Certificate__Path=C:\ProgramData\MxGateway\certs\gateway.pfx
|
||||||
|
Kestrel__Endpoints__Http__Certificate__Password=<pfx-password>
|
||||||
|
Kestrel__Endpoints__Dashboard__Url=https://0.0.0.0:5130
|
||||||
|
Kestrel__Endpoints__Dashboard__Certificate__Path=C:\ProgramData\MxGateway\certs\gateway.pfx
|
||||||
|
Kestrel__Endpoints__Dashboard__Certificate__Password=<pfx-password>
|
||||||
|
```
|
||||||
|
|
||||||
|
Certificate sourcing options (any standard ASP.NET Core form is accepted):
|
||||||
|
|
||||||
|
| Form | Keys |
|
||||||
|
|---|---|
|
||||||
|
| PFX file | `Certificate:Path` (+ `Certificate:Password` if encrypted) |
|
||||||
|
| PEM pair | `Certificate:Path` (cert) + `Certificate:KeyPath` (private key) |
|
||||||
|
| Windows cert store | `Certificate:Subject`, `Certificate:Store` (e.g. `My`), `Certificate:Location` (`LocalMachine`), `Certificate:AllowInvalid` |
|
||||||
|
|
||||||
|
The certificate's CN/SAN must cover the host name clients dial (or clients must
|
||||||
|
set a server-name override — see below). The dashboard endpoint can keep its own
|
||||||
|
certificate independent of the gRPC endpoint; pair this with
|
||||||
|
`MxGateway:Dashboard:RequireHttpsCookie` (`true`) for production HTTPS.
|
||||||
|
|
||||||
|
### Automatic self-signed certificate
|
||||||
|
|
||||||
|
`mxaccessgw` is an internal tool with no PKI to issue certificates, so requiring
|
||||||
|
an operator to supply one before TLS works pushed deployments toward plaintext.
|
||||||
|
To avoid that, the gateway fills in a self-signed certificate when an HTTPS
|
||||||
|
endpoint is configured without one.
|
||||||
|
|
||||||
|
**Trigger.** At startup the gateway inspects `Kestrel:Endpoints:*`. If any
|
||||||
|
endpoint has an `https://` URL and no `Certificate` subsection of its own, and no
|
||||||
|
`Kestrel:Certificates:Default` is set, the gateway generates (or loads) a
|
||||||
|
persisted self-signed certificate and wires it in as the HTTPS *default* via
|
||||||
|
`ConfigureHttpsDefaults`. All-plaintext deployments are untouched: when no HTTPS
|
||||||
|
endpoint is configured, no certificate or key material is generated or written.
|
||||||
|
|
||||||
|
**Generated certificate.** ECDSA P-256, `serverAuth` EKU, validity ≈
|
||||||
|
`ValidityYears` (default 10 years, with one day of clock-skew slack before
|
||||||
|
`notBefore`). SANs cover `localhost`, the machine name (and its FQDN when
|
||||||
|
resolvable), each entry in `AdditionalDnsNames`, and the loopback addresses
|
||||||
|
`127.0.0.1` and `::1`.
|
||||||
|
|
||||||
|
**`MxGateway:Tls:*` options.** All optional; the zero-config path needs none of
|
||||||
|
them.
|
||||||
|
|
||||||
|
| Option | Default | Purpose |
|
||||||
|
|---|---|---|
|
||||||
|
| `Tls:SelfSignedCertPath` | `C:\ProgramData\MxGateway\certs\gateway-selfsigned.pfx` | Where the generated certificate is persisted |
|
||||||
|
| `Tls:ValidityYears` | `10` | Lifetime of the generated certificate (validated 1–100) |
|
||||||
|
| `Tls:AdditionalDnsNames` | `[]` | Extra DNS SANs (e.g. a load-balancer name) |
|
||||||
|
| `Tls:RegenerateIfExpired` | `true` | Replace an expired persisted certificate instead of failing |
|
||||||
|
|
||||||
|
`ValidityYears` is validated by `GatewayOptionsValidator` (range 1–100); the
|
||||||
|
"HTTPS endpoint configured but no certificate available" fail-fast lives in the
|
||||||
|
bootstrap/provider, because the validator only sees the `MxGateway` section, not
|
||||||
|
`Kestrel:Endpoints`.
|
||||||
|
|
||||||
|
**Persistence.** The PFX is written with an **empty** export password — a random
|
||||||
|
in-memory password could not be reused across restarts, which the
|
||||||
|
persist-and-reuse model requires. The private key is instead protected at rest by
|
||||||
|
filesystem permissions: a restrictive ACL on Windows (SYSTEM + Administrators,
|
||||||
|
inherited ACEs stripped) on the `certs` directory and file, and mode `0600` on
|
||||||
|
non-Windows. The write is atomic (hardened temp file, then move). The persisted
|
||||||
|
certificate is reused across restarts (stable thumbprint, so CA-pinning clients
|
||||||
|
keep working) and regenerated only when it is missing, expired (and
|
||||||
|
`RegenerateIfExpired` is `true`), or unreadable/corrupt. If the directory is not
|
||||||
|
writable or the ACL cannot be applied, the gateway fails fast with a diagnostic
|
||||||
|
naming the path rather than falling back to an in-memory certificate.
|
||||||
|
|
||||||
|
**Logging.** On generate or load, the gateway logs the certificate thumbprint,
|
||||||
|
SAN list, and `notAfter` at Information. The PFX bytes, export password, and
|
||||||
|
private key are never logged.
|
||||||
|
|
||||||
|
**Operator override.** The generated certificate is only the HTTPS *default*. To
|
||||||
|
use a real certificate, configure one explicitly — either per endpoint via
|
||||||
|
`Kestrel:Endpoints:<name>:Certificate` (`Path`/`Subject`/`Thumbprint`, etc., as
|
||||||
|
in the table above) or globally via `Kestrel:Certificates:Default`. An
|
||||||
|
explicitly-configured certificate takes precedence, and the gateway then writes
|
||||||
|
no self-signed material.
|
||||||
|
|
||||||
|
### Client side
|
||||||
|
|
||||||
|
Each official client opts into TLS explicitly. For the .NET client
|
||||||
|
(`MxGatewayClientOptions`):
|
||||||
|
|
||||||
|
| Option | Effect |
|
||||||
|
|---|---|
|
||||||
|
| `UseTls` (default `false`) | Enables TLS. Requires an `https://` endpoint; an `https://` endpoint without `UseTls` fails validation, and vice versa. |
|
||||||
|
| `CaCertificatePath` | Pins a custom root (self-signed / private CA) using `CustomRootTrust` chain validation instead of the OS trust store; the .NET client also enforces the certificate hostname/SAN match on this path. |
|
||||||
|
| `RequireCertificateValidation` (default `false`) | Forces OS/system-trust verification on a TLS connection with no pinned CA. Leave `false` for the lenient default. |
|
||||||
|
| `ServerNameOverride` | SNI / certificate host name override when the dialed host differs from the certificate CN/SAN. |
|
||||||
|
|
||||||
|
To pair with the auto-generated self-signed certificate above, the clients are
|
||||||
|
**lenient by default**: a TLS connection with no pinned CA accepts whatever
|
||||||
|
certificate the gateway presents. Pin `CaCertificatePath` to verify, or set
|
||||||
|
`RequireCertificateValidation` to force system-trust verification without
|
||||||
|
pinning. The other language clients expose the equivalent options; the exact
|
||||||
|
behavior differs per stack — Python uses trust-on-first-use and Rust is pin-only.
|
||||||
|
See each client README for the as-built behavior.
|
||||||
|
|
||||||
|
### Gateway↔worker IPC
|
||||||
|
|
||||||
|
Transport security here applies only to the public gRPC channel. The
|
||||||
|
gateway↔worker link is a per-session **named pipe**
|
||||||
|
(`mxaccess-gateway-{gatewayPid}-{sessionId}`), not a network socket. It is not
|
||||||
|
TLS-encrypted and does not need to be: it never leaves the local Windows host and
|
||||||
|
is secured by the OS pipe ACL. See [Worker Frame Protocol](./WorkerFrameProtocol.md).
|
||||||
|
|
||||||
## Related Documentation
|
## Related Documentation
|
||||||
|
|
||||||
- [Gateway Process Detailed Design](./GatewayProcessDesign.md)
|
- [Gateway Process Detailed Design](./GatewayProcessDesign.md)
|
||||||
|
|||||||
@@ -243,9 +243,27 @@ services.AddGrpc(options => options.Interceptors.Add<GatewayGrpcAuthorizationInt
|
|||||||
|
|
||||||
Because the interceptor runs before any handler, `MxAccessGatewayService` can safely assume the call has been authorized and that `IGatewayRequestIdentityAccessor.Current` is populated. The handler's only responsibility is to read the identity for `OpenSession` so the session is owned by the authenticated principal; it does not perform any authorization checks of its own. See [Authorization](./Authorization.md) for the policy and identity model.
|
Because the interceptor runs before any handler, `MxAccessGatewayService` can safely assume the call has been authorized and that `IGatewayRequestIdentityAccessor.Current` is populated. The handler's only responsibility is to read the identity for `OpenSession` so the session is owned by the authenticated principal; it does not perform any authorization checks of its own. See [Authorization](./Authorization.md) for the policy and identity model.
|
||||||
|
|
||||||
|
## Transport Security
|
||||||
|
|
||||||
|
The gRPC endpoint runs over HTTP/2, in cleartext (`h2c`) or TLS depending on the
|
||||||
|
Kestrel endpoint configuration. The current deployments serve it in cleartext, so
|
||||||
|
the API key and request payloads cross the network unencrypted. The endpoint,
|
||||||
|
protocol pinning, and TLS certificate configuration — plus the corresponding
|
||||||
|
client `UseTls` / `CaCertificatePath` options — are documented in
|
||||||
|
[Host Endpoints and Transport Security](./GatewayConfiguration.md#host-endpoints-and-transport-security-kestrel).
|
||||||
|
|
||||||
|
To make TLS usable without PKI, the gateway can auto-generate and persist a
|
||||||
|
self-signed certificate when an HTTPS endpoint is configured without one, and the
|
||||||
|
language clients are lenient by default — a TLS connection with no pinned CA
|
||||||
|
accepts the presented certificate (with per-stack nuances: Python is
|
||||||
|
trust-on-first-use, Rust is pin-only). See
|
||||||
|
[Automatic self-signed certificate](./GatewayConfiguration.md#automatic-self-signed-certificate)
|
||||||
|
and each client README for the as-built behavior.
|
||||||
|
|
||||||
## Related Documentation
|
## Related Documentation
|
||||||
|
|
||||||
- [Contracts](./Contracts.md)
|
- [Contracts](./Contracts.md)
|
||||||
- [Sessions](./Sessions.md)
|
- [Sessions](./Sessions.md)
|
||||||
- [Authorization](./Authorization.md)
|
- [Authorization](./Authorization.md)
|
||||||
|
- [Gateway Configuration](./GatewayConfiguration.md)
|
||||||
- [Gateway Process Design](./GatewayProcessDesign.md)
|
- [Gateway Process Design](./GatewayProcessDesign.md)
|
||||||
|
|||||||
+6
-6
@@ -4,7 +4,7 @@ The metrics subsystem exposes counters, histograms, and observable gauges that d
|
|||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
`GatewayMetrics` is a singleton (registered in `GatewayApplication.cs`) that owns a single `Meter` named `ZB.MOM.WW.MxGateway.Server` and a set of synchronised counters, histograms, and observable gauges. Subsystems call typed mutator methods (`SessionOpened`, `CommandFailed`, `EventReceived`, etc.) rather than touching the `Meter` directly, which keeps the OpenTelemetry instrument names and tag conventions in one place. A `lock (_syncRoot)` block guards the scalar fields used by `GetSnapshot`, while per-event maps use `ConcurrentDictionary<string, long>` so the hot event path avoids the lock.
|
`GatewayMetrics` is a singleton (registered in `GatewayApplication.cs`) that owns a single `Meter` named `ZB.MOM.WW.MxGateway` and a set of synchronised counters, histograms, and observable gauges. Subsystems call typed mutator methods (`SessionOpened`, `CommandFailed`, `EventReceived`, etc.) rather than touching the `Meter` directly, which keeps the OpenTelemetry instrument names and tag conventions in one place. A `lock (_syncRoot)` block guards the scalar fields used by `GetSnapshot`, while per-event maps use `ConcurrentDictionary<string, long>` so the hot event path avoids the lock.
|
||||||
|
|
||||||
## Meter and OpenTelemetry Compatibility
|
## Meter and OpenTelemetry Compatibility
|
||||||
|
|
||||||
@@ -13,7 +13,7 @@ The meter name is exposed as a constant so that hosting code can register it wit
|
|||||||
```csharp
|
```csharp
|
||||||
public sealed class GatewayMetrics : IDisposable
|
public sealed class GatewayMetrics : IDisposable
|
||||||
{
|
{
|
||||||
public const string MeterName = "ZB.MOM.WW.MxGateway.Server";
|
public const string MeterName = "ZB.MOM.WW.MxGateway";
|
||||||
|
|
||||||
public GatewayMetrics()
|
public GatewayMetrics()
|
||||||
{
|
{
|
||||||
@@ -50,12 +50,12 @@ All counters are `Counter<long>`. Tag values come from the call sites listed und
|
|||||||
|
|
||||||
### Histograms
|
### Histograms
|
||||||
|
|
||||||
Histograms record durations in milliseconds (the `unit` argument on `CreateHistogram`):
|
Histograms record durations in seconds (the `unit` argument on `CreateHistogram`):
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
_workerStartupLatencyHistogram = _meter.CreateHistogram<double>("mxgateway.workers.startup.duration", "ms");
|
_workerStartupLatencyHistogram = _meter.CreateHistogram<double>("mxgateway.workers.startup.duration", "s");
|
||||||
_commandLatencyHistogram = _meter.CreateHistogram<double>("mxgateway.commands.duration", "ms");
|
_commandLatencyHistogram = _meter.CreateHistogram<double>("mxgateway.commands.duration", "s");
|
||||||
_eventStreamSendLatencyHistogram = _meter.CreateHistogram<double>("mxgateway.events.stream_send.duration", "ms");
|
_eventStreamSendLatencyHistogram = _meter.CreateHistogram<double>("mxgateway.events.stream_send.duration", "s");
|
||||||
```
|
```
|
||||||
|
|
||||||
| Instrument | Tags | What it measures |
|
| Instrument | Tags | What it measures |
|
||||||
|
|||||||
@@ -0,0 +1,156 @@
|
|||||||
|
# Gateway TLS Auto-Certificate and Lenient Client Trust — Design
|
||||||
|
|
||||||
|
Date: 2026-06-01
|
||||||
|
Status: Approved (brainstorming), pending implementation plan
|
||||||
|
|
||||||
|
## Problem
|
||||||
|
|
||||||
|
The gateway can serve gRPC and the dashboard over TLS, but only if an operator
|
||||||
|
supplies a certificate via the Kestrel `https://` endpoint config. With no cert,
|
||||||
|
an `https` endpoint fails at startup with Kestrel's opaque "No server certificate
|
||||||
|
was specified" error. Both current deployments therefore run plaintext (`h2c`),
|
||||||
|
exposing the API key and request payloads on the wire.
|
||||||
|
|
||||||
|
`mxaccessgw` is an internal tool. The goal is for TLS to "just work" with zero PKI
|
||||||
|
management: the gateway fabricates its own long-lived certificate when an HTTPS
|
||||||
|
endpoint is configured without one, and clients accept whatever certificate is
|
||||||
|
presented unless an operator explicitly opts into pinning.
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
1. **Gateway = fill-missing-cert-only.** No new "enable TLS" switch. TLS is still
|
||||||
|
driven by configuring a Kestrel `https://` endpoint. New behavior: when an
|
||||||
|
HTTPS endpoint has no `Certificate` section, the gateway generates/loads a
|
||||||
|
persisted self-signed cert instead of failing. Plaintext-only hosts are
|
||||||
|
untouched — no certificate or key material is ever written for them.
|
||||||
|
2. **Persist & reuse.** The self-signed cert is saved as a PFX under
|
||||||
|
`C:\ProgramData\MxGateway\certs`, reused across restarts, regenerated only if
|
||||||
|
missing, expired, or unreadable. Stable thumbprint; survives restarts; any
|
||||||
|
CA-pinning client keeps working.
|
||||||
|
3. **Clients = lenient TLS, plaintext default.** When a client connects over TLS
|
||||||
|
without a pinned CA, it skips verification (accepts any cert). Pinning a CA file
|
||||||
|
restores full verification. The per-client connection default (mostly
|
||||||
|
plaintext/`http`) does not change — TLS is still opt-in via the endpoint scheme.
|
||||||
|
|
||||||
|
**Scope boundary:** the gateway↔worker named-pipe IPC is unchanged (local,
|
||||||
|
OS-secured by the pipe ACL). This work touches only the public gRPC/dashboard
|
||||||
|
transport and the five language clients.
|
||||||
|
|
||||||
|
## Gateway component
|
||||||
|
|
||||||
|
New type `SelfSignedCertificateProvider` in
|
||||||
|
`src/ZB.MOM.WW.MxGateway.Server/Security/Tls/`.
|
||||||
|
|
||||||
|
1. **Detect need.** Inspect `Kestrel:Endpoints:*` configuration at startup. If any
|
||||||
|
endpoint has an `https://` URL and no `Certificate` subsection, a default cert
|
||||||
|
is needed. If none do, the provider is a no-op (no file written).
|
||||||
|
2. **Load-or-create.** Look for the persisted PFX. If present, valid, and
|
||||||
|
unexpired, load it. Otherwise generate and persist.
|
||||||
|
3. **Generate.** `CertificateRequest` with **ECDSA P-256**, `notBefore = now - 1
|
||||||
|
day` (clock-skew slack), `notAfter = now + ValidityYears`. SANs: `DNS=localhost`,
|
||||||
|
`DNS=<MachineName>`, `DNS=<MachineName.FQDN>` when resolvable, plus
|
||||||
|
`IP=127.0.0.1` and `IP=::1`. Server-auth EKU.
|
||||||
|
4. **Persist securely.** Write the PFX with an **empty** export password (a random
|
||||||
|
in-memory password cannot be reused across restarts, which the persist-and-reuse
|
||||||
|
decision requires); protect the private key with a restrictive ACL (SYSTEM +
|
||||||
|
Administrators + service account) on the `certs` directory and file on Windows,
|
||||||
|
and `0600` on non-Windows; atomic write (temp + rename). After generating, the
|
||||||
|
cert is reloaded from the persisted PFX so Kestrel always serves the on-disk key.
|
||||||
|
5. **Wire into Kestrel.** In `GatewayApplication.CreateBuilder`, add
|
||||||
|
`builder.WebHost.ConfigureKestrel(o => o.ConfigureHttpsDefaults(h =>
|
||||||
|
h.ServerCertificate = cert))`. `ConfigureHttpsDefaults` supplies the cert only
|
||||||
|
for HTTPS endpoints that did not specify their own, so an operator-configured
|
||||||
|
`Kestrel:Endpoints:*:Certificate` transparently overrides it. One hook covers
|
||||||
|
both the gRPC and dashboard ports.
|
||||||
|
|
||||||
|
### New config block `MxGateway:Tls`
|
||||||
|
|
||||||
|
All optional; the zero-config path needs none of them.
|
||||||
|
|
||||||
|
| Option | Default | Purpose |
|
||||||
|
|---|---|---|
|
||||||
|
| `Tls:SelfSignedCertPath` | `C:\ProgramData\MxGateway\certs\gateway-selfsigned.pfx` | Where the generated cert lives |
|
||||||
|
| `Tls:ValidityYears` | `10` | Lifetime of the generated cert |
|
||||||
|
| `Tls:AdditionalDnsNames` | `[]` | Extra SANs (e.g. a load-balancer name) |
|
||||||
|
| `Tls:RegenerateIfExpired` | `true` | Auto-replace an expired persisted cert |
|
||||||
|
|
||||||
|
Validated by `GatewayOptionsValidator`: `ValidityYears` in 1–100,
|
||||||
|
`SelfSignedCertPath` is a valid path shape when non-blank, and
|
||||||
|
`AdditionalDnsNames` entries are non-blank. (The "https endpoint exists but cert
|
||||||
|
path is blank" fail-fast lives in the bootstrap/provider, not the validator,
|
||||||
|
because the validator only sees the `MxGateway` section, not `Kestrel:Endpoints`.)
|
||||||
|
|
||||||
|
**Logging:** on generate/load, log thumbprint + SAN list + `notAfter` at
|
||||||
|
Information. Never log the PFX password or private key.
|
||||||
|
|
||||||
|
## Client lenient-TLS behavior
|
||||||
|
|
||||||
|
Uniform rule: **TLS on + no CA pinned ⇒ skip verification; CA pinned ⇒ full
|
||||||
|
verification.** No transport default changes. Each client also exposes an explicit
|
||||||
|
switch to force-disable leniency (strict-without-pinning) for the future.
|
||||||
|
|
||||||
|
| Client | Mechanism | Effort |
|
||||||
|
|---|---|---|
|
||||||
|
| .NET | In `CreateHttpHandler`, when `UseTls` and `CaCertificatePath` empty, set `SslOptions.RemoteCertificateValidationCallback = (_,_,_,_) => true`. CA path keeps existing custom-root validation. | trivial |
|
||||||
|
| Go | In `buildCredentials`, when TLS and no `CACertFile`/`TLSConfig`, use `tls.Config{InsecureSkipVerify: true, ServerName: override}`. | trivial |
|
||||||
|
| Java | grpc-netty-shaded 1.76.0 ships `InsecureTrustManagerFactory`. When TLS and no CA, build `GrpcSslContexts.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)`. | easy |
|
||||||
|
| Python | grpc-python has no per-channel skip-verify. Fetch the server leaf cert at connect via `ssl.get_server_certificate((host, port))`, pass it as `root_certificates` to `ssl_channel_credentials`, plus `grpc.ssl_target_name_override`. Effectively trusts what is presented (TOFU). | moderate, special-cased |
|
||||||
|
| Rust | tonic 0.13.1 + rustls (`tls-ring`). Implement a custom `rustls::client::danger::ServerCertVerifier` that accepts everything, build a `rustls::ClientConfig` via `.dangerous().with_custom_certificate_verifier(...)`, feed it to the channel. May require a custom hyper-rustls connector if `ClientTlsConfig` will not take a raw rustls config. **Needs an API spike.** | highest |
|
||||||
|
|
||||||
|
### Honesty caveats
|
||||||
|
|
||||||
|
- **Python** is not literally "ignore the cert"; it pins whatever the server
|
||||||
|
presents on first contact via a separate unverified TLS probe. For a self-signed
|
||||||
|
internal cert this is the intended outcome. Documented as a difference.
|
||||||
|
- **Rust** leniency depends on the tonic 0.13 TLS surface. If a custom verifier is
|
||||||
|
disproportionately invasive, the fallback is to require a CA file for Rust TLS
|
||||||
|
(pin-only) and document Rust as the exception.
|
||||||
|
|
||||||
|
## Error handling
|
||||||
|
|
||||||
|
Gateway:
|
||||||
|
- Cert dir not writable / ACL fails ⇒ fail fast at startup with a diagnostic naming
|
||||||
|
the path and required permission. No silent in-memory fallback.
|
||||||
|
- Persisted PFX corrupt/unreadable ⇒ warn, regenerate, overwrite.
|
||||||
|
- Persisted cert expired ⇒ regenerate if `RegenerateIfExpired` (default), else fail
|
||||||
|
fast instructing the operator to delete it or enable regeneration.
|
||||||
|
- HTTPS endpoint configured but generation disabled / path empty ⇒ validator
|
||||||
|
rejects at startup rather than letting Kestrel throw its opaque error.
|
||||||
|
|
||||||
|
Clients: surface unchanged. Skip-verify cannot itself raise. Python's pre-fetch
|
||||||
|
wraps connect failure into the existing connect-error type with the endpoint in the
|
||||||
|
message. Rust pin-only fallback surfaces the existing CA-file error.
|
||||||
|
|
||||||
|
## Documentation (same commit as source, per CLAUDE.md)
|
||||||
|
|
||||||
|
- `docs/GatewayConfiguration.md` — extend the TLS section: auto-generation, the
|
||||||
|
`MxGateway:Tls:*` block, persistence location/ACL, thumbprint logging, operator
|
||||||
|
override via `Kestrel:Endpoints:*:Certificate`.
|
||||||
|
- Each client README + `*ClientDesign.md` — "TLS is lenient by default; pin a CA to
|
||||||
|
verify," with Python TOFU and any Rust caveat noted.
|
||||||
|
- `docs/DesignDecisions.md` — record both posture choices and the why (internal
|
||||||
|
tool, no PKI) so they are not mistaken for an oversight.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Gateway (`MxGateway.Tests`, no MXAccess):
|
||||||
|
- `SelfSignedCertificateProvider`: SANs, server-auth EKU, `notAfter ≈ now +
|
||||||
|
ValidityYears`, ECDSA P-256.
|
||||||
|
- Load-or-create: valid persisted PFX reused (same thumbprint); expired regenerates
|
||||||
|
when enabled; corrupt regenerates with a warning.
|
||||||
|
- Detection: HTTPS-without-cert engages; all-plaintext no-ops and writes no file;
|
||||||
|
endpoint with its own cert is not overridden.
|
||||||
|
- `GatewayOptionsValidator`: new `Tls:*` rules.
|
||||||
|
- Host integration: `Kestrel:Endpoints:Http:Url=https://127.0.0.1:0` builds and
|
||||||
|
binds (today it throws "no certificate specified").
|
||||||
|
|
||||||
|
Clients: each test project gets a lenient-TLS test against a throwaway self-signed
|
||||||
|
cert — connect with no CA succeeds; pinning a wrong CA fails (proves pinning still
|
||||||
|
verifies). Python exercises the pre-fetch path; mark opt-in if loopback timing is
|
||||||
|
flaky. Standard (non-live) tests; no MXAccess or external services.
|
||||||
|
|
||||||
|
Cross-language: add a TLS variant note to `docs/CrossLanguageSmokeMatrix.md`;
|
||||||
|
running the matrix over TLS stays manual/opt-in, consistent with the existing gate.
|
||||||
|
|
||||||
|
Per-component verification follows CLAUDE.md's source-update table (build + test
|
||||||
|
each touched component independently).
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"planPath": "docs/plans/2026-06-01-gateway-cert-autogen-implementation.md",
|
||||||
|
"tasks": [
|
||||||
|
{"id": 1, "subject": "Task 1: Add TlsOptions config + bind into GatewayOptions", "status": "pending"},
|
||||||
|
{"id": 2, "subject": "Task 2: Validate MxGateway:Tls in GatewayOptionsValidator", "status": "pending", "blockedBy": [1]},
|
||||||
|
{"id": 3, "subject": "Task 3: SelfSignedCertificateProvider.GenerateCertificate", "status": "pending", "blockedBy": [1]},
|
||||||
|
{"id": 4, "subject": "Task 4: SelfSignedCertificateProvider.LoadOrCreate (persist/reuse/regenerate/ACL)", "status": "pending", "blockedBy": [3]},
|
||||||
|
{"id": 5, "subject": "Task 5: KestrelTlsInspector (detect HTTPS-without-cert)", "status": "pending"},
|
||||||
|
{"id": 6, "subject": "Task 6: Wire auto-cert into GatewayApplication.CreateBuilder", "status": "pending", "blockedBy": [1, 4, 5]},
|
||||||
|
{"id": 7, "subject": "Task 7: .NET client lenient TLS by default", "status": "pending"},
|
||||||
|
{"id": 8, "subject": "Task 8: Go client lenient TLS by default", "status": "pending"},
|
||||||
|
{"id": 9, "subject": "Task 9: Java client lenient TLS by default", "status": "pending"},
|
||||||
|
{"id": 10, "subject": "Task 10: Python client lenient TLS via TOFU pre-fetch", "status": "pending"},
|
||||||
|
{"id": 11, "subject": "Task 11: Rust client lenient TLS via rustls verifier (spike + fallback)", "status": "pending"},
|
||||||
|
{"id": 12, "subject": "Task 12: Documentation", "status": "pending", "blockedBy": [6, 7, 8, 9, 10, 11]}
|
||||||
|
],
|
||||||
|
"lastUpdated": "2026-06-01"
|
||||||
|
}
|
||||||
@@ -20,9 +20,9 @@ against them, and what's needed to add a gw-specific role.
|
|||||||
| Host | `localhost` |
|
| Host | `localhost` |
|
||||||
| Port | `3893` |
|
| Port | `3893` |
|
||||||
| LDAPS | disabled in dev (set `[ldaps]` block to enable) |
|
| LDAPS | disabled in dev (set `[ldaps]` block to enable) |
|
||||||
| Base DN | `dc=lmxopcua,dc=local` |
|
| Base DN | `dc=zb,dc=local` |
|
||||||
| Bind DN format | `cn={username},dc=lmxopcua,dc=local` |
|
| Bind DN format | `cn={username},dc=zb,dc=local` |
|
||||||
| Group OU | `ou=<groupname>,ou=groups,dc=lmxopcua,dc=local` |
|
| Group OU | `ou=<groupname>,ou=groups,dc=zb,dc=local` |
|
||||||
| Failed-bind throttle | 3 fails → 10-minute IP lockout (per `[behaviors]`) |
|
| Failed-bind throttle | 3 fails → 10-minute IP lockout (per `[behaviors]`) |
|
||||||
|
|
||||||
## Pre-existing groups (LmxOpcUa role taxonomy)
|
## Pre-existing groups (LmxOpcUa role taxonomy)
|
||||||
@@ -33,11 +33,11 @@ LmxOpcUa write rights doesn't need a second account for the gw.
|
|||||||
|
|
||||||
| Group | GID | DN | LmxOpcUa meaning | Suggested mxgw mapping |
|
| Group | GID | DN | LmxOpcUa meaning | Suggested mxgw mapping |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| ReadOnly | 5501 | `ou=ReadOnly,ou=groups,dc=lmxopcua,dc=local` | Browse + read OPC UA nodes | `Browse` + `Subscribe` (read paths only) |
|
| ReadOnly | 5501 | `ou=ReadOnly,ou=groups,dc=zb,dc=local` | Browse + read OPC UA nodes | `Browse` + `Subscribe` (read paths only) |
|
||||||
| WriteOperate | 5502 | `ou=WriteOperate,ou=groups,dc=lmxopcua,dc=local` | Write FreeAccess / Operate attrs | `Write` (plain) |
|
| WriteOperate | 5502 | `ou=WriteOperate,ou=groups,dc=zb,dc=local` | Write FreeAccess / Operate attrs | `Write` (plain) |
|
||||||
| WriteTune | 5504 | `ou=WriteTune,ou=groups,dc=lmxopcua,dc=local` | Write Tune attrs | `WriteSecured` (Tune only) |
|
| WriteTune | 5504 | `ou=WriteTune,ou=groups,dc=zb,dc=local` | Write Tune attrs | `WriteSecured` (Tune only) |
|
||||||
| WriteConfigure | 5505 | `ou=WriteConfigure,ou=groups,dc=lmxopcua,dc=local` | Write Configure attrs | `WriteSecured` (Configure) |
|
| WriteConfigure | 5505 | `ou=WriteConfigure,ou=groups,dc=zb,dc=local` | Write Configure attrs | `WriteSecured` (Configure) |
|
||||||
| AlarmAck | 5503 | `ou=AlarmAck,ou=groups,dc=lmxopcua,dc=local` | Acknowledge alarms | gw alarm-ack RPC, when added |
|
| AlarmAck | 5503 | `ou=AlarmAck,ou=groups,dc=zb,dc=local` | Acknowledge alarms | gw alarm-ack RPC, when added |
|
||||||
|
|
||||||
**A user can be in multiple groups** — `othergroups = [...]` in the
|
**A user can be in multiple groups** — `othergroups = [...]` in the
|
||||||
config is a list. `admin` is the canonical example (in every role
|
config is a list. `admin` is the canonical example (in every role
|
||||||
@@ -67,12 +67,18 @@ GLAuth config — it must be provisioned before dashboard authn or the
|
|||||||
LDAP live tests work. See [Provisioning the GwAdmin
|
LDAP live tests work. See [Provisioning the GwAdmin
|
||||||
group](#provisioning-the-gwadmin-group) below.
|
group](#provisioning-the-gwadmin-group) below.
|
||||||
|
|
||||||
|
> **Dashboard role value (Task 1.7):** the LDAP `GwAdmin` group now maps to
|
||||||
|
> the canonical dashboard role **`Administrator`** (was `Admin`); `GwReader`
|
||||||
|
> maps to `Viewer`. This is a pure value rename via
|
||||||
|
> `MxGateway:Dashboard:GroupToRole` — same operations are authorized. (This
|
||||||
|
> dashboard role is distinct from the lowercase gRPC `admin` *API-key scope*.)
|
||||||
|
|
||||||
## Two bind patterns
|
## Two bind patterns
|
||||||
|
|
||||||
### 1. Direct bind (simplest)
|
### 1. Direct bind (simplest)
|
||||||
|
|
||||||
```
|
```
|
||||||
DN: cn=admin,dc=lmxopcua,dc=local
|
DN: cn=admin,dc=zb,dc=local
|
||||||
Password: admin123
|
Password: admin123
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -84,9 +90,9 @@ by `sAMAccountName`, not `cn`. Use this only for dev convenience.
|
|||||||
### 2. Bind-then-search (production-grade)
|
### 2. Bind-then-search (production-grade)
|
||||||
|
|
||||||
```
|
```
|
||||||
1. Bind as the service account (cn=serviceaccount,dc=lmxopcua,dc=local
|
1. Bind as the service account (cn=serviceaccount,dc=zb,dc=local
|
||||||
/ serviceaccount123).
|
/ serviceaccount123).
|
||||||
2. Search under dc=lmxopcua,dc=local with filter
|
2. Search under dc=zb,dc=local with filter
|
||||||
(uid=<entered-username>) — or any attribute the deployment
|
(uid=<entered-username>) — or any attribute the deployment
|
||||||
identifies users by. GLAuth populates uid + cn.
|
identifies users by. GLAuth populates uid + cn.
|
||||||
3. Read the returned entry's DN + memberOf list (groups).
|
3. Read the returned entry's DN + memberOf list (groups).
|
||||||
@@ -116,8 +122,8 @@ ldap:
|
|||||||
port: 3893
|
port: 3893
|
||||||
useTls: false
|
useTls: false
|
||||||
allowInsecureLdap: true # dev only
|
allowInsecureLdap: true # dev only
|
||||||
searchBase: "dc=lmxopcua,dc=local"
|
searchBase: "dc=zb,dc=local"
|
||||||
serviceAccountDn: "cn=serviceaccount,dc=lmxopcua,dc=local"
|
serviceAccountDn: "cn=serviceaccount,dc=zb,dc=local"
|
||||||
serviceAccountPassword: "serviceaccount123"
|
serviceAccountPassword: "serviceaccount123"
|
||||||
userNameAttribute: "uid" # GLAuth populates this; AD uses sAMAccountName
|
userNameAttribute: "uid" # GLAuth populates this; AD uses sAMAccountName
|
||||||
displayNameAttribute: "cn"
|
displayNameAttribute: "cn"
|
||||||
@@ -131,7 +137,7 @@ ldap:
|
|||||||
```
|
```
|
||||||
|
|
||||||
`groupAttribute` returns full DNs like
|
`groupAttribute` returns full DNs like
|
||||||
`ou=ReadOnly,ou=groups,dc=lmxopcua,dc=local` — the authenticator
|
`ou=ReadOnly,ou=groups,dc=zb,dc=local` — the authenticator
|
||||||
should strip the leading `ou=` (or `cn=` against AD) RDN value and
|
should strip the leading `ou=` (or `cn=` against AD) RDN value and
|
||||||
look that up in `groupToRole`.
|
look that up in `groupToRole`.
|
||||||
|
|
||||||
@@ -172,7 +178,7 @@ server:
|
|||||||
4. `nssm restart GLAuth`
|
4. `nssm restart GLAuth`
|
||||||
|
|
||||||
After the restart, `admin`'s `memberOf` includes
|
After the restart, `admin`'s `memberOf` includes
|
||||||
`ou=GwAdmin,ou=groups,dc=lmxopcua,dc=local`, which the authenticator
|
`ou=GwAdmin,ou=groups,dc=zb,dc=local`, which the authenticator
|
||||||
strips to `GwAdmin` and matches against `RequiredGroup`. The same
|
strips to `GwAdmin` and matches against `RequiredGroup`. The same
|
||||||
pattern applies to any future permission that doesn't fit the existing
|
pattern applies to any future permission that doesn't fit the existing
|
||||||
five roles.
|
five roles.
|
||||||
@@ -201,7 +207,7 @@ $ldap = New-Object System.DirectoryServices.Protocols.LdapConnection("localhost:
|
|||||||
$ldap.AuthType = [System.DirectoryServices.Protocols.AuthType]::Basic
|
$ldap.AuthType = [System.DirectoryServices.Protocols.AuthType]::Basic
|
||||||
$ldap.SessionOptions.ProtocolVersion = 3
|
$ldap.SessionOptions.ProtocolVersion = 3
|
||||||
$ldap.SessionOptions.SecureSocketLayer = $false
|
$ldap.SessionOptions.SecureSocketLayer = $false
|
||||||
$cred = New-Object System.Net.NetworkCredential("cn=admin,dc=lmxopcua,dc=local","admin123")
|
$cred = New-Object System.Net.NetworkCredential("cn=admin,dc=zb,dc=local","admin123")
|
||||||
$ldap.Bind($cred)
|
$ldap.Bind($cred)
|
||||||
"Bind OK"
|
"Bind OK"
|
||||||
```
|
```
|
||||||
@@ -210,8 +216,8 @@ Or via `ldapsearch` if you have OpenLDAP CLI tools:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
ldapsearch -x -H ldap://localhost:3893 \
|
ldapsearch -x -H ldap://localhost:3893 \
|
||||||
-D "cn=admin,dc=lmxopcua,dc=local" -w admin123 \
|
-D "cn=admin,dc=zb,dc=local" -w admin123 \
|
||||||
-b "dc=lmxopcua,dc=local" "(uid=admin)"
|
-b "dc=zb,dc=local" "(uid=admin)"
|
||||||
```
|
```
|
||||||
|
|
||||||
The response should list `admin`'s entry with `memberOf` populated for
|
The response should list `admin`'s entry with `memberOf` populated for
|
||||||
@@ -257,8 +263,8 @@ applies to mxaccessgw verbatim. Keys that change:
|
|||||||
| `Port` | `3893` | `636` (LDAPS) — AD increasingly rejects plain bind under LDAP-signing enforcement |
|
| `Port` | `3893` | `636` (LDAPS) — AD increasingly rejects plain bind under LDAP-signing enforcement |
|
||||||
| `UseTls` | `false` | `true` |
|
| `UseTls` | `false` | `true` |
|
||||||
| `AllowInsecureLdap` | `true` | `false` |
|
| `AllowInsecureLdap` | `true` | `false` |
|
||||||
| `SearchBase` | `dc=lmxopcua,dc=local` | `DC=corp,DC=example,DC=com` |
|
| `SearchBase` | `dc=zb,dc=local` | `DC=corp,DC=example,DC=com` |
|
||||||
| `ServiceAccountDn` | `cn=serviceaccount,dc=lmxopcua,dc=local` | `CN=MxGwSvc,OU=Service Accounts,DC=corp,...` |
|
| `ServiceAccountDn` | `cn=serviceaccount,dc=zb,dc=local` | `CN=MxGwSvc,OU=Service Accounts,DC=corp,...` |
|
||||||
| `UserNameAttribute` | `uid` | `sAMAccountName` (or `userPrincipalName`) |
|
| `UserNameAttribute` | `uid` | `sAMAccountName` (or `userPrincipalName`) |
|
||||||
| `GroupAttribute` | `memberOf` (unchanged) | `memberOf` (unchanged) |
|
| `GroupAttribute` | `memberOf` (unchanged) | `memberOf` (unchanged) |
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<configuration>
|
||||||
|
<packageSources>
|
||||||
|
<clear />
|
||||||
|
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
|
||||||
|
<add key="dohertj2-gitea" value="https://gitea.dohertylan.com/api/packages/dohertj2/nuget/index.json" />
|
||||||
|
</packageSources>
|
||||||
|
<!-- nuget.org serves everything; the Gitea feed serves only the ZB.MOM.WW.* shared libs.
|
||||||
|
Credentials are NOT committed: they are provided per-developer at the user level. -->
|
||||||
|
<packageSourceMapping>
|
||||||
|
<packageSource key="nuget.org">
|
||||||
|
<package pattern="*" />
|
||||||
|
</packageSource>
|
||||||
|
<packageSource key="dohertj2-gitea">
|
||||||
|
<package pattern="ZB.MOM.WW.Health" />
|
||||||
|
<package pattern="ZB.MOM.WW.Health.*" />
|
||||||
|
<package pattern="ZB.MOM.WW.Telemetry" />
|
||||||
|
<package pattern="ZB.MOM.WW.Telemetry.*" />
|
||||||
|
<package pattern="ZB.MOM.WW.Configuration" />
|
||||||
|
<package pattern="ZB.MOM.WW.Auth" />
|
||||||
|
<package pattern="ZB.MOM.WW.Auth.*" />
|
||||||
|
<package pattern="ZB.MOM.WW.Audit" />
|
||||||
|
<package pattern="ZB.MOM.WW.Theme" />
|
||||||
|
</packageSource>
|
||||||
|
</packageSourceMapping>
|
||||||
|
</configuration>
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using Microsoft.Extensions.Logging.Abstractions;
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||||
|
using ZB.MOM.WW.Auth.Ldap;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Dashboard;
|
using ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||||
|
using LibraryLdapOptions = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapOptions;
|
||||||
|
|
||||||
namespace ZB.MOM.WW.MxGateway.IntegrationTests;
|
namespace ZB.MOM.WW.MxGateway.IntegrationTests;
|
||||||
|
|
||||||
@@ -11,6 +14,7 @@ namespace ZB.MOM.WW.MxGateway.IntegrationTests;
|
|||||||
public sealed class DashboardLdapLiveTests
|
public sealed class DashboardLdapLiveTests
|
||||||
{
|
{
|
||||||
/// <summary>Verifies that an admin user in the GwAdmin group authenticates successfully.</summary>
|
/// <summary>Verifies that an admin user in the GwAdmin group authenticates successfully.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveLdapFact]
|
[LiveLdapFact]
|
||||||
public async Task AuthenticateAsync_AdminInGwAdminGroup_Succeeds()
|
public async Task AuthenticateAsync_AdminInGwAdminGroup_Succeeds()
|
||||||
{
|
{
|
||||||
@@ -28,18 +32,18 @@ public sealed class DashboardLdapLiveTests
|
|||||||
claim.Type == DashboardAuthenticationDefaults.LdapGroupClaimType
|
claim.Type == DashboardAuthenticationDefaults.LdapGroupClaimType
|
||||||
&& claim.Value.Contains("GwAdmin", StringComparison.OrdinalIgnoreCase));
|
&& claim.Value.Contains("GwAdmin", StringComparison.OrdinalIgnoreCase));
|
||||||
|
|
||||||
// IntegrationTests-023: DashboardAuthenticator.CreatePrincipal emits a
|
// IntegrationTests-023: DashboardAuthenticator builds the principal with a
|
||||||
// ClaimTypes.Role claim derived from MapGroupsToRoles. The seeded
|
// ClaimTypes.Role claim resolved from the LDAP groups via the
|
||||||
// GroupToRole map (GwAdmin -> Admin) means the admin principal must
|
// DashboardGroupRoleMapper. The seeded GroupToRole map (GwAdmin -> Admin)
|
||||||
// carry Role=Admin alongside the raw LDAP-group claim. A regression in
|
// means the admin principal must carry Role=Admin alongside the raw LDAP-group
|
||||||
// MapGroupsToRoles (returning an empty list, missing the RDN fallback)
|
// claim. A regression in the group→role mapping would fail this assertion.
|
||||||
// would silently pass without this assertion.
|
|
||||||
Assert.Contains(result.Principal.Claims, claim =>
|
Assert.Contains(result.Principal.Claims, claim =>
|
||||||
claim.Type == ClaimTypes.Role
|
claim.Type == ClaimTypes.Role
|
||||||
&& claim.Value == DashboardRoles.Admin);
|
&& claim.Value == DashboardRoles.Admin);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that a readonly user without GwAdmin group fails to authenticate.</summary>
|
/// <summary>Verifies that a readonly user without GwAdmin group fails to authenticate.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveLdapFact]
|
[LiveLdapFact]
|
||||||
public async Task AuthenticateAsync_ReadOnlyUserMissingGwAdminGroup_Fails()
|
public async Task AuthenticateAsync_ReadOnlyUserMissingGwAdminGroup_Fails()
|
||||||
{
|
{
|
||||||
@@ -56,10 +60,11 @@ public sealed class DashboardLdapLiveTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that authentication with wrong password fails without leaking the password.</summary>
|
/// <summary>Verifies that authentication with wrong password fails without leaking the password.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveLdapFact]
|
[LiveLdapFact]
|
||||||
public async Task AuthenticateAsync_AdminWithWrongPassword_FailsWithoutLeakingPassword()
|
public async Task AuthenticateAsync_AdminWithWrongPassword_FailsWithoutLeakingPassword()
|
||||||
{
|
{
|
||||||
// Exercises the LdapException branch: the user exists and the service
|
// Exercises the user-bind-failure branch: the user exists and the service
|
||||||
// account search succeeds, but the candidate bind is rejected.
|
// account search succeeds, but the candidate bind is rejected.
|
||||||
const string wrongPassword = "definitely-not-the-admin-password";
|
const string wrongPassword = "definitely-not-the-admin-password";
|
||||||
DashboardAuthenticator authenticator = CreateAuthenticator();
|
DashboardAuthenticator authenticator = CreateAuthenticator();
|
||||||
@@ -75,11 +80,12 @@ public sealed class DashboardLdapLiveTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that authentication with unknown username fails.</summary>
|
/// <summary>Verifies that authentication with unknown username fails.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveLdapFact]
|
[LiveLdapFact]
|
||||||
public async Task AuthenticateAsync_UnknownUsername_Fails()
|
public async Task AuthenticateAsync_UnknownUsername_Fails()
|
||||||
{
|
{
|
||||||
// Exercises the `candidate is null` branch: the service-account search
|
// Exercises the user-not-found branch: the service-account search returns no
|
||||||
// returns no entry, so no candidate bind is attempted.
|
// entry, so no candidate bind is attempted.
|
||||||
DashboardAuthenticator authenticator = CreateAuthenticator();
|
DashboardAuthenticator authenticator = CreateAuthenticator();
|
||||||
|
|
||||||
DashboardAuthenticationResult result = await authenticator.AuthenticateAsync(
|
DashboardAuthenticationResult result = await authenticator.AuthenticateAsync(
|
||||||
@@ -92,22 +98,18 @@ public sealed class DashboardLdapLiveTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that authentication fails gracefully when the server is unreachable.</summary>
|
/// <summary>Verifies that authentication fails gracefully when the server is unreachable.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveLdapFact]
|
[LiveLdapFact]
|
||||||
public async Task AuthenticateAsync_ServerUnreachable_FailsWithoutThrowing()
|
public async Task AuthenticateAsync_ServerUnreachable_FailsWithoutThrowing()
|
||||||
{
|
{
|
||||||
// Exercises the connect-failure path: a closed loopback port produces a
|
// Exercises the connect-failure path: a closed loopback port produces a
|
||||||
// connection error that DashboardAuthenticator must absorb into a Fail
|
// connection error that the shared LdapAuthService must absorb into a Fail
|
||||||
// result rather than propagating an exception to the dashboard.
|
// result rather than propagating an exception to the dashboard.
|
||||||
DashboardAuthenticator authenticator = new(
|
DashboardAuthenticator authenticator = CreateAuthenticator(LibraryOptions() with
|
||||||
Options.Create(new GatewayOptions
|
{
|
||||||
{
|
// 1 is a reserved port number that no LDAP server listens on.
|
||||||
Ldap = new LdapOptions
|
Port = 1,
|
||||||
{
|
});
|
||||||
// 1 is a reserved port number that no LDAP server listens on.
|
|
||||||
Port = 1,
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
NullLogger<DashboardAuthenticator>.Instance);
|
|
||||||
|
|
||||||
DashboardAuthenticationResult result = await authenticator.AuthenticateAsync(
|
DashboardAuthenticationResult result = await authenticator.AuthenticateAsync(
|
||||||
"admin",
|
"admin",
|
||||||
@@ -118,19 +120,48 @@ public sealed class DashboardLdapLiveTests
|
|||||||
Assert.Null(result.Principal);
|
Assert.Null(result.Principal);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static DashboardAuthenticator CreateAuthenticator()
|
private static DashboardAuthenticator CreateAuthenticator() => CreateAuthenticator(LibraryOptions());
|
||||||
|
|
||||||
|
private static DashboardAuthenticator CreateAuthenticator(LibraryLdapOptions ldapOptions)
|
||||||
{
|
{
|
||||||
return new DashboardAuthenticator(
|
GatewayOptions gatewayOptions = new()
|
||||||
Options.Create(new GatewayOptions
|
{
|
||||||
|
Dashboard = new DashboardOptions
|
||||||
{
|
{
|
||||||
Dashboard = new DashboardOptions
|
GroupToRole = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||||
{
|
{
|
||||||
GroupToRole = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
["GwAdmin"] = DashboardRoles.Admin,
|
||||||
{
|
|
||||||
["GwAdmin"] = DashboardRoles.Admin,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
}),
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return new DashboardAuthenticator(
|
||||||
|
new LdapAuthService(ldapOptions),
|
||||||
|
new DashboardGroupRoleMapper(Options.Create(gatewayOptions)),
|
||||||
NullLogger<DashboardAuthenticator>.Instance);
|
NullLogger<DashboardAuthenticator>.Instance);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds the shared library <see cref="LibraryLdapOptions"/> from the gateway's
|
||||||
|
/// default LDAP settings so the live tests exercise the same seeded directory the
|
||||||
|
/// gateway connects to (localhost:3893, plaintext, with AllowInsecure for dev).
|
||||||
|
/// </summary>
|
||||||
|
private static LibraryLdapOptions LibraryOptions()
|
||||||
|
{
|
||||||
|
ZB.MOM.WW.MxGateway.Server.Configuration.LdapOptions gateway = new();
|
||||||
|
return new LibraryLdapOptions
|
||||||
|
{
|
||||||
|
Enabled = gateway.Enabled,
|
||||||
|
Server = gateway.Server,
|
||||||
|
Port = gateway.Port,
|
||||||
|
Transport = gateway.Transport,
|
||||||
|
AllowInsecure = gateway.AllowInsecure,
|
||||||
|
SearchBase = gateway.SearchBase,
|
||||||
|
ServiceAccountDn = gateway.ServiceAccountDn,
|
||||||
|
ServiceAccountPassword = gateway.ServiceAccountPassword,
|
||||||
|
UserNameAttribute = gateway.UserNameAttribute,
|
||||||
|
DisplayNameAttribute = gateway.DisplayNameAttribute,
|
||||||
|
GroupAttribute = gateway.GroupAttribute,
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ namespace ZB.MOM.WW.MxGateway.IntegrationTests.Galaxy;
|
|||||||
public sealed class GalaxyRepositoryLiveTests
|
public sealed class GalaxyRepositoryLiveTests
|
||||||
{
|
{
|
||||||
/// <summary>Verifies that the Galaxy Repository can establish a live connection to the ZB database.</summary>
|
/// <summary>Verifies that the Galaxy Repository can establish a live connection to the ZB database.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveGalaxyRepositoryFact]
|
[LiveGalaxyRepositoryFact]
|
||||||
public async Task TestConnection_AgainstZb_Succeeds()
|
public async Task TestConnection_AgainstZb_Succeeds()
|
||||||
{
|
{
|
||||||
@@ -18,6 +19,7 @@ public sealed class GalaxyRepositoryLiveTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that the last deploy time can be retrieved from the ZB database.</summary>
|
/// <summary>Verifies that the last deploy time can be retrieved from the ZB database.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveGalaxyRepositoryFact]
|
[LiveGalaxyRepositoryFact]
|
||||||
public async Task GetLastDeployTime_AgainstZb_ReturnsTimestamp()
|
public async Task GetLastDeployTime_AgainstZb_ReturnsTimestamp()
|
||||||
{
|
{
|
||||||
@@ -29,6 +31,7 @@ public sealed class GalaxyRepositoryLiveTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that the hierarchy can be retrieved from the ZB database.</summary>
|
/// <summary>Verifies that the hierarchy can be retrieved from the ZB database.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveGalaxyRepositoryFact]
|
[LiveGalaxyRepositoryFact]
|
||||||
public async Task GetHierarchy_AgainstZb_ReturnsObjects()
|
public async Task GetHierarchy_AgainstZb_ReturnsObjects()
|
||||||
{
|
{
|
||||||
@@ -46,6 +49,7 @@ public sealed class GalaxyRepositoryLiveTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that object attributes can be retrieved from the ZB database.</summary>
|
/// <summary>Verifies that object attributes can be retrieved from the ZB database.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveGalaxyRepositoryFact]
|
[LiveGalaxyRepositoryFact]
|
||||||
public async Task GetAttributes_AgainstZb_ReturnsAtLeastOneAttribute()
|
public async Task GetAttributes_AgainstZb_ReturnsAtLeastOneAttribute()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies that a gateway session can register, add item, advise, and stream events from live MXAccess.
|
/// Verifies that a gateway session can register, add item, advise, and stream events from live MXAccess.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveMxAccessFact]
|
[LiveMxAccessFact]
|
||||||
public async Task GatewaySession_WithLiveWorker_RegistersAdvisesStreamsDataAndCloses()
|
public async Task GatewaySession_WithLiveWorker_RegistersAdvisesStreamsDataAndCloses()
|
||||||
{
|
{
|
||||||
@@ -119,6 +120,7 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
/// and that the worker emits a matching <see cref="MxEventFamily.OnWriteComplete"/> event
|
/// and that the worker emits a matching <see cref="MxEventFamily.OnWriteComplete"/> event
|
||||||
/// — the proof of round-trip the cross-language client e2e runner relies on.
|
/// — the proof of round-trip the cross-language client e2e runner relies on.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveMxAccessFact]
|
[LiveMxAccessFact]
|
||||||
public async Task GatewaySession_WithLiveWorker_WritesValueToAdvisedItem()
|
public async Task GatewaySession_WithLiveWorker_WritesValueToAdvisedItem()
|
||||||
{
|
{
|
||||||
@@ -235,6 +237,7 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
/// Verifies that an AddItem against an invalid server handle surfaces the MXAccess failure
|
/// Verifies that an AddItem against an invalid server handle surfaces the MXAccess failure
|
||||||
/// without faulting the gateway transport, exercising the invalid-handle parity path.
|
/// without faulting the gateway transport, exercising the invalid-handle parity path.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveMxAccessFact]
|
[LiveMxAccessFact]
|
||||||
public async Task GatewaySession_WithLiveWorker_InvalidHandleCommand_SurfacesFailureWithoutTransportFault()
|
public async Task GatewaySession_WithLiveWorker_InvalidHandleCommand_SurfacesFailureWithoutTransportFault()
|
||||||
{
|
{
|
||||||
@@ -293,6 +296,7 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
/// OnDataChange events for the un-advised item. Exercises the lifecycle-ordering
|
/// OnDataChange events for the un-advised item. Exercises the lifecycle-ordering
|
||||||
/// parity CLAUDE.md singles out as a "do not synthesize" rule.
|
/// parity CLAUDE.md singles out as a "do not synthesize" rule.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveMxAccessFact]
|
[LiveMxAccessFact]
|
||||||
public async Task GatewaySession_WithLiveWorker_UnadviseRemoveItemUnregister_TeardownOrderingParity()
|
public async Task GatewaySession_WithLiveWorker_UnadviseRemoveItemUnregister_TeardownOrderingParity()
|
||||||
{
|
{
|
||||||
@@ -437,6 +441,7 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
/// parity surface the gateway must not "fix" — the test asserts the reply kind and
|
/// parity surface the gateway must not "fix" — the test asserts the reply kind and
|
||||||
/// protocol status, not a fabricated outcome.
|
/// protocol status, not a fabricated outcome.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveMxAccessFact]
|
[LiveMxAccessFact]
|
||||||
public async Task GatewaySession_WithLiveWorker_WriteSecured_AuthenticatedRoundTripParity()
|
public async Task GatewaySession_WithLiveWorker_WriteSecured_AuthenticatedRoundTripParity()
|
||||||
{
|
{
|
||||||
@@ -568,6 +573,7 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
/// must observe the abnormal exit, transition the session, and surface a non-empty
|
/// must observe the abnormal exit, transition the session, and surface a non-empty
|
||||||
/// fault description rather than hanging or crashing.
|
/// fault description rather than hanging or crashing.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[LiveMxAccessFact]
|
[LiveMxAccessFact]
|
||||||
public async Task GatewaySession_WithLiveWorker_AbnormalWorkerExit_MarksSessionFaulted()
|
public async Task GatewaySession_WithLiveWorker_AbnormalWorkerExit_MarksSessionFaulted()
|
||||||
{
|
{
|
||||||
@@ -1114,6 +1120,7 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="sessionId">The session identifier.</param>
|
/// <param name="sessionId">The session identifier.</param>
|
||||||
/// <param name="session">The session if found; otherwise null.</param>
|
/// <param name="session">The session if found; otherwise null.</param>
|
||||||
|
/// <returns>True if the session was found; otherwise false.</returns>
|
||||||
public bool TryGetSession(string sessionId, [MaybeNullWhen(false)] out GatewaySession session)
|
public bool TryGetSession(string sessionId, [MaybeNullWhen(false)] out GatewaySession session)
|
||||||
{
|
{
|
||||||
return _registry.TryGet(sessionId, out session);
|
return _registry.TryGet(sessionId, out session);
|
||||||
@@ -1122,6 +1129,7 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Disposes the fixture resources and closes all sessions.
|
/// Disposes the fixture resources and closes all sessions.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous dispose operation.</returns>
|
||||||
public async ValueTask DisposeAsync()
|
public async ValueTask DisposeAsync()
|
||||||
{
|
{
|
||||||
foreach (GatewaySession session in _registry.Snapshot())
|
foreach (GatewaySession session in _registry.Snapshot())
|
||||||
@@ -1192,6 +1200,7 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
/// Records the message and signals any pending waiter.
|
/// Records the message and signals any pending waiter.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="message">The message to write.</param>
|
/// <param name="message">The message to write.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
public Task WriteAsync(T message)
|
public Task WriteAsync(T message)
|
||||||
{
|
{
|
||||||
lock (syncRoot)
|
lock (syncRoot)
|
||||||
@@ -1374,7 +1383,9 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
return workerProcess;
|
return workerProcess;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <summary>Waits for all recorded worker processes to exit within the specified timeout.</summary>
|
||||||
|
/// <param name="timeout">Maximum time to wait for each process to exit.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
public async Task WaitForProcessesAsync(TimeSpan timeout)
|
public async Task WaitForProcessesAsync(TimeSpan timeout)
|
||||||
{
|
{
|
||||||
foreach (TestWorkerProcess process in processes)
|
foreach (TestWorkerProcess process in processes)
|
||||||
@@ -1454,7 +1465,7 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
process.Kill(entireProcessTree);
|
process.Kill(entireProcessTree);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <summary>Releases the wrapped process resources.</summary>
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
process.Dispose();
|
process.Dispose();
|
||||||
@@ -1466,13 +1477,15 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private sealed class TestOutputLoggerProvider(ITestOutputHelper output) : ILoggerProvider
|
private sealed class TestOutputLoggerProvider(ITestOutputHelper output) : ILoggerProvider
|
||||||
{
|
{
|
||||||
/// <inheritdoc />
|
/// <summary>Creates a logger that writes to the test output helper for the given category.</summary>
|
||||||
|
/// <param name="categoryName">The logger category name.</param>
|
||||||
|
/// <returns>A logger that forwards to the test output helper.</returns>
|
||||||
public ILogger CreateLogger(string categoryName)
|
public ILogger CreateLogger(string categoryName)
|
||||||
{
|
{
|
||||||
return new TestOutputLogger(output, categoryName);
|
return new TestOutputLogger(output, categoryName);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <summary>Releases resources held by the provider (no-op for this test double).</summary>
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
@@ -1485,20 +1498,31 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
ITestOutputHelper output,
|
ITestOutputHelper output,
|
||||||
string categoryName) : ILogger
|
string categoryName) : ILogger
|
||||||
{
|
{
|
||||||
/// <inheritdoc />
|
/// <summary>Begins a log scope; returns null as this test logger does not support scopes.</summary>
|
||||||
|
/// <param name="state">The state object for the scope.</param>
|
||||||
|
/// <typeparam name="TState">The type of the state object.</typeparam>
|
||||||
|
/// <returns>Always null.</returns>
|
||||||
public IDisposable? BeginScope<TState>(TState state)
|
public IDisposable? BeginScope<TState>(TState state)
|
||||||
where TState : notnull
|
where TState : notnull
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <summary>Returns true for log levels at or above <see cref="LogLevel.Information"/>.</summary>
|
||||||
|
/// <param name="logLevel">The log level to check.</param>
|
||||||
|
/// <returns>True if the log level is enabled.</returns>
|
||||||
public bool IsEnabled(LogLevel logLevel)
|
public bool IsEnabled(LogLevel logLevel)
|
||||||
{
|
{
|
||||||
return logLevel >= LogLevel.Information;
|
return logLevel >= LogLevel.Information;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <summary>Writes a log entry to the test output helper.</summary>
|
||||||
|
/// <param name="logLevel">The log level.</param>
|
||||||
|
/// <param name="eventId">The event identifier.</param>
|
||||||
|
/// <param name="state">The state object to log.</param>
|
||||||
|
/// <param name="exception">Optional exception associated with the log entry.</param>
|
||||||
|
/// <param name="formatter">Function to format the state and exception into a string.</param>
|
||||||
|
/// <typeparam name="TState">The type of the state object.</typeparam>
|
||||||
public void Log<TState>(
|
public void Log<TState>(
|
||||||
LogLevel logLevel,
|
LogLevel logLevel,
|
||||||
EventId eventId,
|
EventId eventId,
|
||||||
|
|||||||
@@ -688,6 +688,7 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
|
|||||||
|
|
||||||
/// <summary>Determines whether the alarm reference matches this subscriber's filter.</summary>
|
/// <summary>Determines whether the alarm reference matches this subscriber's filter.</summary>
|
||||||
/// <param name="reference">The alarm reference to match.</param>
|
/// <param name="reference">The alarm reference to match.</param>
|
||||||
|
/// <returns>True if the reference starts with this subscriber's prefix or no prefix is set.</returns>
|
||||||
public bool Matches(string reference)
|
public bool Matches(string reference)
|
||||||
{
|
{
|
||||||
return prefix.Length == 0 || reference.StartsWith(prefix, StringComparison.Ordinal);
|
return prefix.Length == 0 || reference.StartsWith(prefix, StringComparison.Ordinal);
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ public interface IGatewayAlarmService
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="alarmFilterPrefix">Optional alarm-reference prefix scoping the feed.</param>
|
/// <param name="alarmFilterPrefix">Optional alarm-reference prefix scoping the feed.</param>
|
||||||
/// <param name="cancellationToken">Token that ends the subscription.</param>
|
/// <param name="cancellationToken">Token that ends the subscription.</param>
|
||||||
|
/// <returns>An async enumerable of alarm feed messages.</returns>
|
||||||
IAsyncEnumerable<AlarmFeedMessage> StreamAsync(
|
IAsyncEnumerable<AlarmFeedMessage> StreamAsync(
|
||||||
string? alarmFilterPrefix,
|
string? alarmFilterPrefix,
|
||||||
CancellationToken cancellationToken);
|
CancellationToken cancellationToken);
|
||||||
@@ -57,6 +58,7 @@ public interface IGatewayAlarmService
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="request">The acknowledge request.</param>
|
/// <param name="request">The acknowledge request.</param>
|
||||||
/// <param name="cancellationToken">Token to cancel the call.</param>
|
/// <param name="cancellationToken">Token to cancel the call.</param>
|
||||||
|
/// <returns>A task that resolves to the acknowledge reply.</returns>
|
||||||
Task<AcknowledgeAlarmReply> AcknowledgeAsync(
|
Task<AcknowledgeAlarmReply> AcknowledgeAsync(
|
||||||
AcknowledgeAlarmRequest request,
|
AcknowledgeAlarmRequest request,
|
||||||
CancellationToken cancellationToken);
|
CancellationToken cancellationToken);
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ public sealed record EffectiveLdapConfiguration(
|
|||||||
bool Enabled,
|
bool Enabled,
|
||||||
string Server,
|
string Server,
|
||||||
int Port,
|
int Port,
|
||||||
bool UseTls,
|
string Transport,
|
||||||
bool AllowInsecureLdap,
|
bool AllowInsecure,
|
||||||
string SearchBase,
|
string SearchBase,
|
||||||
string ServiceAccountDn,
|
string ServiceAccountDn,
|
||||||
string ServiceAccountPassword,
|
string ServiceAccountPassword,
|
||||||
|
|||||||
@@ -23,8 +23,8 @@ public sealed class GatewayConfigurationProvider(IOptions<GatewayOptions> option
|
|||||||
Enabled: value.Ldap.Enabled,
|
Enabled: value.Ldap.Enabled,
|
||||||
Server: value.Ldap.Server,
|
Server: value.Ldap.Server,
|
||||||
Port: value.Ldap.Port,
|
Port: value.Ldap.Port,
|
||||||
UseTls: value.Ldap.UseTls,
|
Transport: value.Ldap.Transport.ToString(),
|
||||||
AllowInsecureLdap: value.Ldap.AllowInsecureLdap,
|
AllowInsecure: value.Ldap.AllowInsecure,
|
||||||
SearchBase: value.Ldap.SearchBase,
|
SearchBase: value.Ldap.SearchBase,
|
||||||
ServiceAccountDn: value.Ldap.ServiceAccountDn,
|
ServiceAccountDn: value.Ldap.ServiceAccountDn,
|
||||||
ServiceAccountPassword: RedactedValue,
|
ServiceAccountPassword: RedactedValue,
|
||||||
|
|||||||
+7
-7
@@ -1,4 +1,5 @@
|
|||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using ZB.MOM.WW.Configuration;
|
||||||
|
|
||||||
namespace ZB.MOM.WW.MxGateway.Server.Configuration;
|
namespace ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||||
|
|
||||||
@@ -6,15 +7,14 @@ public static class GatewayConfigurationServiceCollectionExtensions
|
|||||||
{
|
{
|
||||||
/// <summary>Registers gateway configuration services in the dependency injection container.</summary>
|
/// <summary>Registers gateway configuration services in the dependency injection container.</summary>
|
||||||
/// <param name="services">The service collection.</param>
|
/// <param name="services">The service collection.</param>
|
||||||
|
/// <param name="configuration">The configuration to bind gateway options from.</param>
|
||||||
/// <returns>The service collection for chaining.</returns>
|
/// <returns>The service collection for chaining.</returns>
|
||||||
public static IServiceCollection AddGatewayConfiguration(this IServiceCollection services)
|
public static IServiceCollection AddGatewayConfiguration(
|
||||||
|
this IServiceCollection services, IConfiguration configuration)
|
||||||
{
|
{
|
||||||
services
|
services.AddValidatedOptions<GatewayOptions, GatewayOptionsValidator>(
|
||||||
.AddOptions<GatewayOptions>()
|
configuration, GatewayOptions.SectionName);
|
||||||
.BindConfiguration(GatewayOptions.SectionName)
|
|
||||||
.ValidateOnStart();
|
|
||||||
|
|
||||||
services.AddSingleton<IValidateOptions<GatewayOptions>, GatewayOptionsValidator>();
|
|
||||||
services.AddSingleton<IGatewayConfigurationProvider, GatewayConfigurationProvider>();
|
services.AddSingleton<IGatewayConfigurationProvider, GatewayConfigurationProvider>();
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
|
|||||||
@@ -43,4 +43,7 @@ public sealed class GatewayOptions
|
|||||||
/// behaviour (alarms disabled).
|
/// behaviour (alarms disabled).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public AlarmsOptions Alarms { get; init; } = new();
|
public AlarmsOptions Alarms { get; init; } = new();
|
||||||
|
|
||||||
|
/// <summary>Gets self-signed TLS certificate auto-generation options.</summary>
|
||||||
|
public TlsOptions Tls { get; init; } = new();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,42 +1,33 @@
|
|||||||
using Microsoft.Extensions.Options;
|
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||||
|
using ZB.MOM.WW.Configuration;
|
||||||
using ZB.MOM.WW.MxGateway.Contracts;
|
using ZB.MOM.WW.MxGateway.Contracts;
|
||||||
|
|
||||||
namespace ZB.MOM.WW.MxGateway.Server.Configuration;
|
namespace ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||||
|
|
||||||
public sealed class GatewayOptionsValidator : IValidateOptions<GatewayOptions>
|
public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOptions>
|
||||||
{
|
{
|
||||||
private const int MinimumMaxMessageBytes = 1024;
|
private const int MinimumMaxMessageBytes = 1024;
|
||||||
private const int MaximumMaxMessageBytes = 256 * 1024 * 1024;
|
private const int MaximumMaxMessageBytes = 256 * 1024 * 1024;
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Validates gateway configuration options.
|
protected override void Validate(ValidationBuilder builder, GatewayOptions options)
|
||||||
/// </summary>
|
|
||||||
/// <param name="name">Options name.</param>
|
|
||||||
/// <param name="options">Gateway options to validate.</param>
|
|
||||||
/// <returns>Validation result.</returns>
|
|
||||||
public ValidateOptionsResult Validate(string? name, GatewayOptions options)
|
|
||||||
{
|
{
|
||||||
List<string> failures = [];
|
ValidateAuthentication(options.Authentication, builder);
|
||||||
|
ValidateLdap(options.Ldap, builder);
|
||||||
ValidateAuthentication(options.Authentication, failures);
|
ValidateWorker(options.Worker, builder);
|
||||||
ValidateLdap(options.Ldap, failures);
|
ValidateSessions(options.Sessions, builder);
|
||||||
ValidateWorker(options.Worker, failures);
|
ValidateEvents(options.Events, builder);
|
||||||
ValidateSessions(options.Sessions, failures);
|
ValidateDashboard(options.Dashboard, builder);
|
||||||
ValidateEvents(options.Events, failures);
|
ValidateProtocol(options.Protocol, builder);
|
||||||
ValidateDashboard(options.Dashboard, failures);
|
ValidateAlarms(options.Alarms, builder);
|
||||||
ValidateProtocol(options.Protocol, failures);
|
ValidateTls(options.Tls, builder);
|
||||||
ValidateAlarms(options.Alarms, failures);
|
|
||||||
|
|
||||||
return failures.Count == 0
|
|
||||||
? ValidateOptionsResult.Success
|
|
||||||
: ValidateOptionsResult.Fail(failures);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void ValidateAuthentication(AuthenticationOptions options, List<string> failures)
|
private static void ValidateAuthentication(AuthenticationOptions options, ValidationBuilder builder)
|
||||||
{
|
{
|
||||||
if (!Enum.IsDefined(options.Mode))
|
if (!Enum.IsDefined(options.Mode))
|
||||||
{
|
{
|
||||||
failures.Add("MxGateway:Authentication:Mode must be a supported authentication mode.");
|
builder.Add("MxGateway:Authentication:Mode must be a supported authentication mode.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,67 +36,67 @@ public sealed class GatewayOptionsValidator : IValidateOptions<GatewayOptions>
|
|||||||
AddIfBlank(
|
AddIfBlank(
|
||||||
options.SqlitePath,
|
options.SqlitePath,
|
||||||
"MxGateway:Authentication:SqlitePath is required when API-key authentication is enabled.",
|
"MxGateway:Authentication:SqlitePath is required when API-key authentication is enabled.",
|
||||||
failures);
|
builder);
|
||||||
AddIfInvalidPath(
|
AddIfInvalidPath(
|
||||||
options.SqlitePath,
|
options.SqlitePath,
|
||||||
"MxGateway:Authentication:SqlitePath must be a valid filesystem path.",
|
"MxGateway:Authentication:SqlitePath must be a valid filesystem path.",
|
||||||
failures);
|
builder);
|
||||||
AddIfBlank(
|
AddIfBlank(
|
||||||
options.PepperSecretName,
|
options.PepperSecretName,
|
||||||
"MxGateway:Authentication:PepperSecretName is required when API-key authentication is enabled.",
|
"MxGateway:Authentication:PepperSecretName is required when API-key authentication is enabled.",
|
||||||
failures);
|
builder);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void ValidateLdap(LdapOptions options, List<string> failures)
|
private static void ValidateLdap(LdapOptions options, ValidationBuilder builder)
|
||||||
{
|
{
|
||||||
if (!options.Enabled)
|
if (!options.Enabled)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
AddIfBlank(options.Server, "MxGateway:Ldap:Server is required when LDAP login is enabled.", failures);
|
AddIfBlank(options.Server, "MxGateway:Ldap:Server is required when LDAP login is enabled.", builder);
|
||||||
AddIfBlank(options.SearchBase, "MxGateway:Ldap:SearchBase is required when LDAP login is enabled.", failures);
|
AddIfBlank(options.SearchBase, "MxGateway:Ldap:SearchBase is required when LDAP login is enabled.", builder);
|
||||||
AddIfBlank(
|
AddIfBlank(
|
||||||
options.ServiceAccountDn,
|
options.ServiceAccountDn,
|
||||||
"MxGateway:Ldap:ServiceAccountDn is required when LDAP login is enabled.",
|
"MxGateway:Ldap:ServiceAccountDn is required when LDAP login is enabled.",
|
||||||
failures);
|
builder);
|
||||||
AddIfBlank(
|
AddIfBlank(
|
||||||
options.ServiceAccountPassword,
|
options.ServiceAccountPassword,
|
||||||
"MxGateway:Ldap:ServiceAccountPassword is required when LDAP login is enabled.",
|
"MxGateway:Ldap:ServiceAccountPassword is required when LDAP login is enabled.",
|
||||||
failures);
|
builder);
|
||||||
AddIfBlank(
|
AddIfBlank(
|
||||||
options.UserNameAttribute,
|
options.UserNameAttribute,
|
||||||
"MxGateway:Ldap:UserNameAttribute is required when LDAP login is enabled.",
|
"MxGateway:Ldap:UserNameAttribute is required when LDAP login is enabled.",
|
||||||
failures);
|
builder);
|
||||||
AddIfBlank(
|
AddIfBlank(
|
||||||
options.DisplayNameAttribute,
|
options.DisplayNameAttribute,
|
||||||
"MxGateway:Ldap:DisplayNameAttribute is required when LDAP login is enabled.",
|
"MxGateway:Ldap:DisplayNameAttribute is required when LDAP login is enabled.",
|
||||||
failures);
|
builder);
|
||||||
AddIfBlank(
|
AddIfBlank(
|
||||||
options.GroupAttribute,
|
options.GroupAttribute,
|
||||||
"MxGateway:Ldap:GroupAttribute is required when LDAP login is enabled.",
|
"MxGateway:Ldap:GroupAttribute is required when LDAP login is enabled.",
|
||||||
failures);
|
builder);
|
||||||
AddIfNotPositive(options.Port, "MxGateway:Ldap:Port must be greater than zero.", failures);
|
builder.Port(options.Port, "MxGateway:Ldap:Port");
|
||||||
|
|
||||||
if (!options.UseTls && !options.AllowInsecureLdap)
|
if (options.Transport == LdapTransport.None && !options.AllowInsecure)
|
||||||
{
|
{
|
||||||
failures.Add("MxGateway:Ldap:AllowInsecureLdap must be true when UseTls is false.");
|
builder.Add("MxGateway:Ldap:AllowInsecure must be true when Transport is None (plaintext).");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void ValidateWorker(WorkerOptions options, List<string> failures)
|
private static void ValidateWorker(WorkerOptions options, ValidationBuilder builder)
|
||||||
{
|
{
|
||||||
AddIfBlank(options.ExecutablePath, "MxGateway:Worker:ExecutablePath is required.", failures);
|
AddIfBlank(options.ExecutablePath, "MxGateway:Worker:ExecutablePath is required.", builder);
|
||||||
AddIfInvalidPath(
|
AddIfInvalidPath(
|
||||||
options.ExecutablePath,
|
options.ExecutablePath,
|
||||||
"MxGateway:Worker:ExecutablePath must be a valid filesystem path.",
|
"MxGateway:Worker:ExecutablePath must be a valid filesystem path.",
|
||||||
failures);
|
builder);
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(options.ExecutablePath)
|
if (!string.IsNullOrWhiteSpace(options.ExecutablePath)
|
||||||
&& !string.Equals(Path.GetExtension(options.ExecutablePath), ".exe", StringComparison.OrdinalIgnoreCase))
|
&& !string.Equals(Path.GetExtension(options.ExecutablePath), ".exe", StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
failures.Add("MxGateway:Worker:ExecutablePath must point to a .exe file.");
|
builder.Add("MxGateway:Worker:ExecutablePath must point to a .exe file.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(options.WorkingDirectory))
|
if (!string.IsNullOrWhiteSpace(options.WorkingDirectory))
|
||||||
@@ -113,94 +104,94 @@ public sealed class GatewayOptionsValidator : IValidateOptions<GatewayOptions>
|
|||||||
AddIfInvalidPath(
|
AddIfInvalidPath(
|
||||||
options.WorkingDirectory,
|
options.WorkingDirectory,
|
||||||
"MxGateway:Worker:WorkingDirectory must be a valid filesystem path.",
|
"MxGateway:Worker:WorkingDirectory must be a valid filesystem path.",
|
||||||
failures);
|
builder);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!Enum.IsDefined(options.RequiredArchitecture))
|
if (!Enum.IsDefined(options.RequiredArchitecture))
|
||||||
{
|
{
|
||||||
failures.Add("MxGateway:Worker:RequiredArchitecture must be a supported worker architecture.");
|
builder.Add("MxGateway:Worker:RequiredArchitecture must be a supported worker architecture.");
|
||||||
}
|
}
|
||||||
|
|
||||||
AddIfNotPositive(
|
AddIfNotPositive(
|
||||||
options.StartupTimeoutSeconds,
|
options.StartupTimeoutSeconds,
|
||||||
"MxGateway:Worker:StartupTimeoutSeconds must be greater than zero.",
|
"MxGateway:Worker:StartupTimeoutSeconds must be greater than zero.",
|
||||||
failures);
|
builder);
|
||||||
AddIfNotPositive(
|
AddIfNotPositive(
|
||||||
options.StartupProbeRetryAttempts,
|
options.StartupProbeRetryAttempts,
|
||||||
"MxGateway:Worker:StartupProbeRetryAttempts must be greater than zero.",
|
"MxGateway:Worker:StartupProbeRetryAttempts must be greater than zero.",
|
||||||
failures);
|
builder);
|
||||||
AddIfNotPositive(
|
AddIfNotPositive(
|
||||||
options.StartupProbeRetryDelayMilliseconds,
|
options.StartupProbeRetryDelayMilliseconds,
|
||||||
"MxGateway:Worker:StartupProbeRetryDelayMilliseconds must be greater than zero.",
|
"MxGateway:Worker:StartupProbeRetryDelayMilliseconds must be greater than zero.",
|
||||||
failures);
|
builder);
|
||||||
AddIfNotPositive(
|
AddIfNotPositive(
|
||||||
options.PipeConnectAttemptTimeoutMilliseconds,
|
options.PipeConnectAttemptTimeoutMilliseconds,
|
||||||
"MxGateway:Worker:PipeConnectAttemptTimeoutMilliseconds must be greater than zero.",
|
"MxGateway:Worker:PipeConnectAttemptTimeoutMilliseconds must be greater than zero.",
|
||||||
failures);
|
builder);
|
||||||
AddIfNotPositive(
|
AddIfNotPositive(
|
||||||
options.ShutdownTimeoutSeconds,
|
options.ShutdownTimeoutSeconds,
|
||||||
"MxGateway:Worker:ShutdownTimeoutSeconds must be greater than zero.",
|
"MxGateway:Worker:ShutdownTimeoutSeconds must be greater than zero.",
|
||||||
failures);
|
builder);
|
||||||
AddIfNotPositive(
|
AddIfNotPositive(
|
||||||
options.HeartbeatIntervalSeconds,
|
options.HeartbeatIntervalSeconds,
|
||||||
"MxGateway:Worker:HeartbeatIntervalSeconds must be greater than zero.",
|
"MxGateway:Worker:HeartbeatIntervalSeconds must be greater than zero.",
|
||||||
failures);
|
builder);
|
||||||
AddIfNotPositive(
|
AddIfNotPositive(
|
||||||
options.HeartbeatGraceSeconds,
|
options.HeartbeatGraceSeconds,
|
||||||
"MxGateway:Worker:HeartbeatGraceSeconds must be greater than zero.",
|
"MxGateway:Worker:HeartbeatGraceSeconds must be greater than zero.",
|
||||||
failures);
|
builder);
|
||||||
|
|
||||||
if (options.HeartbeatGraceSeconds < options.HeartbeatIntervalSeconds)
|
if (options.HeartbeatGraceSeconds < options.HeartbeatIntervalSeconds)
|
||||||
{
|
{
|
||||||
failures.Add(
|
builder.Add(
|
||||||
"MxGateway:Worker:HeartbeatGraceSeconds must be greater than or equal to HeartbeatIntervalSeconds.");
|
"MxGateway:Worker:HeartbeatGraceSeconds must be greater than or equal to HeartbeatIntervalSeconds.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.MaxMessageBytes is < MinimumMaxMessageBytes or > MaximumMaxMessageBytes)
|
if (options.MaxMessageBytes is < MinimumMaxMessageBytes or > MaximumMaxMessageBytes)
|
||||||
{
|
{
|
||||||
failures.Add(
|
builder.Add(
|
||||||
$"MxGateway:Worker:MaxMessageBytes must be between {MinimumMaxMessageBytes} and {MaximumMaxMessageBytes}.");
|
$"MxGateway:Worker:MaxMessageBytes must be between {MinimumMaxMessageBytes} and {MaximumMaxMessageBytes}.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void ValidateSessions(SessionOptions options, List<string> failures)
|
private static void ValidateSessions(SessionOptions options, ValidationBuilder builder)
|
||||||
{
|
{
|
||||||
AddIfNotPositive(
|
AddIfNotPositive(
|
||||||
options.DefaultCommandTimeoutSeconds,
|
options.DefaultCommandTimeoutSeconds,
|
||||||
"MxGateway:Sessions:DefaultCommandTimeoutSeconds must be greater than zero.",
|
"MxGateway:Sessions:DefaultCommandTimeoutSeconds must be greater than zero.",
|
||||||
failures);
|
builder);
|
||||||
AddIfNotPositive(options.MaxSessions, "MxGateway:Sessions:MaxSessions must be greater than zero.", failures);
|
AddIfNotPositive(options.MaxSessions, "MxGateway:Sessions:MaxSessions must be greater than zero.", builder);
|
||||||
AddIfNotPositive(
|
AddIfNotPositive(
|
||||||
options.MaxPendingCommandsPerSession,
|
options.MaxPendingCommandsPerSession,
|
||||||
"MxGateway:Sessions:MaxPendingCommandsPerSession must be greater than zero.",
|
"MxGateway:Sessions:MaxPendingCommandsPerSession must be greater than zero.",
|
||||||
failures);
|
builder);
|
||||||
AddIfNotPositive(
|
AddIfNotPositive(
|
||||||
options.DefaultLeaseSeconds,
|
options.DefaultLeaseSeconds,
|
||||||
"MxGateway:Sessions:DefaultLeaseSeconds must be greater than zero.",
|
"MxGateway:Sessions:DefaultLeaseSeconds must be greater than zero.",
|
||||||
failures);
|
builder);
|
||||||
AddIfNotPositive(
|
AddIfNotPositive(
|
||||||
options.LeaseSweepIntervalSeconds,
|
options.LeaseSweepIntervalSeconds,
|
||||||
"MxGateway:Sessions:LeaseSweepIntervalSeconds must be greater than zero.",
|
"MxGateway:Sessions:LeaseSweepIntervalSeconds must be greater than zero.",
|
||||||
failures);
|
builder);
|
||||||
|
|
||||||
if (options.AllowMultipleEventSubscribers)
|
if (options.AllowMultipleEventSubscribers)
|
||||||
{
|
{
|
||||||
failures.Add(
|
builder.Add(
|
||||||
"MxGateway:Sessions:AllowMultipleEventSubscribers is not supported until event fan-out is implemented.");
|
"MxGateway:Sessions:AllowMultipleEventSubscribers is not supported until event fan-out is implemented.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void ValidateEvents(EventOptions options, List<string> failures)
|
private static void ValidateEvents(EventOptions options, ValidationBuilder builder)
|
||||||
{
|
{
|
||||||
AddIfNotPositive(options.QueueCapacity, "MxGateway:Events:QueueCapacity must be greater than zero.", failures);
|
AddIfNotPositive(options.QueueCapacity, "MxGateway:Events:QueueCapacity must be greater than zero.", builder);
|
||||||
|
|
||||||
if (!Enum.IsDefined(options.BackpressurePolicy))
|
if (!Enum.IsDefined(options.BackpressurePolicy))
|
||||||
{
|
{
|
||||||
failures.Add("MxGateway:Events:BackpressurePolicy must be a supported backpressure policy.");
|
builder.Add("MxGateway:Events:BackpressurePolicy must be a supported backpressure policy.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void ValidateDashboard(DashboardOptions options, List<string> failures)
|
private static void ValidateDashboard(DashboardOptions options, ValidationBuilder builder)
|
||||||
{
|
{
|
||||||
// GroupToRole shape is validated even when the dashboard is disabled so
|
// GroupToRole shape is validated even when the dashboard is disabled so
|
||||||
// misconfiguration surfaces at startup; emptiness is allowed, with the
|
// misconfiguration surfaces at startup; emptiness is allowed, with the
|
||||||
@@ -211,13 +202,13 @@ public sealed class GatewayOptionsValidator : IValidateOptions<GatewayOptions>
|
|||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(entry.Key))
|
if (string.IsNullOrWhiteSpace(entry.Key))
|
||||||
{
|
{
|
||||||
failures.Add("MxGateway:Dashboard:GroupToRole keys (LDAP group names) must be non-blank.");
|
builder.Add("MxGateway:Dashboard:GroupToRole keys (LDAP group names) must be non-blank.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!string.Equals(entry.Value, Dashboard.DashboardRoles.Admin, StringComparison.Ordinal)
|
if (!string.Equals(entry.Value, Dashboard.DashboardRoles.Admin, StringComparison.Ordinal)
|
||||||
&& !string.Equals(entry.Value, Dashboard.DashboardRoles.Viewer, StringComparison.Ordinal))
|
&& !string.Equals(entry.Value, Dashboard.DashboardRoles.Viewer, StringComparison.Ordinal))
|
||||||
{
|
{
|
||||||
failures.Add(
|
builder.Add(
|
||||||
$"MxGateway:Dashboard:GroupToRole['{entry.Key}'] must be '{Dashboard.DashboardRoles.Admin}' or '{Dashboard.DashboardRoles.Viewer}'.");
|
$"MxGateway:Dashboard:GroupToRole['{entry.Key}'] must be '{Dashboard.DashboardRoles.Admin}' or '{Dashboard.DashboardRoles.Viewer}'.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -225,18 +216,18 @@ public sealed class GatewayOptionsValidator : IValidateOptions<GatewayOptions>
|
|||||||
AddIfNotPositive(
|
AddIfNotPositive(
|
||||||
options.SnapshotIntervalMilliseconds,
|
options.SnapshotIntervalMilliseconds,
|
||||||
"MxGateway:Dashboard:SnapshotIntervalMilliseconds must be greater than zero.",
|
"MxGateway:Dashboard:SnapshotIntervalMilliseconds must be greater than zero.",
|
||||||
failures);
|
builder);
|
||||||
AddIfNegative(
|
AddIfNegative(
|
||||||
options.RecentFaultLimit,
|
options.RecentFaultLimit,
|
||||||
"MxGateway:Dashboard:RecentFaultLimit must be greater than or equal to zero.",
|
"MxGateway:Dashboard:RecentFaultLimit must be greater than or equal to zero.",
|
||||||
failures);
|
builder);
|
||||||
AddIfNegative(
|
AddIfNegative(
|
||||||
options.RecentSessionLimit,
|
options.RecentSessionLimit,
|
||||||
"MxGateway:Dashboard:RecentSessionLimit must be greater than or equal to zero.",
|
"MxGateway:Dashboard:RecentSessionLimit must be greater than or equal to zero.",
|
||||||
failures);
|
builder);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void ValidateAlarms(AlarmsOptions options, List<string> failures)
|
private static void ValidateAlarms(AlarmsOptions options, ValidationBuilder builder)
|
||||||
{
|
{
|
||||||
if (!options.Enabled)
|
if (!options.Enabled)
|
||||||
{
|
{
|
||||||
@@ -250,58 +241,79 @@ public sealed class GatewayOptionsValidator : IValidateOptions<GatewayOptions>
|
|||||||
if (string.IsNullOrWhiteSpace(options.SubscriptionExpression)
|
if (string.IsNullOrWhiteSpace(options.SubscriptionExpression)
|
||||||
&& string.IsNullOrWhiteSpace(options.DefaultArea))
|
&& string.IsNullOrWhiteSpace(options.DefaultArea))
|
||||||
{
|
{
|
||||||
failures.Add(
|
builder.Add(
|
||||||
"MxGateway:Alarms requires either a non-blank SubscriptionExpression or a non-blank DefaultArea when Enabled is true.");
|
"MxGateway:Alarms requires either a non-blank SubscriptionExpression or a non-blank DefaultArea when Enabled is true.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(options.SubscriptionExpression)
|
if (!string.IsNullOrWhiteSpace(options.SubscriptionExpression)
|
||||||
&& !options.SubscriptionExpression.StartsWith(@"\\", StringComparison.Ordinal))
|
&& !options.SubscriptionExpression.StartsWith(@"\\", StringComparison.Ordinal))
|
||||||
{
|
{
|
||||||
failures.Add(
|
builder.Add(
|
||||||
@"MxGateway:Alarms:SubscriptionExpression must start with '\\' (canonical \\<host>\Galaxy!<area> shape).");
|
@"MxGateway:Alarms:SubscriptionExpression must start with '\\' (canonical \\<host>\Galaxy!<area> shape).");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void ValidateProtocol(ProtocolOptions options, List<string> failures)
|
private const int MinimumCertValidityYears = 1;
|
||||||
|
private const int MaximumCertValidityYears = 100;
|
||||||
|
|
||||||
|
private static void ValidateTls(TlsOptions options, ValidationBuilder builder)
|
||||||
|
{
|
||||||
|
if (options.ValidityYears is < MinimumCertValidityYears or > MaximumCertValidityYears)
|
||||||
|
{
|
||||||
|
builder.Add(
|
||||||
|
$"MxGateway:Tls:ValidityYears must be between {MinimumCertValidityYears} and {MaximumCertValidityYears}.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The default is non-blank, so this only catches an explicitly-blanked path.
|
||||||
|
AddIfBlank(
|
||||||
|
options.SelfSignedCertPath,
|
||||||
|
"MxGateway:Tls:SelfSignedCertPath must not be blank.",
|
||||||
|
builder);
|
||||||
|
AddIfInvalidPath(
|
||||||
|
options.SelfSignedCertPath,
|
||||||
|
"MxGateway:Tls:SelfSignedCertPath must be a valid filesystem path.",
|
||||||
|
builder);
|
||||||
|
|
||||||
|
foreach (string dns in options.AdditionalDnsNames)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(dns))
|
||||||
|
{
|
||||||
|
builder.Add("MxGateway:Tls:AdditionalDnsNames entries must be non-blank.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ValidateProtocol(ProtocolOptions options, ValidationBuilder builder)
|
||||||
{
|
{
|
||||||
if (options.WorkerProtocolVersion != GatewayContractInfo.WorkerProtocolVersion)
|
if (options.WorkerProtocolVersion != GatewayContractInfo.WorkerProtocolVersion)
|
||||||
{
|
{
|
||||||
failures.Add(
|
builder.Add(
|
||||||
$"MxGateway:Protocol:WorkerProtocolVersion must be {GatewayContractInfo.WorkerProtocolVersion}.");
|
$"MxGateway:Protocol:WorkerProtocolVersion must be {GatewayContractInfo.WorkerProtocolVersion}.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.MaxGrpcMessageBytes is < MinimumMaxMessageBytes or > MaximumMaxMessageBytes)
|
if (options.MaxGrpcMessageBytes is < MinimumMaxMessageBytes or > MaximumMaxMessageBytes)
|
||||||
{
|
{
|
||||||
failures.Add(
|
builder.Add(
|
||||||
$"MxGateway:Protocol:MaxGrpcMessageBytes must be between {MinimumMaxMessageBytes} and {MaximumMaxMessageBytes}.");
|
$"MxGateway:Protocol:MaxGrpcMessageBytes must be between {MinimumMaxMessageBytes} and {MaximumMaxMessageBytes}.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AddIfBlank(string? value, string message, List<string> failures)
|
private static void AddIfBlank(string? value, string message, ValidationBuilder builder)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(value))
|
builder.RequireThat(!string.IsNullOrWhiteSpace(value), message);
|
||||||
{
|
|
||||||
failures.Add(message);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AddIfNotPositive(int value, string message, List<string> failures)
|
private static void AddIfNotPositive(int value, string message, ValidationBuilder builder)
|
||||||
{
|
{
|
||||||
if (value <= 0)
|
builder.RequireThat(value > 0, message);
|
||||||
{
|
|
||||||
failures.Add(message);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AddIfNegative(int value, string message, List<string> failures)
|
private static void AddIfNegative(int value, string message, ValidationBuilder builder)
|
||||||
{
|
{
|
||||||
if (value < 0)
|
builder.RequireThat(value >= 0, message);
|
||||||
{
|
|
||||||
failures.Add(message);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AddIfInvalidPath(string? value, string message, List<string> failures)
|
private static void AddIfInvalidPath(string? value, string message, ValidationBuilder builder)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(value))
|
if (string.IsNullOrWhiteSpace(value))
|
||||||
{
|
{
|
||||||
@@ -314,15 +326,19 @@ public sealed class GatewayOptionsValidator : IValidateOptions<GatewayOptions>
|
|||||||
}
|
}
|
||||||
catch (ArgumentException)
|
catch (ArgumentException)
|
||||||
{
|
{
|
||||||
failures.Add(message);
|
builder.Add(message);
|
||||||
}
|
}
|
||||||
catch (NotSupportedException)
|
catch (NotSupportedException)
|
||||||
{
|
{
|
||||||
failures.Add(message);
|
builder.Add(message);
|
||||||
}
|
}
|
||||||
catch (PathTooLongException)
|
catch (PathTooLongException)
|
||||||
{
|
{
|
||||||
failures.Add(message);
|
builder.Add(message);
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
|
{
|
||||||
|
builder.Add(message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,5 +8,6 @@ public interface IGatewayConfigurationProvider
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Returns the validated and effective gateway configuration.
|
/// Returns the validated and effective gateway configuration.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <returns>The <see cref="EffectiveGatewayConfiguration"/> with validated defaults applied.</returns>
|
||||||
EffectiveGatewayConfiguration GetEffectiveConfiguration();
|
EffectiveGatewayConfiguration GetEffectiveConfiguration();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,32 @@
|
|||||||
|
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||||
|
|
||||||
namespace ZB.MOM.WW.MxGateway.Server.Configuration;
|
namespace ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gateway-side view of the <c>MxGateway:Ldap</c> section. This is a SHADOW of the
|
||||||
|
/// shared <see cref="ZB.MOM.WW.Auth.Abstractions.Ldap.LdapOptions"/> type and is NOT
|
||||||
|
/// used to perform LDAP authentication at runtime — runtime bind/search is done by the
|
||||||
|
/// shared <c>ZB.MOM.WW.Auth.Ldap</c> provider, whose options are bound directly from the
|
||||||
|
/// same <c>MxGateway:Ldap</c> section by <c>AddZbLdapAuth</c> (see
|
||||||
|
/// <see cref="ZB.MOM.WW.MxGateway.Server.Dashboard.DashboardServiceCollectionExtensions"/>).
|
||||||
|
/// <para>
|
||||||
|
/// This shadow exists for three things only: (1) startup validation via
|
||||||
|
/// <see cref="GatewayOptionsValidator"/>; (2) the redacted effective-config display
|
||||||
|
/// (<see cref="EffectiveLdapConfiguration"/> / <see cref="GatewayConfigurationProvider"/>);
|
||||||
|
/// and (3) it is the single home of the gateway's dev/default LDAP values, which the
|
||||||
|
/// integration live-test helper copies onto the shared options.
|
||||||
|
/// </para>
|
||||||
|
/// <para>
|
||||||
|
/// Review C2 — DRIFT WARNING: this class MUST stay field-compatible with the shared
|
||||||
|
/// <see cref="ZB.MOM.WW.Auth.Abstractions.Ldap.LdapOptions"/> so the one config section
|
||||||
|
/// binds cleanly onto both. The two are intentionally NOT merged because their defaults
|
||||||
|
/// differ on purpose: this shadow ships dev-friendly defaults (plaintext localhost,
|
||||||
|
/// <c>AllowInsecure=true</c>, populated <c>SearchBase</c>/<c>ServiceAccount*</c>), whereas
|
||||||
|
/// the shared type is secure-by-default (<c>Transport=Ldaps</c>, <c>AllowInsecure=false</c>,
|
||||||
|
/// empty DN fields). If you add/rename/remove a field on the shared type, mirror it here
|
||||||
|
/// (and in the validator + effective-config) so the section keeps binding to both.
|
||||||
|
/// </para>
|
||||||
|
/// </summary>
|
||||||
public sealed class LdapOptions
|
public sealed class LdapOptions
|
||||||
{
|
{
|
||||||
/// <summary>Gets a value indicating whether LDAP authentication is enabled.</summary>
|
/// <summary>Gets a value indicating whether LDAP authentication is enabled.</summary>
|
||||||
@@ -11,17 +38,24 @@ public sealed class LdapOptions
|
|||||||
/// <summary>Gets the LDAP server port.</summary>
|
/// <summary>Gets the LDAP server port.</summary>
|
||||||
public int Port { get; init; } = 3893;
|
public int Port { get; init; } = 3893;
|
||||||
|
|
||||||
/// <summary>Gets a value indicating whether TLS is required for the connection.</summary>
|
/// <summary>
|
||||||
public bool UseTls { get; init; }
|
/// Gets the transport/TLS mode for the LDAP connection. Replaces the former
|
||||||
|
/// boolean <c>UseTls</c> (true ≈ <see cref="LdapTransport.Ldaps"/>, false =
|
||||||
|
/// <see cref="LdapTransport.None"/>). <see cref="LdapTransport.StartTls"/> upgrades
|
||||||
|
/// a plaintext connection to TLS. Matches the shared
|
||||||
|
/// <see cref="ZB.MOM.WW.Auth.Abstractions.Ldap.LdapOptions.Transport"/> field so the
|
||||||
|
/// <c>MxGateway:Ldap</c> section binds straight onto the shared options.
|
||||||
|
/// </summary>
|
||||||
|
public LdapTransport Transport { get; init; } = LdapTransport.None;
|
||||||
|
|
||||||
/// <summary>Gets a value indicating whether insecure LDAP connections are allowed.</summary>
|
/// <summary>Gets a value indicating whether insecure (plaintext) LDAP connections are allowed.</summary>
|
||||||
public bool AllowInsecureLdap { get; init; } = true;
|
public bool AllowInsecure { get; init; } = true;
|
||||||
|
|
||||||
/// <summary>Gets the LDAP search base distinguished name.</summary>
|
/// <summary>Gets the LDAP search base distinguished name.</summary>
|
||||||
public string SearchBase { get; init; } = "dc=lmxopcua,dc=local";
|
public string SearchBase { get; init; } = "dc=zb,dc=local";
|
||||||
|
|
||||||
/// <summary>Gets the service account distinguished name.</summary>
|
/// <summary>Gets the service account distinguished name.</summary>
|
||||||
public string ServiceAccountDn { get; init; } = "cn=serviceaccount,dc=lmxopcua,dc=local";
|
public string ServiceAccountDn { get; init; } = "cn=serviceaccount,dc=zb,dc=local";
|
||||||
|
|
||||||
/// <summary>Gets the service account password.</summary>
|
/// <summary>Gets the service account password.</summary>
|
||||||
public string ServiceAccountPassword { get; init; } = "serviceaccount123";
|
public string ServiceAccountPassword { get; init; } = "serviceaccount123";
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
namespace ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Options controlling the gateway's self-signed certificate auto-generation.
|
||||||
|
/// Only consulted when a Kestrel HTTPS endpoint is configured without its own
|
||||||
|
/// certificate; plaintext deployments never trigger generation.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class TlsOptions
|
||||||
|
{
|
||||||
|
/// <summary>Path to the persisted self-signed PFX. Reused across restarts.</summary>
|
||||||
|
public string SelfSignedCertPath { get; init; } =
|
||||||
|
@"C:\ProgramData\MxGateway\certs\gateway-selfsigned.pfx";
|
||||||
|
|
||||||
|
/// <summary>Lifetime in years of a freshly generated certificate.</summary>
|
||||||
|
public int ValidityYears { get; init; } = 10;
|
||||||
|
|
||||||
|
/// <summary>Extra DNS SANs to embed (e.g. a load-balancer name).</summary>
|
||||||
|
public IReadOnlyList<string> AdditionalDnsNames { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>Regenerate the persisted certificate when it has expired.</summary>
|
||||||
|
public bool RegenerateIfExpired { get; init; } = true;
|
||||||
|
}
|
||||||
@@ -5,14 +5,14 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<base href="/" />
|
<base href="/" />
|
||||||
<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css" />
|
<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css" />
|
||||||
<link rel="stylesheet" href="/css/theme.css" />
|
<ThemeHead />
|
||||||
<link rel="stylesheet" href="/css/site.css" />
|
<link rel="stylesheet" href="/css/site.css" />
|
||||||
<HeadOutlet @rendermode="InteractiveServer" />
|
<HeadOutlet @rendermode="InteractiveServer" />
|
||||||
</head>
|
</head>
|
||||||
<body class="dashboard-body">
|
<body class="dashboard-body">
|
||||||
<Routes @rendermode="InteractiveServer" />
|
<Routes @rendermode="InteractiveServer" />
|
||||||
<script src="/lib/bootstrap/js/bootstrap.bundle.min.js"></script>
|
<script src="/lib/bootstrap/js/bootstrap.bundle.min.js"></script>
|
||||||
<script src="/js/nav-state.js"></script>
|
<ThemeScripts />
|
||||||
<script src="/_framework/blazor.web.js"></script>
|
<script src="/_framework/blazor.web.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -38,7 +38,8 @@ public abstract class DashboardPageBase : ComponentBase, IAsyncDisposable
|
|||||||
await ConnectHubAsync().ConfigureAwait(false);
|
await ConnectHubAsync().ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <summary>Disposes the SignalR hub connection and suppresses finalization.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
public async ValueTask DisposeAsync()
|
public async ValueTask DisposeAsync()
|
||||||
{
|
{
|
||||||
if (_hub is not null)
|
if (_hub is not null)
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
@inherits LayoutComponentBase
|
||||||
|
|
||||||
|
@* Minimal layout for the login page: no side rail, no brand block. The page
|
||||||
|
renders its own centred card via the shared kit's <LoginCard>. Mirrors
|
||||||
|
OtOpcUa AdminUI's LoginLayout. *@
|
||||||
|
@Body
|
||||||
@@ -1,210 +1,40 @@
|
|||||||
@using System.Linq
|
|
||||||
@using Microsoft.AspNetCore.Components.Routing
|
|
||||||
@using Microsoft.JSInterop
|
|
||||||
@implements IDisposable
|
|
||||||
@inherits LayoutComponentBase
|
@inherits LayoutComponentBase
|
||||||
@inject NavigationManager Navigation
|
|
||||||
@inject IJSRuntime JS
|
|
||||||
|
|
||||||
<div class="d-flex flex-column flex-lg-row" style="min-height: 100vh;">
|
@* Thin layout: delegates the side-rail chassis (hamburger, brand, responsive
|
||||||
@* Hamburger toggle: visible only on viewports <lg. Bootstrap collapse JS
|
collapse) to the shared ZB.MOM.WW.Theme <ThemeShell>. The nav is reproduced
|
||||||
lives in bootstrap.bundle.min.js (loaded in App.razor). *@
|
with the kit's NavRailSection / NavRailItem; section expand-state persistence
|
||||||
<button class="btn btn-outline-secondary btn-sm d-lg-none m-2 align-self-start"
|
is owned by the kit's <details> + ThemeScripts (no JS interop here). *@
|
||||||
type="button"
|
<ThemeShell Product="MXAccess Gateway" Accent="#2f5fd0">
|
||||||
data-bs-toggle="collapse"
|
<Nav>
|
||||||
data-bs-target="#sidebar-collapse"
|
<NavRailItem Href="/" Text="Dashboard" Match="NavLinkMatch.All" />
|
||||||
aria-controls="sidebar-collapse"
|
<NavRailSection Title="Runtime" Key="runtime">
|
||||||
aria-expanded="false"
|
<NavRailItem Href="/sessions" Text="Sessions" />
|
||||||
aria-label="Toggle navigation">
|
<NavRailItem Href="/workers" Text="Workers" />
|
||||||
☰
|
<NavRailItem Href="/events" Text="Events" />
|
||||||
</button>
|
<NavRailItem Href="/alarms" Text="Alarms" />
|
||||||
|
</NavRailSection>
|
||||||
<div class="collapse d-lg-block" id="sidebar-collapse">
|
<NavRailSection Title="Galaxy" Key="galaxy">
|
||||||
<nav class="sidebar d-flex flex-column">
|
<NavRailItem Href="/galaxy" Text="Repository" />
|
||||||
<a class="brand" href="/"><span class="mark">▮</span> MXAccess Gateway</a>
|
<NavRailItem Href="/browse" Text="Browse" />
|
||||||
|
</NavRailSection>
|
||||||
<div style="overflow-y:auto; flex:1 1 auto; min-height:0;">
|
<NavRailSection Title="Admin" Key="admin">
|
||||||
<ul class="nav flex-column">
|
<NavRailItem Href="/apikeys" Text="API Keys" />
|
||||||
<li class="nav-item">
|
<NavRailItem Href="/settings" Text="Settings" />
|
||||||
<NavLink class="nav-link" href="/" Match="NavLinkMatch.All">Dashboard</NavLink>
|
</NavRailSection>
|
||||||
</li>
|
</Nav>
|
||||||
|
<RailFooter>
|
||||||
<NavSection Title="Runtime"
|
<AuthorizeView>
|
||||||
Expanded="@_expanded.Contains("runtime")"
|
<Authorized Context="authState">
|
||||||
OnToggle="@(() => ToggleAsync("runtime"))">
|
<span class="rail-user">@authState.User.Identity?.Name</span>
|
||||||
<li class="nav-item">
|
<form method="post" action="/logout" data-enhance="false">
|
||||||
<NavLink class="nav-link" href="/sessions" Match="NavLinkMatch.Prefix">Sessions</NavLink>
|
<AntiforgeryToken />
|
||||||
</li>
|
<button class="rail-btn" type="submit">Sign Out</button>
|
||||||
<li class="nav-item">
|
</form>
|
||||||
<NavLink class="nav-link" href="/workers" Match="NavLinkMatch.Prefix">Workers</NavLink>
|
</Authorized>
|
||||||
</li>
|
<NotAuthorized>
|
||||||
<li class="nav-item">
|
<a class="rail-btn" href="/login">Sign In</a>
|
||||||
<NavLink class="nav-link" href="/events" Match="NavLinkMatch.Prefix">Events</NavLink>
|
</NotAuthorized>
|
||||||
</li>
|
</AuthorizeView>
|
||||||
<li class="nav-item">
|
</RailFooter>
|
||||||
<NavLink class="nav-link" href="/alarms" Match="NavLinkMatch.Prefix">Alarms</NavLink>
|
<ChildContent>@Body</ChildContent>
|
||||||
</li>
|
</ThemeShell>
|
||||||
</NavSection>
|
|
||||||
|
|
||||||
<NavSection Title="Galaxy"
|
|
||||||
Expanded="@_expanded.Contains("galaxy")"
|
|
||||||
OnToggle="@(() => ToggleAsync("galaxy"))">
|
|
||||||
<li class="nav-item">
|
|
||||||
<NavLink class="nav-link" href="/galaxy" Match="NavLinkMatch.Prefix">Repository</NavLink>
|
|
||||||
</li>
|
|
||||||
<li class="nav-item">
|
|
||||||
<NavLink class="nav-link" href="/browse" Match="NavLinkMatch.Prefix">Browse</NavLink>
|
|
||||||
</li>
|
|
||||||
</NavSection>
|
|
||||||
|
|
||||||
<NavSection Title="Admin"
|
|
||||||
Expanded="@_expanded.Contains("admin")"
|
|
||||||
OnToggle="@(() => ToggleAsync("admin"))">
|
|
||||||
<li class="nav-item">
|
|
||||||
<NavLink class="nav-link" href="/apikeys" Match="NavLinkMatch.Prefix">API Keys</NavLink>
|
|
||||||
</li>
|
|
||||||
<li class="nav-item">
|
|
||||||
<NavLink class="nav-link" href="/settings" Match="NavLinkMatch.Prefix">Settings</NavLink>
|
|
||||||
</li>
|
|
||||||
</NavSection>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<AuthorizeView>
|
|
||||||
<Authorized Context="authState">
|
|
||||||
<div class="border-top px-3 py-2">
|
|
||||||
<div class="d-flex justify-content-between align-items-center">
|
|
||||||
<span class="text-body-secondary small">@authState.User.Identity?.Name</span>
|
|
||||||
<form method="post" action="/logout" data-enhance="false">
|
|
||||||
<AntiforgeryToken />
|
|
||||||
<button type="submit" class="btn btn-outline-secondary btn-sm py-0 px-2">Sign Out</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Authorized>
|
|
||||||
<NotAuthorized>
|
|
||||||
<div class="border-top px-3 py-2">
|
|
||||||
<a href="/login" class="btn btn-outline-secondary btn-sm py-0 px-2 w-100">Sign In</a>
|
|
||||||
</div>
|
|
||||||
</NotAuthorized>
|
|
||||||
</AuthorizeView>
|
|
||||||
</nav>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<main class="page flex-grow-1">
|
|
||||||
@Body
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
@code {
|
|
||||||
// Sections whose collapsed/expanded state we persist. Acts as the allow-list
|
|
||||||
// when parsing the cookie so stale or attacker-supplied ids are ignored.
|
|
||||||
private static readonly string[] SectionIds = { "runtime", "galaxy", "admin" };
|
|
||||||
|
|
||||||
// The currently-expanded sections. Populated from the cookie on first
|
|
||||||
// render; mutated by ToggleAsync and by navigating into a section.
|
|
||||||
private readonly HashSet<string> _expanded = new(StringComparer.Ordinal);
|
|
||||||
|
|
||||||
protected override void OnInitialized()
|
|
||||||
{
|
|
||||||
Navigation.LocationChanged += OnLocationChanged;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
|
||||||
{
|
|
||||||
if (!firstRender)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Hydrate from the cookie. Until this completes the sidebar paints
|
|
||||||
// collapsed, matching the CentralUI behaviour.
|
|
||||||
string saved;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
saved = await JS.InvokeAsync<string>("navState.get") ?? string.Empty;
|
|
||||||
}
|
|
||||||
catch (JSDisconnectedException)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var id in saved.Split(
|
|
||||||
',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
|
||||||
{
|
|
||||||
if (Array.IndexOf(SectionIds, id) >= 0)
|
|
||||||
{
|
|
||||||
_expanded.Add(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The section of the page we loaded on is always expanded.
|
|
||||||
if (EnsureCurrentSectionExpanded())
|
|
||||||
{
|
|
||||||
await PersistAsync();
|
|
||||||
}
|
|
||||||
|
|
||||||
StateHasChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void OnLocationChanged(object? sender, LocationChangedEventArgs e)
|
|
||||||
{
|
|
||||||
if (EnsureCurrentSectionExpanded())
|
|
||||||
{
|
|
||||||
_ = PersistAsync();
|
|
||||||
_ = InvokeAsync(StateHasChanged);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task ToggleAsync(string id)
|
|
||||||
{
|
|
||||||
if (!_expanded.Remove(id))
|
|
||||||
{
|
|
||||||
_expanded.Add(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
await PersistAsync();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Adds the current page's section to _expanded; returns true if it changed.
|
|
||||||
private bool EnsureCurrentSectionExpanded()
|
|
||||||
{
|
|
||||||
var section = CurrentSection();
|
|
||||||
return section is not null && _expanded.Add(section);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Maps the current URL's first path segment to a section id, or null for
|
|
||||||
// sectionless pages (Dashboard, Login).
|
|
||||||
private string? CurrentSection()
|
|
||||||
{
|
|
||||||
var relative = Navigation.ToBaseRelativePath(Navigation.Uri);
|
|
||||||
var firstSegment = relative.Split('?', '#')[0]
|
|
||||||
.Split('/', StringSplitOptions.RemoveEmptyEntries)
|
|
||||||
.FirstOrDefault();
|
|
||||||
|
|
||||||
return firstSegment switch
|
|
||||||
{
|
|
||||||
"sessions" or "workers" or "events" or "alarms" => "runtime",
|
|
||||||
"galaxy" or "browse" => "galaxy",
|
|
||||||
"apikeys" or "settings" => "admin",
|
|
||||||
_ => null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task PersistAsync()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await JS.InvokeVoidAsync("navState.set", string.Join(',', _expanded));
|
|
||||||
}
|
|
||||||
catch (JSDisconnectedException)
|
|
||||||
{
|
|
||||||
// The circuit is gone — nothing to persist to.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
Navigation.LocationChanged -= OnLocationChanged;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
@* A collapsible sidebar nav section. The header is a full-width button that
|
|
||||||
toggles ChildContent visibility. Pattern lifted from ScadaLink CentralUI
|
|
||||||
(Components/Layout/NavSection.razor) — see [[project-deployed-service]]. *@
|
|
||||||
|
|
||||||
<li class="nav-item">
|
|
||||||
<button type="button"
|
|
||||||
class="nav-section-toggle"
|
|
||||||
@onclick="OnToggle"
|
|
||||||
aria-expanded="@(Expanded ? "true" : "false")">
|
|
||||||
<span class="chevron" aria-hidden="true">@(Expanded ? "▾" : "▸")</span>
|
|
||||||
<span>@Title</span>
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
@if (Expanded)
|
|
||||||
{
|
|
||||||
@ChildContent
|
|
||||||
}
|
|
||||||
|
|
||||||
@code {
|
|
||||||
/// <summary>Section label shown in the header (e.g. "Runtime").</summary>
|
|
||||||
[Parameter, EditorRequired]
|
|
||||||
public string Title { get; set; } = string.Empty;
|
|
||||||
|
|
||||||
/// <summary>Whether the section is expanded — its items rendered.</summary>
|
|
||||||
[Parameter]
|
|
||||||
public bool Expanded { get; set; }
|
|
||||||
|
|
||||||
/// <summary>Raised when the header button is clicked.</summary>
|
|
||||||
[Parameter]
|
|
||||||
public EventCallback OnToggle { get; set; }
|
|
||||||
|
|
||||||
/// <summary>The section's nav items, rendered only while expanded.</summary>
|
|
||||||
[Parameter]
|
|
||||||
public RenderFragment? ChildContent { get; set; }
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
@page "/login"
|
||||||
|
@layout LoginLayout
|
||||||
|
@using Microsoft.AspNetCore.Authorization
|
||||||
|
@* Login MUST stay anonymously reachable — [AllowAnonymous] overrides the
|
||||||
|
RequireAuthorization(ViewerPolicy) that MapRazorComponents<App>() applies, so the
|
||||||
|
cookie scheme's LoginPath="/login" redirect lands here for unauthenticated users.
|
||||||
|
|
||||||
|
The card is the shared kit's <LoginCard>: it renders a NATIVE static
|
||||||
|
<form method="post" action="/login"> (username/password + hidden returnUrl). A native
|
||||||
|
form submit is not a Blazor event, so it reaches the minimal-API POST /login endpoint
|
||||||
|
regardless of this app's InteractiveServer render mode. <AntiforgeryToken/> supplies the
|
||||||
|
token that PostLoginAsync's antiforgery.ValidateRequestAsync checks. *@
|
||||||
|
@attribute [AllowAnonymous]
|
||||||
|
|
||||||
|
<LoginCard Product="MXAccess Gateway" Action="/login" ReturnUrl="@ReturnUrl" Error="@Error">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
</LoginCard>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
/// <summary>Original protected URL the operator was bounced from; round-tripped to POST /login.</summary>
|
||||||
|
[SupplyParameterFromQuery(Name = "returnUrl")]
|
||||||
|
private string? ReturnUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Failure message surfaced by POST /login after a failed authentication.</summary>
|
||||||
|
[SupplyParameterFromQuery(Name = "error")]
|
||||||
|
private string? Error { get; set; }
|
||||||
|
}
|
||||||
@@ -26,7 +26,7 @@ else
|
|||||||
<tr><th scope="row">Run migrations</th><td>@Snapshot.Configuration.Authentication.RunMigrationsOnStartup</td></tr>
|
<tr><th scope="row">Run migrations</th><td>@Snapshot.Configuration.Authentication.RunMigrationsOnStartup</td></tr>
|
||||||
<tr><th scope="row">LDAP enabled</th><td>@Snapshot.Configuration.Ldap.Enabled</td></tr>
|
<tr><th scope="row">LDAP enabled</th><td>@Snapshot.Configuration.Ldap.Enabled</td></tr>
|
||||||
<tr><th scope="row">LDAP server</th><td>@Snapshot.Configuration.Ldap.Server:@Snapshot.Configuration.Ldap.Port</td></tr>
|
<tr><th scope="row">LDAP server</th><td>@Snapshot.Configuration.Ldap.Server:@Snapshot.Configuration.Ldap.Port</td></tr>
|
||||||
<tr><th scope="row">LDAP TLS</th><td>@Snapshot.Configuration.Ldap.UseTls</td></tr>
|
<tr><th scope="row">LDAP transport</th><td>@Snapshot.Configuration.Ldap.Transport</td></tr>
|
||||||
<tr><th scope="row">LDAP search base</th><td><code>@Snapshot.Configuration.Ldap.SearchBase</code></td></tr>
|
<tr><th scope="row">LDAP search base</th><td><code>@Snapshot.Configuration.Ldap.SearchBase</code></td></tr>
|
||||||
<tr><th scope="row">LDAP service account</th><td><code>@Snapshot.Configuration.Ldap.ServiceAccountDn</code></td></tr>
|
<tr><th scope="row">LDAP service account</th><td><code>@Snapshot.Configuration.Ldap.ServiceAccountDn</code></td></tr>
|
||||||
<tr><th scope="row">LDAP service password</th><td>@Snapshot.Configuration.Ldap.ServiceAccountPassword</td></tr>
|
<tr><th scope="row">LDAP service password</th><td>@Snapshot.Configuration.Ldap.ServiceAccountPassword</td></tr>
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
<span class="chip @CssClass">@Text</span>
|
@* Thin adapter: maps MxGateway runtime state text → kit StatusPill state.
|
||||||
|
The bespoke .chip rendering now lives in the kit; only the app's domain
|
||||||
|
text→state vocabulary remains here. Call sites (<StatusBadge Text="..."/>) unchanged. *@
|
||||||
|
<StatusPill State="MapState(Text)">@Text</StatusPill>
|
||||||
@code {
|
@code {
|
||||||
[Parameter]
|
[Parameter] public string? Text { get; set; }
|
||||||
public string? Text { get; set; }
|
|
||||||
|
|
||||||
private string CssClass => Text switch
|
private static StatusState MapState(string? text) => text switch
|
||||||
{
|
{
|
||||||
"Ready" or "Healthy" or "Active" => "chip-ok",
|
"Ready" or "Healthy" or "Active" => StatusState.Ok,
|
||||||
"Creating" or "StartingWorker" or "WaitingForPipe" or "InitializingWorker" or "Closing" => "chip-warn",
|
"Creating" or "StartingWorker" or "WaitingForPipe" or "InitializingWorker" or "Closing"
|
||||||
"Stale" or "Degraded" => "chip-warn",
|
or "Stale" or "Degraded" => StatusState.Warn,
|
||||||
"Faulted" or "Unavailable" => "chip-bad",
|
"Faulted" or "Unavailable" => StatusState.Bad,
|
||||||
"Closed" or "Revoked" or "Unknown" => "chip-idle",
|
_ => StatusState.Idle,
|
||||||
_ => "chip-idle"
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,4 +10,5 @@
|
|||||||
@using ZB.MOM.WW.MxGateway.Server.Dashboard.Components.Shared
|
@using ZB.MOM.WW.MxGateway.Server.Dashboard.Components.Shared
|
||||||
@using ZB.MOM.WW.MxGateway.Server.Security.Authorization
|
@using ZB.MOM.WW.MxGateway.Server.Security.Authorization
|
||||||
@using ZB.MOM.WW.MxGateway.Server.Workers
|
@using ZB.MOM.WW.MxGateway.Server.Workers
|
||||||
|
@using ZB.MOM.WW.Theme
|
||||||
@using static Microsoft.AspNetCore.Components.Web.RenderMode
|
@using static Microsoft.AspNetCore.Components.Web.RenderMode
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ public sealed class DashboardApiKeyAuthorization
|
|||||||
{
|
{
|
||||||
/// <summary>Determines whether the user can manage API keys.</summary>
|
/// <summary>Determines whether the user can manage API keys.</summary>
|
||||||
/// <param name="user">The authenticated user principal.</param>
|
/// <param name="user">The authenticated user principal.</param>
|
||||||
|
/// <returns>True if the user is an authenticated admin; otherwise false.</returns>
|
||||||
public bool CanManage(ClaimsPrincipal user)
|
public bool CanManage(ClaimsPrincipal user)
|
||||||
{
|
{
|
||||||
if (user.Identity?.IsAuthenticated != true)
|
if (user.Identity?.IsAuthenticated != true)
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
|
using System.Text.Json;
|
||||||
using Microsoft.Data.Sqlite;
|
using Microsoft.Data.Sqlite;
|
||||||
|
using ZB.MOM.WW.Audit;
|
||||||
|
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||||
|
using ZB.MOM.WW.Auth.ApiKeys.Admin;
|
||||||
|
using ZB.MOM.WW.MxGateway.Server.Security.Audit;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Security.Authentication;
|
using ZB.MOM.WW.MxGateway.Server.Security.Authentication;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Security.Authorization;
|
using ZB.MOM.WW.MxGateway.Server.Security.Authorization;
|
||||||
|
|
||||||
@@ -7,24 +12,21 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
|
|||||||
|
|
||||||
public sealed class DashboardApiKeyManagementService(
|
public sealed class DashboardApiKeyManagementService(
|
||||||
DashboardApiKeyAuthorization authorization,
|
DashboardApiKeyAuthorization authorization,
|
||||||
|
ApiKeyAdminCommands adminCommands,
|
||||||
IApiKeyAdminStore adminStore,
|
IApiKeyAdminStore adminStore,
|
||||||
IApiKeyAuditStore auditStore,
|
IAuditWriter auditWriter,
|
||||||
IApiKeySecretHasher hasher,
|
|
||||||
IHttpContextAccessor httpContextAccessor) : IDashboardApiKeyManagementService
|
IHttpContextAccessor httpContextAccessor) : IDashboardApiKeyManagementService
|
||||||
{
|
{
|
||||||
private const string UnauthorizedMessage = "Sign in with an authorized LDAP account to manage API keys.";
|
private const string UnauthorizedMessage = "Sign in with an authorized LDAP account to manage API keys.";
|
||||||
|
private const string PepperUnavailableMarker = "pepper unavailable";
|
||||||
|
|
||||||
/// <summary>Determines whether the user can manage API keys.</summary>
|
/// <inheritdoc />
|
||||||
/// <param name="user">The authenticated user principal.</param>
|
|
||||||
public bool CanManage(ClaimsPrincipal user)
|
public bool CanManage(ClaimsPrincipal user)
|
||||||
{
|
{
|
||||||
return authorization.CanManage(user);
|
return authorization.CanManage(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Creates an API key asynchronously.</summary>
|
/// <inheritdoc />
|
||||||
/// <param name="user">The authenticated user principal.</param>
|
|
||||||
/// <param name="request">The request payload.</param>
|
|
||||||
/// <param name="cancellationToken">Token to observe for cancellation.</param>
|
|
||||||
public async Task<DashboardApiKeyManagementResult> CreateAsync(
|
public async Task<DashboardApiKeyManagementResult> CreateAsync(
|
||||||
ClaimsPrincipal user,
|
ClaimsPrincipal user,
|
||||||
DashboardApiKeyManagementRequest request,
|
DashboardApiKeyManagementRequest request,
|
||||||
@@ -42,28 +44,31 @@ public sealed class DashboardApiKeyManagementService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
string keyId = request.KeyId.Trim();
|
string keyId = request.KeyId.Trim();
|
||||||
string secret = ApiKeySecretGenerator.Generate();
|
|
||||||
string apiKey = FormatApiKey(keyId, secret);
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await adminStore.CreateAsync(
|
// The shared command set generates the secret, hashes it with the pepper, persists the
|
||||||
new ApiKeyCreateRequest(
|
// record and assembles the mxgw_<id>_<secret> token (shown once). It also appends its own
|
||||||
KeyId: keyId,
|
// "create-key" audit entry (now canonicalized through the IApiKeyAuditStore->IAuditWriter
|
||||||
KeyPrefix: $"mxgw_{keyId}",
|
// adapter); the dashboard layers a richer "dashboard-create-key" canonical AuditEvent
|
||||||
SecretHash: hasher.HashSecret(secret),
|
// (Target + CorrelationId + remote address) on top via IAuditWriter to preserve the
|
||||||
DisplayName: request.DisplayName.Trim(),
|
// dashboard audit vocabulary — both rows land in the canonical audit_event store.
|
||||||
Scopes: request.Scopes,
|
CreateKeyResult created = await adminCommands.CreateKeyAsync(
|
||||||
Constraints: request.Constraints,
|
keyId,
|
||||||
CreatedUtc: DateTimeOffset.UtcNow),
|
request.DisplayName.Trim(),
|
||||||
|
request.Scopes,
|
||||||
|
ApiKeyConstraintSerializer.Serialize(request.Constraints),
|
||||||
|
RemoteAddress(),
|
||||||
cancellationToken)
|
cancellationToken)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
await AppendAuditAsync(keyId, "dashboard-create-key", null, cancellationToken).ConfigureAwait(false);
|
await WriteDashboardAuditAsync(user, keyId, "dashboard-create-key", null, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
return DashboardApiKeyManagementResult.Success("API key created. Copy the key now; it will not be shown again.", apiKey);
|
return DashboardApiKeyManagementResult.Success(
|
||||||
|
"API key created. Copy the key now; it will not be shown again.",
|
||||||
|
created.Token);
|
||||||
}
|
}
|
||||||
catch (ApiKeyPepperUnavailableException)
|
catch (InvalidOperationException exception) when (IsPepperUnavailable(exception))
|
||||||
{
|
{
|
||||||
return DashboardApiKeyManagementResult.Fail("API key pepper is not configured.");
|
return DashboardApiKeyManagementResult.Fail("API key pepper is not configured.");
|
||||||
}
|
}
|
||||||
@@ -73,10 +78,7 @@ public sealed class DashboardApiKeyManagementService(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Revokes an API key asynchronously.</summary>
|
/// <inheritdoc />
|
||||||
/// <param name="user">The authenticated user principal.</param>
|
|
||||||
/// <param name="keyId">The API key identifier.</param>
|
|
||||||
/// <param name="cancellationToken">Token to observe for cancellation.</param>
|
|
||||||
public async Task<DashboardApiKeyManagementResult> RevokeAsync(
|
public async Task<DashboardApiKeyManagementResult> RevokeAsync(
|
||||||
ClaimsPrincipal user,
|
ClaimsPrincipal user,
|
||||||
string keyId,
|
string keyId,
|
||||||
@@ -94,26 +96,24 @@ public sealed class DashboardApiKeyManagementService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
string normalizedKeyId = keyId.Trim();
|
string normalizedKeyId = keyId.Trim();
|
||||||
bool revoked = await adminStore
|
KeyActionResult result = await adminCommands
|
||||||
.RevokeAsync(normalizedKeyId, DateTimeOffset.UtcNow, cancellationToken)
|
.RevokeKeyAsync(normalizedKeyId, RemoteAddress(), cancellationToken)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
await AppendAuditAsync(
|
await WriteDashboardAuditAsync(
|
||||||
|
user,
|
||||||
normalizedKeyId,
|
normalizedKeyId,
|
||||||
"dashboard-revoke-key",
|
"dashboard-revoke-key",
|
||||||
revoked ? "revoked" : "not-found-or-already-revoked",
|
result.Succeeded ? "revoked" : "not-found-or-already-revoked",
|
||||||
cancellationToken)
|
cancellationToken)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
return revoked
|
return result.Succeeded
|
||||||
? DashboardApiKeyManagementResult.Success("API key revoked.")
|
? DashboardApiKeyManagementResult.Success("API key revoked.")
|
||||||
: DashboardApiKeyManagementResult.Fail("API key was not found or is already revoked.");
|
: DashboardApiKeyManagementResult.Fail("API key was not found or is already revoked.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Rotates an API key secret asynchronously.</summary>
|
/// <inheritdoc />
|
||||||
/// <param name="user">The authenticated user principal.</param>
|
|
||||||
/// <param name="keyId">The API key identifier.</param>
|
|
||||||
/// <param name="cancellationToken">Token to observe for cancellation.</param>
|
|
||||||
public async Task<DashboardApiKeyManagementResult> RotateAsync(
|
public async Task<DashboardApiKeyManagementResult> RotateAsync(
|
||||||
ClaimsPrincipal user,
|
ClaimsPrincipal user,
|
||||||
string keyId,
|
string keyId,
|
||||||
@@ -131,36 +131,36 @@ public sealed class DashboardApiKeyManagementService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
string normalizedKeyId = keyId.Trim();
|
string normalizedKeyId = keyId.Trim();
|
||||||
string secret = ApiKeySecretGenerator.Generate();
|
|
||||||
string apiKey = FormatApiKey(normalizedKeyId, secret);
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
bool rotated = await adminStore
|
CreateKeyResult rotated = await adminCommands
|
||||||
.RotateAsync(normalizedKeyId, hasher.HashSecret(secret), DateTimeOffset.UtcNow, cancellationToken)
|
.RotateKeyAsync(normalizedKeyId, RemoteAddress(), cancellationToken)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
await AppendAuditAsync(
|
bool succeeded = rotated.Token is not null;
|
||||||
|
|
||||||
|
await WriteDashboardAuditAsync(
|
||||||
|
user,
|
||||||
normalizedKeyId,
|
normalizedKeyId,
|
||||||
"dashboard-rotate-key",
|
"dashboard-rotate-key",
|
||||||
rotated ? "rotated" : "not-found",
|
succeeded ? "rotated" : "not-found",
|
||||||
cancellationToken)
|
cancellationToken)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
return rotated
|
return succeeded
|
||||||
? DashboardApiKeyManagementResult.Success("API key rotated. Copy the key now; it will not be shown again.", apiKey)
|
? DashboardApiKeyManagementResult.Success(
|
||||||
|
"API key rotated. Copy the key now; it will not be shown again.",
|
||||||
|
rotated.Token)
|
||||||
: DashboardApiKeyManagementResult.Fail("API key was not found.");
|
: DashboardApiKeyManagementResult.Fail("API key was not found.");
|
||||||
}
|
}
|
||||||
catch (ApiKeyPepperUnavailableException)
|
catch (InvalidOperationException exception) when (IsPepperUnavailable(exception))
|
||||||
{
|
{
|
||||||
return DashboardApiKeyManagementResult.Fail("API key pepper is not configured.");
|
return DashboardApiKeyManagementResult.Fail("API key pepper is not configured.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Deletes a revoked API key asynchronously.</summary>
|
/// <inheritdoc />
|
||||||
/// <param name="user">The authenticated user principal.</param>
|
|
||||||
/// <param name="keyId">The API key identifier.</param>
|
|
||||||
/// <param name="cancellationToken">Token to observe for cancellation.</param>
|
|
||||||
public async Task<DashboardApiKeyManagementResult> DeleteAsync(
|
public async Task<DashboardApiKeyManagementResult> DeleteAsync(
|
||||||
ClaimsPrincipal user,
|
ClaimsPrincipal user,
|
||||||
string keyId,
|
string keyId,
|
||||||
@@ -182,7 +182,8 @@ public sealed class DashboardApiKeyManagementService(
|
|||||||
.DeleteAsync(normalizedKeyId, cancellationToken)
|
.DeleteAsync(normalizedKeyId, cancellationToken)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
await AppendAuditAsync(
|
await WriteDashboardAuditAsync(
|
||||||
|
user,
|
||||||
normalizedKeyId,
|
normalizedKeyId,
|
||||||
"dashboard-delete-key",
|
"dashboard-delete-key",
|
||||||
deleted ? "deleted" : "not-found-or-active",
|
deleted ? "deleted" : "not-found-or-active",
|
||||||
@@ -194,22 +195,92 @@ public sealed class DashboardApiKeyManagementService(
|
|||||||
: DashboardApiKeyManagementResult.Fail("API key was not found, or is still active. Revoke it before deleting.");
|
: DashboardApiKeyManagementResult.Fail("API key was not found, or is still active. Revoke it before deleting.");
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task AppendAuditAsync(
|
private string? RemoteAddress() =>
|
||||||
string? keyId,
|
httpContextAccessor.HttpContext?.Connection.RemoteIpAddress?.ToString();
|
||||||
string eventType,
|
|
||||||
string? details,
|
/// <summary>
|
||||||
|
/// Resolves the operator's username from the authenticated dashboard principal.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// The passed <paramref name="user"/> is preferred over the ambient HTTP context because it
|
||||||
|
/// is already in scope at every call site (the callers gate on <see cref="CanManage"/> using
|
||||||
|
/// it) and is unambiguous. Falls back to <see cref="IAuditActorAccessor.CurrentActor"/> for
|
||||||
|
/// defensive coverage, then to <c>"unknown"</c> when neither is available.
|
||||||
|
/// </remarks>
|
||||||
|
private static string ResolveOperatorActor(ClaimsPrincipal user)
|
||||||
|
{
|
||||||
|
// ZbClaimTypes.Username = "zb:username" — the canonical LDAP login name.
|
||||||
|
string? username = user.FindFirstValue(ZB.MOM.WW.Auth.AspNetCore.ZbClaimTypes.Username);
|
||||||
|
if (!string.IsNullOrWhiteSpace(username))
|
||||||
|
{
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Framework fallback: Identity.Name is driven by the nameClaimType on the ClaimsIdentity
|
||||||
|
// (set to ZbClaimTypes.Name = ClaimTypes.Name by DashboardAuthenticator → display name).
|
||||||
|
string? identityName = user.Identity?.Name;
|
||||||
|
if (!string.IsNullOrWhiteSpace(identityName))
|
||||||
|
{
|
||||||
|
return identityName;
|
||||||
|
}
|
||||||
|
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Emits the dashboard's own canonical <see cref="AuditEvent"/> for a <c>dashboard-*</c> op
|
||||||
|
/// directly through the best-effort <see cref="IAuditWriter"/> (Task 2.3 #6). This is in
|
||||||
|
/// addition to the <c>create/revoke/rotate-key</c> event that <see cref="ApiKeyAdminCommands"/>
|
||||||
|
/// emits via the canonical-forwarding <c>IApiKeyAuditStore</c> adapter — the doubled-audit
|
||||||
|
/// behaviour is preserved, both rows now land in the canonical <c>audit_event</c> store.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Phase 3 (Actor = operator principal): <c>Actor</c> is the LDAP operator who performed the
|
||||||
|
/// action (resolved from the <paramref name="user"/> principal); <c>Target</c> is the managed
|
||||||
|
/// API key id. This fixes the pre-Phase-3 semantic gap where both fields held the keyId.
|
||||||
|
/// </remarks>
|
||||||
|
private async Task WriteDashboardAuditAsync(
|
||||||
|
ClaimsPrincipal user,
|
||||||
|
string keyId,
|
||||||
|
string action,
|
||||||
|
string? detail,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
await auditStore.AppendAsync(
|
AuditEvent auditEvent = new()
|
||||||
new ApiKeyAuditEntry(
|
{
|
||||||
KeyId: keyId,
|
EventId = Guid.NewGuid(),
|
||||||
EventType: eventType,
|
OccurredAtUtc = DateTimeOffset.UtcNow,
|
||||||
RemoteAddress: httpContextAccessor.HttpContext?.Connection.RemoteIpAddress?.ToString(),
|
Actor = ResolveOperatorActor(user),
|
||||||
Details: details),
|
Action = action,
|
||||||
cancellationToken)
|
Outcome = AuditOutcome.Success,
|
||||||
.ConfigureAwait(false);
|
Category = CanonicalForwardingApiKeyAuditStore.ApiKeyCategory,
|
||||||
|
Target = keyId,
|
||||||
|
SourceNode = RemoteAddress(),
|
||||||
|
CorrelationId = ParseCorrelationId(),
|
||||||
|
DetailsJson = WrapDetail(detail),
|
||||||
|
};
|
||||||
|
|
||||||
|
await auditWriter.WriteAsync(auditEvent, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Derives a correlation id from the ASP.NET Core request trace identifier when it is a
|
||||||
|
/// well-formed GUID; otherwise null (the default <c>HttpContext.TraceIdentifier</c> is the
|
||||||
|
/// connection:request form, not a GUID, so it correlates to null rather than fabricating one).
|
||||||
|
/// </summary>
|
||||||
|
private Guid? ParseCorrelationId() =>
|
||||||
|
Guid.TryParse(httpContextAccessor.HttpContext?.TraceIdentifier, out Guid correlationId)
|
||||||
|
? correlationId
|
||||||
|
: null;
|
||||||
|
|
||||||
|
private static string? WrapDetail(string? detail) =>
|
||||||
|
detail is null
|
||||||
|
? null
|
||||||
|
: JsonSerializer.Serialize(new Dictionary<string, string> { ["detail"] = detail });
|
||||||
|
|
||||||
|
private static bool IsPepperUnavailable(InvalidOperationException exception) =>
|
||||||
|
exception.Message.Contains(PepperUnavailableMarker, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
private static string? ValidateCreateRequest(DashboardApiKeyManagementRequest request)
|
private static string? ValidateCreateRequest(DashboardApiKeyManagementRequest request)
|
||||||
{
|
{
|
||||||
string? keyIdValidation = ValidateKeyId(request.KeyId);
|
string? keyIdValidation = ValidateKeyId(request.KeyId);
|
||||||
@@ -248,9 +319,4 @@ public sealed class DashboardApiKeyManagementService(
|
|||||||
? null
|
? null
|
||||||
: "API key id may contain only letters, numbers, periods, and hyphens.";
|
: "API key id may contain only letters, numbers, periods, and hyphens.";
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string FormatApiKey(string keyId, string secret)
|
|
||||||
{
|
|
||||||
return $"mxgw_{keyId}_{secret}";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ public sealed record DashboardAuthenticationResult(
|
|||||||
/// Creates a successful authentication result.
|
/// Creates a successful authentication result.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="principal">Authenticated principal.</param>
|
/// <param name="principal">Authenticated principal.</param>
|
||||||
|
/// <returns>A successful <see cref="DashboardAuthenticationResult"/> wrapping the principal.</returns>
|
||||||
public static DashboardAuthenticationResult Success(ClaimsPrincipal principal)
|
public static DashboardAuthenticationResult Success(ClaimsPrincipal principal)
|
||||||
{
|
{
|
||||||
return new DashboardAuthenticationResult(true, principal, null);
|
return new DashboardAuthenticationResult(true, principal, null);
|
||||||
@@ -32,6 +33,7 @@ public sealed record DashboardAuthenticationResult(
|
|||||||
/// Creates a failed authentication result.
|
/// Creates a failed authentication result.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="failureMessage">Diagnostic message describing the failure.</param>
|
/// <param name="failureMessage">Diagnostic message describing the failure.</param>
|
||||||
|
/// <returns>A failed <see cref="DashboardAuthenticationResult"/> with the given message.</returns>
|
||||||
public static DashboardAuthenticationResult Fail(string failureMessage)
|
public static DashboardAuthenticationResult Fail(string failureMessage)
|
||||||
{
|
{
|
||||||
return new DashboardAuthenticationResult(false, null, failureMessage);
|
return new DashboardAuthenticationResult(false, null, failureMessage);
|
||||||
|
|||||||
@@ -1,14 +1,26 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using System.Text;
|
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||||
using Microsoft.Extensions.Options;
|
using ZB.MOM.WW.Auth.Abstractions.Roles;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
using ZB.MOM.WW.Auth.AspNetCore;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Security.Authorization;
|
|
||||||
using Novell.Directory.Ldap;
|
|
||||||
|
|
||||||
namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
|
namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Authenticates interactive dashboard logins against LDAP. The bind/search
|
||||||
|
/// mechanics are delegated to the shared <see cref="ILdapAuthService"/>
|
||||||
|
/// (<c>ZB.MOM.WW.Auth.Ldap</c>), which performs bind-then-search, fails closed,
|
||||||
|
/// and never throws — returning the user's display name and LDAP groups on
|
||||||
|
/// success. This class keeps the dashboard-specific policy: groups are resolved
|
||||||
|
/// to dashboard roles via <see cref="IGroupRoleMapper{TRole}"/>, a login with no
|
||||||
|
/// matching role is denied, and the resulting <see cref="ClaimsPrincipal"/> is
|
||||||
|
/// shaped exactly as before (see <see cref="CreatePrincipal"/>).
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="ldapAuthService">Shared LDAP bind-then-search provider.</param>
|
||||||
|
/// <param name="roleMapper">Maps LDAP groups to dashboard roles (Task 1.1 seam).</param>
|
||||||
|
/// <param name="logger">Logger for diagnostic, credential-free login outcomes.</param>
|
||||||
public sealed class DashboardAuthenticator(
|
public sealed class DashboardAuthenticator(
|
||||||
IOptions<GatewayOptions> options,
|
ILdapAuthService ldapAuthService,
|
||||||
|
IGroupRoleMapper<string> roleMapper,
|
||||||
ILogger<DashboardAuthenticator> logger) : IDashboardAuthenticator
|
ILogger<DashboardAuthenticator> logger) : IDashboardAuthenticator
|
||||||
{
|
{
|
||||||
private const string GenericFailureMessage = "The username or password is invalid, or the user is not authorized.";
|
private const string GenericFailureMessage = "The username or password is invalid, or the user is not authorized.";
|
||||||
@@ -19,240 +31,72 @@ public sealed class DashboardAuthenticator(
|
|||||||
string? password,
|
string? password,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
LdapOptions ldapOptions = options.Value.Ldap;
|
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
|
||||||
DashboardOptions dashboardOptions = options.Value.Dashboard;
|
|
||||||
if (!ldapOptions.Enabled
|
|
||||||
|| string.IsNullOrWhiteSpace(username)
|
|
||||||
|| string.IsNullOrWhiteSpace(password))
|
|
||||||
{
|
|
||||||
return DashboardAuthenticationResult.Fail(GenericFailureMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!ldapOptions.UseTls && !ldapOptions.AllowInsecureLdap)
|
|
||||||
{
|
{
|
||||||
return DashboardAuthenticationResult.Fail(GenericFailureMessage);
|
return DashboardAuthenticationResult.Fail(GenericFailureMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
string normalizedUsername = username.Trim();
|
string normalizedUsername = username.Trim();
|
||||||
|
|
||||||
try
|
// The shared service owns connect/bind/search and the fail-closed contract:
|
||||||
|
// it returns Fail(Disabled) when LDAP is off, enforces TLS-or-AllowInsecure via
|
||||||
|
// its startup validator, and never throws. We only translate its outcome into a
|
||||||
|
// dashboard principal here.
|
||||||
|
LdapAuthResult ldapResult = await ldapAuthService
|
||||||
|
.AuthenticateAsync(normalizedUsername, password, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (!ldapResult.Succeeded)
|
||||||
{
|
{
|
||||||
using LdapConnection connection = new();
|
return DashboardAuthenticationResult.Fail(GenericFailureMessage);
|
||||||
connection.SecureSocketLayer = ldapOptions.UseTls;
|
|
||||||
|
|
||||||
await Task.Run(
|
|
||||||
() => connection.Connect(ldapOptions.Server, ldapOptions.Port),
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
await BindServiceAccountAsync(connection, ldapOptions, cancellationToken).ConfigureAwait(false);
|
|
||||||
LdapEntry? candidate = await SearchUserAsync(
|
|
||||||
connection,
|
|
||||||
ldapOptions,
|
|
||||||
normalizedUsername,
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
if (candidate is null)
|
|
||||||
{
|
|
||||||
return DashboardAuthenticationResult.Fail(GenericFailureMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
await Task.Run(
|
|
||||||
() => connection.Bind(candidate.Dn, password),
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
await BindServiceAccountAsync(connection, ldapOptions, cancellationToken).ConfigureAwait(false);
|
|
||||||
LdapEntry? authenticatedEntry = await SearchUserAsync(
|
|
||||||
connection,
|
|
||||||
ldapOptions,
|
|
||||||
normalizedUsername,
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
if (authenticatedEntry is null)
|
|
||||||
{
|
|
||||||
return DashboardAuthenticationResult.Fail(GenericFailureMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
string displayName = ReadAttribute(authenticatedEntry, ldapOptions.DisplayNameAttribute)
|
|
||||||
?? normalizedUsername;
|
|
||||||
IReadOnlyList<string> groups = ReadAttributeValues(authenticatedEntry, ldapOptions.GroupAttribute);
|
|
||||||
|
|
||||||
IReadOnlyList<string> roles = MapGroupsToRoles(groups, dashboardOptions.GroupToRole);
|
|
||||||
if (roles.Count == 0)
|
|
||||||
{
|
|
||||||
logger.LogInformation(
|
|
||||||
"LDAP dashboard login denied for user {User}: no GroupToRole mapping matched their LDAP groups.",
|
|
||||||
normalizedUsername);
|
|
||||||
|
|
||||||
return DashboardAuthenticationResult.Fail(GenericFailureMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
return DashboardAuthenticationResult.Success(CreatePrincipal(
|
|
||||||
normalizedUsername,
|
|
||||||
displayName,
|
|
||||||
groups,
|
|
||||||
roles));
|
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException)
|
|
||||||
{
|
GroupRoleMapping<string> mapping = await roleMapper
|
||||||
throw;
|
.MapAsync(ldapResult.Groups, cancellationToken)
|
||||||
}
|
.ConfigureAwait(false);
|
||||||
catch (LdapException ex)
|
|
||||||
|
IReadOnlyList<string> roles = mapping.Roles;
|
||||||
|
if (roles.Count == 0)
|
||||||
{
|
{
|
||||||
|
// Preserve the long-standing "no roles matched -> login denied" rule.
|
||||||
logger.LogInformation(
|
logger.LogInformation(
|
||||||
"LDAP dashboard login rejected for user {User}: result code {ResultCode}.",
|
"LDAP dashboard login denied for user {User}: no GroupToRole mapping matched their LDAP groups.",
|
||||||
normalizedUsername,
|
ldapResult.Username);
|
||||||
ex.ResultCode);
|
|
||||||
|
|
||||||
return DashboardAuthenticationResult.Fail(GenericFailureMessage);
|
return DashboardAuthenticationResult.Fail(GenericFailureMessage);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
logger.LogError(ex, "Unexpected LDAP dashboard login error for user {User}.", normalizedUsername);
|
|
||||||
|
|
||||||
return DashboardAuthenticationResult.Fail(GenericFailureMessage);
|
return DashboardAuthenticationResult.Success(CreatePrincipal(
|
||||||
}
|
ldapResult.Username,
|
||||||
}
|
ldapResult.DisplayName,
|
||||||
|
ldapResult.Groups,
|
||||||
/// <summary>Escapes special characters in LDAP filter strings.</summary>
|
roles));
|
||||||
/// <param name="value">The string value to escape.</param>
|
|
||||||
internal static string EscapeLdapFilter(string value)
|
|
||||||
{
|
|
||||||
StringBuilder builder = new(value.Length);
|
|
||||||
foreach (char character in value)
|
|
||||||
{
|
|
||||||
builder.Append(character switch
|
|
||||||
{
|
|
||||||
'\\' => @"\5c",
|
|
||||||
'*' => @"\2a",
|
|
||||||
'(' => @"\28",
|
|
||||||
')' => @"\29",
|
|
||||||
'\0' => @"\00",
|
|
||||||
_ => character.ToString()
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return builder.ToString();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Maps the user's LDAP groups to dashboard roles. A user can pick up
|
/// Builds the dashboard <see cref="ClaimsPrincipal"/> from the LDAP outcome.
|
||||||
/// multiple roles; Admin and Viewer are the only legal values. Returns
|
|
||||||
/// an empty list when no group matches (caller rejects the login).
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="groups">The collection of LDAP groups the user belongs to.</param>
|
/// <param name="username">
|
||||||
/// <param name="groupToRole">The mapping from group names to dashboard role names.</param>
|
/// The (trimmed) login name. Emitted as <see cref="ClaimTypes.NameIdentifier"/> (kept for
|
||||||
internal static IReadOnlyList<string> MapGroupsToRoles(
|
/// back-compat reads) and as the canonical <see cref="ZbClaimTypes.Username"/> ("zb:username").
|
||||||
IEnumerable<string> groups,
|
/// </param>
|
||||||
IReadOnlyDictionary<string, string> groupToRole)
|
/// <param name="displayName">
|
||||||
{
|
/// The user's display name. Emitted as <see cref="ZbClaimTypes.Name"/> (= <see cref="ClaimTypes.Name"/>
|
||||||
if (groupToRole.Count == 0)
|
/// so <c>Identity.Name</c> resolves) and as <see cref="ZbClaimTypes.DisplayName"/> ("zb:displayname")
|
||||||
{
|
/// for cross-app consistency.
|
||||||
return [];
|
/// </param>
|
||||||
}
|
/// <param name="groups">
|
||||||
|
/// The user's LDAP groups, as returned by <see cref="ILdapAuthService"/>. NOTE
|
||||||
HashSet<string> roles = new(StringComparer.Ordinal);
|
/// (review C1): these are <b>already-normalized short RDN names</b> (e.g.
|
||||||
foreach (string group in groups)
|
/// <c>GwAdmin</c>), not raw distinguished names. The shared
|
||||||
{
|
/// <c>ZB.MOM.WW.Auth.Ldap</c> provider strips each group DN to its first RDN
|
||||||
string normalizedGroup = group.Trim();
|
/// value before returning it, so the <see cref="DashboardAuthenticationDefaults.LdapGroupClaimType"/>
|
||||||
|
/// claim carries the short name. This differs from the pre-cutover behaviour,
|
||||||
// Lookup precedence (Server-040): the full literal group string is
|
/// which surfaced the raw <c>memberOf</c> values (full DNs) on the claim; the
|
||||||
// tried first; only if that misses do we fall back to the leading
|
/// claim is informational only (no policy or UI reads its value — authorization
|
||||||
// RDN value (e.g. "GwAdmin" extracted from
|
/// is role-based), so the shape change is non-breaking for dashboard consumers.
|
||||||
// "ou=GwAdmin,ou=groups,..."). The map's comparer is
|
/// </param>
|
||||||
// OrdinalIgnoreCase (see DashboardOptions.GroupToRole), so e.g.
|
/// <param name="roles">The dashboard roles resolved from <paramref name="groups"/>.</param>
|
||||||
// "GwAdmin" and "gwadmin" both match.
|
|
||||||
if (groupToRole.TryGetValue(normalizedGroup, out string? mapped)
|
|
||||||
|| groupToRole.TryGetValue(ExtractFirstRdnValue(normalizedGroup), out mapped))
|
|
||||||
{
|
|
||||||
roles.Add(mapped);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return [.. roles];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Extracts the first RDN value from a distinguished name.</summary>
|
|
||||||
/// <param name="distinguishedName">The LDAP distinguished name.</param>
|
|
||||||
internal static string ExtractFirstRdnValue(string distinguishedName)
|
|
||||||
{
|
|
||||||
int equalsIndex = distinguishedName.IndexOf('=');
|
|
||||||
if (equalsIndex < 0)
|
|
||||||
{
|
|
||||||
return distinguishedName;
|
|
||||||
}
|
|
||||||
|
|
||||||
int valueStart = equalsIndex + 1;
|
|
||||||
int commaIndex = distinguishedName.IndexOf(',', valueStart);
|
|
||||||
|
|
||||||
return commaIndex > valueStart
|
|
||||||
? distinguishedName[valueStart..commaIndex]
|
|
||||||
: distinguishedName[valueStart..];
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Task BindServiceAccountAsync(
|
|
||||||
LdapConnection connection,
|
|
||||||
LdapOptions ldapOptions,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return Task.Run(
|
|
||||||
() => connection.Bind(ldapOptions.ServiceAccountDn, ldapOptions.ServiceAccountPassword),
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<LdapEntry?> SearchUserAsync(
|
|
||||||
LdapConnection connection,
|
|
||||||
LdapOptions ldapOptions,
|
|
||||||
string username,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
string filter = $"({ldapOptions.UserNameAttribute}={EscapeLdapFilter(username)})";
|
|
||||||
ILdapSearchResults results = await Task.Run(
|
|
||||||
() => connection.Search(
|
|
||||||
ldapOptions.SearchBase,
|
|
||||||
LdapConnection.ScopeSub,
|
|
||||||
filter,
|
|
||||||
attrs: null,
|
|
||||||
typesOnly: false),
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
LdapEntry? entry = null;
|
|
||||||
while (results.HasMore())
|
|
||||||
{
|
|
||||||
LdapEntry next = results.Next();
|
|
||||||
if (entry is not null)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
entry = next;
|
|
||||||
}
|
|
||||||
|
|
||||||
return entry;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string? ReadAttribute(LdapEntry entry, string attributeName)
|
|
||||||
{
|
|
||||||
return ReadLdapAttribute(entry, attributeName)?.StringValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static IReadOnlyList<string> ReadAttributeValues(LdapEntry entry, string attributeName)
|
|
||||||
{
|
|
||||||
LdapAttribute? attribute = ReadLdapAttribute(entry, attributeName);
|
|
||||||
return attribute?.StringValueArray ?? [];
|
|
||||||
}
|
|
||||||
|
|
||||||
private static LdapAttribute? ReadLdapAttribute(LdapEntry entry, string attributeName)
|
|
||||||
{
|
|
||||||
return entry.GetAttribute(attributeName)
|
|
||||||
?? entry.GetAttribute(attributeName.ToLowerInvariant())
|
|
||||||
?? entry.GetAttribute(attributeName.ToUpperInvariant());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static ClaimsPrincipal CreatePrincipal(
|
private static ClaimsPrincipal CreatePrincipal(
|
||||||
string username,
|
string username,
|
||||||
string displayName,
|
string displayName,
|
||||||
@@ -261,11 +105,21 @@ public sealed class DashboardAuthenticator(
|
|||||||
{
|
{
|
||||||
List<Claim> claims =
|
List<Claim> claims =
|
||||||
[
|
[
|
||||||
|
// Keep NameIdentifier so any existing read-site that uses it continues to work.
|
||||||
new Claim(ClaimTypes.NameIdentifier, username),
|
new Claim(ClaimTypes.NameIdentifier, username),
|
||||||
new Claim(ClaimTypes.Name, displayName),
|
// Canonical login-username claim (Task 1.5).
|
||||||
|
new Claim(ZbClaimTypes.Username, username),
|
||||||
|
// ZbClaimTypes.Name == ClaimTypes.Name — drives Identity.Name resolution.
|
||||||
|
new Claim(ZbClaimTypes.Name, displayName),
|
||||||
|
// Canonical display-name claim for cross-app consistency (Task 1.5).
|
||||||
|
new Claim(ZbClaimTypes.DisplayName, displayName),
|
||||||
];
|
];
|
||||||
|
|
||||||
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
|
// ZbClaimTypes.Role == ClaimTypes.Role — drives IsInRole and [Authorize(Roles=...)].
|
||||||
|
claims.AddRange(roles.Select(role => new Claim(ZbClaimTypes.Role, role)));
|
||||||
|
// Groups are short RDN names from ILdapAuthService (see param doc above), so
|
||||||
|
// this claim value is the short group name, not the original DN.
|
||||||
|
// LdapGroupClaimType is MxGateway-specific ("mxgateway:ldap_group") — no ZbClaimType for groups.
|
||||||
claims.AddRange(groups.Select(group => new Claim(
|
claims.AddRange(groups.Select(group => new Claim(
|
||||||
DashboardAuthenticationDefaults.LdapGroupClaimType,
|
DashboardAuthenticationDefaults.LdapGroupClaimType,
|
||||||
group)));
|
group)));
|
||||||
@@ -273,8 +127,8 @@ public sealed class DashboardAuthenticator(
|
|||||||
ClaimsIdentity claimsIdentity = new(
|
ClaimsIdentity claimsIdentity = new(
|
||||||
claims,
|
claims,
|
||||||
DashboardAuthenticationDefaults.AuthenticationScheme,
|
DashboardAuthenticationDefaults.AuthenticationScheme,
|
||||||
ClaimTypes.Name,
|
ZbClaimTypes.Name,
|
||||||
ClaimTypes.Role);
|
ZbClaimTypes.Role);
|
||||||
|
|
||||||
return new ClaimsPrincipal(claimsIdentity);
|
return new ClaimsPrincipal(claimsIdentity);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ public static class DashboardConnectionStringDisplay
|
|||||||
{
|
{
|
||||||
/// <summary>Returns a sanitized Galaxy Repository connection string for display.</summary>
|
/// <summary>Returns a sanitized Galaxy Repository connection string for display.</summary>
|
||||||
/// <param name="connectionString">The connection string to sanitize.</param>
|
/// <param name="connectionString">The connection string to sanitize.</param>
|
||||||
|
/// <returns>A sanitized connection string with credentials removed, or <c>"[invalid connection string]"</c> if parsing fails.</returns>
|
||||||
public static string GalaxyRepositoryConnectionString(string connectionString)
|
public static string GalaxyRepositoryConnectionString(string connectionString)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
|||||||
+14
-59
@@ -1,7 +1,6 @@
|
|||||||
using System.Text.Encodings.Web;
|
using System.Text.Encodings.Web;
|
||||||
using Microsoft.AspNetCore.Antiforgery;
|
using Microsoft.AspNetCore.Antiforgery;
|
||||||
using Microsoft.AspNetCore.Authentication;
|
using Microsoft.AspNetCore.Authentication;
|
||||||
using Microsoft.AspNetCore.Http.HttpResults;
|
|
||||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Dashboard.Components;
|
using ZB.MOM.WW.MxGateway.Server.Dashboard.Components;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
|
using ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
|
||||||
@@ -25,12 +24,11 @@ public static class DashboardEndpointRouteBuilderExtensions
|
|||||||
return endpoints;
|
return endpoints;
|
||||||
}
|
}
|
||||||
|
|
||||||
endpoints.MapGet(
|
// GET /login is served by the [AllowAnonymous] Blazor <Login> component
|
||||||
"/login",
|
// (Components/Pages/Login.razor → @page "/login"), which renders the shared
|
||||||
(HttpContext httpContext, IAntiforgery antiforgery) => GetLoginAsync(httpContext, antiforgery))
|
// kit's <LoginCard>. Its [AllowAnonymous] attribute overrides the
|
||||||
.AllowAnonymous()
|
// RequireAuthorization(ViewerPolicy) that MapRazorComponents<App>() applies,
|
||||||
.WithName("DashboardLogin");
|
// so the cookie scheme's LoginPath="/login" redirect resolves for anonymous users.
|
||||||
|
|
||||||
endpoints.MapPost(
|
endpoints.MapPost(
|
||||||
"/login",
|
"/login",
|
||||||
(HttpContext httpContext, IAntiforgery antiforgery, IDashboardAuthenticator authenticator) =>
|
(HttpContext httpContext, IAntiforgery antiforgery, IDashboardAuthenticator authenticator) =>
|
||||||
@@ -92,17 +90,6 @@ public static class DashboardEndpointRouteBuilderExtensions
|
|||||||
return endpoints;
|
return endpoints;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Task<ContentHttpResult> GetLoginAsync(
|
|
||||||
HttpContext httpContext,
|
|
||||||
IAntiforgery antiforgery)
|
|
||||||
{
|
|
||||||
string returnUrl = SanitizeReturnUrl(httpContext.Request.Query["returnUrl"].ToString());
|
|
||||||
|
|
||||||
return Task.FromResult(TypedResults.Content(
|
|
||||||
RenderLoginPage(httpContext, antiforgery, returnUrl, failureMessage: null),
|
|
||||||
"text/html"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<IResult> PostLoginAsync(
|
private static async Task<IResult> PostLoginAsync(
|
||||||
HttpContext httpContext,
|
HttpContext httpContext,
|
||||||
IAntiforgery antiforgery,
|
IAntiforgery antiforgery,
|
||||||
@@ -124,10 +111,13 @@ public static class DashboardEndpointRouteBuilderExtensions
|
|||||||
|
|
||||||
if (!result.Succeeded || result.Principal is null)
|
if (!result.Succeeded || result.Principal is null)
|
||||||
{
|
{
|
||||||
return TypedResults.Content(
|
// Round-trip the failure back to the anonymous Blazor /login page, carrying
|
||||||
RenderLoginPage(httpContext, antiforgery, returnUrl, result.FailureMessage),
|
// the (sanitized) returnUrl so a successful retry still lands on the target.
|
||||||
"text/html",
|
string failureMessage = result.FailureMessage
|
||||||
statusCode: StatusCodes.Status401Unauthorized);
|
?? "The username or password is invalid, or the user is not authorized.";
|
||||||
|
return Results.Redirect(
|
||||||
|
$"/login?error={Uri.EscapeDataString(failureMessage)}"
|
||||||
|
+ $"&returnUrl={Uri.EscapeDataString(returnUrl)}");
|
||||||
}
|
}
|
||||||
|
|
||||||
await httpContext
|
await httpContext
|
||||||
@@ -158,42 +148,6 @@ public static class DashboardEndpointRouteBuilderExtensions
|
|||||||
return Results.LocalRedirect("/login");
|
return Results.LocalRedirect("/login");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string RenderLoginPage(
|
|
||||||
HttpContext httpContext,
|
|
||||||
IAntiforgery antiforgery,
|
|
||||||
string returnUrl,
|
|
||||||
string? failureMessage)
|
|
||||||
{
|
|
||||||
AntiforgeryTokenSet tokens = antiforgery.GetAndStoreTokens(httpContext);
|
|
||||||
string requestToken = tokens.RequestToken ?? string.Empty;
|
|
||||||
string alert = string.IsNullOrWhiteSpace(failureMessage)
|
|
||||||
? string.Empty
|
|
||||||
: $"<p class=\"alert alert-danger\" role=\"alert\">{HtmlEncoder.Default.Encode(failureMessage)}</p>";
|
|
||||||
|
|
||||||
string body = $"""
|
|
||||||
<section class="dashboard-login">
|
|
||||||
{alert}
|
|
||||||
<form method="post" action="/login" class="card login-card">
|
|
||||||
<div class="card-body">
|
|
||||||
<input name="{tokens.FormFieldName}" type="hidden" value="{HtmlEncoder.Default.Encode(requestToken)}" />
|
|
||||||
<input name="returnUrl" type="hidden" value="{HtmlEncoder.Default.Encode(returnUrl)}" />
|
|
||||||
<div class="mb-3">
|
|
||||||
<label for="username" class="form-label">Username</label>
|
|
||||||
<input id="username" name="username" type="text" autocomplete="username" class="form-control" />
|
|
||||||
</div>
|
|
||||||
<div class="mb-3">
|
|
||||||
<label for="password" class="form-label">Password</label>
|
|
||||||
<input id="password" name="password" type="password" autocomplete="current-password" class="form-control" />
|
|
||||||
</div>
|
|
||||||
<button type="submit" class="btn btn-primary">Sign in</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</section>
|
|
||||||
""";
|
|
||||||
|
|
||||||
return RenderPage("Dashboard Sign In", heading: null, body);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string RenderPage(string title, string body)
|
private static string RenderPage(string title, string body)
|
||||||
=> RenderPage(title, heading: title, body);
|
=> RenderPage(title, heading: title, body);
|
||||||
|
|
||||||
@@ -215,7 +169,8 @@ public static class DashboardEndpointRouteBuilderExtensions
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<title>{HtmlEncoder.Default.Encode(title)}</title>
|
<title>{HtmlEncoder.Default.Encode(title)}</title>
|
||||||
<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css" />
|
<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css" />
|
||||||
<link rel="stylesheet" href="/css/theme.css" />
|
<link rel="stylesheet" href="/_content/ZB.MOM.WW.Theme/css/theme.css" />
|
||||||
|
<link rel="stylesheet" href="/_content/ZB.MOM.WW.Theme/css/layout.css" />
|
||||||
<link rel="stylesheet" href="/css/site.css" />
|
<link rel="stylesheet" href="/css/site.css" />
|
||||||
</head>
|
</head>
|
||||||
<body class="dashboard-body">
|
<body class="dashboard-body">
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ internal static class DashboardGalaxyProjector
|
|||||||
{
|
{
|
||||||
/// <summary>Projects the cache entry to a dashboard Galaxy summary.</summary>
|
/// <summary>Projects the cache entry to a dashboard Galaxy summary.</summary>
|
||||||
/// <param name="entry">The Galaxy hierarchy cache entry.</param>
|
/// <param name="entry">The Galaxy hierarchy cache entry.</param>
|
||||||
|
/// <returns>The precomputed <see cref="DashboardGalaxySummary"/> from the cache entry.</returns>
|
||||||
public static DashboardGalaxySummary Project(GalaxyHierarchyCacheEntry entry)
|
public static DashboardGalaxySummary Project(GalaxyHierarchyCacheEntry entry)
|
||||||
{
|
{
|
||||||
return entry.DashboardSummary;
|
return entry.DashboardSummary;
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using ZB.MOM.WW.Auth.Abstractions.Roles;
|
||||||
|
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Shared-Auth <see cref="IGroupRoleMapper{TRole}"/> seam over the dashboard's
|
||||||
|
/// LDAP-group → role mapping. Roles are plain strings
|
||||||
|
/// (<see cref="DashboardRoles.Admin"/> / <see cref="DashboardRoles.Viewer"/>),
|
||||||
|
/// so <c>TRole</c> is <see cref="string"/>. The mapping rules (full-DN first,
|
||||||
|
/// leading-RDN fallback, case-insensitive) live in
|
||||||
|
/// <see cref="DashboardGroupRoleMapping"/>, shared with
|
||||||
|
/// <see cref="DashboardAuthenticator"/> so behaviour stays identical.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="options">Gateway options supplying the dashboard GroupToRole map.</param>
|
||||||
|
public sealed class DashboardGroupRoleMapper(IOptions<GatewayOptions> options)
|
||||||
|
: IGroupRoleMapper<string>
|
||||||
|
{
|
||||||
|
/// <summary>Maps LDAP group memberships to dashboard roles using the configured group-to-role rules.</summary>
|
||||||
|
/// <param name="groups">The list of LDAP group names or distinguished names for the authenticated user.</param>
|
||||||
|
/// <param name="ct">Token to cancel the asynchronous operation.</param>
|
||||||
|
/// <returns>A task that resolves to the role mapping for the supplied groups.</returns>
|
||||||
|
public Task<GroupRoleMapping<string>> MapAsync(
|
||||||
|
IReadOnlyList<string> groups,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
IReadOnlyList<string> roles = DashboardGroupRoleMapping.MapGroupsToRoles(
|
||||||
|
groups,
|
||||||
|
options.Value.Dashboard.GroupToRole);
|
||||||
|
|
||||||
|
return Task.FromResult(new GroupRoleMapping<string>(roles, Scope: null));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Single source of truth for mapping a user's LDAP groups to dashboard roles.
|
||||||
|
/// Both <see cref="DashboardAuthenticator"/> (the existing login flow) and
|
||||||
|
/// <see cref="DashboardGroupRoleMapper"/> (the shared-Auth
|
||||||
|
/// <see cref="ZB.MOM.WW.Auth.Abstractions.Roles.IGroupRoleMapper{TRole}"/> seam)
|
||||||
|
/// delegate here so the precedence and case rules stay identical.
|
||||||
|
/// </summary>
|
||||||
|
internal static class DashboardGroupRoleMapping
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Maps the user's LDAP groups to dashboard roles. A user can pick up
|
||||||
|
/// multiple roles; Admin and Viewer are the only legal values. Returns
|
||||||
|
/// an empty list when no group matches (caller rejects the login).
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="groups">The collection of LDAP groups the user belongs to.</param>
|
||||||
|
/// <param name="groupToRole">The mapping from group names to dashboard role names.</param>
|
||||||
|
/// <returns>The distinct set of dashboard roles matched from the user's groups.</returns>
|
||||||
|
internal static IReadOnlyList<string> MapGroupsToRoles(
|
||||||
|
IEnumerable<string> groups,
|
||||||
|
IReadOnlyDictionary<string, string> groupToRole)
|
||||||
|
{
|
||||||
|
if (groupToRole.Count == 0)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
HashSet<string> roles = new(StringComparer.Ordinal);
|
||||||
|
foreach (string group in groups)
|
||||||
|
{
|
||||||
|
string normalizedGroup = group.Trim();
|
||||||
|
|
||||||
|
// Lookup precedence (Server-040): the full literal group string is
|
||||||
|
// tried first; only if that misses do we fall back to the leading
|
||||||
|
// RDN value (e.g. "GwAdmin" extracted from
|
||||||
|
// "ou=GwAdmin,ou=groups,..."). The map's comparer is
|
||||||
|
// OrdinalIgnoreCase (see DashboardOptions.GroupToRole), so e.g.
|
||||||
|
// "GwAdmin" and "gwadmin" both match.
|
||||||
|
//
|
||||||
|
// Review C1: with the shared ZB.MOM.WW.Auth.Ldap provider, groups
|
||||||
|
// arrive here already stripped to short RDN names (the library calls
|
||||||
|
// FirstRdnValue before returning them). So through the live login path
|
||||||
|
// the full-string branch only ever sees short names and the RDN
|
||||||
|
// fallback is effectively a no-op — they collapse to the same key.
|
||||||
|
// The fallback is retained because this mapping is also reachable
|
||||||
|
// directly via the IGroupRoleMapper<string> seam (DashboardGroupRoleMapper),
|
||||||
|
// where a caller could still pass a full DN. CONSEQUENCE: configuring a
|
||||||
|
// full-DN GroupToRole *key* (e.g. "ou=GwAdmin,ou=groups,...") is
|
||||||
|
// UNSUPPORTED with the shared library — the incoming group is a short
|
||||||
|
// name, so it will never equal a full-DN key. Keep GroupToRole keys as
|
||||||
|
// short group names.
|
||||||
|
if (groupToRole.TryGetValue(normalizedGroup, out string? mapped)
|
||||||
|
|| groupToRole.TryGetValue(ExtractFirstRdnValue(normalizedGroup), out mapped))
|
||||||
|
{
|
||||||
|
roles.Add(mapped);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [.. roles];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Extracts the first RDN value from a distinguished name.</summary>
|
||||||
|
/// <param name="distinguishedName">The LDAP distinguished name.</param>
|
||||||
|
/// <returns>The value portion of the first RDN component, or the full string if no <c>=</c> is found.</returns>
|
||||||
|
internal static string ExtractFirstRdnValue(string distinguishedName)
|
||||||
|
{
|
||||||
|
int equalsIndex = distinguishedName.IndexOf('=');
|
||||||
|
if (equalsIndex < 0)
|
||||||
|
{
|
||||||
|
return distinguishedName;
|
||||||
|
}
|
||||||
|
|
||||||
|
int valueStart = equalsIndex + 1;
|
||||||
|
int commaIndex = distinguishedName.IndexOf(',', valueStart);
|
||||||
|
|
||||||
|
return commaIndex > valueStart
|
||||||
|
? distinguishedName[valueStart..commaIndex]
|
||||||
|
: distinguishedName[valueStart..];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -192,7 +192,8 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <summary>Releases resources and closes the associated gateway session.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous dispose operation.</returns>
|
||||||
public async ValueTask DisposeAsync()
|
public async ValueTask DisposeAsync()
|
||||||
{
|
{
|
||||||
if (_disposed)
|
if (_disposed)
|
||||||
|
|||||||
@@ -8,8 +8,10 @@ public static class DashboardRoles
|
|||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Read-write access: API-key CRUD, settings, any state-changing UI.
|
/// Read-write access: API-key CRUD, settings, any state-changing UI.
|
||||||
|
/// Canonical role value (Task 1.7); formerly <c>"Admin"</c> — pure value
|
||||||
|
/// rename, the operations this role authorizes are unchanged.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public const string Admin = "Admin";
|
public const string Admin = "Administrator";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Read-only access: all pages render but write affordances are hidden.
|
/// Read-only access: all pages render but write affordances are hidden.
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
using Microsoft.AspNetCore.Authentication;
|
using Microsoft.AspNetCore.Authentication;
|
||||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
using ZB.MOM.WW.Auth.Abstractions.Roles;
|
||||||
|
using ZB.MOM.WW.Auth.AspNetCore;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||||
|
using ZB.MOM.WW.MxGateway.Server.Security.Audit;
|
||||||
|
|
||||||
namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
|
namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||||
|
|
||||||
@@ -15,11 +19,26 @@ public static class DashboardServiceCollectionExtensions
|
|||||||
/// Registers all dashboard services, authentication, and Razor components.
|
/// Registers all dashboard services, authentication, and Razor components.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="services">Service collection to register services.</param>
|
/// <param name="services">Service collection to register services.</param>
|
||||||
public static IServiceCollection AddGatewayDashboard(this IServiceCollection services)
|
/// <param name="configuration">
|
||||||
|
/// Application configuration, used to bind the shared LDAP provider's options
|
||||||
|
/// from the <c>MxGateway:Ldap</c> section.
|
||||||
|
/// </param>
|
||||||
|
/// <returns>The <paramref name="services"/> collection for chaining.</returns>
|
||||||
|
public static IServiceCollection AddGatewayDashboard(
|
||||||
|
this IServiceCollection services,
|
||||||
|
IConfiguration configuration)
|
||||||
{
|
{
|
||||||
|
// Dashboard logins delegate bind/search to the shared ZB.MOM.WW.Auth.Ldap
|
||||||
|
// provider. Its LdapOptions bind straight from MxGateway:Ldap (the gateway's
|
||||||
|
// LdapOptions field names match the shared options: Transport / AllowInsecure /
|
||||||
|
// SearchBase / ServiceAccount* / *Attribute). AddZbLdapAuth also adds a
|
||||||
|
// ValidateOnStart() so an insecure-transport misconfiguration fails fast at boot.
|
||||||
|
services.AddZbLdapAuth(configuration, "MxGateway:Ldap");
|
||||||
|
|
||||||
services.AddSingleton<IDashboardSnapshotService, DashboardSnapshotService>();
|
services.AddSingleton<IDashboardSnapshotService, DashboardSnapshotService>();
|
||||||
services.AddSingleton<IDashboardLiveDataService, DashboardLiveDataService>();
|
services.AddSingleton<IDashboardLiveDataService, DashboardLiveDataService>();
|
||||||
services.AddSingleton<IDashboardAuthenticator, DashboardAuthenticator>();
|
services.AddSingleton<IDashboardAuthenticator, DashboardAuthenticator>();
|
||||||
|
services.AddSingleton<IGroupRoleMapper<string>, DashboardGroupRoleMapper>();
|
||||||
services.AddSingleton<DashboardApiKeyAuthorization>();
|
services.AddSingleton<DashboardApiKeyAuthorization>();
|
||||||
services.AddSingleton<IDashboardApiKeyManagementService, DashboardApiKeyManagementService>();
|
services.AddSingleton<IDashboardApiKeyManagementService, DashboardApiKeyManagementService>();
|
||||||
services.AddSingleton<IDashboardSessionAdminService, DashboardSessionAdminService>();
|
services.AddSingleton<IDashboardSessionAdminService, DashboardSessionAdminService>();
|
||||||
@@ -30,6 +49,7 @@ public static class DashboardServiceCollectionExtensions
|
|||||||
services.AddHostedService<Hubs.DashboardSnapshotPublisher>();
|
services.AddHostedService<Hubs.DashboardSnapshotPublisher>();
|
||||||
services.AddHostedService<Hubs.AlarmsHubPublisher>();
|
services.AddHostedService<Hubs.AlarmsHubPublisher>();
|
||||||
services.AddHttpContextAccessor();
|
services.AddHttpContextAccessor();
|
||||||
|
services.AddSingleton<IAuditActorAccessor, HttpAuditActorAccessor>();
|
||||||
services.AddAntiforgery();
|
services.AddAntiforgery();
|
||||||
services.AddCascadingAuthenticationState();
|
services.AddCascadingAuthenticationState();
|
||||||
services.AddRazorComponents()
|
services.AddRazorComponents()
|
||||||
@@ -40,23 +60,25 @@ public static class DashboardServiceCollectionExtensions
|
|||||||
.AddAuthentication(DashboardAuthenticationDefaults.AuthenticationScheme)
|
.AddAuthentication(DashboardAuthenticationDefaults.AuthenticationScheme)
|
||||||
.AddCookie(DashboardAuthenticationDefaults.AuthenticationScheme, cookieOptions =>
|
.AddCookie(DashboardAuthenticationDefaults.AuthenticationScheme, cookieOptions =>
|
||||||
{
|
{
|
||||||
|
// Hardened defaults (HttpOnly, SameSite=Strict, SecurePolicy, SlidingExpiration,
|
||||||
|
// ExpireTimeSpan) via the shared ZbCookieDefaults.Apply. requireHttps is set to
|
||||||
|
// its default (true / Always) here and overridden per-environment by the
|
||||||
|
// PostConfigure below; the 8-hour idle timeout is preserved (not the 30-min default).
|
||||||
|
ZbCookieDefaults.Apply(cookieOptions, requireHttps: true, idleTimeout: TimeSpan.FromHours(8));
|
||||||
|
// Cookie name, path, and redirect paths are MxGateway-specific — set after Apply
|
||||||
|
// so they are never overwritten by the shared helper (Apply intentionally skips name).
|
||||||
cookieOptions.Cookie.Name = DashboardAuthenticationDefaults.CookieName;
|
cookieOptions.Cookie.Name = DashboardAuthenticationDefaults.CookieName;
|
||||||
cookieOptions.Cookie.HttpOnly = true;
|
|
||||||
cookieOptions.Cookie.SameSite = SameSiteMode.Strict;
|
|
||||||
// SecurePolicy is bound via PostConfigure below so it can honour
|
|
||||||
// DashboardOptions.RequireHttpsCookie (default Always; dev HTTP
|
|
||||||
// deployments set RequireHttpsCookie=false to use SameAsRequest).
|
|
||||||
cookieOptions.Cookie.Path = "/";
|
cookieOptions.Cookie.Path = "/";
|
||||||
cookieOptions.LoginPath = "/login";
|
cookieOptions.LoginPath = "/login";
|
||||||
cookieOptions.LogoutPath = "/logout";
|
cookieOptions.LogoutPath = "/logout";
|
||||||
cookieOptions.AccessDeniedPath = "/denied";
|
cookieOptions.AccessDeniedPath = "/denied";
|
||||||
cookieOptions.ExpireTimeSpan = TimeSpan.FromHours(8);
|
|
||||||
cookieOptions.SlidingExpiration = true;
|
|
||||||
})
|
})
|
||||||
.AddScheme<AuthenticationSchemeOptions, HubTokenAuthenticationHandler>(
|
.AddScheme<AuthenticationSchemeOptions, HubTokenAuthenticationHandler>(
|
||||||
DashboardAuthenticationDefaults.HubAuthenticationScheme,
|
DashboardAuthenticationDefaults.HubAuthenticationScheme,
|
||||||
_ => { });
|
_ => { });
|
||||||
|
|
||||||
|
// Honour DashboardOptions.RequireHttpsCookie (default true / Always; set false for dev
|
||||||
|
// HTTP deployments → SameAsRequest). This overrides the Apply default above.
|
||||||
services.AddOptions<CookieAuthenticationOptions>(DashboardAuthenticationDefaults.AuthenticationScheme)
|
services.AddOptions<CookieAuthenticationOptions>(DashboardAuthenticationDefaults.AuthenticationScheme)
|
||||||
.Configure<IOptions<GatewayOptions>>((cookieOptions, gatewayOptions) =>
|
.Configure<IOptions<GatewayOptions>>((cookieOptions, gatewayOptions) =>
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ public sealed record DashboardSessionAdminResult(
|
|||||||
{
|
{
|
||||||
/// <summary>Creates a successful result with the given message.</summary>
|
/// <summary>Creates a successful result with the given message.</summary>
|
||||||
/// <param name="message">The result message.</param>
|
/// <param name="message">The result message.</param>
|
||||||
|
/// <returns>A <see cref="DashboardSessionAdminResult"/> with <c>Succeeded</c> set to <c>true</c>.</returns>
|
||||||
public static DashboardSessionAdminResult Success(string message)
|
public static DashboardSessionAdminResult Success(string message)
|
||||||
{
|
{
|
||||||
return new DashboardSessionAdminResult(true, message);
|
return new DashboardSessionAdminResult(true, message);
|
||||||
@@ -13,6 +14,7 @@ public sealed record DashboardSessionAdminResult(
|
|||||||
|
|
||||||
/// <summary>Creates a failed result with the given message.</summary>
|
/// <summary>Creates a failed result with the given message.</summary>
|
||||||
/// <param name="message">The result message.</param>
|
/// <param name="message">The result message.</param>
|
||||||
|
/// <returns>A <see cref="DashboardSessionAdminResult"/> with <c>Succeeded</c> set to <c>false</c>.</returns>
|
||||||
public static DashboardSessionAdminResult Fail(string message)
|
public static DashboardSessionAdminResult Fail(string message)
|
||||||
{
|
{
|
||||||
return new DashboardSessionAdminResult(false, message);
|
return new DashboardSessionAdminResult(false, message);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ using System.Runtime.CompilerServices;
|
|||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Logging.Abstractions;
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Galaxy;
|
using ZB.MOM.WW.MxGateway.Server.Galaxy;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Metrics;
|
using ZB.MOM.WW.MxGateway.Server.Metrics;
|
||||||
@@ -64,10 +65,7 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
|
|||||||
_logger = logger ?? NullLogger<DashboardSnapshotService>.Instance;
|
_logger = logger ?? NullLogger<DashboardSnapshotService>.Instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Gets a current dashboard snapshot of gateway state.
|
|
||||||
/// </summary>
|
|
||||||
/// <returns>Dashboard snapshot.</returns>
|
|
||||||
public DashboardSnapshot GetSnapshot()
|
public DashboardSnapshot GetSnapshot()
|
||||||
{
|
{
|
||||||
DateTimeOffset generatedAt = _timeProvider.GetUtcNow();
|
DateTimeOffset generatedAt = _timeProvider.GetUtcNow();
|
||||||
@@ -99,11 +97,7 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
|
|||||||
Galaxy: DashboardGalaxyProjector.Project(_galaxyHierarchyCache.Current));
|
Galaxy: DashboardGalaxyProjector.Project(_galaxyHierarchyCache.Current));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <inheritdoc />
|
||||||
/// Watches dashboard snapshots at regular intervals asynchronously.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="cancellationToken">Cancellation token.</param>
|
|
||||||
/// <returns>Async enumerable of dashboard snapshots.</returns>
|
|
||||||
public async IAsyncEnumerable<DashboardSnapshot> WatchSnapshotsAsync(
|
public async IAsyncEnumerable<DashboardSnapshot> WatchSnapshotsAsync(
|
||||||
[EnumeratorCancellation] CancellationToken cancellationToken)
|
[EnumeratorCancellation] CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
@@ -242,7 +236,7 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
|
|||||||
KeyId: key.KeyId,
|
KeyId: key.KeyId,
|
||||||
DisplayName: key.DisplayName,
|
DisplayName: key.DisplayName,
|
||||||
Scopes: key.Scopes,
|
Scopes: key.Scopes,
|
||||||
Constraints: key.Constraints,
|
Constraints: ApiKeyConstraintSerializer.Deserialize(key.ConstraintsJson),
|
||||||
CreatedUtc: key.CreatedUtc,
|
CreatedUtc: key.CreatedUtc,
|
||||||
LastUsedUtc: key.LastUsedUtc,
|
LastUsedUtc: key.LastUsedUtc,
|
||||||
RevokedUtc: key.RevokedUtc))
|
RevokedUtc: key.RevokedUtc))
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user