diff --git a/docs/requirements/Component-ScriptAnalysis.md b/docs/requirements/Component-ScriptAnalysis.md index 941bf8dd..948f403e 100644 --- a/docs/requirements/Component-ScriptAnalysis.md +++ b/docs/requirements/Component-ScriptAnalysis.md @@ -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. diff --git a/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ScriptTrustValidator.cs b/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ScriptTrustValidator.cs index 8156f411..489647f5 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ScriptTrustValidator.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ScriptTrustValidator.cs @@ -70,23 +70,81 @@ public static class ScriptTrustValidator /// /// /// A read-only list of trust-model violation messages; empty if the script is clean. - /// When 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 . Extra references without a stable + /// identity (not file-backed) cannot be digested, so such a call always analyses afresh. /// public static IReadOnlyList FindViolations( string code, IEnumerable? extraReferences = null) { var extras = extraReferences as IReadOnlyCollection ?? 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)); + } + + /// + /// Fingerprint of (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. + /// + private static readonly Lazy BaseReferencesFingerprint = new(() => + HashLines(ScriptTrustPolicy.AnalysisReferences.Select(r => r.Display ?? string.Empty))); + + /// + /// Digests a set of extra references for the verdict cache key, or returns + /// null 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. + /// + /// The extra references. + /// The digest, or null if the set cannot be cached. + internal static string? DigestExtraReferences(IEnumerable extras) + { + var lines = new List(); + 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 lines) + { + var joined = string.Join('\n', lines); + return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(joined))); } /// diff --git a/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/TrustVerdictCache.cs b/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/TrustVerdictCache.cs index cc1e5c11..9b60cef8 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/TrustVerdictCache.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/TrustVerdictCache.cs @@ -5,18 +5,22 @@ using System.Text; namespace ZB.MOM.WW.ScadaBridge.ScriptAnalysis; /// -/// Process-wide memo of 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 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 +/// flag) and a digest of any caller-supplied extra references. /// /// -/// A verdict is a pure function of (code, , -/// ), 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, , 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. /// /// /// @@ -38,15 +42,31 @@ internal static class TrustVerdictCache private static volatile ConcurrentDictionary> _cold = new(); /// - /// Returns the cached verdict for , or computes it with - /// 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. /// /// The script source. + /// Whether the base analysis reference set is the degraded fallback. + /// Fingerprint of the base analysis reference set. + /// Digest of the extra references; empty when there are none. + /// The cache key. + 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}"; + } + + /// + /// Returns the cached verdict for , or computes it with + /// and caches it on a miss. + /// + /// The full verdict key from . /// Computes the verdict on a miss; a throw is not cached. /// The (read-only) violation list. - internal static IReadOnlyList GetOrAdd(string code, Func> analyse) + internal static IReadOnlyList GetOrAdd(string key, Func> analyse) { - var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(code))); var hot = _hot; var cold = _cold; diff --git a/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.csproj b/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.csproj index 10236627..bd6f3545 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.csproj +++ b/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.csproj @@ -12,6 +12,10 @@ + + + + diff --git a/tests/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.Tests/ScriptTrustValidatorCacheTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.Tests/ScriptTrustValidatorCacheTests.cs index 9d374e20..444ca74f 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.Tests/ScriptTrustValidatorCacheTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.Tests/ScriptTrustValidatorCacheTests.cs @@ -36,22 +36,75 @@ public class ScriptTrustValidatorCacheTests } /// - /// 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. /// [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); + } + + /// An extra reference with no stable identity (an in-memory image) is never cached. + [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); + } + + /// Distinct extra-reference sets digest differently; the same set digests the same. + [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])); + } + + /// + /// 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. + /// + [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")); } /// Verifies that the shared verdict cannot be mutated by a caller to poison the cache.