using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Acls;
/// EF-backed .
///
/// The two trees are projected from the services that already own them —
/// for the raw side (keeping its lazy expansion) and
/// for the UNS side (which loads whole) — so the picker cannot show a
/// hierarchy that disagrees with /raw or /uns. Only and the
/// principal lookups go to the database directly.
///
public sealed class AclScopeService : IAclScopeService
{
private readonly IDbContextFactory _dbFactory;
private readonly IRawTreeService _raw;
private readonly IUnsTreeService _uns;
private readonly TimeProvider _time;
/// Initializes a new instance of the class.
/// The config DB context factory.
/// The raw project-tree service.
/// The UNS tree service.
/// Clock used to decide whether a key has already expired.
public AclScopeService(
IDbContextFactory dbFactory,
IRawTreeService raw,
IUnsTreeService uns,
TimeProvider? time = null)
{
_dbFactory = dbFactory;
_raw = raw;
_uns = uns;
_time = time ?? TimeProvider.System;
}
///
public async Task LoadRootsAsync(string clusterId, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(clusterId);
// Both services root their trees at Enterprise → Cluster, but searching the roots as well as their
// children keeps this working if a cluster ever surfaces at the top level.
var rawRoots = await _raw.LoadRootsAsync(ct).ConfigureAwait(false);
var rawCluster = rawRoots
.Concat(rawRoots.SelectMany(r => r.Children))
.FirstOrDefault(n => n.Kind == RawNodeKind.Cluster
&& string.Equals(n.EntityId, clusterId, StringComparison.Ordinal));
var unsRoots = await _uns.LoadStructureAsync(ct).ConfigureAwait(false);
var unsCluster = unsRoots
.Concat(unsRoots.SelectMany(r => r.Children))
.FirstOrDefault(n => n.Kind == UnsNodeKind.Cluster
&& string.Equals(n.EntityId, clusterId, StringComparison.Ordinal));
var raw = rawCluster is null
? Array.Empty()
: new[] { ProjectRaw(rawCluster, parentPath: null) };
var uns = unsCluster is null
? Array.Empty()
: ProjectUnsChildren(unsCluster, parentPath: null);
return new AclScopeRoots(raw, uns);
}
///
public async Task> LoadChildrenAsync(
AclScopeNode parent, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(parent);
if (parent.RawSource is null) return Array.Empty();
var children = await _raw.LoadChildrenAsync(parent.RawSource, ct).ConfigureAwait(false);
return children.Select(c => ProjectRaw(c, parent.PathLabel)).ToList();
}
///
public async Task CheckScopeAsync(
string clusterId, NodeAclScopeKind kind, string? scopeId, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(clusterId);
// Mirrors DraftValidator.ValidateNodeAclScopes, in its order, so the page and the deploy gate
// cannot disagree about which rows are authorable. The messages are shorter because the operator
// is looking at the field; the rules are the same.
if (!Enum.IsDefined(kind))
return new AclScopeCheck(false,
$"Scope kind ordinal {(int)kind} is not a defined kind — re-pick the scope.");
if (kind == NodeAclScopeKind.Cluster)
return string.IsNullOrWhiteSpace(scopeId)
? new AclScopeCheck(true, $"The whole of cluster '{clusterId}', in both namespaces.")
: new AclScopeCheck(false,
"A Cluster grant covers the whole cluster and ignores the scope target — clear the " +
"target, or pick the level the id names. Leaving both would grant more than intended.");
if (kind == NodeAclScopeKind.FolderSegment)
return new AclScopeCheck(false,
"FolderSegment is a retired v2 kind with no v3 entity behind it; it can never resolve, " +
"whatever its target. Re-scope to RawFolder.");
if (string.IsNullOrWhiteSpace(scopeId))
return new AclScopeCheck(false,
$"{kind} needs a scope target. Only a Cluster grant may omit one; without it the grant " +
"resolves to no node and is dropped when the configuration is built.");
var id = scopeId.Trim();
if (kind == NodeAclScopeKind.Namespace)
{
var realm = NodeAclRealms.TryCanonicalize(id);
return realm is null
? new AclScopeCheck(false,
$"'{id}' names no OPC UA namespace. Use '{NodeAclRealms.Raw}' or '{NodeAclRealms.Uns}'.")
: new AclScopeCheck(true,
realm == NodeAclRealms.Raw
? $"Every raw node in cluster '{clusterId}'."
: $"Every UNS node in cluster '{clusterId}'.");
}
await using var db = await _dbFactory.CreateDbContextAsync(ct).ConfigureAwait(false);
// Each arm names the entity type the kind's ScopeId is drawn from, and walks to the cluster that
// owns it. Switch arms evaluate lazily, so only the matched kind's query runs. No AsNoTracking:
// every arm projects into Found, and EF tracks nothing it does not materialise as an entity.
var (entity, owner, name) = kind switch
{
NodeAclScopeKind.RawFolder => await ResolveAsync(
"raw folder",
db.RawFolders.Where(f => f.RawFolderId == id).Select(f => new Found(f.ClusterId, f.Name)),
ct).ConfigureAwait(false),
NodeAclScopeKind.RawDriver => await ResolveAsync(
"driver",
db.DriverInstances.Where(d => d.DriverInstanceId == id).Select(d => new Found(d.ClusterId, d.Name)),
ct).ConfigureAwait(false),
NodeAclScopeKind.RawDevice => await ResolveAsync(
"device",
from d in db.Devices
where d.DeviceId == id
join dr in db.DriverInstances on d.DriverInstanceId equals dr.DriverInstanceId
select new Found(dr.ClusterId, d.Name),
ct).ConfigureAwait(false),
NodeAclScopeKind.RawTagGroup => await ResolveAsync(
"tag group",
from g in db.TagGroups
where g.TagGroupId == id
join dev in db.Devices on g.DeviceId equals dev.DeviceId
join dr in db.DriverInstances on dev.DriverInstanceId equals dr.DriverInstanceId
select new Found(dr.ClusterId, g.Name),
ct).ConfigureAwait(false),
NodeAclScopeKind.Tag => await ResolveAsync(
"raw tag",
from t in db.Tags
where t.TagId == id
join dev in db.Devices on t.DeviceId equals dev.DeviceId
join dr in db.DriverInstances on dev.DriverInstanceId equals dr.DriverInstanceId
select new Found(dr.ClusterId, t.Name),
ct).ConfigureAwait(false),
NodeAclScopeKind.UnsArea => await ResolveAsync(
"UNS area",
db.UnsAreas.Where(a => a.UnsAreaId == id).Select(a => new Found(a.ClusterId, a.Name)),
ct).ConfigureAwait(false),
NodeAclScopeKind.UnsLine => await ResolveAsync(
"UNS line",
from l in db.UnsLines
where l.UnsLineId == id
join a in db.UnsAreas on l.UnsAreaId equals a.UnsAreaId
select new Found(a.ClusterId, l.Name),
ct).ConfigureAwait(false),
NodeAclScopeKind.Equipment => await ResolveAsync(
"equipment",
from e in db.Equipment
where e.EquipmentId == id
join l in db.UnsLines on e.UnsLineId equals l.UnsLineId
join a in db.UnsAreas on l.UnsAreaId equals a.UnsAreaId
select new Found(a.ClusterId, e.Name),
ct).ConfigureAwait(false),
// Cluster / Namespace / FolderSegment all returned above, and an undefined ordinal did too.
_ => ("scope", null, null),
};
if (owner is null)
return new AclScopeCheck(false,
$"No {entity} in this configuration has the id '{id}' — or its parent chain is broken, so " +
"no cluster owns it. The grant would be dropped when the configuration is built and would " +
"authorize nothing.");
if (!string.Equals(owner, clusterId, StringComparison.OrdinalIgnoreCase))
return new AclScopeCheck(false,
$"That {entity} belongs to cluster '{owner}', but this grant is in cluster '{clusterId}'. " +
"The id is real, so the grant would confer authority across a cluster boundary. Author it " +
$"under '{owner}' instead.");
return new AclScopeCheck(true,
$"{char.ToUpperInvariant(entity[0])}{entity[1..]} '{name}' in cluster '{clusterId}'.");
}
///
public async Task> LoadKnownPrincipalsAsync(CancellationToken ct = default)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct).ConfigureAwait(false);
var fromKeys = await db.ApiKeys.AsNoTracking().Select(k => k.Principal).Distinct()
.ToListAsync(ct).ConfigureAwait(false);
var fromAcls = await db.NodeAcls.AsNoTracking().Select(a => a.Principal).Distinct()
.ToListAsync(ct).ConfigureAwait(false);
return fromKeys
.Concat(fromAcls)
.Append(OpcUaPrincipals.Anonymous)
.Where(p => !string.IsNullOrWhiteSpace(p))
.Select(p => p.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
.ToList();
}
///
public async Task CheckPrincipalAsync(string principal, CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(principal)) return new PrincipalUsage(false, 0, 0);
var name = principal.Trim();
if (string.Equals(name, OpcUaPrincipals.Anonymous, StringComparison.OrdinalIgnoreCase))
return new PrincipalUsage(true, 0, 0);
await using var db = await _dbFactory.CreateDbContextAsync(ct).ConfigureAwait(false);
var keys = await db.ApiKeys.AsNoTracking()
.Where(k => k.Principal == name)
.Select(k => new { k.Enabled, k.ExpiresUtc })
.ToListAsync(ct).ConfigureAwait(false);
var now = _time.GetUtcNow().UtcDateTime;
var live = keys.Count(k => k.Enabled && (k.ExpiresUtc is null || k.ExpiresUtc > now));
return new PrincipalUsage(false, live, keys.Count - live);
}
// --- Projection --------------------------------------------------------------------------------
private static AclScopeNode ProjectRaw(RawNode node, string? parentPath)
{
var kind = RawScopeKind(node.Kind);
var path = Join(parentPath, node.DisplayName);
var projected = new AclScopeNode
{
Key = node.Key,
DisplayName = node.DisplayName,
Icon = RawIcon(node.Kind),
ScopeKind = kind,
// A Cluster grant covers its whole cluster and carries no id — the deploy gate rejects one
// that does, so the picker must not produce one.
ScopeId = kind == NodeAclScopeKind.Cluster ? null : node.EntityId,
PathLabel = path,
HasLazyChildren = node.HasLazyChildren,
RawSource = node,
};
foreach (var child in node.Children) projected.Children.Add(ProjectRaw(child, path));
return projected;
}
private static IReadOnlyList ProjectUnsChildren(UnsNode cluster, string? parentPath) =>
cluster.Children.Select(c => ProjectUns(c, parentPath)).ToList();
private static AclScopeNode ProjectUns(UnsNode node, string? parentPath)
{
var path = Join(parentPath, node.DisplayName);
var projected = new AclScopeNode
{
Key = node.Key,
DisplayName = node.DisplayName,
Icon = UnsIcon(node.Kind),
ScopeKind = UnsScopeKind(node.Kind),
ScopeId = node.EntityId,
PathLabel = path,
HasLazyChildren = false,
// Everything below the cluster is already materialised — nothing to expand lazily, and no raw
// node to expand it from.
RawSource = null,
Expanded = true,
};
foreach (var child in node.Children) projected.Children.Add(ProjectUns(child, path));
return projected;
}
private static string Join(string? parent, string name) =>
string.IsNullOrEmpty(parent) ? name : $"{parent} / {name}";
private static NodeAclScopeKind? RawScopeKind(RawNodeKind kind) => kind switch
{
RawNodeKind.Cluster => NodeAclScopeKind.Cluster,
RawNodeKind.Folder => NodeAclScopeKind.RawFolder,
RawNodeKind.Driver => NodeAclScopeKind.RawDriver,
RawNodeKind.Device => NodeAclScopeKind.RawDevice,
RawNodeKind.TagGroup => NodeAclScopeKind.RawTagGroup,
RawNodeKind.Tag => NodeAclScopeKind.Tag,
_ => null, // Enterprise: a label, not a scope.
};
// Area/Line/Equipment only. A UNS tag row is a UnsTagReference, not a Tag — its scope is the RAW tag it
// points at, and a Tag grant already covers the raw node AND every UNS projection of it (see
// AclScopePathResolver). Offering a UNS tag here would produce a grant that reads as narrower than the
// one it actually creates.
private static NodeAclScopeKind? UnsScopeKind(UnsNodeKind kind) => kind switch
{
UnsNodeKind.Area => NodeAclScopeKind.UnsArea,
UnsNodeKind.Line => NodeAclScopeKind.UnsLine,
UnsNodeKind.Equipment => NodeAclScopeKind.Equipment,
_ => null,
};
private static string RawIcon(RawNodeKind kind) => kind switch
{
RawNodeKind.Enterprise => "🏢",
RawNodeKind.Cluster => "🖥️",
RawNodeKind.Folder => "📁",
RawNodeKind.Driver => "🔌",
RawNodeKind.Device => "📟",
RawNodeKind.TagGroup => "🗂️",
RawNodeKind.Tag => "🏷️",
_ => "•",
};
private static string UnsIcon(UnsNodeKind kind) => kind switch
{
UnsNodeKind.Area => "🗺️",
UnsNodeKind.Line => "🏭",
UnsNodeKind.Equipment => "⚙️",
_ => "•",
};
// --- Resolution helpers ------------------------------------------------------------------------
// A class, not a struct: FirstOrDefaultAsync over a struct yields default(T), which is indistinguishable
// from a real row whose fields happen to be empty — a null reference cannot be misread that way.
private sealed record Found(string ClusterId, string Name);
private static async Task<(string Entity, string? Owner, string? Name)> ResolveAsync(
string entity, IQueryable query, CancellationToken ct)
{
// FirstOrDefault, not Single: a duplicated id is a different rule's business, and throwing here
// would replace a precise message with an exception page.
var hit = await query.FirstOrDefaultAsync(ct).ConfigureAwait(false);
return hit is null ? (entity, null, null) : (entity, hit.ClusterId, hit.Name);
}
}