using System.Collections.Concurrent; using Akka.Actor; using Microsoft.EntityFrameworkCore; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; using ZB.MOM.WW.OtOpcUa.Commons.Types; using ZB.MOM.WW.OtOpcUa.Configuration; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; using ZB.MOM.WW.OtOpcUa.Configuration.Validation; using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Scripting; namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests; /// /// lmxopcua#971 follow-up — the deploy-time script compile gate, exercised THROUGH the actor with the real Roslyn /// checker (and a recording fake where the test is about what is sent). A script the runtime would refuse blocks /// the deploy in Error mode (the default) and rides the accepted message in Warn mode; a legitimate draft deploys /// clean (the positive control every reject test leans on); each seam compiles as itself; {{equip}} is resolved /// before compiling; an absent checker or mode Off skips the gate. /// public sealed class AdminOperationsActorScriptCompileGateTests : ControlPlaneActorTestBase { private const string Legit = "var v = ctx.GetTag(\"{{equip}}/speed\").Value; return v is null ? 0.0 : Convert.ToDouble(v) * 2;"; // Reads a tag so the draft is otherwise valid (a VirtualTag with no input never triggers — a DraftValidator error). private const string Forbidden = "var v = ctx.GetTag(\"{{equip}}/speed\").Value; return v is null ? null : System.IO.File.ReadAllText(\"/etc/passwd\");"; private const string LegitPredicate = "return Convert.ToDouble(ctx.GetTag(\"{{equip}}/speed\").Value ?? 0.0) > 5;"; private const string LegitCalc = "return Convert.ToDouble(ctx.GetTag(\"plant/drv/dev/speed\").Value ?? 0.0) + 1;"; private const string CleanModbus = "{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Int16\"}"; private sealed record Seed( string VtSource = Legit, string PredicateSource = LegitPredicate, string CalcSource = LegitCalc, bool VtEnabled = true, bool AlarmEnabled = true, int Equipments = 1, bool SharedVtScript = true, string DeviceName = "dev"); /// A complete, DraftValidator-clean draft: area/line/equipment(s), a Modbus tag referenced into each /// equipment as speed, a VirtualTag + scripted alarm per equipment, and one Calculation tag. private static IDbContextFactory SeedDraft(Seed seed) { var dbFactory = NewInMemoryDbFactory(); using var db = dbFactory.CreateDbContext(); db.RawFolders.Add(new RawFolder { RawFolderId = "rf-plant", ClusterId = "", Name = "plant" }); db.DriverInstances.Add(new DriverInstance { DriverInstanceId = "d-1", ClusterId = "", RawFolderId = "rf-plant", Name = "drv", DriverType = "Modbus", DriverConfig = "{}", }); db.Devices.Add(new Device { DeviceId = "dev-1", DriverInstanceId = "d-1", Name = seed.DeviceName, DeviceConfig = "{}" }); db.Tags.Add(new Tag { TagId = "tag-speed", DeviceId = "dev-1", Name = "speed", DataType = "Int16", AccessLevel = TagAccessLevel.Read, TagConfig = CleanModbus, }); db.DriverInstances.Add(new DriverInstance { DriverInstanceId = "d-calc", ClusterId = "", RawFolderId = "rf-plant", Name = "calc", DriverType = DriverTypeNames.Calculation, DriverConfig = "{}", }); db.Devices.Add(new Device { DeviceId = "dev-calc", DriverInstanceId = "d-calc", Name = "cdev", DeviceConfig = "{}" }); db.Tags.Add(new Tag { TagId = "tag-calc", DeviceId = "dev-calc", Name = "sum", DataType = "Double", AccessLevel = TagAccessLevel.Read, TagConfig = "{\"scriptId\":\"s-calc\"}", }); db.UnsAreas.Add(new UnsArea { UnsAreaId = "area-1", ClusterId = "", Name = "area" }); db.UnsLines.Add(new UnsLine { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "line" }); db.Scripts.Add(new Script { ScriptId = "s-pred", Name = "pred", SourceCode = seed.PredicateSource, SourceHash = "h-pred" }); db.Scripts.Add(new Script { ScriptId = "s-calc", Name = "calc", SourceCode = seed.CalcSource, SourceHash = "h-calc" }); for (var i = 1; i <= seed.Equipments; i++) { var uuid = Guid.NewGuid(); var equipmentId = DraftValidator.DeriveEquipmentId(uuid); db.Equipment.Add(new Equipment { EquipmentUuid = uuid, EquipmentId = equipmentId, Name = $"eq{i}", UnsLineId = "line-1", MachineCode = $"m{i}", }); db.UnsTagReferences.Add(new UnsTagReference { UnsTagReferenceId = $"ref-{i}", EquipmentId = equipmentId, TagId = "tag-speed" }); var vtScriptId = seed.SharedVtScript ? "s-vt" : $"s-vt-{i}"; if (!seed.SharedVtScript || i == 1) db.Scripts.Add(new Script { ScriptId = vtScriptId, Name = vtScriptId, SourceCode = seed.VtSource, SourceHash = "h-" + vtScriptId }); db.VirtualTags.Add(new VirtualTag { VirtualTagId = $"vt-{i}", EquipmentId = equipmentId, Name = "doubled", DataType = "Double", ScriptId = vtScriptId, Enabled = seed.VtEnabled, }); db.ScriptedAlarms.Add(new ScriptedAlarm { ScriptedAlarmId = $"al-{i}", EquipmentId = equipmentId, Name = "high", AlarmType = "LimitAlarm", MessageTemplate = "speed high", PredicateScriptId = "s-pred", Enabled = seed.AlarmEnabled, }); } db.SaveChanges(); return dbFactory; } private StartDeploymentResult Deploy( IDbContextFactory dbFactory, IDeployScriptChecker? checker, ScriptCompileGateMode mode = ScriptCompileGateMode.Error, bool expectDispatch = true) { var coordinator = CreateTestProbe(); var actor = Sys.ActorOf(AdminOperationsActor.Props( dbFactory, coordinator.Ref, Enumerable.Empty(), scriptChecker: checker, scriptCompileGateMode: mode)); actor.Tell(new StartDeployment("joe", CorrelationId.NewId())); if (expectDispatch) coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); else coordinator.ExpectNoMsg(TimeSpan.FromMilliseconds(300), TestContext.Current.CancellationToken); return ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); } /// Records every request and answers from a rule; optionally throws. private sealed class RecordingChecker(Func>? rule = null, bool @throw = false) : IDeployScriptChecker { public ConcurrentQueue Requests { get; } = new(); public ConcurrentQueue> Calls { get; } = new(); public IReadOnlyList Check(IReadOnlyList requests, CancellationToken cancellationToken = default) { Calls.Enqueue(requests.ToList()); foreach (var r in requests) Requests.Enqueue(r); if (@throw) throw new InvalidOperationException("checker exploded"); return requests.Select(r => new DeployScriptCheckResult(r, rule?.Invoke(r) ?? [])).ToList(); } } [Fact] public void A_legitimate_draft_deploys_clean_positive_control() { var checker = new RoslynDeployScriptChecker(); var reply = Deploy(SeedDraft(new Seed()), checker); reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); (reply.Message ?? string.Empty).ShouldNotContain("does not compile"); checker.CompilesPerformed.ShouldBeGreaterThan(0); // the gate really ran } [Fact] public void A_forbidden_api_blocks_the_deploy_in_error_mode_naming_the_script_and_its_users() { var dbFactory = SeedDraft(new Seed(VtSource: Forbidden, Equipments: 2)); var reply = Deploy(dbFactory, new RoslynDeployScriptChecker(), expectDispatch: false); reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected); reply.Message.ShouldNotBeNull(); reply.Message.ShouldContain(DeployScriptGate.ErrorCode); reply.Message.ShouldContain("script 's-vt'"); reply.Message.ShouldContain("VirtualTag 'vt-1'"); reply.Message.ShouldContain("VirtualTag 'vt-2'"); // one finding, both users reply.Message.ShouldContain("sandbox violation"); using var verify = dbFactory.CreateDbContext(); verify.Deployments.Count().ShouldBe(0); } [Fact] public void Error_is_the_default_mode() { var dbFactory = SeedDraft(new Seed(VtSource: Forbidden)); var coordinator = CreateTestProbe(); var actor = Sys.ActorOf(AdminOperationsActor.Props( dbFactory, coordinator.Ref, Enumerable.Empty(), scriptChecker: new RoslynDeployScriptChecker())); actor.Tell(new StartDeployment("joe", CorrelationId.NewId())); ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) .Outcome.ShouldBe(StartDeploymentOutcome.Rejected); ServiceCollectionExtensions.ParseScriptCompileGateMode(null).ShouldBe(ScriptCompileGateMode.Error); ServiceCollectionExtensions.ParseScriptCompileGateMode("Warning").ShouldBe(ScriptCompileGateMode.Error); ServiceCollectionExtensions.ParseScriptCompileGateMode("7").ShouldBe(ScriptCompileGateMode.Error); ServiceCollectionExtensions.ParseScriptCompileGateMode("warn").ShouldBe(ScriptCompileGateMode.Warn); ServiceCollectionExtensions.ParseScriptCompileGateMode(" Off ").ShouldBe(ScriptCompileGateMode.Off); } [Fact] public void Warn_mode_accepts_and_surfaces_the_finding_in_the_message() { var reply = Deploy(SeedDraft(new Seed(VtSource: Forbidden)), new RoslynDeployScriptChecker(), ScriptCompileGateMode.Warn); reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted); reply.Message.ShouldNotBeNull(); reply.Message.ShouldContain("script 's-vt'"); reply.Message.ShouldContain("sandbox violation"); } [Fact] public void Each_seam_compiles_as_itself_a_value_script_used_as_a_predicate_is_refused() { // `return 1.5;` is a fine VirtualTag / Calculation body and a non-bool predicate. const string returnsDouble = "return 1.5;"; var reply = Deploy(SeedDraft(new Seed(VtSource: returnsDouble, PredicateSource: returnsDouble, CalcSource: returnsDouble)), new RoslynDeployScriptChecker(), expectDispatch: false); reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected); reply.Message.ShouldNotBeNull(); reply.Message.ShouldContain("script 's-pred' does not compile as a scripted-alarm predicate"); reply.Message.ShouldContain("ScriptedAlarm 'al-1'"); reply.Message.ShouldNotContain("script 's-vt'"); reply.Message.ShouldNotContain("script 's-calc'"); } [Fact] public void A_forbidden_calculation_script_names_the_calculation_tag() { var reply = Deploy(SeedDraft(new Seed(CalcSource: Forbidden)), new RoslynDeployScriptChecker(), expectDispatch: false); reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected); reply.Message.ShouldNotBeNull(); reply.Message.ShouldContain("script 's-calc' does not compile as a Calculation script"); reply.Message.ShouldContain("Calculation tag 'tag-calc' (plant/calc/cdev/sum)"); } [Fact] public void Disabled_users_are_not_checked_they_never_compile_at_runtime() { var reply = Deploy(SeedDraft(new Seed(VtSource: Forbidden, PredicateSource: Forbidden, VtEnabled: false, AlarmEnabled: false)), new RoslynDeployScriptChecker()); reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); } [Fact] public void An_absent_checker_skips_the_gate() { var reply = Deploy(SeedDraft(new Seed(VtSource: Forbidden)), checker: null); reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); } [Fact] public void Mode_off_skips_the_gate_and_never_calls_the_checker() { var checker = new RecordingChecker(_ => ["compile error: nope"]); var reply = Deploy(SeedDraft(new Seed()), checker, ScriptCompileGateMode.Off); reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); checker.Requests.ShouldBeEmpty(); } [Fact] public void Equip_tokens_resolve_before_compiling_and_a_template_is_sent_once_for_every_equipment() { // Three equipments share one VT template: substitution only rewrites literal text (escaped), so the gate // sends the template once per seam rather than three resolved copies. var checker = new RecordingChecker(); var reply = Deploy(SeedDraft(new Seed(Equipments: 3)), checker); reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); // Two passes: the warm-up outside the transaction, then the authoritative in-snapshot pass. checker.Calls.Count.ShouldBe(2); var inSnapshotPass = checker.Calls.Last(); // One request per (seam, source): the shared template once — no per-equipment resolved copies. inSnapshotPass.Count.ShouldBe(3); inSnapshotPass.ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit)); inSnapshotPass.ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.AlarmPredicate, LegitPredicate)); inSnapshotPass.ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.Calculation, LegitCalc)); // The warm-up asked for the same template, so the in-snapshot pass is a cache hit on a real checker. checker.Calls.First().ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit)); } [Fact] public async Task Collected_uses_resolve_equip_exactly_as_the_compose_seams_do() { // The draft-side collection on its own: the substitution the gate reasons about is the compose seams' one. var dbFactory = SeedDraft(new Seed(Equipments: 1)); using var db = dbFactory.CreateDbContext(); var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, TestContext.Current.CancellationToken); var uses = DeployScriptGate.CollectUses(draft); var vt = uses.Single(u => u.Kind == ScriptContextKind.VirtualTag); vt.CompileSource.ShouldBe(Legit); // equivalent template sent… EquipmentScriptPaths.SubstituteEquipmentToken(Legit, new Dictionary { ["speed"] = "plant/drv/dev/speed" }) .ShouldContain("ctx.GetTag(\"plant/drv/dev/speed\")"); // …for what the seams will run uses.Single(u => u.Kind == ScriptContextKind.AlarmPredicate).UsedBy.ShouldContain("ScriptedAlarm 'al-1'"); uses.Single(u => u.Kind == ScriptContextKind.Calculation).UsedBy.ShouldContain("Calculation tag 'tag-calc'"); } /// /// A RawPath segment may legally contain a backslash or a quote, and substitution pastes the RawPath into a C# /// string literal. Substitution ESCAPES the paste (EquipmentScriptPaths.EscapeForRegularLiteral), so /// {{equip}}/speed over a device named de\qv still compiles and still reads the exact RawPath /// (EquipTokenLiteralEscapingTests in Runtime.Tests runs it end to end). It used to paste raw — an /// invalid escape the runtime refused to compile, which only compiling the resolved source caught. Now the /// substitution is provably compile-neutral, so the gate compiles the shared template once and the real /// compiler accepts the draft; the resolved source itself is also compiled to prove it. /// [Theory] [InlineData(@"de\qv")] [InlineData("a\"b")] [InlineData(@"x\vy")] public void An_equip_substitution_over_a_RawPath_with_escape_characters_compiles_and_is_sent_once(string deviceName) { var checker = new RoslynDeployScriptChecker(); var reply = Deploy(SeedDraft(new Seed(DeviceName: deviceName, Equipments: 2)), checker); reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); (reply.Message ?? string.Empty).ShouldNotContain("does not compile"); // The resolved source (what the seams will run) compiles too — the gate's dedupe is not hiding a failure. var map = new Dictionary(StringComparer.Ordinal) { ["speed"] = $"plant/drv/{deviceName}/speed" }; EquipmentScriptPaths.SubstitutionPreservesCompilation(Legit, map).ShouldBeTrue(); var resolved = EquipmentScriptPaths.SubstituteEquipmentToken(Legit, map); resolved.ShouldNotBe(Legit); var verdict = new RoslynDeployScriptChecker() .Check([new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, resolved)], TestContext.Current.CancellationToken).Single(); verdict.Problems.ShouldBeEmpty(); } [Fact] public void The_cache_makes_a_redeploy_compile_nothing() { var checker = new RoslynDeployScriptChecker(); var dbFactory = SeedDraft(new Seed(Equipments: 2)); Deploy(dbFactory, checker).Outcome.ShouldBe(StartDeploymentOutcome.Accepted); var afterFirst = checker.CompilesPerformed; afterFirst.ShouldBeGreaterThan(0); // Close the first deployment so the next one is not refused as in-flight. using (var db = dbFactory.CreateDbContext()) { foreach (var d in db.Deployments) d.Status = DeploymentStatus.Sealed; db.SaveChanges(); } Deploy(dbFactory, checker).Outcome.ShouldBe(StartDeploymentOutcome.Accepted); checker.CompilesPerformed.ShouldBe(afterFirst); } [Fact] public void An_internal_checker_failure_never_blocks_the_deploy() { var reply = Deploy(SeedDraft(new Seed()), new RecordingChecker(@throw: true)); reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted); reply.Message.ShouldNotBeNull(); reply.Message.ShouldContain("script compile gate skipped"); } }