fix(script-analysis): key the trust verdict cache on every verdict input (CMN-5, WP1 task 1.3)

TrustVerdictCache keyed on the code hash alone while the verdict also
depends on the analysis reference set (and its degraded-fallback mode).
The key is now (code SHA-256, degraded flag, base-reference fingerprint,
extra-reference digest), length-prefixed. File-backed extra references
are digested (path/size/mtime/kind/aliases/embed) so the Central UI run
gate's calls are cached under their own key; an extra reference with no
stable identity stays uncacheable.

The old extras test passed a PortableExecutableReference[] positionally,
which binds to the explicit-base overload, so it never exercised the
extras path; the tests now use the named argument.
This commit is contained in:
Joseph Doherty
2026-12-03 09:46:32 -05:00
parent a9549fbc6e
commit 5469ece012
5 changed files with 167 additions and 32 deletions
@@ -223,7 +223,7 @@ All five call sites that previously maintained their own script trust enforcemen
| **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 |
| **Transport** `BundleImporter.RunSemanticValidationAsync` / `DetectBlockersAsync` | No trust gate — a bundle's forbidden-API scripts imported clean, deferred to runtime (fifth write path) | Runs `ScriptTrustValidator.FindViolations` over every non-Skip template / shared / ApiMethod body, template script + alarm Expression-trigger bodies, **and instance alarm-override trigger expressions** at import review — hard error (apply) / Blocker row (preview) for all kinds |
**Trust verdicts are memoised (review 2026-10-21 04/P3).** `ScriptTrustValidator.FindViolations(code)` — the default-reference-set entry point every consumer above uses — caches its verdict process-wide by SHA-256 of the code (`TrustVerdictCache`: two generations of 1 024, cold-hit promotion, a throwing analysis is never stored; verdicts are returned as read-only collections and a hit returns the same instance). The verdict is a pure function of the code because the policy and `AnalysisReferences` are process-static. This removes the repeat full-framework semantic analysis the Transport importer used to pay on preview **and** again on apply (and on every wizard re-entry to preview) with no change at its call sites. A call that passes non-empty `extraReferences` (Central UI's run gate) bypasses the cache, since extra references can change resolution; the explicit-`baseReferences` overload is never cached.
**Trust verdicts are memoised (review 2026-10-21 04/P3).** `ScriptTrustValidator.FindViolations(code)` — the default-reference-set entry point every consumer above uses — caches its verdict process-wide (`TrustVerdictCache`: two generations of 1 024, cold-hit promotion, a throwing analysis is never stored; verdicts are returned as read-only collections and a hit returns the same instance). Since code review 2026-12-02 CMN-5 the key is every input the verdict depends on — the SHA-256 of the code, a fingerprint of `AnalysisReferences`, the `AnalysisReferencesDegraded` flag and a digest of the `extraReferences` — not the code alone; the base set and the flag are process-static today, but carrying them makes the memo self-invalidating if the resolution surface ever varies. This removes the repeat full-framework semantic analysis the Transport importer used to pay on preview **and** again on apply (and on every wizard re-entry to preview) with no change at its call sites. A call that passes non-empty `extraReferences` (Central UI's run gate) is cached under its own key when every extra reference is file-backed (digest = path, size, last-write time, kind, aliases, embed-interop flag), so it is never served the no-extras verdict or vice versa; an extra reference with no stable identity (an in-memory image) makes the call uncacheable. The explicit-`baseReferences` overload is never cached. (Note: a positional `PortableExecutableReference[]` second argument binds to that explicit-base overload, not to `extraReferences` — use the named argument.)
The static enforcement is **defence-in-depth**, not a true runtime sandbox. The denied API list blocks disallowed APIs at compile time but does not establish an operating-system security boundary. Site-runtime consumers execute in-process. Central UI Test Run uses a bounded, killable worker process; that adds resource/lifetime containment, while the worker retains the same operating-system identity and permitted gateway access.
@@ -70,23 +70,81 @@ public static class ScriptTrustValidator
/// </param>
/// <returns>
/// A read-only list of trust-model violation messages; empty if the script is clean.
/// When <paramref name="extraReferences"/> is null or empty the verdict is memoised
/// process-wide by code hash (a repeat call returns the same instance); a call with
/// extra references always analyses afresh, since they can change resolution.
/// The verdict is memoised process-wide (a repeat call returns the same instance),
/// keyed on the code, the analysis reference set (fingerprint + degraded flag) and a
/// digest of <paramref name="extraReferences"/>. Extra references without a stable
/// identity (not file-backed) cannot be digested, so such a call always analyses afresh.
/// </returns>
public static IReadOnlyList<string> FindViolations(
string code,
IEnumerable<MetadataReference>? extraReferences = null)
{
var extras = extraReferences as IReadOnlyCollection<MetadataReference> ?? extraReferences?.ToList();
if (extras is { Count: > 0 } || string.IsNullOrWhiteSpace(code))
if (string.IsNullOrWhiteSpace(code))
return FindViolations(code, ScriptTrustPolicy.AnalysisReferences, extras);
// Review 2026-10-21 04/P3: the default-reference verdict is a pure function of
// the code, so memoise it — the importer's preview and apply passes otherwise
// re-run a full-framework semantic analysis for every script, every time.
return TrustVerdictCache.GetOrAdd(code,
() => FindViolations(code, ScriptTrustPolicy.AnalysisReferences, extraReferences: null));
// Code review 2026-12-02 CMN-5: the extras are part of the key, so a call that
// widens resolution can never be served a verdict computed without them (or
// vice versa). An extra reference with no stable identity is uncacheable.
var extrasDigest = extras is { Count: > 0 } ? DigestExtraReferences(extras) : string.Empty;
if (extrasDigest is null)
return FindViolations(code, ScriptTrustPolicy.AnalysisReferences, extras);
// Review 2026-10-21 04/P3: the verdict is a pure function of its key, so memoise
// it — the importer's preview and apply passes otherwise re-run a full-framework
// semantic analysis for every script, every time.
var key = TrustVerdictCache.BuildKey(
code, ScriptTrustPolicy.AnalysisReferencesDegraded, BaseReferencesFingerprint.Value, extrasDigest);
return TrustVerdictCache.GetOrAdd(key,
() => FindViolations(code, ScriptTrustPolicy.AnalysisReferences, extras));
}
/// <summary>
/// Fingerprint of <see cref="ScriptTrustPolicy.AnalysisReferences"/> (the sorted
/// reference display names). Computed once — the set is process-static — but folded
/// into every cache key so the memo would self-invalidate if it ever changed.
/// </summary>
private static readonly Lazy<string> BaseReferencesFingerprint = new(() =>
HashLines(ScriptTrustPolicy.AnalysisReferences.Select(r => r.Display ?? string.Empty)));
/// <summary>
/// Digests a set of extra references for the verdict cache key, or returns
/// <c>null</c> when any of them has no stable identity. A file-backed reference is
/// identified by its path, size and last-write time (so a rebuilt assembly at the
/// same path is a different key) plus the reference properties that change binding
/// (aliases, embedded interop types). Anything else — an in-memory image, a
/// compilation reference — makes the call uncacheable.
/// </summary>
/// <param name="extras">The extra references.</param>
/// <returns>The digest, or <c>null</c> if the set cannot be cached.</returns>
internal static string? DigestExtraReferences(IEnumerable<MetadataReference> extras)
{
var lines = new List<string>();
foreach (var reference in extras)
{
if (reference is not PortableExecutableReference { FilePath: { Length: > 0 } path } pe)
return null;
var file = new FileInfo(path);
if (!file.Exists)
return null;
lines.Add(string.Join('|',
path,
file.Length.ToString(System.Globalization.CultureInfo.InvariantCulture),
file.LastWriteTimeUtc.Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture),
pe.Properties.Kind.ToString(),
pe.Properties.EmbedInteropTypes ? "embed" : "-",
string.Join(',', pe.Properties.Aliases)));
}
return HashLines(lines);
}
private static string HashLines(IEnumerable<string> lines)
{
var joined = string.Join('\n', lines);
return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(joined)));
}
/// <summary>
@@ -5,18 +5,22 @@ using System.Text;
namespace ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
/// <summary>
/// Process-wide memo of <see cref="ScriptTrustValidator"/> verdicts for the
/// default policy reference set, keyed on the SHA-256 of the script code (review
/// 2026-10-21 04/P3).
/// Process-wide memo of <see cref="ScriptTrustValidator"/> verdicts (review
/// 2026-10-21 04/P3), keyed on everything a verdict depends on (code review
/// 2026-12-02 CMN-5): the SHA-256 of the script code, the analysis reference set
/// (its fingerprint and the <see cref="ScriptTrustPolicy.AnalysisReferencesDegraded"/>
/// flag) and a digest of any caller-supplied extra references.
///
/// <para>
/// A verdict is a pure function of (code, <see cref="ScriptTrustPolicy"/>,
/// <see cref="ScriptTrustPolicy.AnalysisReferences"/>), and the policy and
/// reference set are process-static, so the code hash alone identifies it. Each
/// miss is a full-framework semantic analysis (~170 references) — the bundle
/// importer runs the same script set through it on preview and again on apply,
/// and the wizard re-enters preview — so memoising here removes that repeat cost
/// without any change at the call sites.
/// A verdict is a pure function of (code, <see cref="ScriptTrustPolicy"/>, the
/// base reference set, the extra references). The policy and the base set are
/// process-static today, but they are part of the key anyway so the memo is
/// self-invalidating if the resolution surface ever varies (lazy TPA discovery, a
/// degraded-mode toggle) instead of silently serving a verdict computed against a
/// different surface. Each miss is a full-framework semantic analysis (~170
/// references) — the bundle importer runs the same script set through it on preview
/// and again on apply, and the wizard re-enters preview — so memoising here removes
/// that repeat cost without any change at the call sites.
/// </para>
///
/// <para>
@@ -38,15 +42,31 @@ internal static class TrustVerdictCache
private static volatile ConcurrentDictionary<string, IReadOnlyList<string>> _cold = new();
/// <summary>
/// Returns the cached verdict for <paramref name="code"/>, or computes it with
/// <paramref name="analyse"/> and caches it on a miss.
/// Builds the cache key from every input a verdict depends on. Each component is
/// length-prefixed so no two distinct tuples can collide by concatenation.
/// </summary>
/// <param name="code">The script source.</param>
/// <param name="degraded">Whether the base analysis reference set is the degraded fallback.</param>
/// <param name="baseReferencesFingerprint">Fingerprint of the base analysis reference set.</param>
/// <param name="extraReferencesDigest">Digest of the extra references; empty when there are none.</param>
/// <returns>The cache key.</returns>
internal static string BuildKey(
string code, bool degraded, string baseReferencesFingerprint, string extraReferencesDigest)
{
var codeHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(code)));
return $"{codeHash}|{(degraded ? 'D' : 'F')}|{baseReferencesFingerprint.Length}:{baseReferencesFingerprint}" +
$"|{extraReferencesDigest.Length}:{extraReferencesDigest}";
}
/// <summary>
/// Returns the cached verdict for <paramref name="key"/>, or computes it with
/// <paramref name="analyse"/> and caches it on a miss.
/// </summary>
/// <param name="key">The full verdict key from <see cref="BuildKey"/>.</param>
/// <param name="analyse">Computes the verdict on a miss; a throw is not cached.</param>
/// <returns>The (read-only) violation list.</returns>
internal static IReadOnlyList<string> GetOrAdd(string code, Func<IReadOnlyList<string>> analyse)
internal static IReadOnlyList<string> GetOrAdd(string key, Func<IReadOnlyList<string>> analyse)
{
var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(code)));
var hot = _hot;
var cold = _cold;
@@ -12,6 +12,10 @@
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="ZB.MOM.WW.ScadaBridge.ScriptAnalysis.Tests" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.Commons/ZB.MOM.WW.ScadaBridge.Commons.csproj" />
</ItemGroup>
@@ -36,22 +36,75 @@ public class ScriptTrustValidatorCacheTests
}
/// <summary>
/// Verifies that a call with extra references is never served from (or stored in)
/// the cache — extra references can change symbol resolution, so the verdict is a
/// pure function of the code only for the default reference set.
/// Code review 2026-12-02 CMN-5: the extra references are part of the cache key, so a
/// call with extras is never served the no-extras verdict (or vice versa), while a
/// repeat call with the same file-backed extras is a cache hit.
/// </summary>
[Fact]
public void FindViolations_WithExtraReferences_BypassesCache()
public void FindViolations_WithExtraReferences_KeyedSeparatelyFromNoExtras()
{
var code = $"var x = System.IO.File.Exists(\"{Guid.NewGuid()}\");";
var extra = new[] { Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(ScriptCompileSurface).Assembly.Location) };
var a = ScriptTrustValidator.FindViolations(code, extra);
var b = ScriptTrustValidator.FindViolations(code, extra);
// Named argument: a PortableExecutableReference[] positional argument binds to the
// explicit-base-references overload instead (the pre-CMN-5 version of this test did
// exactly that, so it never exercised the extras path).
var a = ScriptTrustValidator.FindViolations(code, extraReferences: extra);
var b = ScriptTrustValidator.FindViolations(code, extraReferences: extra);
var cached = ScriptTrustValidator.FindViolations(code);
Assert.Same(a, b); // same extras → same key
Assert.NotSame(a, cached); // extras vs none → different keys
Assert.NotEmpty(a);
Assert.NotEmpty(cached);
}
/// <summary>An extra reference with no stable identity (an in-memory image) is never cached.</summary>
[Fact]
public void FindViolations_WithInMemoryExtraReference_BypassesCache()
{
var code = $"var x = System.IO.File.Exists(\"{Guid.NewGuid()}\");";
var image = File.ReadAllBytes(typeof(ScriptCompileSurface).Assembly.Location);
var extra = new[] { Microsoft.CodeAnalysis.MetadataReference.CreateFromImage(image) };
Assert.Null(ScriptTrustValidator.DigestExtraReferences(extra));
var a = ScriptTrustValidator.FindViolations(code, extraReferences: extra);
var b = ScriptTrustValidator.FindViolations(code, extraReferences: extra);
Assert.NotSame(a, b);
Assert.NotSame(a, cached);
Assert.NotSame(b, cached);
}
/// <summary>Distinct extra-reference sets digest differently; the same set digests the same.</summary>
[Fact]
public void DigestExtraReferences_DistinguishesSets()
{
var surface = Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(ScriptCompileSurface).Assembly.Location);
var surfaceAgain = Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(ScriptCompileSurface).Assembly.Location);
var linq = Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).Assembly.Location);
var aliased = surface.WithAliases(["other"]);
var one = ScriptTrustValidator.DigestExtraReferences([surface]);
Assert.NotNull(one);
Assert.Equal(one, ScriptTrustValidator.DigestExtraReferences([surfaceAgain]));
Assert.NotEqual(one, ScriptTrustValidator.DigestExtraReferences([surface, linq]));
Assert.NotEqual(one, ScriptTrustValidator.DigestExtraReferences([aliased]));
}
/// <summary>
/// The key carries every verdict input: code, the degraded flag, the base reference
/// fingerprint and the extras digest. Changing any one of them changes the key.
/// </summary>
[Fact]
public void BuildKey_ChangesWithEveryInput()
{
var baseKey = TrustVerdictCache.BuildKey("code", degraded: false, "fp", "");
Assert.Equal(baseKey, TrustVerdictCache.BuildKey("code", degraded: false, "fp", ""));
Assert.NotEqual(baseKey, TrustVerdictCache.BuildKey("code2", degraded: false, "fp", ""));
Assert.NotEqual(baseKey, TrustVerdictCache.BuildKey("code", degraded: true, "fp", ""));
Assert.NotEqual(baseKey, TrustVerdictCache.BuildKey("code", degraded: false, "fp2", ""));
Assert.NotEqual(baseKey, TrustVerdictCache.BuildKey("code", degraded: false, "fp", "x"));
// Length-prefixing: moving characters between components cannot collide.
Assert.NotEqual(
TrustVerdictCache.BuildKey("code", degraded: false, "ab", "c"),
TrustVerdictCache.BuildKey("code", degraded: false, "a", "bc"));
}
/// <summary>Verifies that the shared verdict cannot be mutated by a caller to poison the cache.</summary>