Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataIngressAuthTests.cs
T

52 lines
2.8 KiB
C#

using Microsoft.Extensions.Options;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
using ZB.MOM.WW.OtOpcUa.Host.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
public sealed class GrpcDataIngressAuthTests
{
[Fact]
public void Authentication_uses_the_current_snapshot_and_original_key_material()
{
var (bearer, id, hash) = ApiKeySecret.Generate("pepper");
var authority = new DataPlaneAuthorityState();
var key = new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true };
authority.Apply("cluster", "v1", [key], [], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
var auth = new DataConnectionAuthenticator(authority,
Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System);
var context = auth.Authenticate(bearer);
context.PrincipalId.ShouldBe("peer");
context.ApiKeyId.ShouldBe(id);
context.CredentialVersion.ShouldBe(DataCallerIdentity.CredentialVersionFor(key));
auth.IsCurrent(context).ShouldBeTrue();
authority.Apply("cluster", "v2", [], [], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
auth.IsCurrent(context).ShouldBeFalse();
Should.Throw<UnauthorizedAccessException>(() => auth.Authenticate(bearer));
}
[Fact]
public void Missing_pepper_missing_authority_and_forged_or_expired_keys_deny()
{
var (bearer, id, hash) = ApiKeySecret.Generate("pepper");
var authority = new DataPlaneAuthorityState();
var auth = new DataConnectionAuthenticator(authority,
Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System);
Should.Throw<UnauthorizedAccessException>(() => auth.Authenticate(bearer));
var expired = new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash,
Enabled = true, ExpiresUtc = DateTime.UtcNow.AddMinutes(-1) };
authority.Apply("cluster", "v1", [expired], [], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
Should.Throw<UnauthorizedAccessException>(() => auth.Authenticate(bearer));
expired.ExpiresUtc = null;
authority.Apply("cluster", "v2", [expired], [], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
Should.Throw<UnauthorizedAccessException>(() => auth.Authenticate("not-a-key"));
Should.Throw<UnauthorizedAccessException>(() => new DataConnectionAuthenticator(authority,
Options.Create(new ApiKeyOptions()), TimeProvider.System).Authenticate(bearer));
}
}