Compare commits

...

11 Commits

Author SHA1 Message Date
Joseph Doherty 9106efafd8 Merge main (DCL alarm fixes 06ef177..9b78e60) into M3 branch 2026-06-16 20:20:27 -04:00
Joseph Doherty fb5f14e04f docs(m3): document Script Analysis component (#25); reconcile consumer specs + README/CLAUDE component list 2026-06-16 20:05:24 -04:00
Joseph Doherty 069757209a fix(scriptanalysis): M3.6 — full-framework analysis refs close forbidden-type-in-allowed-ns blind spot; pin Process/Stopwatch; fix stale codec test; drop dead ContainsInCode 2026-06-16 20:00:28 -04:00
Joseph Doherty cf935d5744 refactor(centralui): M3.5 ScriptAnalysisService uses shared deny-list + delegates trust verdict 2026-06-16 19:40:03 -04:00
Joseph Doherty 64d6ac7288 refactor(siteruntime): M3.3 ValidateTrustModel delegates to shared ScriptAnalysis + compile-surface parity test 2026-06-16 19:37:50 -04:00
Joseph Doherty 14bd25196a feat(templateengine): M3.2 deploy gate delegates to shared ScriptAnalysis (real compile + authoritative forbidden-API) 2026-06-16 19:36:03 -04:00
Joseph Doherty 784fee7b07 refactor(inboundapi): M3.4 ForbiddenApiChecker delegates to shared ScriptAnalysis validator 2026-06-16 19:35:43 -04:00
Joseph Doherty 069c0e0b1a fix(scriptanalysis): M3.1 review — Pass 2 self-sufficient descent, pin nested-forbidden + nameof cases, drop dead code 2026-06-16 19:29:59 -04:00
Joseph Doherty 4f2b17ce6d feat(scriptanalysis): M3.1 shared trust validator + compiler + compile surfaces + tests 2026-06-16 19:18:39 -04:00
Joseph Doherty 0cc8642cfa docs(m3): implementation plan + tasks for shared ScriptAnalysis consolidation 2026-06-16 19:09:12 -04:00
Joseph Doherty 8e99f22b24 docs(m3): design — shared ScriptAnalysis project consolidating the 4 trust-model analyzers 2026-06-16 19:07:32 -04:00
37 changed files with 2298 additions and 854 deletions
+3 -2
View File
@@ -63,7 +63,7 @@ Related repos cloned as sibling directories under `~/Desktop/` — referenced fo
- Commit related changes together with a descriptive message summarizing the design decision and the implementation slice.
- After non-trivial code changes, build (`dotnet build ZB.MOM.WW.ScadaBridge.slnx`) and run relevant tests before declaring done; for cluster-runtime changes, rebuild the image with `bash docker/deploy.sh`.
## Current Component List (24 components)
## Current Component List (25 components)
1. Template Engine — Template modeling, inheritance, composition, validation, flattening, diffs.
2. Deployment Manager — Central-side deployment pipeline, system-wide artifact deployment, instance lifecycle.
@@ -89,6 +89,7 @@ Related repos cloned as sibling directories under `~/Desktop/` — referenced fo
22. Site Call Audit — Central component auditing site cached calls (`CachedCall`/`CachedWrite`); `SiteCalls` audit table, telemetry ingest, reconciliation, KPIs, central→site Retry/Discard relay; sites remain the source of truth.
23. Audit Log — Central append-only AuditLog table spanning every script-trust-boundary action (outbound API sync+cached, outbound DB sync+cached, notifications, inbound API). Site SQLite hot-path + gRPC telemetry + reconciliation; combined telemetry with Site Call Audit; central direct-write for Notification Outbox dispatch + Inbound API; monthly partitioning, 365-day retention.
24. Transport — File-based, encrypted bundle export/import via Central UI. Templates, system artifacts, central-only configuration. Per-conflict resolution. Correlated audit via `BundleImportId`. No site involvement.
25. Script Analysis — Shared authoritative script-trust analyzer: unified forbidden-API deny-list (`ScriptTrustPolicy`), fused semantic+syntactic validator (`ScriptTrustValidator`), Roslyn compile wrapper (`RoslynScriptCompiler`), and compile-only globals stubs (`ScriptCompileSurface`/`TriggerCompileSurface`); consumed by Template Engine, Site Runtime, Inbound API, and Central UI.
## Key Design Decisions (for context across sessions)
@@ -211,7 +212,7 @@ Related repos cloned as sibling directories under `~/Desktop/` — referenced fo
### Akka.NET Conventions
- Tell for hot-path internal communication; Ask reserved for system boundaries.
- ClusterClient for cross-cluster communication; ClusterClientReceptionist for service discovery across cluster boundaries.
- Script trust model: forbidden APIs (System.IO, Process, Threading, Reflection, raw network).
- Script trust model: forbidden APIs (System.IO, Process, Threading, Reflection, raw network). The trust boundary is centralized in the Script Analysis component (#25) — `ScriptTrustPolicy` is the single source of truth; all four call sites (Template Engine, Site Runtime, Inbound API, Central UI) delegate to `ScriptTrustValidator`. The design-time deploy gate in Template Engine is authoritative (real semantic compile), not advisory.
- Application-level correlation IDs on all request/response messages.
## Tool Usage
+1
View File
@@ -100,6 +100,7 @@ Both stacks share the infrastructure services in [`infra/`](infra/) (MS SQL, LDA
| 22 | Site Call Audit | [docs/requirements/Component-SiteCallAudit.md](docs/requirements/Component-SiteCallAudit.md) | Central component auditing site cached calls (`ExternalSystem.CachedCall`/`Database.CachedWrite`) into the `SiteCalls` audit table, with `SiteCallAuditActor` singleton, telemetry ingest, periodic reconciliation, point-in-time KPIs, daily purge, and central→site Retry/Discard relay for parked calls. |
| 23 | Audit Log | [docs/requirements/Component-AuditLog.md](docs/requirements/Component-AuditLog.md) | New central append-only AuditLog spanning every script-trust-boundary action (outbound API sync+cached, outbound DB sync+cached, notifications, inbound API). Site-local SQLite hot-path append + gRPC telemetry + central reconciliation; combined telemetry packet with Site Call Audit; central direct-write for Notification Outbox dispatch + Inbound API middleware; monthly partitioning, 365-day default retention. |
| 24 | Transport | [docs/requirements/Component-Transport.md](docs/requirements/Component-Transport.md) | Bundle export/import for templates, shared scripts, external systems, central-only artifacts. AES-256-GCM encryption; per-conflict resolution on import; correlated audit trail. |
| 25 | Script Analysis | [docs/requirements/Component-ScriptAnalysis.md](docs/requirements/Component-ScriptAnalysis.md) | Shared authoritative script-trust analyzer: unified forbidden-API deny-list (`ScriptTrustPolicy`), fused semantic+syntactic validator (`ScriptTrustValidator`), Roslyn compile wrapper (`RoslynScriptCompiler`), and compile-only globals stubs (`ScriptCompileSurface`/`TriggerCompileSurface`); consumed by Template Engine, Site Runtime, Inbound API, and Central UI. |
**Shared UI sub-component** (not a top-level component): [TreeView](docs/requirements/Component-TreeView.md) — reusable hierarchical tree/grid Blazor component used by the Central UI (#9) for the templates folder hierarchy, data-connection browse, and tag pickers.
+2
View File
@@ -23,6 +23,7 @@
<Project Path="src/ZB.MOM.WW.ScadaBridge.ManagementService/ZB.MOM.WW.ScadaBridge.ManagementService.csproj" />
<Project Path="src/ZB.MOM.WW.ScadaBridge.CLI/ZB.MOM.WW.ScadaBridge.CLI.csproj" />
<Project Path="src/ZB.MOM.WW.ScadaBridge.Transport/ZB.MOM.WW.ScadaBridge.Transport.csproj" />
<Project Path="src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests.csproj" />
@@ -51,5 +52,6 @@
<Project Path="tests/ZB.MOM.WW.ScadaBridge.CentralUI.PlaywrightTests/ZB.MOM.WW.ScadaBridge.CentralUI.PlaywrightTests.csproj" />
<Project Path="tests/ZB.MOM.WW.ScadaBridge.Transport.Tests/ZB.MOM.WW.ScadaBridge.Transport.Tests.csproj" />
<Project Path="tests/ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests/ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests.csproj" />
<Project Path="tests/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.Tests/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.Tests.csproj" />
</Folder>
</Solution>
@@ -0,0 +1,159 @@
# Shared Script-Analysis Consolidation (M3) — Design
**Status:** Proposed (awaiting approval)
**Supersedes:** the M3.1–M3.4 tasks in `docs/plans/2026-06-15-stillpending-phase1-implementation.md` (those assumed a contained "wire Roslyn into TemplateEngine.ScriptCompiler" change; this design replaces them with a consolidation, per the chosen approach).
**Worktree/branch:** `worktree-m3-script-trust-boundary`.
## Goal
Make the **design-time script trust gate authoritative** and eliminate the four-way
divergence in script trust enforcement by extracting one shared, authoritative
analyzer that every script call site delegates to.
## Background — the problem
Script trust enforcement (forbidden-API deny-list + compile) exists in **four**
places, each implemented differently, and they disagree:
| Site | File | Mechanism | Forbidden-API gaps |
|---|---|---|---|
| **TemplateEngine** (the deploy gate) | `Validation/ScriptCompiler.cs`, `ValidationService.cs` | **Fake**: substring scan + brace balancing | Bypassable by alias / `using static` / `global::`; no real compile. **This is the authoritative deploy-blocking gate** (`DeploymentManager.FlatteningPipeline`, `ManagementActor`). |
| **SiteRuntime** | `Scripts/ScriptCompilationService.cs` | Semantic symbol analysis + `CSharpScript.Compile` against real `ScriptGlobals` | No reflection-gateway hardening (`typeof(x).Assembly.GetType("System.IO.File")`). |
| **InboundAPI** | `ForbiddenApiChecker.cs` | Syntactic walker + reflection-gateway + `dynamic`/`Activator` hardening | Syntactic only (no symbol resolution); forbids all `System.Diagnostics`. |
| **CentralUI** | `ScriptAnalysis/ScriptAnalysisService.cs` (+ `SandboxScriptHost`) | Semantic + full `CSharpScript.Compile` against a globals stub | Lenient threading list (allows most `System.Threading`). |
The deploy gate — the one that actually blocks a bad script from shipping — is the
**weakest**. The strong machinery exists only in higher layers
(SiteRuntime/InboundAPI/CentralUI), which TemplateEngine cannot reference.
## Approach (chosen): extract a shared analyzer project
New project **`ZB.MOM.WW.ScadaBridge.ScriptAnalysis`** sitting just above Commons
(references only `Commons` + `Microsoft.CodeAnalysis.CSharp.Scripting` +
`Microsoft.CodeAnalysis.CSharp.Workspaces`). The four call sites delegate to it.
### Public surface
1. **`ScriptTrustPolicy`** — the single source of truth for the trust model:
- `ForbiddenScopes` (namespaces/types), `AllowedExceptions`,
`ReflectionGatewayMembers`, `ForbiddenIdentifiers` (`dynamic`, `Activator`),
- `DefaultReferences` (canonical script metadata references) + `DefaultImports`.
2. **`ScriptTrustValidator.FindViolations(code, extraReferences?)`** — the
**authoritative forbidden-API gate**. Fuses SiteRuntime's *semantic* symbol
resolution (resolves aliases, `using static`, `global::`, transitive imports —
inspects the resolved symbol, not the spelling) with InboundAPI's *syntactic*
reflection-gateway / `dynamic` / `Activator` hardening. Needs **no** globals type.
Returns violation messages; empty == clean.
3. **`RoslynScriptCompiler`** —
- `Compile(code, globalsType?, extraReferences?, extraImports?)` → real
`CSharpScript.Create(...).Compile()`, returns error diagnostics. Each caller
passes **its own** `globalsType`.
- `ParseDiagnostics(code)` → syntax-only diagnostics (for callers without globals).
4. **`ScriptCompileSurface`** / **`TriggerCompileSurface`** — lightweight
**compile-only** globals stubs mirroring `ScriptGlobals` / `TriggerExpressionGlobals`
member-for-member, depending only on `Commons.Types(.Scripts)`. **Never executed** —
they exist purely so the deploy gate can bind real API-using scripts
(`Attributes[...]`, `Notify.To(...).Send(...)`, `ExternalSystem.Call(...)`, …) and
thus catch undefined-symbol / type errors at central validation time. Drift from the
real globals is caught by a reflection parity test (below).
### Per-consumer migration (behavior-preserving delegation)
- **TemplateEngine** (`ScriptCompiler.TryCompile`): `FindViolations` +
`RoslynScriptCompiler.Compile(code, typeof(ScriptCompileSurface))` → the deploy
gate now does authoritative forbidden-API **and** a real type-checking compile.
`ValidationService.CheckExpressionSyntax` → `FindViolations` + compile against
`TriggerCompileSurface`. Delete `ForbiddenPatterns` + the substring scan. Add
project ref to `ScriptAnalysis`.
- **SiteRuntime** (`ScriptCompilationService.ValidateTrustModel`): delegate to
`FindViolations`; keep `CSharpScript.Compile` against the **real** `ScriptGlobals`
for execution.
- **InboundAPI** (`ForbiddenApiChecker.FindViolations`): delegate to shared
(reflection-gateway behavior preserved, now centralized).
- **CentralUI** (`ScriptAnalysisService.FindForbiddenApiUsages` / `ValidateTrustModel`):
delegate to shared; keep the editor diagnostic-marker mapping and the Test-Run
executing host (`SandboxScriptHost`, which fires real central services).
## Unified forbidden-API policy (strictest-safe union)
- **Forbid:** `System.IO`, `System.Diagnostics.Process`, `System.Threading`,
`System.Reflection`, `System.Net`, `System.Runtime.InteropServices`, `Microsoft.Win32`.
- **Allow exceptions:** `System.Threading.Tasks`, `System.Threading.CancellationToken`,
`System.Threading.CancellationTokenSource`.
- **Reflection-gateway members** (blocked on any receiver): `GetType`, `GetTypeInfo`,
`Assembly`, `Module`, `CreateInstance`, `InvokeMember`, `GetMethod(s)`,
`GetConstructor(s)`, `GetField(s)`, `GetProperty(ies)`, `GetMember(s)`,
`GetRuntimeMethod(s)`, `MethodHandle`, `TypeHandle`.
- **Forbidden identifiers:** `dynamic`, `Activator`.
Three genuine conflicts between the current lists, resolved toward the actual runtime gate:
1. **`System.Diagnostics`** — InboundAPI forbids the whole namespace; SiteRuntime
forbids only `.Process`. → **Forbid `.Process` only** (allow `Stopwatch`, `Debug`,
`Activity`). *Slightly loosens InboundAPI on harmless types; matches the real runtime.*
2. **`System.Net`** — SiteRuntime forbids only `Sockets`+`Http`; others forbid all. →
**Forbid all `System.Net`** (scripts use the `ExternalSystem` helper for HTTP).
*Slightly tightens SiteRuntime; safe.*
3. **`System.Threading`** — CentralUI allows most of it. → **Forbid all except Tasks +
CancellationToken(Source)** (matches the real runtime). *Tightens the CentralUI editor.*
**Net effect:** the unified policy ≈ SiteRuntime's runtime policy (the gate that
actually executes) + InboundAPI's reflection hardening + all-`System.Net` +
`InteropServices`/`Win32`. Because SiteRuntime already enforces ~this at execution
time, no script that currently deploys-and-runs newly breaks; several real gaps close
(the deploy gate becomes real; the editor stops under-warning; reflection escapes are
blocked everywhere).
## Layering / cycle check
`ScriptAnalysis → { Commons, Microsoft.CodeAnalysis.* }`. Referenced by TemplateEngine,
SiteRuntime, InboundAPI, CentralUI. None of those are referenced *by* Commons, and
ScriptAnalysis references none of them → **no cycles**.
## Test strategy
- **New `ScriptAnalysis.Tests`** — adversarial corpus that must all yield violations:
namespace alias, `using static`, `global::`, `typeof(x).Assembly.GetType("System.IO.File")`,
`dynamic`, `Activator`, `InteropServices`, `Microsoft.Win32`. Legit scripts must be
clean: `await Task`, `Stopwatch`, LINQ, `Math`, `CancellationToken`. `ParseDiagnostics`
catches syntax errors; `Compile(..., typeof(ScriptCompileSurface))` catches
undefined-symbol/type errors **and** accepts real API-using scripts.
- **Drift parity test** — reflect over `ScriptGlobals` vs `ScriptCompileSurface` (and
`TriggerExpressionGlobals` vs `TriggerCompileSurface`); assert public member-name parity
so the stub can't silently drift.
- **Preserve & re-point existing tests** — `ScriptCompilerTests`,
`ForbiddenApiCheckerTests`, `ScriptAnalysisServiceTests` (+ async-resolve, console),
`ScriptCompilationServiceTests`, `TrustModelSemanticTests`, `SandboxTests` must stay
green against the delegating implementations (adjust expected wording where messages change).
- **Adversarial deploy test** (TemplateEngine integration) — a bypass script **fails to deploy**.
## Migration sequencing
- **Wave 0 — spike (M3.0):** confirm `ScriptCompileSurface` can mirror `ScriptGlobals`
with Commons-only deps; confirm package refs resolve in the new project.
- **Wave 1 — foundation (M3.1):** build `ScriptAnalysis` (policy + validator + compiler +
surfaces) with its full test suite. Everything else depends on this.
- **Wave 2 — consumers (M3.2–M3.5, parallelizable, disjoint projects):** TemplateEngine ∥
SiteRuntime ∥ InboundAPI ∥ CentralUI each delegate to the shared analyzer; each keeps
its own tests green. *Pathspec commits to avoid shared-index contamination.*
- **Wave 3 — integration + docs (M3.6):** full-solution build; targeted tests across all
five projects + adversarial deploy test; docs (Component-TemplateEngine / -SiteRuntime /
-InboundAPI / -Commons, README + CLAUDE.md component list, remove the "SECURITY
LIMITATION / advisory" notes now that the gate is real); fixture cleanup for any
latent-invalid scripts the real compile surfaces.
## Risks
- **Policy change surfaces latent-invalid fixtures/scripts** — budgeted in Wave 3
(same risk the original plan flagged for M3.4).
- **`ScriptCompileSurface` drift** vs real `ScriptGlobals` — mitigated by the parity test.
- **Touching four working, security-sensitive components** — mitigated by
behavior-preserving delegation + keeping each consumer's existing tests + the
classification-driven review chain (high-risk = serial spec→code review).
## Out of scope
- Physically unifying the **executing** globals types (`ScriptGlobals`, `SandboxScriptHost`)
— they stay with their owners; only the compile-surface stub + trust policy are shared.
- A true runtime sandbox (restricted `AssemblyLoadContext` / out-of-process) — still
future work; the static gate is defence-in-depth, as already noted in InboundAPI-015.
@@ -0,0 +1,89 @@
# Shared Script-Analysis Consolidation (M3) — Implementation Plan
> **For Claude:** executed via superpowers-extended-cc:subagent-driven-development in this session.
**Goal:** Extract one shared, authoritative script-trust analyzer (`ZB.MOM.WW.ScadaBridge.ScriptAnalysis`) and make all four call sites delegate to it, turning the fake design-time deploy gate into a real semantic compile + authoritative forbidden-API check.
**Architecture:** New project just above Commons (refs Commons + Microsoft.CodeAnalysis.CSharp.Scripting/Workspaces). Hosts the trust policy, the fused semantic+syntactic validator, a Roslyn compile wrapper, and compile-only globals stubs. TemplateEngine/SiteRuntime/InboundAPI/CentralUI delegate; the executing globals stay with their owners. Design: `docs/plans/2026-06-16-script-analysis-consolidation-design.md`.
**Tech Stack:** C#/.NET 10, Microsoft.CodeAnalysis (Roslyn) C# Scripting + Workspaces, xUnit.
**Conventions:** targeted builds/tests per task (`dotnet build <project>`, `dotnet test --filter`); full-solution build only in M3.6. Implementers do NOT create worktrees (already in one) and commit with pathspec form `git commit -m "..." -- <paths>` (retry on index.lock).
---
# Wave 0 — Spike
### Task M3.0: Confirm compile-surface stub feasibility + package refs
**Classification:** small · **Estimated implement time:** ~4 min · **Parallelizable with:** none
**Files (read-only spike):** `src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/ScriptCompilationService.cs` (ScriptGlobals), `TriggerExpressionGlobals.cs`, `src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/SandboxScriptHost.cs`, `Directory.Packages.props`.
**Steps:**
1. Enumerate the full public member surface of `ScriptGlobals` and `TriggerExpressionGlobals` (names + rough shapes) that a script can reference.
2. Confirm every member's referenced types resolve from Commons alone (e.g. `ScriptParameters`, `AlarmContext`, `ScriptScope` in `Commons.Types(.Scripts)`); list any member whose type lives in SiteRuntime/CentralUI and would need a loose (`object`/`dynamic`-returning) stand-in on the stub.
3. Confirm `Microsoft.CodeAnalysis.CSharp.Scripting` (5.0.0) + `Microsoft.CodeAnalysis.CSharp.Workspaces` (5.0.0) are in `Directory.Packages.props`.
**AC:** a short written inventory the M3.1 implementer can build `ScriptCompileSurface`/`TriggerCompileSurface` from, with each member's compile-surface return type decided (Commons type vs loose `object`). No code committed.
---
# Wave 1 — Foundation
### Task M3.1: Build `ZB.MOM.WW.ScadaBridge.ScriptAnalysis` (policy + validator + compiler + surfaces + tests)
**Classification:** high-risk (security boundary) · **Estimated implement time:** ~5 min · **Parallelizable with:** none · **Depends on:** M3.0
**Files:**
- Create: `src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.csproj` (refs Commons + the two CodeAnalysis packages; add to `ZB.MOM.WW.ScadaBridge.slnx`).
- Create: `ScriptTrustPolicy.cs`, `ScriptTrustValidator.cs`, `RoslynScriptCompiler.cs`, `ScriptCompileSurface.cs`, `TriggerCompileSurface.cs`.
- Create: `tests/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.Tests/...` (+ add to slnx).
**Design points:**
- `ScriptTrustPolicy`: ForbiddenScopes = `System.IO`, `System.Diagnostics.Process`, `System.Threading`, `System.Reflection`, `System.Net`, `System.Runtime.InteropServices`, `Microsoft.Win32`. AllowedExceptions = `System.Threading.Tasks`, `System.Threading.CancellationToken`, `System.Threading.CancellationTokenSource`. ReflectionGatewayMembers = the InboundAPI `ForbiddenMemberNames` set. ForbiddenIdentifiers = `dynamic`, `Activator`. DefaultReferences = the SiteRuntime `ScriptAssemblies` set (object, Enumerable, Math, CSharpArgumentInfo, Commons). DefaultImports = `System`, `System.Collections.Generic`, `System.Linq`, `System.Threading.Tasks`.
- `ScriptTrustValidator.FindViolations(code, extraReferences?)`: port SiteRuntime `ValidateTrustModel` (CreateScriptCompilation + semantic model; `GetSymbolScopes`/`GetSyntacticScopes`/`IsUnderScope` symbol-vs-syntax resolution; dedup via `SortedSet`), and FUSE in InboundAPI's reflection-gateway member-name + `dynamic`/`Activator` syntactic checks. Returns combined violations.
- `RoslynScriptCompiler.Compile(code, globalsType?, extraReferences?, extraImports?)`: `CSharpScript.Create<object?>(code, options, globalsType).Compile()`, map error diagnostics to messages. `ParseDiagnostics(code)`: parse with `SourceCodeKind.Script`, return syntax error diagnostics.
- `ScriptCompileSurface`/`TriggerCompileSurface`: mirror the M3.0 inventory; compile-only, never executed.
**Tests (TDD):** adversarial corpus → violations (alias, `using static`, `global::`, `typeof(x).Assembly.GetType("System.IO.File")`, `dynamic`, `Activator`, `System.Runtime.InteropServices`, `Microsoft.Win32`); legit → clean (`await Task.Delay`, `Stopwatch`, LINQ, `Math`, `CancellationToken`); `ParseDiagnostics` flags syntax error; `Compile(..., typeof(ScriptCompileSurface))` rejects undefined symbol AND accepts a real script using `Attributes`/`Notify`/`ExternalSystem`; parity test: public member names of `ScriptCompileSurface` ⊇ those of … (parity asserted in M3.3 once SiteRuntime references the project — here assert the surface compiles a representative real script).
**AC:** `dotnet build` + `dotnet test` for ScriptAnalysis green; adversarial corpus all rejected; legit all clean.
---
# Wave 2 — Consumers delegate (parallelizable; disjoint projects)
### Task M3.2: TemplateEngine deploy gate → shared analyzer
**Classification:** high-risk (the authoritative deploy gate) · **~5 min** · **Parallelizable with:** M3.3, M3.4, M3.5 · **Depends on:** M3.1
**Files:** `src/ZB.MOM.WW.ScadaBridge.TemplateEngine/ZB.MOM.WW.ScadaBridge.TemplateEngine.csproj` (+ ProjectReference to ScriptAnalysis), `Validation/ScriptCompiler.cs`, `Validation/ValidationService.cs` (`CheckExpressionSyntax`), `tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Validation/ScriptCompilerTests.cs`.
**Changes:** `ScriptCompiler.TryCompile` → empty-check, then `ScriptTrustValidator.FindViolations`, then `RoslynScriptCompiler.Compile(code, typeof(ScriptCompileSurface))`; return first failure as `Result<bool>.Failure`. `CheckExpressionSyntax` → `FindViolations` + `Compile(expr, typeof(TriggerCompileSurface))`. Delete `ForbiddenPatterns` + the substring/brace path (keep `CSharpDelimiterScanner` only if still referenced elsewhere — else remove). Re-point/adjust `ScriptCompilerTests` expected messages.
**AC:** invalid C# (undefined symbol) fails validation; adversarial alias/`using static`/`global::`/reflection-gateway scripts fail; valid real scripts pass. `dotnet test` TemplateEngine green.
### Task M3.3: SiteRuntime → shared analyzer (keep real-globals compile)
**Classification:** high-risk (runtime trust gate) · **~4 min** · **Parallelizable with:** M3.2, M3.4, M3.5 · **Depends on:** M3.1
**Files:** `src/ZB.MOM.WW.ScadaBridge.SiteRuntime/ZB.MOM.WW.ScadaBridge.SiteRuntime.csproj` (+ ref), `Scripts/ScriptCompilationService.cs`, `tests/.../Scripts/TrustModelSemanticTests.cs`, `ScriptCompilationServiceTests.cs`.
**Changes:** `ValidateTrustModel` → delegate to `ScriptTrustValidator.FindViolations`. Keep `CompileCore`/`CSharpScript.Compile` against the real `ScriptGlobals`/`TriggerExpressionGlobals`. Remove the now-duplicated `ForbiddenNamespaces`/`AllowedExceptions`/scope helpers. **Add the parity test** (`ScriptCompileSurface` public member-name set ⊇ `ScriptGlobals`; `TriggerCompileSurface` ⊇ `TriggerExpressionGlobals`) here, where both types are referenceable.
**AC:** SiteRuntime trust tests green; parity test green; reflection-gateway bypass now rejected at the site too.
### Task M3.4: InboundAPI → shared analyzer
**Classification:** standard · **~3 min** · **Parallelizable with:** M3.2, M3.3, M3.5 · **Depends on:** M3.1
**Files:** `src/ZB.MOM.WW.ScadaBridge.InboundAPI/ZB.MOM.WW.ScadaBridge.InboundAPI.csproj` (+ ref to ScriptAnalysis), `ForbiddenApiChecker.cs`, `InboundScriptExecutor.cs` (call site if needed), `tests/.../ForbiddenApiCheckerTests.cs`.
**Changes:** `ForbiddenApiChecker.FindViolations` → delegate to `ScriptTrustValidator.FindViolations` (keep the public method as a thin shim so callers are untouched). Remove the local walker/lists. Adjust test expectations where wording changed; the now-loosened `System.Diagnostics` (Stopwatch allowed) and now-semantic resolution should be reflected.
**AC:** InboundAPI forbidden-API tests green against the shared validator; reflection-gateway + `dynamic` + `Activator` still rejected.
### Task M3.5: CentralUI → shared analyzer (keep editor markers + Test-Run host)
**Classification:** standard · **~4 min** · **Parallelizable with:** M3.2, M3.3, M3.4 · **Depends on:** M3.1
**Files:** `src/ZB.MOM.WW.ScadaBridge.CentralUI/ZB.MOM.WW.ScadaBridge.CentralUI.csproj` (+ ref), `ScriptAnalysis/ScriptAnalysisService.cs`, `tests/.../ScriptAnalysis/ScriptAnalysisServiceTests.cs`.
**Changes:** `FindForbiddenApiUsages`/`ValidateTrustModel` → delegate to `ScriptTrustValidator.FindViolations` for the trust verdict, then map to `DiagnosticMarker`s (keep marker positions/codes). Remove the local `ForbiddenNamespacePrefixes`/`ForbiddenNameFor`/`IsForbiddenName`. Keep `Diagnose` compile + `SandboxScriptHost` Test-Run execution unchanged. Adjust tests where the (now stricter) threading policy changes a marker.
**AC:** CentralUI script-analysis tests green; editor now flags the previously-allowed `System.Threading` usages.
---
# Wave 3 — Integration + docs
### Task M3.6: Integration verification + docs + fixture cleanup
**Classification:** high-risk (final integration reviewer) · **~5 min** · **Parallelizable with:** none · **Depends on:** M3.2–M3.5
**Steps:**
1. `dotnet build ZB.MOM.WW.ScadaBridge.slnx` (full solution).
2. Targeted tests across ScriptAnalysis, TemplateEngine, SiteRuntime, InboundAPI, CentralUI; fix any latent-invalid fixtures/scripts the real compile surfaces.
3. Docs: `docs/requirements/Component-TemplateEngine.md` (real compile gate), `Component-SiteRuntime.md`, `Component-InboundAPI.md`, `Component-Commons.md` if surfaces move; add the new component to `README.md` table + `CLAUDE.md` component list (24 → 25); remove the "SECURITY LIMITATION / advisory" notes in `ScriptCompiler.cs`/`ValidationService.cs` now that the gate is authoritative.
4. Commit; final integration code review of the whole `8e99f22..HEAD` diff.
**AC:** full build green; trust tests + adversarial deploy test green; no doc claims the design-time gate is advisory; component list updated.
---
## Native tasks & dependencies
Sub-tasks created as native tasks under umbrella #14 (M3). Edges: M3.1 ⟵ M3.0; M3.2/M3.3/M3.4/M3.5 ⟵ M3.1; M3.6 ⟵ M3.2..M3.5.
@@ -0,0 +1,13 @@
{
"planPath": "docs/plans/2026-06-16-script-analysis-consolidation.md",
"tasks": [
{"id": 103, "subject": "M3.0: Spike — compile-surface stub feasibility + package refs", "status": "pending"},
{"id": 104, "subject": "M3.1: Build ScriptAnalysis project (policy+validator+compiler+surfaces+tests)", "status": "pending", "blockedBy": [103]},
{"id": 105, "subject": "M3.2: TemplateEngine deploy gate → shared analyzer", "status": "pending", "blockedBy": [104]},
{"id": 106, "subject": "M3.3: SiteRuntime → shared analyzer + parity test", "status": "pending", "blockedBy": [104]},
{"id": 107, "subject": "M3.4: InboundAPI → shared analyzer", "status": "pending", "blockedBy": [104]},
{"id": 108, "subject": "M3.5: CentralUI → shared analyzer (keep markers + Test-Run host)", "status": "pending", "blockedBy": [104]},
{"id": 109, "subject": "M3.6: Integration verification + docs + fixture cleanup", "status": "pending", "blockedBy": [105, 106, 107, 108]}
],
"lastUpdated": "2026-06-16"
}
+12 -6
View File
@@ -197,12 +197,17 @@ Inbound API scripts **cannot** call shared scripts directly — shared scripts a
> **No direct database access.** Inbound API scripts are not given a raw database
> client. Handing a script a raw `SqlConnection` is in direct tension with the
> ScadaBridge script trust model (scripts are forbidden `System.IO`, `Process`,
> `Threading`, `Reflection`, and raw network access; `ForbiddenApiChecker`
> statically enforces this). Scripts interact with the system only through the
> curated `Route` and `Parameters` surfaces above. If a method needs data from
> the configuration or machine-data databases, that access belongs behind a
> dedicated, scoped helper — not a general-purpose connection — and would be
> added here as an explicit design change.
> `Threading`, `Reflection`, and raw network access). The `ForbiddenApiChecker`
> statically enforces this by delegating to the shared `ScriptAnalysis`
> `ScriptTrustValidator` (component #25), which is the single authoritative
> source of truth for the forbidden-API policy. The unified policy permits
> `System.Diagnostics.Stopwatch`/`Debug` while retaining the `Process`-only ban,
> and adds reflection-gateway member and `dynamic`/`Activator` hardening.
> This is defence-in-depth static enforcement, not a true runtime sandbox. Scripts
> interact with the system only through the curated `Route` and `Parameters`
> surfaces above. If a method needs data from the configuration or machine-data
> databases, that access belongs behind a dedicated, scoped helper — not a
> general-purpose connection — and would be added here as an explicit design change.
### Routing Behavior
- The `Route.To()` helper resolves the instance's site assignment from the configuration database and routes the request to the correct site cluster via the Communication Layer.
@@ -232,6 +237,7 @@ Inbound API scripts **cannot** call shared scripts directly — shared scripts a
- **Communication Layer**: Routes requests to sites when method implementations need site data.
- **Security & Auth**: API key validation (separate from LDAP/AD — API uses key-based auth).
- **Configuration Database (via IAuditService)**: All API key and method definition changes are audit logged.
- **Script Analysis (#25)**: `ForbiddenApiChecker` delegates to `ScriptTrustValidator.FindViolations` for the authoritative forbidden-API verdict during script compilation and validation.
- **Audit Log (#23)**: Every inbound API request emits an `ApiInbound.Completed` row via `ICentralAuditWriter` from request middleware (non-blocking for the HTTP response). Request and response bodies are captured in full up to `AuditLog:InboundMaxBytes` (default 1 MiB) per the Audit Log Payload Capture Policy; redaction (headers + per-target body redactors) still applies before persistence.
- **Cluster Infrastructure**: API is hosted on the active central node and fails over with it.
@@ -0,0 +1,168 @@
# Component: Script Analysis
## Purpose
The Script Analysis component is the single authoritative source of truth for the ScadaBridge script trust model. It provides a unified forbidden-API deny-list, a fused semantic and syntactic trust validator, a Roslyn compile wrapper, and compile-only globals stubs used by the design-time deploy gate. All four call sites that enforce the script trust boundary — Template Engine, Site Runtime, Inbound API, and Central UI — delegate to this component rather than maintaining their own divergent implementations.
## Location
`src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/`
Referenced by: Template Engine, Site Runtime, Inbound API, Central UI.
## Responsibilities
- Define the canonical forbidden-API deny-list (`ScriptTrustPolicy`) as the single source of truth for all trust enforcement decisions across the system.
- Provide an authoritative forbidden-API verdict (`ScriptTrustValidator.FindViolations`) that fuses semantic symbol resolution with syntactic reflection-gateway hardening.
- Wrap Roslyn `CSharpScript` compilation (`RoslynScriptCompiler`) so callers share one implementation of compile + diagnostics extraction.
- Provide compile-only globals stubs (`ScriptCompileSurface`, `TriggerCompileSurface`) that mirror the real execution-time globals member-for-member, allowing the design-time deploy gate to do a real type-checking compile without depending on the execution-time projects.
---
## Requirements
### REQ-SA-1: Trust Policy (`ScriptTrustPolicy`)
`ScriptTrustPolicy` is a static class (or record) that publishes the complete, authoritative forbidden-API policy used at every call site.
#### Forbidden scopes
The following namespace/type prefixes are forbidden in all scripts:
| Scope | Rationale |
|-------|-----------|
| `System.IO` | File system access — forbidden entirely |
| `System.Diagnostics.Process` | Process spawning — forbidden; `Stopwatch`, `Debug`, `Activity`, and other `System.Diagnostics` types are **allowed** |
| `System.Threading` | Raw thread manipulation — forbidden, with the exceptions below |
| `System.Reflection` | Reflection — forbidden entirely |
| `System.Net` | Raw network access — forbidden entirely (scripts must use `ExternalSystem.Call`) |
| `System.Runtime.InteropServices` | Native interop — forbidden entirely |
| `Microsoft.Win32` | Win32 API access — forbidden entirely |
#### Allowed exceptions within forbidden scopes
The following types are explicitly allowed despite falling within a forbidden namespace:
- `System.Threading.Tasks` (and all subtypes) — async/await support
- `System.Threading.CancellationToken` — cooperative cancellation
- `System.Threading.CancellationTokenSource` — cooperative cancellation
The scoping rationale: `System.Diagnostics.Process` is the dangerous type (spawns processes); `Stopwatch`, `Debug`, and `Activity` are harmless diagnostic utilities. Forbidding the whole `System.Diagnostics` namespace, as some earlier call sites did, was overly broad.
#### Reflection-gateway members
The following member names are blocked regardless of the receiver type, to prevent reflection-based bypasses such as `typeof(x).Assembly.GetType("System.IO.File")`:
`GetType`, `GetTypeInfo`, `Assembly`, `Module`, `CreateInstance`, `InvokeMember`, `GetMethod`, `GetMethods`, `GetConstructor`, `GetConstructors`, `GetField`, `GetFields`, `GetProperty`, `GetProperties`, `GetMember`, `GetMembers`, `GetRuntimeMethod`, `GetRuntimeMethods`, `MethodHandle`, `TypeHandle`.
#### Forbidden identifiers
The identifiers `dynamic` and `Activator` are forbidden at any scope, as they provide type-system escape hatches equivalent to reflection.
#### Default references and imports
`ScriptTrustPolicy` also publishes `DefaultReferences` (the canonical set of trusted-platform `MetadataReference` entries used when constructing the Roslyn script compilation context) and `DefaultImports` (the default `using` directives injected into every script). These are consumed by `RoslynScriptCompiler` and by the compile-only surfaces below.
---
### REQ-SA-2: Trust Validator (`ScriptTrustValidator`)
`ScriptTrustValidator.FindViolations(string code, IEnumerable<MetadataReference>? extraReferences = null)` is the **authoritative forbidden-API gate**. It returns a list of violation messages; an empty list means the script is clean.
#### Two-pass design
**Pass 1 — semantic symbol resolution (adapted from Site Runtime)**
- Builds a Roslyn compilation using the full trusted-platform reference set from `ScriptTrustPolicy.DefaultReferences` (plus any `extraReferences`).
- For each identifier in the syntax tree, resolves the underlying symbol to its fully qualified containing namespace and type name.
- Flags any symbol whose containing namespace or type matches a forbidden scope in `ScriptTrustPolicy.ForbiddenScopes`, taking `AllowedExceptions` into account.
- Correctly handles aliases (`using X = System.IO.File`), `using static`, and `global::` prefixes — the resolved symbol is checked, not the spelling.
- Because the full reference set is loaded, this pass also catches a forbidden type accessed inside an otherwise-allowed namespace (e.g., bare `Process` after `using System.Diagnostics;`).
**Pass 2 — syntactic reflection-gateway and identifier hardening (adapted from Inbound API)**
- Walks the syntax tree for member-access expressions and simple name references.
- Flags any member name found in `ScriptTrustPolicy.ReflectionGatewayMembers`, regardless of receiver type.
- Flags any identifier token found in `ScriptTrustPolicy.ForbiddenIdentifiers` (`dynamic`, `Activator`).
Violations from both passes are merged and deduplicated before being returned.
#### Design notes
- `FindViolations` needs no globals type; it operates solely on the script text and the trusted-platform reference set.
- The function is stateless and thread-safe — callers share a single instance or call it as a static method.
- A violation does not abort compilation; callers may choose to report violations and continue, or treat any violation as a hard reject.
---
### REQ-SA-3: Roslyn Compile Wrapper (`RoslynScriptCompiler`)
`RoslynScriptCompiler` wraps `CSharpScript` to give callers a single implementation of compile + diagnostics extraction.
#### `Compile(string code, Type? globalsType = null, IEnumerable<MetadataReference>? extraReferences = null, IEnumerable<string>? extraImports = null)`
- Creates a `CSharpScript` with the given code, `globalsType`, references (defaults from `ScriptTrustPolicy.DefaultReferences` plus `extraReferences`), and imports (defaults from `ScriptTrustPolicy.DefaultImports` plus `extraImports`).
- Calls `.Compile()` and returns the resulting `Diagnostic[]` filtered to errors and warnings.
- Each caller passes its own `globalsType` — `ScriptCompileSurface` for the design-time deploy gate, the real `ScriptGlobals` for Site Runtime execution, `null` for pure syntax checks.
#### `ParseDiagnostics(string code)`
- Parses the script text using Roslyn's `CSharpSyntaxTree.ParseText` and returns syntax-level diagnostics (errors and warnings).
- No compilation is performed — useful for fast syntax checks where no globals type is available.
---
### REQ-SA-4: Compile-Only Globals Stubs
The deploy gate in Template Engine must do a real type-checking compile (to catch undefined-symbol and type errors) but cannot depend on the execution-time projects (Site Runtime, Inbound API) that own the real globals. Two compile-only stubs solve this:
#### `ScriptCompileSurface`
Mirrors `ScriptGlobals` member-for-member (same public property names, same return types, same method signatures) but with no implementation bodies. All properties return `default` and all methods return `default` or `Task.CompletedTask`. Depends only on `Commons.Types` — no Akka.NET, no external system clients.
Used by the Template Engine deploy gate:
```csharp
var errors = RoslynScriptCompiler.Compile(code, typeof(ScriptCompileSurface));
```
This allows the compile to bind `Attributes["name"]`, `Notify.To("x").Send(...)`, `ExternalSystem.Call(...)`, and similar API calls against real types, catching undefined-symbol and type-mismatch errors before deployment.
#### `TriggerCompileSurface`
Mirrors `TriggerExpressionGlobals` in the same way. Used by `ValidationService.CheckExpressionSyntax` in the Template Engine for conditional and expression trigger validation.
#### Parity guard
A reflection-based parity test in `SiteRuntime.Tests` compares the public member names on `ScriptCompileSurface` against `ScriptGlobals` (and `TriggerCompileSurface` against `TriggerExpressionGlobals`). Any drift between the stub and the real globals causes this test to fail, ensuring the stubs cannot silently fall out of sync.
---
### REQ-SA-5: Consumer Delegation
All four call sites that previously maintained their own script trust enforcement now delegate to this component. The key behavioral changes per consumer:
| Consumer | Before | After |
|----------|--------|-------|
| **Template Engine** `ScriptCompiler.TryCompile` | Substring scan + brace-balance (advisory, bypassable) | `FindViolations` + real `Compile` against `ScriptCompileSurface` — authoritative gate |
| **Template Engine** `ValidationService.CheckExpressionSyntax` | Regex / brace scan | `FindViolations` + `Compile` against `TriggerCompileSurface` |
| **Site Runtime** `ScriptCompilationService.ValidateTrustModel` | Semantic resolver, no reflection-gateway hardening | Delegates to `FindViolations`; retains `CSharpScript.Compile` against real `ScriptGlobals` for execution |
| **Inbound API** `ForbiddenApiChecker.FindViolations` | Syntactic walker, forbade all `System.Diagnostics` | Thin shim delegating to `ScriptTrustValidator.FindViolations`; `System.Diagnostics` loosened to `.Process`-only |
| **Central UI** `ScriptAnalysisService` | Semantic + full compile, lenient threading | Delegates forbidden-API verdict and sources editor-marker deny-list from `ScriptTrustPolicy`; retains Test-Run execution host |
The static enforcement is **defence-in-depth**, not a true runtime sandbox. Scripts execute in-process; the denied API list prevents obvious escapes at compile time but does not provide the isolation guarantees of an out-of-process sandbox or a restricted `AssemblyLoadContext`. This caveat applies to all consumers.
---
## Dependencies
- **Commons**: Shared types referenced by `ScriptCompileSurface` and `TriggerCompileSurface` (e.g., `DataType`, attribute access types).
- **Microsoft.CodeAnalysis.CSharp.Scripting**: Roslyn scripting APIs used by `RoslynScriptCompiler` and `ScriptTrustValidator`.
- **Microsoft.CodeAnalysis.CSharp.Workspaces**: Roslyn workspace/syntax APIs used by `ScriptTrustValidator`.
No dependency on Akka.NET, ASP.NET Core, Entity Framework, or any other ScadaBridge component above Commons.
## Interactions
- **Template Engine (#1)**: Consumes `ScriptTrustValidator.FindViolations`, `RoslynScriptCompiler.Compile`, `ScriptCompileSurface`, and `TriggerCompileSurface` in the design-time deploy gate (`ScriptCompiler.TryCompile`) and expression syntax validator (`ValidationService.CheckExpressionSyntax`).
- **Site Runtime (#3)**: `ScriptCompilationService.ValidateTrustModel` delegates the trust verdict to `ScriptTrustValidator.FindViolations`; retains its own `CSharpScript.Compile` against the real `ScriptGlobals` for execution-time compilation.
- **Inbound API (#14)**: `ForbiddenApiChecker.FindViolations` is a thin shim over `ScriptTrustValidator.FindViolations`.
- **Central UI (#9)**: `ScriptAnalysisService` delegates the run-gate forbidden-API verdict and sources the editor-marker deny-list from `ScriptTrustPolicy`; retains the Test-Run execution host (`SandboxScriptHost`).
+4 -3
View File
@@ -392,12 +392,12 @@ Available to all Script Execution Actors and Alarm Execution Actors:
Scripts execute **in-process** with constrained access. The following restrictions are enforced at compilation and runtime:
- **Allowed**: Access to the Script Runtime API (GetAttribute, SetAttribute, CallScript, CallShared, ExternalSystem, Notify, Database, Tracking), standard C# language features, basic .NET types (collections, string manipulation, math, date/time).
- **Forbidden**: File system access (`System.IO`), process spawning (`System.Diagnostics.Process`), threading (`System.Threading` — except async/await), reflection (`System.Reflection`), raw network access (`System.Net.Sockets`, `System.Net.Http` — must use `ExternalSystem.Call`), assembly loading, unsafe code.
- **Allowed**: Access to the Script Runtime API (GetAttribute, SetAttribute, CallScript, CallShared, ExternalSystem, Notify, Database, Tracking), standard C# language features, basic .NET types (collections, string manipulation, math, date/time). `System.Diagnostics.Stopwatch`, `Debug`, and `Activity` are permitted.
- **Forbidden**: File system access (`System.IO`), process spawning (`System.Diagnostics.Process`), threading (`System.Threading` — except `Tasks`, `CancellationToken`, and `CancellationTokenSource`), reflection (`System.Reflection`), all raw network access (`System.Net` — must use `ExternalSystem.Call`), native interop (`System.Runtime.InteropServices`, `Microsoft.Win32`), assembly loading, unsafe code, `dynamic`, `Activator`.
- **Execution timeout**: Configurable per-script maximum execution time. Exceeding the timeout cancels the script and logs an error.
- **Memory**: Scripts share the host process memory. No per-script memory limit, but the execution timeout prevents runaway allocations.
These constraints are enforced by restricting the set of assemblies and namespaces available to the script compilation context.
The forbidden-API policy is defined authoritatively in `ScriptTrustPolicy` (Script Analysis component, #25). `ScriptCompilationService.ValidateTrustModel` delegates to `ScriptTrustValidator.FindViolations` for the trust verdict; the Site Runtime also performs a `CSharpScript.Compile` against the real `ScriptGlobals` for execution. This is defence-in-depth static enforcement, not a true runtime sandbox.
### Script Trust Boundary Auditing
@@ -466,6 +466,7 @@ Per Akka.NET best practices, internal actor communication uses **Tell** (fire-an
## Dependencies
- **Script Analysis (#25)**: `ScriptCompilationService.ValidateTrustModel` delegates the forbidden-API verdict to `ScriptTrustValidator.FindViolations`. The Site Runtime retains its own `CSharpScript.Compile` against the real `ScriptGlobals` for execution.
- **Data Connection Layer**: Provides tag value updates to Instance Actors. Receives write requests from Instance Actors. Also feeds Native Alarm Actors: connections implementing `IAlarmSubscribableConnection` (OPC UA A&C servers, MxAccess Gateway) deliver `NativeAlarmTransitionUpdate` events in response to a `SubscribeAlarmsRequest`, and signal `NativeAlarmSourceUnavailable` on connection loss.
- **Store-and-Forward Engine**: Handles reliable delivery for external system calls, cached database writes, and notifications submitted by scripts. For the notification category specifically, it forwards to the central cluster for delivery (not directly to SMTP). Owns the site-local operation tracking table that backs `Tracking.Status(id)`.
- **External System Gateway**: Provides external system method invocations for scripts.
@@ -153,7 +153,7 @@ Before a deployment is sent to a site, the Template Engine performs comprehensiv
- **Flattening**: The full template hierarchy resolves and flattens without errors.
- **Naming collision detection**: No duplicate attribute, alarm, or script names in the flattened configuration.
- **Script compilation**: All instance scripts and alarm on-trigger scripts are test-compiled and must compile without errors.
- **Script compilation and trust check**: All instance scripts and alarm on-trigger scripts are compiled via `ScriptCompiler.TryCompile`, which performs a real Roslyn type-checking compile (using `ScriptCompileSurface` from the Script Analysis component as the globals type) and an authoritative forbidden-API check (via `ScriptTrustValidator.FindViolations`). Scripts with compilation errors, type errors, or forbidden-API violations are rejected. This gate is authoritative — not advisory — meaning alias, `using static`, and `global::` bypasses are caught by semantic symbol resolution.
- **Alarm trigger references**: Alarm trigger definitions reference attributes that exist in the flattened configuration.
- **Script trigger references**: Script triggers (value change, conditional) reference attributes that exist in the flattened configuration.
- **Data connection binding completeness**: Every attribute with a data source reference has a data connection binding assigned on the instance, and the bound data connection name exists as a defined connection at the instance's site.
@@ -192,13 +192,14 @@ The same validation logic is available to Design users in the Central UI without
### Shared Script Validation
For shared scripts, pre-compilation validation is performed before deployment. Since shared scripts have no instance context, validation is limited to C# syntax and structural correctness.
For shared scripts, pre-compilation validation is performed before deployment. Since shared scripts have no instance context, validation uses `RoslynScriptCompiler.ParseDiagnostics` for syntax errors and `ScriptTrustValidator.FindViolations` for the forbidden-API check. Full type-checking compilation is not performed (no globals type is available), but syntax and trust violations are caught and reported.
## Dependencies
- **Configuration Database (MS SQL)**: Stores all templates, instances, areas, and their relationships.
- **Security & Auth**: Enforces Design role for template authoring, Deployment role for instance management.
- **Configuration Database (via IAuditService)**: All template and instance changes are audit logged.
- **Script Analysis (#25)**: `ScriptCompiler.TryCompile` uses `RoslynScriptCompiler` and `ScriptTrustValidator.FindViolations` from this component for the deploy-gate script compilation and forbidden-API check. `ValidationService.CheckExpressionSyntax` uses `ScriptTrustValidator` and `TriggerCompileSurface` for expression trigger validation.
## Interactions
@@ -12,6 +12,7 @@ using Microsoft.CodeAnalysis.Text;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using SharedTrust = ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.ScriptAnalysis;
@@ -56,18 +57,6 @@ public class ScriptAnalysisService
"System.Text",
"System.Threading.Tasks");
// Namespaces and types banned by the script trust model.
// Tasks live under System.Threading.Tasks and remain allowed.
private static readonly string[] ForbiddenNamespacePrefixes =
{
"System.IO",
"System.Diagnostics",
"System.Reflection",
"System.Net",
"System.Threading.Thread",
"System.Threading.Tasks.Sources",
};
private readonly ISharedScriptCatalog _sharedScripts;
private readonly IMemoryCache _cache;
private readonly IServiceProvider _services;
@@ -1152,14 +1141,22 @@ public class ScriptAnalysisService
}
/// <summary>
/// Finds every reference to a forbidden API — the documented script trust model,
/// see <see cref="ForbiddenNamespacePrefixes"/>. Identifiers are resolved against
/// the semantic model, so a forbidden type or member is caught however it is
/// written: bare (<c>File</c>), fully qualified
/// (<c>System.IO.File.WriteAllText</c>), or via an alias — while a user identifier
/// that merely shares a name with a forbidden type (<c>var File = …</c>) does not
/// false-positive. Used both for editor diagnostics and as the pre-execution
/// trust-model gate (see <see cref="EnforceTrustModel"/>).
/// Finds every reference to a forbidden API for the editor squiggle — the
/// documented script trust model, sourced from the shared
/// <see cref="SharedTrust.ScriptTrustPolicy.ForbiddenScopes"/> /
/// <see cref="SharedTrust.ScriptTrustPolicy.AllowedExceptions"/> deny-list via
/// <see cref="IsForbiddenName"/>. Identifiers are resolved against the semantic
/// model, so a forbidden type or member is caught however it is written: bare
/// (<c>File</c>), fully qualified (<c>System.IO.File.WriteAllText</c>), or via an
/// alias — while a user identifier that merely shares a name with a forbidden type
/// (<c>var File = …</c>) does not false-positive.
///
/// This is the position-aware, namespace-level editor advisory: it keeps the
/// line/column markers Monaco needs. The authoritative run verdict lives in
/// <see cref="EnforceTrustModel"/>, which delegates to the shared
/// <see cref="SharedTrust.ScriptTrustValidator"/> (and additionally covers
/// reflection-gateway members + dynamic/Activator hardening that the editor
/// advisory does not mark).
/// </summary>
private static IEnumerable<DiagnosticMarker> FindForbiddenApiUsages(SyntaxTree tree, SemanticModel model)
{
@@ -1208,25 +1205,45 @@ public class ScriptAnalysisService
/// <summary>
/// The forbidden namespace/type a symbol implicates, or null if it is allowed.
/// Checks the symbol's namespace and — for a type or member — the type's full
/// name, so an entry like <c>System.Threading.Thread</c> bans that exact type
/// while <c>System.Threading</c> (e.g. <c>CancellationToken</c>) stays allowed.
/// name. M3.5: the allowed-exception carve-out is applied at the WHOLE-SYMBOL
/// level (mirroring the shared <see cref="SharedTrust.ScriptTrustValidator"/>
/// semantic pass), so a type whose full name is an allowed exception
/// (e.g. <c>System.Threading.CancellationTokenSource</c>) is NOT flagged even
/// though its bare containing namespace <c>System.Threading</c> is a forbidden
/// root. Without the symbol-level check the namespace scope alone would
/// false-positive the allowed cancellation types.
/// </summary>
private static string? ForbiddenNameFor(ISymbol? symbol)
{
if (symbol == null) return null;
foreach (var name in QualifiedNamesOf(symbol))
if (IsForbiddenName(name))
return name;
return null;
var names = QualifiedNamesOf(symbol).ToList();
if (names.Count == 0) return null;
// Allowed exception on ANY of the symbol's qualified names wins outright —
// the rest of System.Threading stays forbidden, but Tasks +
// CancellationToken(Source) survive.
if (names.Any(n =>
SharedTrust.ScriptTrustPolicy.AllowedExceptions.Any(a => IsUnderScope(n, a))))
return null;
return names.FirstOrDefault(IsForbiddenName);
}
/// <summary>Fully-qualified names a symbol reference implicates for trust-model checking.</summary>
/// <summary>
/// Fully-qualified names a symbol reference implicates for trust-model checking.
/// M3.5: a bare namespace symbol is intentionally ignored — mirroring the shared
/// <see cref="SharedTrust.ScriptTrustValidator"/> semantic pass. A namespace name
/// on its own performs no action; harm requires referencing a type or member, so
/// flagging the bare <c>System.Threading</c> qualifier of an otherwise-allowed
/// type (<c>System.Threading.CancellationTokenSource</c>) would be a false
/// positive. The forbidden-<c>using</c>-directive path is checked separately on
/// the directive text, so namespace imports are still caught.
/// </summary>
private static IEnumerable<string> QualifiedNamesOf(ISymbol symbol)
{
switch (symbol)
{
case INamespaceSymbol { IsGlobalNamespace: false } ns:
yield return ns.ToDisplayString();
case INamespaceSymbol:
break;
case ITypeSymbol type:
if (type.ContainingNamespace is { IsGlobalNamespace: false } tn)
@@ -1249,23 +1266,74 @@ public class ScriptAnalysisService
? ns.ToDisplayString() + "." + type.Name
: type.Name;
private static bool IsForbiddenName(string qualifiedName) =>
ForbiddenNamespacePrefixes.Any(p =>
qualifiedName == p || qualifiedName.StartsWith(p + ".", StringComparison.Ordinal));
/// <summary>
/// M3.5: the forbidden-namespace verdict for the editor walker is sourced
/// from the shared <see cref="SharedTrust.ScriptTrustPolicy"/> — the single
/// deny-list the run gate (<see cref="ScriptTrustValidator"/>) also uses, so
/// the editor squiggle and the run gate agree on which namespaces are
/// forbidden. A name under a <see cref="SharedTrust.ScriptTrustPolicy.ForbiddenScopes"/>
/// root is forbidden UNLESS it is also under a
/// <see cref="SharedTrust.ScriptTrustPolicy.AllowedExceptions"/> entry
/// (async/await + cancellation tokens survive the System.Threading block).
/// </summary>
private static bool IsForbiddenName(string qualifiedName)
{
if (SharedTrust.ScriptTrustPolicy.AllowedExceptions.Any(a => IsUnderScope(qualifiedName, a)))
return false;
return SharedTrust.ScriptTrustPolicy.ForbiddenScopes.Any(f => IsUnderScope(qualifiedName, f));
}
private static bool IsUnderScope(string actual, string root) =>
actual.Equals(root, StringComparison.Ordinal)
|| actual.StartsWith(root + ".", StringComparison.Ordinal);
/// <summary>
/// Pre-execution trust-model gate (CentralUI-001). Returns the forbidden-API
/// markers (SCADA001/SCADA002) for a compiled script; an empty list means the
/// script is clear to run. This is a static semantic gate, not a process
/// sandbox — reflection-based indirection is still out of its reach; full
/// isolation would require running scripts in a separate constrained process.
/// Pre-execution trust-model gate (CentralUI-001). M3.5: the VERDICT is
/// delegated to the shared <see cref="SharedTrust.ScriptTrustValidator"/> —
/// the single source of truth the editor squiggle deny-list also derives from,
/// so the run gate and the editor agree. The shared validator additionally
/// enforces reflection-gateway members + dynamic/Activator hardening beyond the
/// editor's namespace-level advisory. An empty result means clear to run.
///
/// The compilation's own metadata references are forwarded to the shared
/// validator as extra references so its semantic pass resolves symbols against
/// the SAME metadata the script was compiled against (the full BCL surface,
/// including the SandboxScriptHost globals assembly). This keeps the gate's
/// resolution identical to the editor walker's — e.g. a bare <c>Process</c>
/// reached through <c>using System.Diagnostics;</c> resolves to
/// <c>System.Diagnostics.Process</c> and is caught. Forwarding references never
/// whitelists anything: the deny-list still applies regardless of what is
/// referenced.
///
/// The shared validator returns positionless messages; the run gate doesn't
/// need precise positions (only the verdict), so each violation is surfaced as a
/// single error marker anchored at the script start. This is a static semantic
/// gate, not a process sandbox — full isolation would require a separate
/// constrained process.
/// </summary>
private static IReadOnlyList<DiagnosticMarker> EnforceTrustModel(Compilation compilation)
{
var tree = compilation.SyntaxTrees.FirstOrDefault();
if (tree == null) return Array.Empty<DiagnosticMarker>();
var model = compilation.GetSemanticModel(tree);
return FindForbiddenApiUsages(tree, model).ToList();
var violations = SharedTrust.ScriptTrustValidator.FindViolations(
tree.ToString(), compilation.References);
if (violations.Count == 0) return Array.Empty<DiagnosticMarker>();
// Positionless verdict → one error marker per violation at the script
// start. Code SCADA002 (forbidden API reference) matches the editor's
// semantic-marker code, so existing gate assertions ("SCADA001"/"SCADA002")
// continue to hold.
return violations
.Select(v => new DiagnosticMarker(
Severity: 8,
StartLineNumber: 1,
StartColumn: 1,
EndLineNumber: 1,
EndColumn: 2,
Message: $"{v} — not allowed in scripts (script trust model).",
Code: "SCADA002"))
.ToList();
}
private static CompletionItem ToCompletionItem(ISymbol symbol)
@@ -23,6 +23,7 @@
<ItemGroup>
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.Commons/ZB.MOM.WW.ScadaBridge.Commons.csproj" />
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.csproj" />
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.Security/ZB.MOM.WW.ScadaBridge.Security.csproj" />
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.TemplateEngine/ZB.MOM.WW.ScadaBridge.TemplateEngine.csproj" />
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.DeploymentManager/ZB.MOM.WW.ScadaBridge.DeploymentManager.csproj" />
@@ -1,6 +1,4 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
namespace ZB.MOM.WW.ScadaBridge.InboundAPI;
@@ -8,89 +6,30 @@ namespace ZB.MOM.WW.ScadaBridge.InboundAPI;
/// InboundAPI-005: Enforces the ScadaBridge script trust model on inbound API method
/// scripts before they are compiled into executable handlers.
///
/// The trust model (CLAUDE.md, Akka.NET conventions) forbids scripts from reaching
/// <c>System.IO</c>, <c>System.Diagnostics.Process</c>, <c>System.Threading</c>,
/// <c>System.Reflection</c>, and raw network APIs. Roslyn scripting performs no
/// API allow/deny-listing — restricting default imports is a convenience, not a
/// sandbox — so a script can fully-qualify any referenced type. This static check
/// walks the script syntax tree and rejects any reference to a forbidden namespace,
/// whether reached through a <c>using</c> directive or a fully-qualified name.
/// This class is now a thin shim that delegates to the shared, authoritative
/// <see cref="ScriptTrustValidator.FindViolations"/> implemented in
/// <c>ZB.MOM.WW.ScadaBridge.ScriptAnalysis</c> (M3.4). The unified validator runs
/// both a semantic symbol pass (catching alias / <c>global::</c> / <c>using static</c>
/// escapes) and the reflection-gateway + <c>dynamic</c> / <c>Activator</c> syntactic
/// hardening that previously lived exclusively in this file.
///
/// <para>
/// InboundAPI-015: a purely namespace-textual deny-list is bypassable because
/// reflection is reachable through members of <em>permitted</em> types that never
/// spell a forbidden namespace, e.g.
/// <c>typeof(string).Assembly.GetType("System.IO.File")</c>. The walker therefore
/// also rejects a curated set of reflection-gateway member names (<c>GetType</c>,
/// <c>Assembly</c>, <c>GetMethod</c>, <c>InvokeMember</c>, <c>CreateInstance</c>, …)
/// and the <c>dynamic</c> keyword. This is hardening of a best-effort static check,
/// <strong>not</strong> a true sandbox — a determined script author may still find
/// a vector the syntax walker cannot see (see the security notes in
/// <c>code-reviews/InboundAPI/findings.md</c>, InboundAPI-015). The check is
/// defence-in-depth; genuine containment needs a runtime boundary (restricted
/// <c>AssemblyLoadContext</c> / curated reference set / out-of-process sandbox).
/// <c>typeof(string).Assembly.GetType("System.IO.File")</c>. The shared validator
/// handles this with both semantic resolution and reflection-gateway member
/// hardening — <c>GetType</c>, <c>Assembly</c>, <c>GetMethod</c>, <c>InvokeMember</c>,
/// <c>CreateInstance</c>, and the <c>dynamic</c> keyword are all rejected. This
/// remains hardening of a best-effort static check, <strong>not</strong> a true sandbox
/// (see the security notes in <c>code-reviews/InboundAPI/findings.md</c>,
/// InboundAPI-015). The check is defence-in-depth; genuine containment needs a
/// runtime boundary (restricted <c>AssemblyLoadContext</c> / curated reference set /
/// out-of-process sandbox).
/// </para>
/// </summary>
public static class ForbiddenApiChecker
{
/// <summary>
/// Namespace prefixes the trust model forbids. A script segment matches if it is
/// equal to one of these or is a child namespace of it.
/// </summary>
private static readonly string[] ForbiddenNamespaces =
{
"System.IO",
"System.Diagnostics", // covers Process
"System.Threading", // Task/Tasks is explicitly re-allowed below
"System.Reflection",
"System.Net", // raw network (Sockets, HttpClient, etc.)
"System.Runtime.InteropServices",
"Microsoft.Win32",
};
/// <summary>
/// Namespaces that would otherwise be caught by a forbidden prefix but are
/// required for normal async script authoring and carry no host-access risk.
/// </summary>
private static readonly string[] AllowedExceptions =
{
"System.Threading.Tasks",
};
/// <summary>
/// InboundAPI-015: member names that are reflection gateways. Reaching any of
/// these — even off a permitted type such as <c>typeof(string)</c> or a plain
/// <c>string</c> — lets a script escape the namespace deny-list (obtain an
/// arbitrary <c>Type</c>, load an assembly, late-bind a method). They are
/// rejected regardless of the receiver expression. <c>Invoke</c> is deliberately
/// excluded because <c>Action</c>/<c>Func</c> delegate invocation is legitimate;
/// the reflection <c>MethodInfo.Invoke</c> path is already cut off by rejecting
/// the <c>GetMethod</c>/<c>GetConstructor</c> that produces the <c>MethodInfo</c>.
/// </summary>
private static readonly HashSet<string> ForbiddenMemberNames = new(StringComparer.Ordinal)
{
"GetType", // object.GetType() / Type.GetType(string) — yields a System.Type
"GetTypeInfo", // -> TypeInfo (reflection)
"Assembly", // Type.Assembly — yields a System.Reflection.Assembly
"Module", // Type.Module / MethodBase.Module
"CreateInstance", // Activator.CreateInstance / Assembly.CreateInstance
"InvokeMember", // Type.InvokeMember — late-bound dispatch
"GetMethod",
"GetMethods",
"GetConstructor",
"GetConstructors",
"GetField",
"GetFields",
"GetProperty",
"GetProperties",
"GetMember",
"GetMembers",
"GetRuntimeMethod",
"GetRuntimeMethods",
"MethodHandle", // RuntimeMethodHandle escape
"TypeHandle",
};
/// <summary>
/// Analyses the script source and returns the list of trust-model violations.
/// An empty list means the script is acceptable.
@@ -102,111 +41,6 @@ public static class ForbiddenApiChecker
if (string.IsNullOrWhiteSpace(scriptCode))
return Array.Empty<string>();
var tree = CSharpSyntaxTree.ParseText(
scriptCode,
new CSharpParseOptions(kind: SourceCodeKind.Script));
var walker = new ForbiddenApiWalker();
walker.Visit(tree.GetRoot());
return walker.Violations;
}
private static bool IsForbidden(string dottedName)
{
foreach (var allowed in AllowedExceptions)
{
if (dottedName == allowed || dottedName.StartsWith(allowed + ".", StringComparison.Ordinal))
return false;
}
foreach (var forbidden in ForbiddenNamespaces)
{
if (dottedName == forbidden || dottedName.StartsWith(forbidden + ".", StringComparison.Ordinal))
return true;
}
return false;
}
private sealed class ForbiddenApiWalker : CSharpSyntaxWalker
{
private readonly List<string> _violations = new();
/// <summary>Gets the accumulated list of trust-model violation descriptions.</summary>
public IReadOnlyList<string> Violations => _violations;
/// <inheritdoc />
public override void VisitUsingDirective(UsingDirectiveSyntax node)
{
if (node.Name is not null && IsForbidden(node.Name.ToString()))
_violations.Add($"forbidden namespace import '{node.Name}'");
base.VisitUsingDirective(node);
}
/// <inheritdoc />
public override void VisitQualifiedName(QualifiedNameSyntax node)
{
// Check the longest qualified name; do not descend so a single
// System.IO.File reference is reported once, not three times.
var text = node.ToString();
if (IsForbidden(text))
{
_violations.Add($"forbidden type reference '{text}'");
return;
}
base.VisitQualifiedName(node);
}
/// <inheritdoc />
public override void VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
// Catches fully-qualified expressions such as System.IO.File.Delete(...).
var text = node.ToString();
if (IsForbidden(text))
{
_violations.Add($"forbidden API access '{text}'");
return;
}
// InboundAPI-015: reject reflection-gateway members regardless of the
// receiver. typeof(string).Assembly.GetType("System.IO.File") never
// spells a forbidden namespace, but '.Assembly' and '.GetType' do
// appear here as the accessed member name.
var memberName = node.Name.Identifier.ValueText;
if (ForbiddenMemberNames.Contains(memberName))
{
_violations.Add($"forbidden reflection member access '.{memberName}'");
// Still descend: the receiver may contain a further violation.
}
base.VisitMemberAccessExpression(node);
}
/// <inheritdoc />
public override void VisitIdentifierName(IdentifierNameSyntax node)
{
// InboundAPI-015: 'dynamic' widens late-bound member access that the
// static walker cannot see through — reject its use outright. The
// 'dynamic' contextual keyword surfaces as an identifier name.
if (node.Identifier.ValueText == "dynamic")
{
_violations.Add("forbidden use of the 'dynamic' keyword");
return;
}
// InboundAPI-015: a bare reference to the reflection entry-point types
// (e.g. 'Activator', 'Type') as an identifier. 'Activator' has no
// non-reflection use; flag it. ('Type' as an identifier is too broad
// to flag here — the gateway members above already cut off its use.)
if (node.Identifier.ValueText == "Activator")
{
_violations.Add("forbidden reflection type reference 'Activator'");
return;
}
base.VisitIdentifierName(node);
}
return ScriptTrustValidator.FindViolations(scriptCode);
}
}
@@ -17,6 +17,7 @@
<!-- AuditWriteMiddleware reads AuditLogOptions.InboundMaxBytes to bound
per-request request/response audit capture at the source. -->
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.AuditLog/ZB.MOM.WW.ScadaBridge.AuditLog.csproj" />
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.csproj" />
</ItemGroup>
<ItemGroup>
@@ -0,0 +1,83 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
namespace ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
/// <summary>
/// M3.1: the single authoritative Roslyn compile gate. Ported from the
/// SiteRuntime <c>ScriptCompilationService.CompileCore</c>, but returns
/// diagnostic messages rather than a compiled <c>Script</c> delegate — this is
/// the design-time gate (the deploy-time validation that previously relied on
/// the FAKE substring + brace-balance check in
/// <c>TemplateEngine/Validation/ScriptCompiler.cs</c>), which needs to know
/// whether the script <em>compiles</em>, not to execute it.
/// </summary>
public static class RoslynScriptCompiler
{
/// <summary>
/// Parses the script as C# script source and returns syntax-error diagnostic
/// messages (severity Error only). Empty list means the script parses.
/// </summary>
/// <param name="code">The C# script source to parse.</param>
/// <returns>Error-severity parse diagnostic messages; empty if the script parses.</returns>
public static IReadOnlyList<string> ParseDiagnostics(string code)
{
var tree = CSharpSyntaxTree.ParseText(
code, new CSharpParseOptions(kind: SourceCodeKind.Script));
return tree.GetDiagnostics()
.Where(d => d.Severity == DiagnosticSeverity.Error)
.Select(d => d.GetMessage())
.ToList();
}
/// <summary>
/// Compiles the script against the trust-model references and imports and
/// returns error-severity compilation diagnostic messages. Empty list means
/// the script compiles cleanly against <paramref name="globalsType"/>.
/// </summary>
/// <param name="code">The C# script source to compile.</param>
/// <param name="globalsType">
/// Optional globals type the script binds against — e.g.
/// <c>ScriptCompileSurface</c> for instance/shared scripts or
/// <c>TriggerCompileSurface</c> for trigger expressions.
/// </param>
/// <param name="extraReferences">Optional additional metadata references.</param>
/// <param name="extraImports">Optional additional namespace imports.</param>
/// <returns>Error-severity compile diagnostic messages; empty if the script compiles.</returns>
public static IReadOnlyList<string> Compile(
string code,
Type? globalsType = null,
IEnumerable<MetadataReference>? extraReferences = null,
IEnumerable<string>? extraImports = null)
{
try
{
var references = ScriptTrustPolicy.DefaultReferences.ToList();
if (extraReferences != null)
references.AddRange(extraReferences);
var imports = ScriptTrustPolicy.DefaultImports.AsEnumerable();
if (extraImports != null)
imports = imports.Concat(extraImports);
var options = ScriptOptions.Default
.WithReferences(references)
.WithImports(imports);
var script = CSharpScript.Create<object?>(code, options, globalsType);
var diagnostics = script.Compile();
return diagnostics
.Where(d => d.Severity == DiagnosticSeverity.Error)
.Select(d => d.GetMessage())
.ToList();
}
catch (Exception ex)
{
return [$"Compilation exception: {ex.Message}"];
}
}
}
@@ -0,0 +1,212 @@
using System.Data.Common;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Notification;
using ZB.MOM.WW.ScadaBridge.Commons.Types;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Scripts;
namespace ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
/// <summary>
/// M3.1: a <b>compile-only</b> globals type that mirrors the real SiteRuntime
/// <c>ScriptGlobals</c> (+ <c>ScriptRuntimeContext</c> helper surface)
/// member-for-member, so a real instance / shared / on-trigger-handler script
/// BINDS against it at design time. It is NEVER executed — every member body
/// throws <see cref="NotSupportedException"/> or returns <c>default</c>. The
/// design-time deploy gate (M3.5) compiles candidate scripts against this type
/// via <see cref="RoslynScriptCompiler.Compile(string, Type, System.Collections.Generic.IEnumerable{Microsoft.CodeAnalysis.MetadataReference}, System.Collections.Generic.IEnumerable{string})"/>
/// to catch undefined symbols and signature mismatches without touching the
/// site runtime.
///
/// <para>
/// Keeping this surface faithful is enforced by the
/// <c>RoslynScriptCompilerTests</c> "representative real script" corpus — if a
/// member or signature drifts from the runtime <c>ScriptGlobals</c>, that test
/// fails.
/// </para>
/// </summary>
public sealed class ScriptCompileSurface
{
private const string CompileOnly = "compile-only surface";
/// <summary>Mirrors <c>ScriptGlobals.Instance</c>.</summary>
public CompileInstance Instance { get; set; } = null!;
/// <summary>Mirrors <c>ScriptGlobals.Parameters</c>.</summary>
public ScriptParameters Parameters { get; set; } = new();
/// <summary>Mirrors <c>ScriptGlobals.CancellationToken</c>.</summary>
public CancellationToken CancellationToken { get; set; }
/// <summary>Mirrors <c>ScriptGlobals.Alarm</c>.</summary>
public AlarmContext? Alarm { get; set; }
/// <summary>Mirrors <c>ScriptGlobals.Scope</c>.</summary>
public ScriptScope Scope { get; set; } = ScriptScope.Root;
/// <summary>Mirrors <c>ScriptGlobals.ExternalSystem</c> (delegates to Instance).</summary>
public CompileExternalSystem ExternalSystem => Instance.ExternalSystem;
/// <summary>Mirrors <c>ScriptGlobals.Database</c>.</summary>
public CompileDatabase Database => Instance.Database;
/// <summary>Mirrors <c>ScriptGlobals.Notify</c>.</summary>
public CompileNotify Notify => Instance.Notify;
/// <summary>Mirrors <c>ScriptGlobals.Scripts</c>.</summary>
public CompileScripts Scripts => Instance.Scripts;
/// <summary>Mirrors <c>ScriptGlobals.Attributes</c>.</summary>
public CompileAttributeAccessor Attributes => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>ScriptGlobals.Children</c>.</summary>
public CompileChildrenAccessor Children => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>ScriptGlobals.Parent</c>.</summary>
public CompileCompositionAccessor? Parent => throw new NotSupportedException(CompileOnly);
/// <summary>Compile-only mirror of <c>ScriptRuntimeContext</c> (the <c>Instance</c> global).</summary>
public sealed class CompileInstance
{
/// <summary>Mirrors <c>ScriptRuntimeContext.GetAttribute</c>.</summary>
public Task<object?> GetAttribute(string attributeName) => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>ScriptRuntimeContext.SetAttribute</c>.</summary>
public Task SetAttribute(string attributeName, string value) => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>ScriptRuntimeContext.CallScript</c>.</summary>
public Task<object?> CallScript(string scriptName, object? parameters = null) => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>ScriptRuntimeContext.ExternalSystem</c>.</summary>
public CompileExternalSystem ExternalSystem => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>ScriptRuntimeContext.Database</c>.</summary>
public CompileDatabase Database => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>ScriptRuntimeContext.Notify</c>.</summary>
public CompileNotify Notify => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>ScriptRuntimeContext.Scripts</c>.</summary>
public CompileScripts Scripts => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>ScriptRuntimeContext.Tracking</c>.</summary>
public CompileTracking Tracking => throw new NotSupportedException(CompileOnly);
}
/// <summary>Compile-only mirror of <c>ScriptRuntimeContext.ExternalSystemHelper</c>.</summary>
public sealed class CompileExternalSystem
{
/// <summary>Mirrors <c>ExternalSystemHelper.Call</c>.</summary>
public Task<ExternalCallResult> Call(
string systemName,
string methodName,
IReadOnlyDictionary<string, object?>? parameters = null,
CancellationToken cancellationToken = default)
=> throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>ExternalSystemHelper.CachedCall</c>.</summary>
public Task<TrackedOperationId> CachedCall(
string systemName,
string methodName,
IReadOnlyDictionary<string, object?>? parameters = null,
CancellationToken cancellationToken = default)
=> throw new NotSupportedException(CompileOnly);
}
/// <summary>Compile-only mirror of <c>ScriptRuntimeContext.DatabaseHelper</c>.</summary>
public sealed class CompileDatabase
{
/// <summary>Mirrors <c>DatabaseHelper.Connection</c>.</summary>
public Task<DbConnection> Connection(string name, CancellationToken cancellationToken = default)
=> throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>DatabaseHelper.CachedWrite</c>.</summary>
public Task<TrackedOperationId> CachedWrite(
string name,
string sql,
IReadOnlyDictionary<string, object?>? parameters = null,
CancellationToken cancellationToken = default)
=> throw new NotSupportedException(CompileOnly);
}
/// <summary>Compile-only mirror of <c>ScriptRuntimeContext.NotifyHelper</c>.</summary>
public sealed class CompileNotify
{
/// <summary>Mirrors <c>NotifyHelper.To</c>.</summary>
public CompileNotifyTarget To(string listName) => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>NotifyHelper.Status</c>.</summary>
public Task<NotificationDeliveryStatus> Status(string notificationId) => throw new NotSupportedException(CompileOnly);
}
/// <summary>Compile-only mirror of <c>ScriptRuntimeContext.NotifyTarget</c>.</summary>
public sealed class CompileNotifyTarget
{
/// <summary>Mirrors <c>NotifyTarget.Send</c>.</summary>
public Task<string> Send(string subject, string message, CancellationToken cancellationToken = default)
=> throw new NotSupportedException(CompileOnly);
}
/// <summary>Compile-only mirror of <c>ScriptRuntimeContext.ScriptCallHelper</c>.</summary>
public sealed class CompileScripts
{
/// <summary>Mirrors <c>ScriptCallHelper.CallShared</c>.</summary>
public Task<object?> CallShared(
string scriptName,
object? parameters = null,
CancellationToken cancellationToken = default)
=> throw new NotSupportedException(CompileOnly);
}
/// <summary>Compile-only mirror of <c>ScriptRuntimeContext.TrackingHelper</c>.</summary>
public sealed class CompileTracking
{
/// <summary>Mirrors <c>TrackingHelper.Status</c>.</summary>
public Task<TrackingStatusSnapshot?> Status(
TrackedOperationId trackedOperationId,
CancellationToken cancellationToken = default)
=> throw new NotSupportedException(CompileOnly);
}
/// <summary>Compile-only mirror of <c>AttributeAccessor</c>.</summary>
public sealed class CompileAttributeAccessor
{
/// <summary>Mirrors <c>AttributeAccessor.this[string]</c>.</summary>
public object? this[string key]
{
get => throw new NotSupportedException(CompileOnly);
set => throw new NotSupportedException(CompileOnly);
}
/// <summary>Mirrors <c>AttributeAccessor.GetAsync</c>.</summary>
public Task<object?> GetAsync(string key) => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>AttributeAccessor.SetAsync</c>.</summary>
public Task SetAsync(string key, object? value) => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>AttributeAccessor.Resolve</c>.</summary>
public string Resolve(string key) => throw new NotSupportedException(CompileOnly);
}
/// <summary>Compile-only mirror of <c>ChildrenAccessor</c>.</summary>
public sealed class CompileChildrenAccessor
{
/// <summary>Mirrors <c>ChildrenAccessor.this[string]</c>.</summary>
public CompileCompositionAccessor this[string compositionName] => throw new NotSupportedException(CompileOnly);
}
/// <summary>Compile-only mirror of <c>CompositionAccessor</c>.</summary>
public sealed class CompileCompositionAccessor
{
/// <summary>Mirrors <c>CompositionAccessor.Attributes</c>.</summary>
public CompileAttributeAccessor Attributes => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>CompositionAccessor.CallScript</c>.</summary>
public Task<object?> CallScript(string scriptName, object? parameters = null) => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>CompositionAccessor.ResolveScript</c>.</summary>
public string ResolveScript(string scriptName) => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>CompositionAccessor.Path</c>.</summary>
public string Path => throw new NotSupportedException(CompileOnly);
}
}
@@ -0,0 +1,196 @@
using System.IO;
using System.Reflection;
using Microsoft.CodeAnalysis;
using ZB.MOM.WW.ScadaBridge.Commons.Types;
namespace ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
/// <summary>
/// M3.1: the single authoritative source of truth for the ScadaBridge script
/// trust model. Previously the forbidden-API deny-list, allowed exceptions,
/// reflection-gateway member names, default metadata references, and default
/// imports were duplicated (and disagreed) across four call sites — the
/// SiteRuntime <c>ScriptCompilationService</c>, the InboundAPI
/// <c>ForbiddenApiChecker</c>, and the design-time deploy gate. This class
/// fuses them into one collection set that <see cref="ScriptTrustValidator"/>
/// and <see cref="RoslynScriptCompiler"/> consume; the four consumers delegate
/// here in later tasks (M3.2–M3.5).
///
/// <para>
/// The deny-list is intentionally the UNION of the two existing
/// implementations — it forbids <c>System.Diagnostics.Process</c> (not all of
/// <c>System.Diagnostics</c>, so <c>Stopwatch</c> stays allowed), all of
/// <c>System.Net</c>, all of <c>System.Threading</c> except Tasks /
/// CancellationToken(Source), plus <c>System.Reflection</c>,
/// <c>System.Runtime.InteropServices</c>, and <c>Microsoft.Win32</c>.
/// </para>
/// </summary>
public static class ScriptTrustPolicy
{
/// <summary>
/// Forbidden API roots. Each entry is matched as a prefix against the
/// resolved symbol's containing namespace and fully-qualified containing
/// type — an entry may name a whole namespace ("System.IO") or a single
/// type ("System.Diagnostics.Process").
/// </summary>
public static readonly string[] ForbiddenScopes =
[
"System.IO",
"System.Diagnostics.Process",
"System.Threading",
"System.Reflection",
"System.Net",
"System.Runtime.InteropServices",
"Microsoft.Win32",
];
/// <summary>
/// Specific namespaces/types allowed even though they sit under a forbidden
/// root. async/await and cancellation tokens are OK despite
/// <c>System.Threading</c> being blocked.
/// </summary>
public static readonly string[] AllowedExceptions =
[
"System.Threading.Tasks",
"System.Threading.CancellationToken",
"System.Threading.CancellationTokenSource",
];
/// <summary>
/// Member names that are reflection gateways. Reaching any of these — even
/// off a permitted type such as <c>typeof(string)</c> — lets a script
/// escape the namespace deny-list (obtain an arbitrary <c>Type</c>, load an
/// assembly, late-bind a method). They are rejected regardless of the
/// receiver expression.
/// </summary>
public static readonly HashSet<string> ReflectionGatewayMembers = new(StringComparer.Ordinal)
{
"GetType",
"GetTypeInfo",
"Assembly",
"Module",
"CreateInstance",
"InvokeMember",
"GetMethod",
"GetMethods",
"GetConstructor",
"GetConstructors",
"GetField",
"GetFields",
"GetProperty",
"GetProperties",
"GetMember",
"GetMembers",
"GetRuntimeMethod",
"GetRuntimeMethods",
"MethodHandle",
"TypeHandle",
};
/// <summary>
/// Bare identifiers that are forbidden outright. <c>dynamic</c> widens
/// late-bound member access the static walker cannot see through;
/// <c>Activator</c> has no non-reflection use.
/// </summary>
public static readonly HashSet<string> ForbiddenIdentifiers = new(StringComparer.Ordinal)
{
"dynamic",
"Activator",
};
/// <summary>
/// Assemblies referenced by compiled scripts. Shared between the Roslyn
/// scripting options and the semantic-analysis compilation built for trust
/// validation, so the validator resolves symbols against exactly the same
/// metadata the script is compiled against.
/// </summary>
public static readonly IReadOnlyList<Assembly> DefaultAssemblies =
[
typeof(object).Assembly,
typeof(System.Linq.Enumerable).Assembly,
typeof(System.Math).Assembly,
typeof(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo).Assembly,
typeof(DynamicJsonElement).Assembly,
];
/// <summary>
/// Metadata references for the trust-validation semantic compilation and
/// the design-time script compilation.
/// </summary>
public static readonly IReadOnlyList<MetadataReference> DefaultReferences =
DefaultAssemblies
.Select(a => (MetadataReference)MetadataReference.CreateFromFile(a.Location))
.ToList();
/// <summary>
/// The full trusted-platform reference set used ONLY by
/// <see cref="ScriptTrustValidator"/>'s semantic analysis — NOT by
/// <see cref="RoslynScriptCompiler"/>. Unlike <see cref="DefaultReferences"/>
/// (the minimal, runtime-fidelity set used to decide script <i>validity</i>,
/// which must mirror exactly what the site runtime compiles against), the
/// trust validator references the entire framework so that EVERY type a
/// script names resolves to a real symbol and is judged by its true
/// namespace. Without this, a forbidden TYPE that sits inside an ALLOWED
/// namespace and is reached as a bare identifier — the only such case in the
/// policy being <c>System.Diagnostics.Process</c> via
/// <c>using System.Diagnostics;</c> — would not resolve against a minimal
/// reference set and would slip past the semantic pass (still blocked
/// downstream as an undefined-symbol compile error, but with a misleading
/// message). Referencing the full framework lets the validator flag it
/// authoritatively as a forbidden API. Enriching the analysis reference set
/// can only IMPROVE detection — the verdict is by namespace/type, so more
/// resolvable symbols means more correct verdicts, never a false allow.
/// </summary>
public static readonly IReadOnlyList<MetadataReference> AnalysisReferences = BuildAnalysisReferences();
private static IReadOnlyList<MetadataReference> BuildAnalysisReferences()
{
var byPath = new Dictionary<string, MetadataReference>(StringComparer.OrdinalIgnoreCase);
// Trusted platform assemblies = the full framework reference set the host
// started with; lets the semantic pass resolve any BCL type.
if (AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") is string tpa)
{
foreach (var path in tpa.Split(Path.PathSeparator))
{
if (path.Length == 0 ||
!path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
byPath.ContainsKey(path) ||
!File.Exists(path))
{
continue;
}
try { byPath[path] = MetadataReference.CreateFromFile(path); }
catch { /* skip an unreadable assembly rather than fail validation */ }
}
}
// Ensure app assemblies the script API surface needs are present even if
// not in the TPA list (e.g. Commons / DynamicJsonElement).
foreach (var asm in DefaultAssemblies)
{
var loc = asm.Location;
if (loc.Length == 0 || byPath.ContainsKey(loc) || !File.Exists(loc))
continue;
try { byPath[loc] = MetadataReference.CreateFromFile(loc); }
catch { /* ignore */ }
}
// Fallback to the minimal set if the TPA list was unavailable (e.g. a
// single-file/AOT host) so validation still functions.
return byPath.Count > 0 ? byPath.Values.ToList() : DefaultReferences;
}
/// <summary>
/// Default namespace imports made available to compiled scripts.
/// </summary>
public static readonly string[] DefaultImports =
[
"System",
"System.Collections.Generic",
"System.Linq",
"System.Threading.Tasks",
];
}
@@ -0,0 +1,397 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
/// <summary>
/// M3.1: the single authoritative script-trust validator, fusing the two
/// previously-divergent implementations:
///
/// <list type="number">
/// <item>
/// <b>Semantic symbol analysis</b> (ported from the SiteRuntime
/// <c>ScriptCompilationService.ValidateTrustModel</c>): the script is parsed and
/// a semantic model built; every identifier / type reference / member access /
/// object creation is resolved to its symbol and the symbol's containing
/// namespace + type are checked against <see cref="ScriptTrustPolicy.ForbiddenScopes"/>.
/// This catches forbidden types regardless of how they are written —
/// <c>global::</c> prefixes, aliases, <c>using static</c>, transitively-imported
/// namespaces — because it inspects the resolved symbol, not the spelling.
/// </item>
/// <item>
/// <b>Reflection-gateway + dynamic/Activator hardening</b> (ported from the
/// InboundAPI <c>ForbiddenApiChecker.ForbiddenApiWalker</c>): a syntactic walk
/// that rejects any member access whose accessed member is in
/// <see cref="ScriptTrustPolicy.ReflectionGatewayMembers"/> (regardless of
/// receiver — so <c>typeof(string).Assembly.GetType("System.IO.File")</c> is
/// caught even though it never spells a forbidden namespace), any identifier in
/// <see cref="ScriptTrustPolicy.ForbiddenIdentifiers"/> (<c>dynamic</c>,
/// <c>Activator</c>), and forbidden <c>using</c>/qualified-name spellings.
/// </item>
/// </list>
///
/// <para>
/// Keeping BOTH passes is deliberate: the semantic pass catches alias /
/// <c>using static</c> / <c>global::</c> escapes; the syntactic pass catches
/// reflection reached through members of <em>permitted</em> types. Neither pass
/// is a true sandbox — this is best-effort defence-in-depth; genuine containment
/// needs a runtime boundary.
/// </para>
///
/// <para>
/// A forbidden type reference inside <c>nameof(...)</c> (e.g.
/// <c>nameof(System.IO.File)</c>) is deliberately flagged: this is
/// conservative/fail-safe — <c>nameof</c> is rare in scripts and a script has
/// no business naming a forbidden type even there, so we prefer fail-safe over
/// adding special-case suppression logic to a security trust boundary.
/// </para>
/// </summary>
public static class ScriptTrustValidator
{
/// <summary>
/// Analyses the script source and returns the deduped, sorted list of
/// trust-model violations. An empty list means the script is clean.
/// </summary>
/// <param name="code">The C# script source to analyse.</param>
/// <param name="extraReferences">
/// Optional additional metadata references to add to
/// <see cref="ScriptTrustPolicy.DefaultReferences"/> for semantic
/// resolution — e.g. the compile-surface globals assembly so a script
/// referencing the API surface resolves cleanly. Forbidden references are
/// NOT added here (a script can't reach a forbidden API just because the
/// assembly is referenced; the deny-list still applies).
/// </param>
/// <returns>A list of trust-model violation messages; empty if the script is clean.</returns>
public static IReadOnlyList<string> FindViolations(
string code,
IEnumerable<MetadataReference>? extraReferences = null)
{
if (string.IsNullOrWhiteSpace(code))
return Array.Empty<string>();
var tree = CSharpSyntaxTree.ParseText(
code, new CSharpParseOptions(kind: SourceCodeKind.Script));
var root = tree.GetRoot();
// Deduplicate so a forbidden symbol used many times is reported once but
// distinct forbidden symbols are all reported.
var violations = new SortedSet<string>(StringComparer.Ordinal);
// ---- Pass 1: semantic symbol analysis (ported from SiteRuntime) ----
// Use the full trusted-platform reference set (not the minimal
// runtime-fidelity DefaultReferences) so EVERY type a script names
// resolves and is judged by its true namespace — closing the
// forbidden-type-in-allowed-namespace blind spot (e.g. a bare
// System.Diagnostics.Process via `using System.Diagnostics;`).
var references = ScriptTrustPolicy.AnalysisReferences.ToList();
if (extraReferences != null)
references.AddRange(extraReferences);
var compilation = CSharpCompilation.CreateScriptCompilation(
"TrustValidation",
tree,
references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
var model = compilation.GetSemanticModel(tree);
foreach (var node in root.DescendantNodes())
{
// Only inspect nodes that name a type or member; skip declarations,
// string literals and comments entirely. Member-access and
// qualified-name parents are evaluated as a whole, so their nested
// name parts are skipped.
if (node is not (SimpleNameSyntax or MemberAccessExpressionSyntax
or QualifiedNameSyntax or ObjectCreationExpressionSyntax))
{
continue;
}
var info = model.GetSymbolInfo(node);
var symbol = info.Symbol ?? info.CandidateSymbols.FirstOrDefault();
// The set of fully-qualified scopes this reference touches: the
// resolved symbol's containing namespace and type, or — when the
// symbol could not be resolved (a type from an unreferenced
// assembly) — the syntactic fully-qualified name written in source
// as a safe fallback.
var scopes = symbol != null
? GetSymbolScopes(symbol)
: GetSyntacticScopes(node);
if (scopes.Count == 0)
continue;
var forbidden = ScriptTrustPolicy.ForbiddenScopes.FirstOrDefault(
f => scopes.Any(s => IsUnderScope(s, f)));
if (forbidden == null)
continue;
// Allow specific exception namespaces/types (async/await, cancellation).
if (scopes.Any(s => ScriptTrustPolicy.AllowedExceptions.Any(a => IsUnderScope(s, a))))
continue;
var name = symbol?.Name ?? node.ToString();
violations.Add($"Forbidden API reference: '{forbidden}' ({scopes[0]}.{name})");
}
// ---- Pass 2: reflection-gateway + dynamic/Activator hardening
// (ported from InboundAPI) ----
var walker = new HardeningWalker(violations);
walker.Visit(root);
return violations.ToList();
}
/// <summary>
/// Returns the fully-qualified scopes a resolved symbol belongs to — its
/// containing namespace and, for a type or member, the fully-qualified
/// containing type. A bare namespace symbol is intentionally ignored: a
/// namespace name on its own performs no action; harm requires referencing
/// a type or a member.
/// </summary>
private static List<string> GetSymbolScopes(ISymbol symbol)
{
var scopes = new List<string>();
switch (symbol)
{
case INamespaceSymbol:
// A namespace reference alone is harmless — skip it. (This
// avoids a false positive on the "System.Threading" qualifier
// of the allowed "System.Threading.Tasks.Task".)
break;
case ITypeSymbol typeSymbol:
scopes.Add(typeSymbol.ToDisplayString());
if (typeSymbol.ContainingNamespace is { IsGlobalNamespace: false } typeNs)
scopes.Add(typeNs.ToDisplayString());
break;
default:
if (symbol.ContainingType != null)
{
scopes.Add(symbol.ContainingType.ToDisplayString());
if (symbol.ContainingType.ContainingNamespace is { IsGlobalNamespace: false } memberNs)
scopes.Add(memberNs.ToDisplayString());
}
else if (symbol.ContainingNamespace is { IsGlobalNamespace: false } ns)
{
scopes.Add(ns.ToDisplayString());
}
break;
}
return scopes;
}
/// <summary>
/// Fallback used when a name could not be resolved to a symbol (e.g. a type
/// from an assembly the script is not allowed to reference). The
/// fully-qualified name as written in source is used directly — a script
/// that names <c>System.Net.Http.HttpClient</c> is still rejected even
/// though that assembly is deliberately absent from the script's metadata
/// references.
/// </summary>
private static List<string> GetSyntacticScopes(SyntaxNode node)
{
// A dotted name written in source is itself the fully-qualified scope.
// Only consider names that actually contain a dot — bare local
// identifiers cannot reach a forbidden namespace.
var text = node switch
{
QualifiedNameSyntax q => q.ToString(),
MemberAccessExpressionSyntax m => m.ToString(),
_ => string.Empty,
};
// Strip whitespace/newlines that a multi-line member-access chain may contain.
text = new string(text.Where(c => !char.IsWhiteSpace(c)).ToArray());
return string.IsNullOrEmpty(text) || !text.Contains('.')
? []
: [text];
}
/// <summary>
/// True if <paramref name="actual"/> is exactly, or nested within,
/// <paramref name="root"/> (e.g. "System.IO.Compression" is under
/// "System.IO", "System.Diagnostics.Process" is under
/// "System.Diagnostics.Process").
/// </summary>
private static bool IsUnderScope(string actual, string root)
=> actual.Equals(root, StringComparison.Ordinal)
|| actual.StartsWith(root + ".", StringComparison.Ordinal);
/// <summary>
/// True if a dotted name (a <c>using</c> import or qualified name as written)
/// is forbidden — under a forbidden scope and not under an allowed exception.
/// </summary>
private static bool IsForbiddenDottedName(string dottedName)
{
foreach (var allowed in ScriptTrustPolicy.AllowedExceptions)
{
if (IsUnderScope(dottedName, allowed))
return false;
}
foreach (var forbidden in ScriptTrustPolicy.ForbiddenScopes)
{
if (IsUnderScope(dottedName, forbidden))
return true;
}
return false;
}
/// <summary>
/// True if a dotted name is exactly an allowed-exception scope OR a strict
/// prefix of one — e.g. <c>System.Threading</c> is a prefix of the allowed
/// <c>System.Threading.Tasks</c>. Used by the hardening walker to stop
/// descending into the namespace qualifier of an allowed type so the bare
/// <c>System.Threading</c> qualifier of <c>System.Threading.Tasks.Task</c>
/// is not falsely flagged (the semantic pass already ignores bare
/// namespaces; this keeps the syntactic pass consistent).
/// </summary>
private static bool IsAllowedExceptionPrefix(string dottedName)
{
foreach (var allowed in ScriptTrustPolicy.AllowedExceptions)
{
if (IsUnderScope(dottedName, allowed)
|| allowed.StartsWith(dottedName + ".", StringComparison.Ordinal))
{
return true;
}
}
return false;
}
/// <summary>
/// Syntactic walker porting the InboundAPI <c>ForbiddenApiWalker</c>
/// hardening rules — reflection-gateway members, the <c>dynamic</c> keyword,
/// <c>Activator</c>, and forbidden <c>using</c>/qualified-name spellings.
/// Writes into the same dedup set as the semantic pass.
/// </summary>
private sealed class HardeningWalker : CSharpSyntaxWalker
{
private readonly SortedSet<string> _violations;
internal HardeningWalker(SortedSet<string> violations) => _violations = violations;
/// <summary>
/// Strips whitespace/newlines a multi-line member-access chain may carry,
/// so prefix matching against the dotted policy scopes is reliable.
/// </summary>
private static string StripWhitespace(string text)
=> new(text.Where(c => !char.IsWhiteSpace(c)).ToArray());
/// <inheritdoc />
public override void VisitUsingDirective(UsingDirectiveSyntax node)
{
if (node.Name is not null && IsForbiddenDottedName(node.Name.ToString()))
_violations.Add($"forbidden namespace import '{node.Name}'");
base.VisitUsingDirective(node);
}
/// <inheritdoc />
public override void VisitQualifiedName(QualifiedNameSyntax node)
{
var text = StripWhitespace(node.ToString());
// An allowed-exception name (or a strict prefix of one, e.g.
// "System.Threading" under "System.Threading.Tasks") must NOT be
// reported — but we STILL DESCEND into its children so a forbidden
// type nested inside (e.g. a generic argument under an allowed
// System.Threading.Tasks.TaskCompletionSource<System.Threading.Mutex>)
// is independently visited and flagged by this pass. Suppress the
// outer report, do not stop the walk. (Pass 2 is self-sufficient and
// does not rely on the semantic pass to catch nested forbidden refs.)
if (IsAllowedExceptionPrefix(text))
{
base.VisitQualifiedName(node);
return;
}
// Check the longest qualified name; do not descend so a single
// System.IO.File reference is reported once, not three times.
if (IsForbiddenDottedName(text))
{
_violations.Add($"forbidden type reference '{text}'");
return;
}
base.VisitQualifiedName(node);
}
/// <inheritdoc />
public override void VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
var text = StripWhitespace(node.ToString());
// Reject reflection-gateway members regardless of the receiver — run
// this FIRST, before any allowed-exception early-return, so a
// gateway member hung off an allowed type
// (e.g. System.Threading.Tasks.Task.GetType()) is still caught.
// typeof(string).Assembly.GetType("System.IO.File") never spells a
// forbidden namespace, but '.Assembly' and '.GetType' appear here as
// the accessed member name.
var memberName = node.Name.Identifier.ValueText;
if (ScriptTrustPolicy.ReflectionGatewayMembers.Contains(memberName))
{
_violations.Add($"forbidden reflection member access '.{memberName}'");
// Still descend: the receiver may contain a further violation.
}
// An allowed-exception member-access (or a strict prefix of one)
// must NOT be reported — the bare forbidden-namespace qualifier of an
// allowed type (e.g. the "System.Threading" inside
// "System.Threading.Tasks.Task.Delay") is a false positive. But we
// STILL DESCEND into its children so a forbidden reference nested
// inside (e.g. a System.IO.File access in an allowed
// System.Threading.Tasks.Task.Run(...) lambda body) is independently
// visited and flagged by this pass. Suppress the outer report, do not
// stop the walk. (Pass 2 is self-sufficient — it does not rely on the
// semantic pass to catch nested forbidden refs.)
if (IsAllowedExceptionPrefix(text))
{
base.VisitMemberAccessExpression(node);
return;
}
// Catches fully-qualified expressions such as System.IO.File.Delete(...).
if (IsForbiddenDottedName(text))
{
_violations.Add($"forbidden API access '{text}'");
return;
}
base.VisitMemberAccessExpression(node);
}
/// <inheritdoc />
public override void VisitIdentifierName(IdentifierNameSyntax node)
{
var text = node.Identifier.ValueText;
// 'dynamic' widens late-bound member access the static walker cannot
// see through — reject its use outright. The 'dynamic' contextual
// keyword surfaces as an identifier name.
if (text == "dynamic")
{
_violations.Add("forbidden use of the 'dynamic' keyword");
return;
}
// A bare reference to a reflection entry-point type. 'Activator' has
// no non-reflection use. ('dynamic' already returned above.)
if (ScriptTrustPolicy.ForbiddenIdentifiers.Contains(text))
{
_violations.Add($"forbidden reflection type reference '{text}'");
return;
}
base.VisitIdentifierName(node);
}
}
}
@@ -0,0 +1,51 @@
namespace ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
/// <summary>
/// M3.1: a <b>compile-only</b> mirror of the SiteRuntime
/// <c>TriggerExpressionGlobals</c> bind surface. A trigger expression is a bare
/// boolean expression referencing <c>Attributes["x"]</c> / <c>Children["c"]</c>
/// / <c>Parent</c>; the design-time deploy gate (M3.5) compiles candidate
/// trigger expressions against this type to catch undefined symbols.
///
/// <para>
/// Only the read-only bind surface is reproduced — the runtime
/// <c>ExtractExpression</c> helper and the snapshot-backed constructor are
/// intentionally omitted; they are runtime concerns, not part of what an
/// expression binds against. Member bodies are compile-only and throw
/// <see cref="NotSupportedException"/>.
/// </para>
/// </summary>
public sealed class TriggerCompileSurface
{
private const string CompileOnly = "compile-only surface";
/// <summary>Mirrors <c>TriggerExpressionGlobals.Attributes</c>.</summary>
public ReadOnlyAttributes Attributes => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>TriggerExpressionGlobals.Children</c>.</summary>
public ReadOnlyChildren Children => throw new NotSupportedException(CompileOnly);
/// <summary>Mirrors <c>TriggerExpressionGlobals.Parent</c>.</summary>
public ReadOnlyComposition? Parent => throw new NotSupportedException(CompileOnly);
/// <summary>Compile-only mirror of <c>TriggerExpressionGlobals.ReadOnlyAttributes</c>.</summary>
public sealed class ReadOnlyAttributes
{
/// <summary>Mirrors <c>ReadOnlyAttributes.this[string]</c>.</summary>
public object? this[string key] => throw new NotSupportedException(CompileOnly);
}
/// <summary>Compile-only mirror of <c>TriggerExpressionGlobals.ReadOnlyComposition</c>.</summary>
public sealed class ReadOnlyComposition
{
/// <summary>Mirrors <c>ReadOnlyComposition.Attributes</c>.</summary>
public ReadOnlyAttributes Attributes => throw new NotSupportedException(CompileOnly);
}
/// <summary>Compile-only mirror of <c>TriggerExpressionGlobals.ReadOnlyChildren</c>.</summary>
public sealed class ReadOnlyChildren
{
/// <summary>Mirrors <c>ReadOnlyChildren.this[string]</c>.</summary>
public ReadOnlyComposition this[string compositionName] => throw new NotSupportedException(CompileOnly);
}
}
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.Commons/ZB.MOM.WW.ScadaBridge.Commons.csproj" />
</ItemGroup>
</Project>
@@ -1,49 +1,23 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.ScadaBridge.Commons.Types;
using ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
/// <summary>
/// WP-19: Script Trust Model — compiles C# scripts using Roslyn with restricted API access.
/// Forbidden APIs: System.IO, Process, Threading (except async/await), Reflection,
/// System.Net.Sockets, System.Net.Http.
/// The forbidden-API verdict is delegated to the shared authoritative
/// <see cref="ScriptTrustValidator"/> (M3.1 consolidation); this service keeps the real
/// execution-path compile of the script against <see cref="ScriptGlobals"/> /
/// <see cref="TriggerExpressionGlobals"/>.
/// </summary>
public class ScriptCompilationService
{
private readonly ILogger<ScriptCompilationService> _logger;
/// <summary>
/// Forbidden API roots. Each entry is matched as a prefix against both the resolved
/// symbol's containing namespace and its fully-qualified containing type name, so an
/// entry may name a whole namespace ("System.IO") or a single type
/// ("System.Diagnostics.Process").
/// </summary>
private static readonly string[] ForbiddenNamespaces =
[
"System.IO",
"System.Diagnostics.Process",
"System.Threading",
"System.Reflection",
"System.Net.Sockets",
"System.Net.Http"
];
/// <summary>
/// Specific namespaces/types allowed even though they sit under a forbidden root.
/// async/await and cancellation tokens are OK despite System.Threading being blocked.
/// </summary>
private static readonly string[] AllowedExceptions =
[
"System.Threading.Tasks",
"System.Threading.CancellationToken",
"System.Threading.CancellationTokenSource"
];
/// <summary>Initializes a new instance of the ScriptCompilationService class.</summary>
/// <param name="logger">Logger instance.</param>
public ScriptCompilationService(ILogger<ScriptCompilationService> logger)
@@ -54,160 +28,24 @@ public class ScriptCompilationService
/// <summary>
/// SiteRuntime-011: validates that the script does not reference forbidden APIs.
///
/// Validation is performed with Roslyn semantic analysis rather than a raw substring
/// scan of the source text. The script is parsed and a semantic model is built; every
/// identifier, type reference, member access, and object creation is resolved to its
/// symbol and the symbol's containing namespace is checked against the forbidden list.
///
/// This is reliable in both directions a textual scan was not:
/// - it catches forbidden types regardless of how they are written (<c>global::</c>
/// prefixes, aliases, transitively-imported namespaces) because it inspects the
/// resolved symbol, not the spelling;
/// - it does not raise false positives for the namespace string appearing in a
/// comment, a string literal, or an unrelated identifier.
/// As of the M3.1 script-analysis consolidation this delegates to the shared
/// authoritative <see cref="ScriptTrustValidator.FindViolations(string, System.Collections.Generic.IEnumerable{MetadataReference})"/>,
/// which is the same Roslyn semantic-symbol analysis this service previously hosted
/// plus reflection-gateway / <c>dynamic</c> / <c>Activator</c> hardening ported from
/// the InboundAPI checker. The shared validator is the single source of truth for the
/// forbidden-API deny-list; SiteRuntime retains only the real execution-path compile
/// in <see cref="CompileCore"/>.
///
/// Returns a list of violation messages, empty if clean.
/// </summary>
/// <param name="code">The script code to validate.</param>
/// <returns>A list of trust-model violation messages; empty if the script is clean.</returns>
public IReadOnlyList<string> ValidateTrustModel(string code)
{
var tree = CSharpSyntaxTree.ParseText(
code, new CSharpParseOptions(kind: SourceCodeKind.Script));
var compilation = CSharpCompilation.CreateScriptCompilation(
"TrustValidation",
tree,
ScriptReferences,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
var model = compilation.GetSemanticModel(tree);
var root = tree.GetRoot();
// Deduplicate so a forbidden symbol used many times is reported once but
// distinct forbidden symbols are all reported.
var violations = new SortedSet<string>(StringComparer.Ordinal);
foreach (var node in root.DescendantNodes())
{
// Only inspect nodes that name a type or member; skip declarations,
// string literals and comments entirely. Member-access and qualified-name
// parents are evaluated as a whole, so their nested name parts are skipped.
if (node is not (SimpleNameSyntax or MemberAccessExpressionSyntax
or QualifiedNameSyntax or ObjectCreationExpressionSyntax))
{
continue;
}
var info = model.GetSymbolInfo(node);
var symbol = info.Symbol ?? info.CandidateSymbols.FirstOrDefault();
// The set of fully-qualified scopes this reference touches: the resolved
// symbol's containing namespace and type, or — when the symbol could not
// be resolved (a type from an unreferenced assembly) — the syntactic
// fully-qualified name written in source as a safe fallback.
var scopes = symbol != null
? GetSymbolScopes(symbol)
: GetSyntacticScopes(node);
if (scopes.Count == 0)
continue;
var forbidden = ForbiddenNamespaces.FirstOrDefault(
f => scopes.Any(s => IsUnderScope(s, f)));
if (forbidden == null)
continue;
// Allow specific exception namespaces/types (async/await, cancellation).
if (scopes.Any(s => AllowedExceptions.Any(a => IsUnderScope(s, a))))
continue;
var name = symbol?.Name ?? node.ToString();
violations.Add($"Forbidden API reference: '{forbidden}' ({scopes[0]}.{name})");
}
return violations.ToList();
}
=> ScriptTrustValidator.FindViolations(code);
/// <summary>
/// Returns the fully-qualified scopes a resolved symbol belongs to — its containing
/// namespace and, for a type or member, the fully-qualified containing type. A bare
/// namespace symbol is intentionally ignored: a namespace name on its own performs
/// no action; harm requires referencing a type or a member.
/// </summary>
private static List<string> GetSymbolScopes(ISymbol symbol)
{
var scopes = new List<string>();
switch (symbol)
{
case INamespaceSymbol:
// A namespace reference alone is harmless — skip it. (This avoids a
// false positive on the "System.Threading" qualifier of the allowed
// "System.Threading.Tasks.Task".)
break;
case ITypeSymbol typeSymbol:
scopes.Add(typeSymbol.ToDisplayString());
if (typeSymbol.ContainingNamespace is { IsGlobalNamespace: false } typeNs)
scopes.Add(typeNs.ToDisplayString());
break;
default:
if (symbol.ContainingType != null)
{
scopes.Add(symbol.ContainingType.ToDisplayString());
if (symbol.ContainingType.ContainingNamespace is { IsGlobalNamespace: false } memberNs)
scopes.Add(memberNs.ToDisplayString());
}
else if (symbol.ContainingNamespace is { IsGlobalNamespace: false } ns)
{
scopes.Add(ns.ToDisplayString());
}
break;
}
return scopes;
}
/// <summary>
/// Fallback used when a name could not be resolved to a symbol (e.g. a type from an
/// assembly the script is not allowed to reference). The fully-qualified name as
/// written in source is used directly — a script that names
/// <c>System.Net.Http.HttpClient</c> is still rejected even though that assembly is
/// deliberately absent from the script's metadata references.
/// </summary>
private static List<string> GetSyntacticScopes(SyntaxNode node)
{
// A dotted name written in source is itself the fully-qualified scope. Only
// consider names that actually contain a dot — bare local identifiers cannot
// reach a forbidden namespace.
var text = node switch
{
QualifiedNameSyntax q => q.ToString(),
MemberAccessExpressionSyntax m => m.ToString(),
_ => string.Empty
};
// Strip whitespace/newlines that a multi-line member-access chain may contain.
text = new string(text.Where(c => !char.IsWhiteSpace(c)).ToArray());
return string.IsNullOrEmpty(text) || !text.Contains('.')
? []
: [text];
}
/// <summary>
/// True if <paramref name="actual"/> is exactly, or nested within,
/// <paramref name="root"/> (e.g. "System.IO.Compression" is under "System.IO",
/// "System.Diagnostics.Process" is under "System.Diagnostics.Process").
/// </summary>
private static bool IsUnderScope(string actual, string root)
=> actual.Equals(root, StringComparison.Ordinal)
|| actual.StartsWith(root + ".", StringComparison.Ordinal);
/// <summary>
/// Assemblies referenced by compiled scripts. Shared between the Roslyn scripting
/// options and the semantic-analysis compilation built for trust validation
/// (SiteRuntime-011), so the validator resolves symbols against exactly the same
/// metadata the script is compiled against.
/// Assemblies referenced by compiled scripts, used to build the Roslyn scripting
/// options for the real execution-path compile.
/// </summary>
private static readonly System.Reflection.Assembly[] ScriptAssemblies =
[
@@ -218,14 +56,6 @@ public class ScriptCompilationService
typeof(Commons.Types.DynamicJsonElement).Assembly
];
/// <summary>
/// Metadata references for the trust-validation semantic compilation.
/// </summary>
private static readonly MetadataReference[] ScriptReferences =
ScriptAssemblies
.Select(a => (MetadataReference)MetadataReference.CreateFromFile(a.Location))
.ToArray();
/// <summary>
/// Shared Roslyn scripting options (references + imports) used by both full
/// script compilation and trigger-expression compilation.
@@ -35,6 +35,7 @@
<ItemGroup>
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.Commons/ZB.MOM.WW.ScadaBridge.Commons.csproj" />
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.Communication/ZB.MOM.WW.ScadaBridge.Communication.csproj" />
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.csproj" />
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.HealthMonitoring/ZB.MOM.WW.ScadaBridge.HealthMonitoring.csproj" />
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.SiteEventLogging/ZB.MOM.WW.ScadaBridge.SiteEventLogging.csproj" />
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.StoreAndForward/ZB.MOM.WW.ScadaBridge.StoreAndForward.csproj" />
@@ -2,12 +2,11 @@ namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
/// <summary>
/// String/comment-aware scanner for the balanced-delimiter ("does it look like
/// valid C#") checks used by <see cref="ScriptCompiler"/> and
/// <c>SharedScriptService.ValidateSyntax</c>.
/// valid C#") check used by <c>SharedScriptService.ValidateSyntax</c>.
///
/// <para>
/// This is <b>not</b> a compiler. It is an interim structural check that walks
/// the source once and tracks <c>{}</c>, <c>[]</c> and <c>()</c> depth while
/// This is <b>not</b> a compiler. It is a structural check that walks the
/// source once and tracks <c>{}</c>, <c>[]</c> and <c>()</c> depth while
/// correctly skipping over the C# lexical constructs in which a delimiter is
/// inert: line/block comments, regular string literals (with <c>\</c> escapes),
/// verbatim strings (<c>@"..."</c>, where <c>""</c> escapes a quote and <c>\</c>
@@ -17,11 +16,11 @@ namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
/// </para>
///
/// <para>
/// It is intentionally conservative: when the real Roslyn-based compiler is
/// wired in (see <see cref="ScriptCompiler"/>) this hand-rolled scan should be
/// replaced by <c>CSharpSyntaxTree.ParseText</c> diagnostics. Until then this
/// scanner removes the false positives that a naive character count produced
/// for valid scripts containing a delimiter inside a string or comment.
/// Trust enforcement and full compilation are NOT done here — those are the
/// authoritative <see cref="ScriptCompiler"/> (which delegates to the shared
/// <c>ZB.MOM.WW.ScadaBridge.ScriptAnalysis</c> validator + Roslyn compile). This
/// scanner only provides <c>SharedScriptService</c> a cheap pre-compile sanity
/// check for balanced delimiters.
/// </para>
/// </summary>
internal static class CSharpDelimiterScanner
@@ -41,121 +40,6 @@ internal static class CSharpDelimiterScanner
UnterminatedChar,
}
/// <summary>
/// Returns true when <paramref name="pattern"/> occurs in a <b>code</b>
/// region of <paramref name="code"/> — i.e. not wholly inside a string
/// literal, char literal, or comment. Used by the interim forbidden-API
/// scan so that the inert text <c>System.IO.</c> in a comment or string
/// literal is not flagged as a forbidden API call (TemplateEngine-006).
///
/// <para>
/// This removes the false-positive half of the substring scan. It does
/// <b>not</b> close the bypass half: namespace aliases, <c>using static</c>,
/// and <c>global::</c>-qualified references still evade a pure text match.
/// Authoritative forbidden-API enforcement requires Roslyn semantic symbol
/// analysis and is deferred to the real script compiler / Site Runtime
/// sandbox; this check is advisory only.
/// </para>
/// </summary>
/// <param name="code">The C# source code to scan.</param>
/// <param name="pattern">The substring to search for in code regions only.</param>
/// <returns><c>true</c> if <paramref name="pattern"/> occurs in a code region (not inside a comment, string, or char literal); otherwise <c>false</c>.</returns>
internal static bool ContainsInCode(string code, string pattern)
{
if (string.IsNullOrEmpty(pattern))
return false;
// Blank out every string/char-literal/comment span, then do an ordinary
// substring search over what remains (the code regions).
var codeOnly = BlankNonCodeSpans(code);
return codeOnly.Contains(pattern, StringComparison.Ordinal);
}
/// <summary>
/// Replaces the content of every comment, string literal, and char literal
/// with spaces (newlines preserved), leaving only code regions intact.
/// Delimiter characters themselves are also blanked so a pattern cannot
/// straddle a literal boundary.
/// </summary>
private static string BlankNonCodeSpans(string code)
{
var buffer = code.ToCharArray();
int n = code.Length;
int i = 0;
void Blank(int from, int to)
{
for (int k = from; k < to && k < n; k++)
if (buffer[k] != '\n' && buffer[k] != '\r')
buffer[k] = ' ';
}
while (i < n)
{
char c = code[i];
char next = i + 1 < n ? code[i + 1] : '\0';
int start = i;
if (c == '/' && next == '/')
{
i += 2;
while (i < n && code[i] != '\n') i++;
Blank(start, i);
continue;
}
if (c == '/' && next == '*')
{
i += 2;
while (i < n && !(code[i] == '*' && i + 1 < n && code[i + 1] == '/')) i++;
if (i < n) i += 2;
Blank(start, i);
continue;
}
if (c == '"' && next == '"' && i + 2 < n && code[i + 2] == '"')
{
SkipRawString(code, ref i);
Blank(start, i);
continue;
}
if (c == '$')
{
int j = i + 1;
bool verbatim = false;
if (j < n && code[j] == '@') { verbatim = true; j++; }
if (j < n && code[j] == '"')
{
i = j;
SkipInterpolatedString(code, ref i, verbatim);
Blank(start, i);
continue;
}
}
if (c == '@' && next == '"')
{
i++;
SkipVerbatimString(code, ref i);
Blank(start, i);
continue;
}
if (c == '"')
{
SkipRegularString(code, ref i);
Blank(start, i);
continue;
}
if (c == '\'')
{
SkipCharLiteral(code, ref i);
Blank(start, i);
continue;
}
i++;
}
return new string(buffer);
}
/// <summary>
/// Walks <paramref name="code"/> once and reports the first structural
/// delimiter problem, or <see cref="Mismatch.None"/> when the source is
@@ -1,105 +1,51 @@
using ZB.MOM.WW.ScadaBridge.Commons.Types;
using ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
/// <summary>
/// Validates script code by attempting to compile it using Roslyn.
/// In production, this would compile C# scripts against a stub ScriptApi assembly
/// that provides the allowed API surface (attribute read/write, CallScript, CallShared, etc.)
/// and enforces the forbidden API list (System.IO, Process, Threading, Reflection, raw network).
///
/// For now, this implementation performs basic syntax validation.
/// The authoritative design-time / deploy-blocking script gate. Delegates to the
/// shared <see cref="ZB.MOM.WW.ScadaBridge.ScriptAnalysis"/> analyzer (M3.2): a
/// real Roslyn semantic forbidden-API verdict
/// (<see cref="ScriptTrustValidator.FindViolations(string, System.Collections.Generic.IEnumerable{Microsoft.CodeAnalysis.MetadataReference})"/>)
/// followed by a real CSharpScript compile against the
/// <see cref="ScriptCompileSurface"/> globals
/// (<see cref="RoslynScriptCompiler.Compile(string, System.Type, System.Collections.Generic.IEnumerable{Microsoft.CodeAnalysis.MetadataReference}, System.Collections.Generic.IEnumerable{string})"/>).
///
/// <para>
/// <b>SECURITY LIMITATION (TemplateEngine-006):</b> the forbidden-API check below
/// is an interim, <i>advisory</i> text scan — it is NOT an authoritative trust-model
/// boundary. <see cref="CSharpDelimiterScanner.ContainsInCode"/> removes the
/// false-positive half (forbidden text inside a string/comment is ignored), but a
/// determined script can still bypass the literal patterns via namespace aliases,
/// <c>using static</c>, or <c>global::</c>-qualified references. Authoritative
/// enforcement requires Roslyn semantic symbol analysis of the referenced
/// types/namespaces and is the responsibility of the real script compiler and the
/// Site Runtime sandbox. Do not rely on this class as the sole trust-model gate.
/// This is a real trust-model boundary, not the previous advisory substring +
/// brace-balance scan: the forbidden-API check resolves symbols (so namespace
/// aliases, <c>using static</c>, <c>global::</c>-qualified references, and the
/// reflection gateway are all caught), and the compile catches undefined symbols
/// and signature mismatches that a structural scan could never see.
/// </para>
/// </summary>
public class ScriptCompiler
{
/// <summary>
/// Forbidden namespace patterns — scripts (and trigger expressions, via
/// <see cref="ValidationService"/>) must not use these. Trigger expressions run
/// under the same trust model as scripts, so the list is shared from here rather
/// than duplicated.
///
/// <para>
/// Matched with <see cref="CSharpDelimiterScanner.ContainsInCode"/> against code
/// regions only. This is advisory — see the class summary's SECURITY LIMITATION
/// note; the substring patterns are bypassable and the authoritative check is
/// deferred to Roslyn semantic analysis.
/// </para>
/// </summary>
internal static readonly string[] ForbiddenPatterns =
[
"System.IO.",
"System.Diagnostics.Process",
"System.Threading.",
"System.Reflection.",
"System.Net.Sockets.",
"System.Net.Http.",
];
/// <summary>
/// Attempts to compile a script and returns success or a compilation error.
/// The security check runs first: a script that uses a forbidden API is
/// rejected before any compile diagnostics are considered.
/// </summary>
/// <param name="code">The C# script code.</param>
/// <param name="scriptName">The canonical name of the script (for error messages).</param>
/// <returns>Success if the script compiles, or Failure with the error message.</returns>
/// <returns>Success if the script is clean and compiles, or Failure with the error message.</returns>
public Result<bool> TryCompile(string code, string scriptName)
{
if (string.IsNullOrWhiteSpace(code))
return Result<bool>.Failure($"Script '{scriptName}' has empty code.");
// Check for forbidden APIs. Advisory only (see class summary): the scan is
// code-region-aware so forbidden text inside a string/comment is ignored,
// but it remains a substring match and is not an authoritative boundary.
foreach (var pattern in ForbiddenPatterns)
{
if (CSharpDelimiterScanner.ContainsInCode(code, pattern))
{
return Result<bool>.Failure(
$"Script '{scriptName}' uses forbidden API: '{pattern.TrimEnd('.')}'. " +
"Scripts cannot use System.IO, Process, Threading, Reflection, or raw network APIs.");
}
}
// Authoritative forbidden-API verdict first — a security violation must
// gate the script regardless of whether it otherwise compiles.
var violations = ScriptTrustValidator.FindViolations(code);
if (violations.Count > 0)
return Result<bool>.Failure($"Script '{scriptName}' uses forbidden API: {violations[0]}");
// Basic structural validation: balanced braces/brackets/parens. The scan
// is string- and comment-aware (see CSharpDelimiterScanner) so a delimiter
// inside a regular/verbatim/interpolated/raw string, a char literal, or a
// comment does not produce a false mismatch. This remains an interim check
// until the Roslyn-based compiler is wired in.
var mismatch = CSharpDelimiterScanner.Scan(code);
return mismatch switch
{
CSharpDelimiterScanner.Mismatch.None =>
Result<bool>.Success(true),
CSharpDelimiterScanner.Mismatch.UnexpectedCloseBrace =>
Result<bool>.Failure($"Script '{scriptName}' has mismatched braces (unexpected closing brace)."),
CSharpDelimiterScanner.Mismatch.UnclosedBrace =>
Result<bool>.Failure($"Script '{scriptName}' has mismatched braces (unclosed opening brace)."),
CSharpDelimiterScanner.Mismatch.UnexpectedCloseBracket =>
Result<bool>.Failure($"Script '{scriptName}' has mismatched brackets (unexpected closing bracket)."),
CSharpDelimiterScanner.Mismatch.UnclosedBracket =>
Result<bool>.Failure($"Script '{scriptName}' has mismatched brackets (unclosed opening bracket)."),
CSharpDelimiterScanner.Mismatch.UnexpectedCloseParen =>
Result<bool>.Failure($"Script '{scriptName}' has mismatched parentheses (unexpected closing parenthesis)."),
CSharpDelimiterScanner.Mismatch.UnclosedParen =>
Result<bool>.Failure($"Script '{scriptName}' has mismatched parentheses (unclosed opening parenthesis)."),
CSharpDelimiterScanner.Mismatch.UnclosedBlockComment =>
Result<bool>.Failure($"Script '{scriptName}' has an unclosed block comment."),
CSharpDelimiterScanner.Mismatch.UnterminatedString =>
Result<bool>.Failure($"Script '{scriptName}' has an unterminated string literal."),
CSharpDelimiterScanner.Mismatch.UnterminatedChar =>
Result<bool>.Failure($"Script '{scriptName}' has an unterminated character literal."),
_ => Result<bool>.Success(true),
};
// Real CSharpScript compile against the runtime-mirroring globals surface.
var errors = RoslynScriptCompiler.Compile(code, typeof(ScriptCompileSurface));
if (errors.Count > 0)
return Result<bool>.Failure($"Script '{scriptName}' failed to compile: {errors[0]}");
return Result<bool>.Success(true);
}
}
@@ -1,5 +1,6 @@
using System.Text.Json;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
using ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
@@ -247,10 +248,11 @@ public class ValidationService
/// checks against the <c>{ "expression": "..." }</c> trigger configuration:
/// <list type="bullet">
/// <item>Blank expression → warning (the trigger will never fire).</item>
/// <item>Syntax check → error if the expression uses a forbidden API or has
/// unbalanced brackets/quotes. The TemplateEngine project does not reference a
/// Roslyn compiler (see <see cref="ScriptCompiler"/>), so this mirrors that
/// string-based syntax check rather than a full compile.</item>
/// <item>Syntax/compile check → error if the expression uses a forbidden API
/// or does not compile as a bare boolean expression. Delegates to the shared
/// authoritative analyzer (see <see cref="ScriptCompiler"/> and
/// <see cref="CheckExpressionSyntax"/>) — a real Roslyn compile against the
/// <see cref="TriggerCompileSurface"/>, not a string scan.</item>
/// <item>Attribute-reference scan → error for any <c>Attributes["X"]</c> literal
/// whose key is absent from the flattened configuration, mirroring
/// <see cref="ValidateScriptTriggerReferences"/> for the structured triggers.</item>
@@ -373,113 +375,27 @@ public class ValidationService
}
/// <summary>
/// Lightweight string-based syntax check for a trigger expression. Mirrors the
/// approach in <see cref="ScriptCompiler"/> (the TemplateEngine project has no
/// Roslyn compiler reference): rejects forbidden APIs and unbalanced
/// brackets/quotes. Returns an error message, or <c>null</c> when the expression
/// looks well-formed.
/// Authoritative syntax/trust check for a trigger expression. Delegates to the
/// shared <see cref="ZB.MOM.WW.ScadaBridge.ScriptAnalysis"/> analyzer (same gate
/// as <see cref="ScriptCompiler"/>): a real forbidden-API verdict
/// (<see cref="ScriptTrustValidator.FindViolations(string, System.Collections.Generic.IEnumerable{Microsoft.CodeAnalysis.MetadataReference})"/>)
/// followed by a real CSharpScript compile of the bare boolean expression against
/// the <see cref="TriggerCompileSurface"/> globals. Returns an error message, or
/// <c>null</c> when the expression is clean and compiles.
/// </summary>
/// <param name="expression">The expression to check for syntax errors.</param>
/// <param name="expression">The expression to check.</param>
/// <returns>A human-readable error message if the expression is invalid; <c>null</c> if well-formed.</returns>
internal static string? CheckExpressionSyntax(string expression)
{
// Advisory forbidden-API scan (TemplateEngine-006): code-region-aware so
// the inert text inside a string/comment is not flagged, but still a
// substring match — not an authoritative boundary. See ScriptCompiler.
foreach (var pattern in ScriptCompiler.ForbiddenPatterns)
{
if (CSharpDelimiterScanner.ContainsInCode(expression, pattern))
{
return $"uses forbidden API '{pattern.TrimEnd('.')}'. " +
"Trigger expressions cannot use System.IO, Process, Threading, Reflection, or raw network APIs.";
}
}
// Authoritative forbidden-API verdict first.
var violations = ScriptTrustValidator.FindViolations(expression);
if (violations.Count > 0)
return $"uses forbidden API: {violations[0]}";
var parenDepth = 0;
var bracketDepth = 0;
var braceDepth = 0;
var inString = false;
var inChar = false;
var inLineComment = false;
var inBlockComment = false;
for (int i = 0; i < expression.Length; i++)
{
var c = expression[i];
var next = i + 1 < expression.Length ? expression[i + 1] : '\0';
if (inLineComment)
{
if (c == '\n') inLineComment = false;
continue;
}
if (inBlockComment)
{
if (c == '*' && next == '/')
{
inBlockComment = false;
i++;
}
continue;
}
if (inString)
{
if (c == '\\') { i++; continue; }
if (c == '"') inString = false;
continue;
}
if (inChar)
{
if (c == '\\') { i++; continue; }
if (c == '\'') inChar = false;
continue;
}
if (c == '/' && next == '/')
{
inLineComment = true;
i++;
continue;
}
if (c == '/' && next == '*')
{
inBlockComment = true;
i++;
continue;
}
switch (c)
{
case '"': inString = true; break;
case '\'': inChar = true; break;
case '(': parenDepth++; break;
case ')':
parenDepth--;
if (parenDepth < 0) return "mismatched parentheses (unexpected ')').";
break;
case '[': bracketDepth++; break;
case ']':
bracketDepth--;
if (bracketDepth < 0) return "mismatched brackets (unexpected ']').";
break;
case '{': braceDepth++; break;
case '}':
braceDepth--;
if (braceDepth < 0) return "mismatched braces (unexpected '}').";
break;
}
}
if (inBlockComment) return "unterminated block comment.";
if (inString) return "unterminated string literal.";
if (inChar) return "unterminated character literal.";
if (parenDepth != 0) return $"mismatched parentheses ({parenDepth} unclosed).";
if (bracketDepth != 0) return $"mismatched brackets ({bracketDepth} unclosed).";
if (braceDepth != 0) return $"mismatched braces ({braceDepth} unclosed).";
// Real compile of the bare boolean expression against the trigger globals.
var errors = RoslynScriptCompiler.Compile(expression, typeof(TriggerCompileSurface));
if (errors.Count > 0)
return $"is not a valid expression: {errors[0]}";
return null;
}
@@ -18,6 +18,7 @@
<ItemGroup>
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.Commons/ZB.MOM.WW.ScadaBridge.Commons.csproj" />
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.csproj" />
</ItemGroup>
</Project>
@@ -54,11 +54,14 @@ public class ScriptAnalysisServiceTests
}
[Theory]
[InlineData("System.Diagnostics")]
[InlineData("System.Reflection")]
[InlineData("System.Net")]
[InlineData("System.Threading")]
public void ForbiddenUsing_AllBannedNamespaces(string ns)
{
// M3.5: the editor deny-list is sourced from the shared ScriptTrustPolicy.
// System.Threading is now a forbidden root (only Tasks +
// CancellationToken(Source) are excepted).
var resp = _svc.Diagnose(new DiagnoseRequest($"using {ns};"));
Assert.Contains(resp.Markers, m => m.Code == "SCADA001" && m.Message.Contains(ns));
}
@@ -71,6 +74,61 @@ public class ScriptAnalysisServiceTests
Assert.Contains(resp.Markers, m => m.Code == "SCADA002" && m.Message.Contains("File"));
}
[Fact]
public void SystemDiagnosticsNamespace_NoLongerWholesaleForbidden()
{
// M3.5: the unified policy forbids only System.Diagnostics.Process, not the
// whole System.Diagnostics namespace — so a bare `using System.Diagnostics;`
// is no longer flagged (Stopwatch & friends are allowed).
var resp = _svc.Diagnose(new DiagnoseRequest("using System.Diagnostics;"));
Assert.DoesNotContain(resp.Markers, m => m.Code == "SCADA001");
}
[Fact]
public void StopwatchUsage_IsAllowedUnderUnifiedPolicy()
{
// System.Diagnostics.Stopwatch is NOT under the forbidden
// System.Diagnostics.Process scope — it must not be flagged.
var resp = _svc.Diagnose(new DiagnoseRequest(
"using System.Diagnostics; var sw = Stopwatch.StartNew(); return sw.ElapsedMilliseconds;"));
Assert.DoesNotContain(resp.Markers, m => m.Code is "SCADA001" or "SCADA002");
}
[Fact]
public void ProcessUsage_IsForbiddenUnderUnifiedPolicy()
{
// System.Diagnostics.Process IS the forbidden scope — flagged via the
// semantic marker even though the parent namespace is allowed.
var resp = _svc.Diagnose(new DiagnoseRequest(
"using System.Diagnostics; var p = Process.GetCurrentProcess(); return p.Id;"));
Assert.Contains(resp.Markers, m => m.Code == "SCADA002" && m.Message.Contains("Process"));
}
[Theory]
[InlineData("Monitor")]
[InlineData("Interlocked")]
[InlineData("Mutex")]
public void ThreadingPrimitives_NowFlagged_UnderUnifiedPolicy(string typeName)
{
// CentralUI's old deny-list allowed most of System.Threading (only Thread +
// Tasks.Sources were blocked). The unified policy forbids ALL of
// System.Threading except Tasks + CancellationToken(Source), so these
// previously-clean primitives are now flagged by the editor.
var resp = _svc.Diagnose(new DiagnoseRequest(
$"using System.Threading; var x = typeof({typeName}); return 1;"));
Assert.Contains(resp.Markers, m => m.Code is "SCADA001" or "SCADA002");
}
[Fact]
public void CancellationToken_StaysAllowed_UnderUnifiedPolicy()
{
// The AllowedExceptions carve-out keeps CancellationToken(Source) clean even
// though the rest of System.Threading is forbidden.
var resp = _svc.Diagnose(new DiagnoseRequest(
"var cts = new System.Threading.CancellationTokenSource(); return cts.Token.IsCancellationRequested;"));
Assert.DoesNotContain(resp.Markers, m => m.Code is "SCADA001" or "SCADA002");
}
[Fact]
public void UserIdentifierNamedFile_DoesNotFalsePositive()
{
@@ -3,9 +3,18 @@ namespace ZB.MOM.WW.ScadaBridge.InboundAPI.Tests;
/// <summary>
/// InboundAPI-005 / InboundAPI-015: tests for the script-trust-model checker.
///
/// InboundAPI-015 hardens the textual walker against reflection reached through
/// permitted-type members that never spell a forbidden namespace, e.g.
/// <c>typeof(string).Assembly.GetType("System.IO.File")</c>.
/// Since M3.4 <see cref="ForbiddenApiChecker"/> delegates to the shared
/// <c>ScriptTrustValidator</c> in <c>ZB.MOM.WW.ScadaBridge.ScriptAnalysis</c>.
/// The unified policy differs from the old local deny-list in one notable way:
/// <c>System.Diagnostics</c> is loosened to <c>System.Diagnostics.Process</c>
/// only — <c>Stopwatch</c>, <c>Debug</c>, and other non-Process Diagnostics
/// types are now ALLOWED.
///
/// InboundAPI-015 hardening (reflection-gateway / dynamic / Activator) is
/// preserved unchanged via the shared validator.
///
/// Violation message wording is intentionally not asserted — callers should
/// use <c>.Count</c> / <c>.Any()</c> rather than exact strings.
/// </summary>
public class ForbiddenApiCheckerTests
{
@@ -26,11 +35,37 @@ public class ForbiddenApiCheckerTests
Assert.False(IsRejected(script), script);
}
// --- System.Diagnostics loosening: Process is still forbidden; non-Process types
// (Stopwatch, Debug) are now ALLOWED by the unified policy (M3.4). The old
// InboundAPI checker blocked the entire System.Diagnostics namespace. ---
[Fact]
public void Diagnostics_Process_StillForbidden()
{
// System.Diagnostics.Process is an explicit forbidden scope in ScriptTrustPolicy.
Assert.True(IsRejected("System.Diagnostics.Process.Start(\"/bin/sh\"); return null;"));
}
[Fact]
public void Diagnostics_Stopwatch_NowAllowed()
{
// System.Diagnostics.Stopwatch is NOT under the forbidden scope
// "System.Diagnostics.Process" — the unified policy only forbids
// System.Diagnostics.Process, not the whole System.Diagnostics namespace.
Assert.False(IsRejected("var sw = new System.Diagnostics.Stopwatch(); sw.Start(); return null;"));
}
[Fact]
public void Diagnostics_Debug_NowAllowed()
{
// System.Diagnostics.Debug is also not covered by the Process-only scope.
Assert.False(IsRejected("System.Diagnostics.Debug.WriteLine(\"hi\"); return null;"));
}
// --- Baseline: forbidden namespaces (textual) must still be rejected ---
[Theory]
[InlineData("System.IO.File.Delete(\"/tmp/x\"); return null;")]
[InlineData("System.Diagnostics.Process.Start(\"/bin/sh\"); return null;")]
[InlineData("using System.Reflection; return null;")]
[InlineData("var s = new System.Net.Sockets.Socket(default, default, default); return null;")]
public void ForbiddenNamespace_Rejected(string script)
@@ -101,4 +136,17 @@ public class ForbiddenApiCheckerTests
// dynamic widens late-bound member access the static walker cannot see through.
Assert.True(IsRejected("dynamic d = Parameters; return null;"));
}
// --- FindViolations returns a non-null, non-throwing result for edge inputs ---
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData(null!)]
public void EmptyOrWhitespace_ReturnsEmptyList(string? script)
{
var result = ForbiddenApiChecker.FindViolations(script!);
Assert.NotNull(result);
Assert.Empty(result);
}
}
@@ -0,0 +1,72 @@
using ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
namespace ZB.MOM.WW.ScadaBridge.ScriptAnalysis.Tests;
/// <summary>
/// M3.1: parse + compile gate tests. The "representative real script" corpus is
/// the PRIMARY guard that <see cref="ScriptCompileSurface"/> faithfully mirrors
/// the runtime <c>ScriptGlobals</c> surface — if a member or signature drifts,
/// the corpus stops binding and this test fails.
/// </summary>
public class RoslynScriptCompilerTests
{
[Fact]
public void ParseDiagnostics_NonEmpty_ForSyntaxError()
{
Assert.NotEmpty(RoslynScriptCompiler.ParseDiagnostics("var x = ;"));
}
[Fact]
public void ParseDiagnostics_Empty_ForValidSyntax()
{
Assert.Empty(RoslynScriptCompiler.ParseDiagnostics("var x = 1;"));
}
[Fact]
public void Compile_NonEmpty_ForUndefinedSymbol()
{
var code = "var x = NoSuchThing.Foo();";
Assert.NotEmpty(RoslynScriptCompiler.Compile(code, typeof(ScriptCompileSurface)));
}
[Fact]
public void Compile_Empty_ForRepresentativeRealScript()
{
const string code = """
var temp = Attributes["Temperature"];
Attributes["Setpoint"] = 42;
var r = await ExternalSystem.Call("erp", "sync");
var op = await Database.CachedWrite("hist", "INSERT ...");
await Notify.To("ops").Send("subj", "msg");
var shared = await Scripts.CallShared("Helper");
var child = Children["Pump"].Attributes["Speed"];
// Widen coverage across the rest of the surface.
var attr = await Instance.GetAttribute("Temperature");
await Instance.SetAttribute("Setpoint", "43");
var track = await Instance.Tracking.Status(op);
var parentSpeed = Parent?.Attributes["Speed"];
var alarmName = Alarm?.Name;
var p = Parameters;
var ct = CancellationToken;
var status = await Notify.Status("notif-id");
var cachedCall = await ExternalSystem.CachedCall("erp", "ping");
var resolved = Attributes.Resolve("Temperature");
var conn = await Database.Connection("hist");
var scope = Scope;
""";
var diagnostics = RoslynScriptCompiler.Compile(code, typeof(ScriptCompileSurface));
Assert.Empty(diagnostics);
}
[Fact]
public void Compile_Empty_ForTriggerExpression()
{
const string expr =
"Attributes[\"Temp\"] != null && (int)(Children[\"P\"].Attributes[\"S\"] ?? 0) > 5";
var diagnostics = RoslynScriptCompiler.Compile(expr, typeof(TriggerCompileSurface));
Assert.Empty(diagnostics);
}
}
@@ -0,0 +1,196 @@
using ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
namespace ZB.MOM.WW.ScadaBridge.ScriptAnalysis.Tests;
/// <summary>
/// M3.1: adversarial + legitimate cases for the fused trust validator. Reject
/// cases exercise the semantic pass (alias / using static / global::), the
/// reflection-gateway hardening pass, and the namespace deny-list union; clean
/// cases pin the allowed exceptions (Tasks, CancellationToken, Diagnostics
/// other than Process).
/// </summary>
public class ScriptTrustValidatorTests
{
// ---- Reject (non-empty violations) --------------------------------------
[Fact]
public void Rejects_SystemIo_Using()
{
var code = "using System.IO; var x = File.ReadAllText(\"/etc/passwd\");";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_SystemIo_GlobalQualified()
{
var code = "var x = global::System.IO.File.ReadAllText(\"x\");";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_SystemIo_Aliased()
{
var code = "using IO = System.IO; var f = IO.File.ReadAllText(\"x\");";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_SystemIo_UsingStatic()
{
var code = "using static System.IO.File; var s = ReadAllText(\"x\");";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_ReflectionGateway_OffPermittedType()
{
var code = "var t = typeof(string).Assembly.GetType(\"System.IO.File\");";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_Dynamic_Keyword()
{
var code = "dynamic d = 5; d.Foo();";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_Activator_CreateInstance()
{
var code = "var o = Activator.CreateInstance(typeof(string));";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_RuntimeInteropServices()
{
var code = "using System.Runtime.InteropServices; var h = Marshal.SizeOf<int>();";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_MicrosoftWin32()
{
var code = "using Microsoft.Win32; var k = Registry.LocalMachine;";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_Threading_Thread_Sleep()
{
var code = "System.Threading.Thread.Sleep(10);";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_All_SystemNet()
{
var code = "System.Net.WebClient w = null;";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_ReflectionGateway_OffAllowedTaskType()
{
// Guards the reflection-first ordering: a gateway member hung off an
// allowed System.Threading.Tasks type must still be rejected even though
// the chain's namespace prefix is an allowed exception.
var code = "var a = System.Threading.Tasks.Task.CompletedTask.GetType().Assembly;";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_ForbiddenIo_NestedInAllowedTaskRunLambda()
{
// A forbidden System.IO reference buried inside an allowed Task.Run lambda.
// The allowed-exception prefix on the outer member access must NOT shadow
// the nested forbidden reference — Pass 2 must descend into the lambda.
var code = "await System.Threading.Tasks.Task.Run(() => System.IO.File.ReadAllText(\"x\"));";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_ForbiddenMutex_AsGenericArg_UnderAllowedTasksPrefix()
{
// System.Threading.Mutex (forbidden) appears as a generic argument of an
// allowed System.Threading.Tasks.TaskCompletionSource<T>. The allowed
// outer name must not shadow the forbidden generic arg.
var code = "System.Threading.Tasks.TaskCompletionSource<System.Threading.Mutex> tcs = null;";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_DirectThreadingMutex_NotThreadSleep()
{
// A direct forbidden System.Threading type (not Thread.Sleep) — pins that
// the broad System.Threading deny-list catches more than the one cased test.
var code = "var m = new System.Threading.Mutex();";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_ForbiddenFileInfo_AsGenericArg()
{
// System.IO.FileInfo (forbidden) as a generic argument of an allowed
// System.Collections.Generic.List<T>.
var code = "System.Collections.Generic.List<System.IO.FileInfo> x = null;";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_NameOf_ForbiddenType()
{
// Conservative fail-safe: naming a forbidden type inside nameof(...) is
// deliberately flagged (a script has no business naming it even there).
var code = "var s = nameof(System.IO.File);";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_Process_QualifiedType()
{
var code = "var p = System.Diagnostics.Process.Start(\"x\");";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Rejects_Process_BareIdentifier_ViaUsing()
{
// System.Diagnostics is an ALLOWED namespace (Stopwatch/Debug ok), so the
// using directive is not flagged; Process is a forbidden TYPE reached as a
// bare identifier. This pins whether FindViolations resolves it.
var code = "using System.Diagnostics; var p = Process.Start(\"x\");";
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
}
// ---- Clean (empty violations) -------------------------------------------
[Fact]
public void Allows_TasksDelay()
{
var code = "await System.Threading.Tasks.Task.Delay(1);";
Assert.Empty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Allows_DiagnosticsStopwatch_NotProcess()
{
var code = "var sw = System.Diagnostics.Stopwatch.StartNew();";
Assert.Empty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Allows_CancellationTokenSource()
{
var code = "var c = new System.Threading.CancellationTokenSource();";
Assert.Empty(ScriptTrustValidator.FindViolations(code));
}
[Fact]
public void Allows_LinqAndMath()
{
var code = "var n = System.Linq.Enumerable.Range(0,3).Sum(); var m = System.Math.Max(1,2);";
Assert.Empty(ScriptTrustValidator.FindViolations(code));
}
}
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,105 @@
using System.Reflection;
using ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Scripts;
/// <summary>
/// M3.3: compile-surface parity guard. The shared
/// <see cref="ScriptCompileSurface"/> / <see cref="TriggerCompileSurface"/> are
/// compile-only stubs the design-time deploy gate binds candidate scripts
/// against; they must mirror the real SiteRuntime <see cref="ScriptGlobals"/> /
/// <see cref="TriggerExpressionGlobals"/> bind surfaces. If a member a script can
/// reference on the real globals is missing from the compile surface, a script
/// that uses it would pass the design-time gate but fail at the site — so the
/// compile surface's public top-level member NAMES must be a SUPERSET of the
/// real globals' names. This test fails loudly (listing the missing names) when
/// the surface drifts behind the runtime globals.
///
/// <para>
/// Top-level member-name parity is sufficient: the design-time compile against
/// the surface catches deeper signature mismatches itself; this guard only
/// ensures every entry point a script can name on the real globals exists on the
/// stub.
/// </para>
/// </summary>
public class CompileSurfaceParityTests
{
[Fact]
public void ScriptCompileSurface_MemberNames_AreSupersetOf_ScriptGlobals()
{
AssertSurfaceCoversGlobals(
surface: typeof(ScriptCompileSurface),
globals: typeof(ScriptGlobals));
}
[Fact]
public void TriggerCompileSurface_MemberNames_AreSupersetOf_TriggerExpressionGlobals()
{
AssertSurfaceCoversGlobals(
surface: typeof(TriggerCompileSurface),
globals: typeof(TriggerExpressionGlobals));
}
/// <summary>
/// Asserts that the public instance property + method member names of
/// <paramref name="surface"/> are a superset of those of
/// <paramref name="globals"/>. Inherited <see cref="object"/> members
/// (ToString/GetHashCode/Equals/GetType) are excluded. Fails with the exact
/// list of missing names when the surface does not cover the globals.
/// </summary>
private static void AssertSurfaceCoversGlobals(Type surface, Type globals)
{
var surfaceNames = PublicInstanceMemberNames(surface);
var globalsNames = PublicInstanceMemberNames(globals);
var missing = globalsNames
.Where(name => !surfaceNames.Contains(name))
.OrderBy(name => name, StringComparer.Ordinal)
.ToList();
Assert.True(
missing.Count == 0,
$"Compile surface '{surface.Name}' is missing {missing.Count} member name(s) "
+ $"present on '{globals.Name}': {string.Join(", ", missing)}. "
+ "The compile-only surface must mirror the runtime globals — add the "
+ "missing member(s) to the ScriptAnalysis surface type.");
}
/// <summary>
/// Public instance property + method member names declared on or inherited by
/// <paramref name="type"/>, excluding the inherited <see cref="object"/>
/// members (ToString, GetHashCode, Equals, GetType) so only script-reachable
/// API names remain. Property/method names are compared (no signatures).
/// </summary>
private static HashSet<string> PublicInstanceMemberNames(Type type)
{
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
var objectMembers = new HashSet<string>(StringComparer.Ordinal)
{
nameof(ToString),
nameof(GetHashCode),
nameof(Equals),
nameof(GetType),
};
var names = new HashSet<string>(StringComparer.Ordinal);
foreach (var property in type.GetProperties(flags))
names.Add(property.Name);
foreach (var method in type.GetMethods(flags))
{
// Skip compiler-generated property accessors (get_X / set_X) — the
// property itself is already counted by name above.
if (method.IsSpecialName)
continue;
if (objectMembers.Contains(method.Name))
continue;
names.Add(method.Name);
}
return names;
}
}
@@ -130,9 +130,10 @@ public class ScopeAccessorTests
[Fact]
public void AttributeValueCodec_Encode_IntList_ProducesJsonArray()
{
// Integer list elements encode via InvariantCulture IFormattable.
// Integer list elements encode as native-typed JSON numbers (NJ-1):
// [1,2,3], not the old quoted-element form ["1","2","3"].
var list = new List<int> { 1, 2, 3 };
var encoded = AttributeValueCodec.Encode(list);
Assert.Equal("[\"1\",\"2\",\"3\"]", encoded);
Assert.Equal("[1,2,3]", encoded);
}
}
@@ -5,6 +5,16 @@ namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Scripts;
/// <summary>
/// WP-19: Script Trust Model tests — validates forbidden API detection and compilation.
///
/// As of the M3.3 consolidation, <c>ScriptCompilationService.ValidateTrustModel</c>
/// delegates its forbidden-API verdict to the shared authoritative
/// <c>ScriptAnalysis.ScriptTrustValidator</c>, which is stricter than SiteRuntime's
/// original deny-list: ALL of <c>System.Net</c> is forbidden (not just Sockets/Http),
/// plus reflection gateways, <c>dynamic</c>, <c>Activator</c>,
/// <c>System.Runtime.InteropServices</c> and <c>Microsoft.Win32</c>. Only
/// <c>System.Diagnostics.Process</c> is blocked under System.Diagnostics —
/// <c>Stopwatch</c> stays allowed. The real execution-path compile against
/// <c>ScriptGlobals</c> / <c>TriggerExpressionGlobals</c> is unchanged.
/// </summary>
public class ScriptCompilationServiceTests
{
@@ -108,4 +118,61 @@ public class ScriptCompilationServiceTests
Assert.False(result.IsSuccess);
Assert.NotEmpty(result.Errors);
}
// ── M3.3: stricter shared-validator behavior ──
[Fact]
public void ValidateTrustModel_SystemNetDns_Forbidden()
{
// The shared validator forbids ALL of System.Net — not just Sockets/Http.
// System.Net.Dns was allowed under the old SiteRuntime list; now blocked.
var violations = _service.ValidateTrustModel(
"System.Net.Dns.GetHostName()");
Assert.NotEmpty(violations);
Assert.Contains(violations, v => v.Contains("System.Net"));
}
[Fact]
public void ValidateTrustModel_ReflectionGatewayViaPermittedType_Forbidden()
{
// typeof(x).Assembly.GetType(...) never spells a forbidden namespace, but
// the shared validator rejects the reflection-gateway members regardless of
// receiver — this was NOT caught by the old SiteRuntime list.
var violations = _service.ValidateTrustModel(
"typeof(string).Assembly.GetType(\"System.IO.File\")");
Assert.NotEmpty(violations);
}
[Fact]
public void ValidateTrustModel_Dynamic_Forbidden()
{
var violations = _service.ValidateTrustModel("dynamic d = 1; return d;");
Assert.NotEmpty(violations);
}
[Fact]
public void ValidateTrustModel_Activator_Forbidden()
{
var violations = _service.ValidateTrustModel(
"Activator.CreateInstance(typeof(string))");
Assert.NotEmpty(violations);
}
[Fact]
public void ValidateTrustModel_InteropServices_Forbidden()
{
var violations = _service.ValidateTrustModel(
"System.Runtime.InteropServices.Marshal.SizeOf<int>()");
Assert.NotEmpty(violations);
}
[Fact]
public void ValidateTrustModel_Stopwatch_Allowed()
{
// Only System.Diagnostics.Process is blocked under System.Diagnostics —
// Stopwatch stays allowed.
var violations = _service.ValidateTrustModel(
"var sw = System.Diagnostics.Stopwatch.StartNew(); return sw.ElapsedMilliseconds;");
Assert.Empty(violations);
}
}
@@ -8,6 +8,12 @@ namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Scripts;
/// The previous implementation was a raw substring scan of the source text — it both
/// missed forbidden APIs (no literal namespace string) and raised false positives on
/// the namespace string appearing in comments, string literals or unrelated identifiers.
///
/// As of M3.3, <c>ValidateTrustModel</c> delegates to the shared authoritative
/// <c>ScriptAnalysis.ScriptTrustValidator</c>, which retains this same Roslyn
/// semantic-symbol analysis (plus reflection-gateway hardening), so these bypass /
/// false-positive / allowed-exception regressions continue to hold through the
/// delegating service.
/// </summary>
public class TrustModelSemanticTests
{
@@ -25,6 +25,7 @@
<ItemGroup>
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.SiteRuntime/ZB.MOM.WW.ScadaBridge.SiteRuntime.csproj" />
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.csproj" />
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.Commons/ZB.MOM.WW.ScadaBridge.Commons.csproj" />
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/ZB.MOM.WW.ScadaBridge.HealthMonitoring.csproj" />
</ItemGroup>
@@ -2,17 +2,18 @@ using ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests.Validation;
/// <summary>
/// M3.2: the design-time deploy gate now delegates to the shared
/// <c>ZB.MOM.WW.ScadaBridge.ScriptAnalysis</c> analyzer — a real Roslyn semantic
/// forbidden-API verdict plus a real CSharpScript compile against the
/// runtime-mirroring <c>ScriptCompileSurface</c>. These tests assert the
/// authoritative behavior: bypasses the old substring scan missed are now caught,
/// and undefined symbols (which a structural scan could never see) fail compile.
/// </summary>
public class ScriptCompilerTests
{
private readonly ScriptCompiler _sut = new();
[Fact]
public void TryCompile_ValidCode_ReturnsSuccess()
{
var result = _sut.TryCompile("var x = 1; if (x > 0) { x++; }", "Test");
Assert.True(result.IsSuccess);
}
[Fact]
public void TryCompile_EmptyCode_ReturnsFailure()
{
@@ -22,29 +23,33 @@ public class ScriptCompilerTests
}
[Fact]
public void TryCompile_MismatchedBraces_ReturnsFailure()
public void TryCompile_WhitespaceOnly_ReturnsFailure()
{
var result = _sut.TryCompile("if (true) { x = 1;", "Test");
var result = _sut.TryCompile(" \n\t ", "Test");
Assert.True(result.IsFailure);
Assert.Contains("braces", result.Error, StringComparison.OrdinalIgnoreCase);
Assert.Contains("empty", result.Error, StringComparison.OrdinalIgnoreCase);
}
// --- Forbidden-API gate (authoritative) ---
[Fact]
public void TryCompile_UnclosedBlockComment_ReturnsFailure()
public void TryCompile_ForbiddenApi_ReturnsFailure()
{
var result = _sut.TryCompile("/* this is never closed", "Test");
var result = _sut.TryCompile("using System.IO; File.ReadAllText(\"x\");", "Test");
Assert.True(result.IsFailure);
Assert.Contains("comment", result.Error, StringComparison.OrdinalIgnoreCase);
Assert.Contains("forbidden", result.Error, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("System.IO.File.ReadAllText(\"x\");")]
[InlineData("System.Diagnostics.Process.Start(\"cmd\");")]
[InlineData("System.Threading.Thread.Sleep(1000);")]
[InlineData("System.Reflection.Assembly.Load(\"x\");")]
[InlineData("System.Net.Sockets.TcpClient c;")]
[InlineData("System.Net.Http.HttpClient c;")]
public void TryCompile_ForbiddenApi_ReturnsFailure(string code)
// Namespace alias — the old substring scan never saw "System.IO." spelled out.
[InlineData("using IO = System.IO; IO.File.ReadAllText(\"x\");")]
// using static — the call site is a bare ReadAllText(...) with no namespace text.
[InlineData("using static System.IO.File; ReadAllText(\"x\");")]
// global::-qualified reference.
[InlineData("global::System.IO.File.ReadAllText(\"x\");")]
// Reflection gateway — never spells a forbidden namespace at all.
[InlineData("typeof(string).Assembly.GetType(\"System.IO.File\");")]
public void TryCompile_AdversarialForbiddenApiBypass_StillRejected(string code)
{
var result = _sut.TryCompile(code, "Test");
Assert.True(result.IsFailure);
@@ -52,104 +57,82 @@ public class ScriptCompilerTests
}
[Fact]
public void TryCompile_BracesInStrings_Ignored()
public void TryCompile_ForbiddenTypeInAllowedNamespace_RejectedAsForbidden()
{
var result = _sut.TryCompile("var s = \"{ not a brace }\";", "Test");
Assert.True(result.IsSuccess);
}
[Fact]
public void TryCompile_BracesInComments_Ignored()
{
var result = _sut.TryCompile("// { not a brace\nvar x = 1;", "Test");
Assert.True(result.IsSuccess);
}
[Fact]
public void TryCompile_BlockCommentWithBraces_Ignored()
{
var result = _sut.TryCompile("/* { } */ var x = 1;", "Test");
Assert.True(result.IsSuccess);
}
// --- TemplateEngine-007 regression: string-literal awareness ---
[Fact]
public void TryCompile_VerbatimStringWithBrace_NotFlaggedAsMismatched()
{
// @"..." — backslash is literal, "" is the escape. The closing brace
// inside the verbatim string must not affect the brace balance.
var result = _sut.TryCompile("var s = @\"a brace } and a \\ slash\"; if (true) { }", "Test");
Assert.True(result.IsSuccess);
}
[Fact]
public void TryCompile_VerbatimStringWithEscapedQuote_NotFlaggedAsMismatched()
{
// The "" inside a verbatim string is an escaped quote, not a string end.
var result = _sut.TryCompile("var s = @\"he said \"\"hi}\"\"\"; { }", "Test");
Assert.True(result.IsSuccess);
}
[Fact]
public void TryCompile_InterpolatedStringWithBraces_NotFlaggedAsMismatched()
{
// The braces in $"{x}" are interpolation holes; the literal "}}" is an
// escaped brace. Neither should unbalance the real braces.
var result = _sut.TryCompile("var x = 1; var s = $\"val={x} literal}}\"; if (x>0) { x++; }", "Test");
Assert.True(result.IsSuccess);
}
[Fact]
public void TryCompile_RawStringLiteralWithBraces_NotFlaggedAsMismatched()
{
// C# 11 raw string literal — the triple quotes delimit, braces inside are text.
var result = _sut.TryCompile("var s = \"\"\"a } brace { in raw\"\"\"; { }", "Test");
Assert.True(result.IsSuccess);
}
[Fact]
public void TryCompile_CharLiteralWithBrace_NotFlaggedAsMismatched()
{
// A '}' char literal must not decrement the brace depth.
var result = _sut.TryCompile("var c = '}'; if (true) { }", "Test");
Assert.True(result.IsSuccess);
}
[Fact]
public void TryCompile_GenuineMismatchedBraces_StillDetected()
{
// Sanity check that the string-aware scan still catches real mismatches.
var result = _sut.TryCompile("var s = \"ok\"; if (true) { x++;", "Test");
Assert.True(result.IsFailure);
Assert.Contains("braces", result.Error, StringComparison.OrdinalIgnoreCase);
}
// --- TemplateEngine-006 regression: forbidden-API scan false positives ---
[Fact]
public void TryCompile_ForbiddenApiTextInsideStringLiteral_NotFlagged()
{
// "System.IO." appears only inside a string literal — it is inert text,
// not a use of the forbidden API, and must not be rejected.
var result = _sut.TryCompile("var msg = \"see System.IO.File docs\"; var x = 1;", "Test");
Assert.True(result.IsSuccess);
}
[Fact]
public void TryCompile_ForbiddenApiTextInsideComment_NotFlagged()
{
// "System.Threading." appears only inside a comment — inert.
var result = _sut.TryCompile("// avoid System.Threading.Thread here\nvar x = 1;", "Test");
Assert.True(result.IsSuccess);
}
[Fact]
public void TryCompile_ForbiddenApiInRealCode_StillFlagged()
{
// Sanity check: a genuine use in code is still rejected.
var result = _sut.TryCompile("var x = System.IO.File.ReadAllText(\"a\");", "Test");
// System.Diagnostics is an ALLOWED namespace (Stopwatch/Debug ok), so the
// `using` directive can't be flagged; Process is a forbidden TYPE reached
// as a bare identifier. The validator's full-framework semantic resolution
// must catch it authoritatively as a forbidden API (not merely as an
// undefined-symbol compile error).
var result = _sut.TryCompile(
"using System.Diagnostics; var p = Process.Start(\"x\");", "Test");
Assert.True(result.IsFailure);
Assert.Contains("forbidden", result.Error, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void TryCompile_StopwatchInAllowedDiagnostics_ReturnsSuccess()
{
// The companion to the Process case: Stopwatch lives in the same allowed
// System.Diagnostics namespace and must NOT be flagged.
var result = _sut.TryCompile(
"using System.Diagnostics; var sw = Stopwatch.StartNew(); var e = sw.ElapsedMilliseconds;",
"Test");
Assert.True(result.IsSuccess, result.IsFailure ? result.Error : null);
}
// --- Real-compile gate (the win over the old structural-only scan) ---
[Fact]
public void TryCompile_UndefinedSymbol_ReturnsFailure()
{
// A brace-balanced, forbidden-API-free script that references an undefined
// symbol. The old substring + brace scan accepted this; the real compile
// rejects it.
var result = _sut.TryCompile("var x = NoSuchThing.Foo();", "Test");
Assert.True(result.IsFailure);
Assert.Contains("compile", result.Error, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void TryCompile_SyntaxError_ReturnsFailure()
{
// Genuinely malformed — must fail the real compile.
var result = _sut.TryCompile("if (true) { var x = 1;", "Test");
Assert.True(result.IsFailure);
}
// --- Valid real script against the script API surface ---
[Fact]
public void TryCompile_ValidScriptUsingApiSurface_ReturnsSuccess()
{
const string code = """
var t = Attributes["Temperature"];
Attributes["Setpoint"] = 42;
var r = await ExternalSystem.Call("erp", "sync");
await Notify.To("ops").Send("s", "m");
""";
var result = _sut.TryCompile(code, "Test");
Assert.True(result.IsSuccess, result.IsFailure ? result.Error : null);
}
// --- Trigger-expression gate via ValidationService.CheckExpressionSyntax ---
[Fact]
public void CheckExpressionSyntax_ValidExpression_ReturnsNull()
{
// A bare boolean expression binding against the trigger globals surface.
var error = ValidationService.CheckExpressionSyntax("Attributes[\"Temp\"] != null");
Assert.Null(error);
}
[Fact]
public void CheckExpressionSyntax_ForbiddenApi_ReturnsMessage()
{
var error = ValidationService.CheckExpressionSyntax("System.IO.File.Exists(\"x\")");
Assert.NotNull(error);
Assert.Contains("forbidden", error, StringComparison.OrdinalIgnoreCase);
}
}