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
@@ -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>