6e912bb070
The deploy gate never compiled scripts, so a stored script the #971 allow-list now refuses only failed after the deploy (VirtualTag/Calculation Bad "sandbox violation", scripted-alarm load failing for every alarm on the node). - Core.Scripting.Abstractions: IDeployScriptChecker (Roslyn-free) + request/result records; ScriptContextKind moved here (same namespace). - Core.Scripting: ScriptEvaluator.Verify shares a private BuildCheckedCompilation factory with CompileToImage (wrap, injection guard, sandbox compile, ForbiddenTypeAnalyzer; no stack-guard rewrite, no emit). RoslynDeployScriptChecker checks per seam (VT/Calc as VirtualTagContext->object?, passthrough/blank skipped; predicates DependencyExtractor first then AlarmPredicateContext->bool), caches by (compile identity, SHA-256), parallel, bounded. - ControlPlane: DeployScriptGate collects enabled VTs / enabled alarm predicates / Calculation tags, resolves {{equip}} through EquipmentReferenceMap exactly as the compose seams do (template compiled once when SubstitutionPreservesCompilation, else the resolved source), groups findings per script naming its users. AdminOperationsActor warms the cache before the snapshot transaction and runs the authoritative pass on the same snapshot; Deployment:ScriptCompileGateMode = Error (default) | Warn | Off; an absent checker or an internal failure never blocks. - Host binds RoslynDeployScriptChecker on admin nodes. - Docs: VirtualTags.md (gate + upgrade note), ScriptEditor.md, security.md, CLAUDE.md. Found while testing: {{equip}} substitution pastes RawPaths into C# literals unescaped, so a segment containing \ or " breaks (or silently alters) the script; the gate now reports it at deploy.
322 lines
17 KiB
C#
322 lines
17 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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");
|
|
|
|
/// <summary>A complete, DraftValidator-clean draft: area/line/equipment(s), a Modbus tag referenced into each
|
|
/// equipment as <c>speed</c>, a VirtualTag + scripted alarm per equipment, and one Calculation tag.</summary>
|
|
private static IDbContextFactory<OtOpcUaConfigDbContext> 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<OtOpcUaConfigDbContext> dbFactory, IDeployScriptChecker? checker,
|
|
ScriptCompileGateMode mode = ScriptCompileGateMode.Error, bool expectDispatch = true)
|
|
{
|
|
var coordinator = CreateTestProbe();
|
|
var actor = Sys.ActorOf(AdminOperationsActor.Props(
|
|
dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>(),
|
|
scriptChecker: checker, scriptCompileGateMode: mode));
|
|
actor.Tell(new StartDeployment("joe", CorrelationId.NewId()));
|
|
if (expectDispatch) coordinator.ExpectMsg<DispatchDeployment>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
else coordinator.ExpectNoMsg(TimeSpan.FromMilliseconds(300), TestContext.Current.CancellationToken);
|
|
return ExpectMsg<StartDeploymentResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
}
|
|
|
|
/// <summary>Records every request and answers from a rule; optionally throws.</summary>
|
|
private sealed class RecordingChecker(Func<DeployScriptCheckRequest, IReadOnlyList<string>>? rule = null, bool @throw = false)
|
|
: IDeployScriptChecker
|
|
{
|
|
public ConcurrentQueue<DeployScriptCheckRequest> Requests { get; } = new();
|
|
|
|
public ConcurrentQueue<IReadOnlyList<DeployScriptCheckRequest>> Calls { get; } = new();
|
|
|
|
public IReadOnlyList<DeployScriptCheckResult> Check(IReadOnlyList<DeployScriptCheckRequest> 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<IDriverProbe>(), scriptChecker: new RoslynDeployScriptChecker()));
|
|
actor.Tell(new StartDeployment("joe", CorrelationId.NewId()));
|
|
ExpectMsg<StartDeploymentResult>(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 escape-free literal text, 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<string, string> { ["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'");
|
|
}
|
|
|
|
/// <summary>
|
|
/// A RawPath segment may legally contain a backslash, and substitution pastes the RawPath into a C# string
|
|
/// literal — so <c>{{equip}}/speed</c> over a device named <c>de\qv</c> becomes an invalid escape the runtime
|
|
/// refuses to compile. The template compiles fine; only compiling the RESOLVED source (what the gate does
|
|
/// whenever substitution is not provably compile-neutral) catches it.
|
|
/// </summary>
|
|
[Fact]
|
|
public void An_equip_substitution_that_breaks_the_literal_is_caught_by_compiling_the_resolved_source()
|
|
{
|
|
var reply = Deploy(SeedDraft(new Seed(DeviceName: @"de\qv")), new RoslynDeployScriptChecker(), expectDispatch: false);
|
|
reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected);
|
|
reply.Message.ShouldNotBeNull();
|
|
reply.Message.ShouldContain("script 's-vt' does not compile as a VirtualTag script");
|
|
reply.Message.ShouldContain("compile error");
|
|
reply.Message.ShouldContain("script 's-pred'"); // the predicate resolves through the same reference
|
|
}
|
|
|
|
[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");
|
|
}
|
|
}
|