From 5a5513240901265cc913d0016b9099daf87896d4 Mon Sep 17 00:00:00 2001 From: waldekmastykarz Date: Sat, 21 Nov 2026 14:57:43 +0100 Subject: [PATCH 1/8] Cache schema validation and load plugin data files from a stream - Cache downloaded JSON schemas per process. - Skip validating a data file or plugin config section that hasn't changed since it last passed validation (keyed by path, size, last write time, schema URL and, when placeholders were resolved, a hash of the contents). Failed validations aren't cached. The schema version warning is kept. - Read $schema with Utf8JsonReader, stopping at the top-level property, instead of parsing the whole file into a JsonDocument. - Load JSON data files from the file stream instead of a string, so JsonSerializer no longer rents a UTF-8 buffer about 3x the string. YAML files and files with environment variable placeholders still go through the string path. BaseLoader.LoadData(string) is now virtual and a new LoadData(Stream) overload is used by built-in loaders. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Utils/ProxyUtilsTests.cs | 56 ++++++ DevProxy.Abstractions/Plugins/BaseLoader.cs | 178 +++++++++++++++--- DevProxy.Abstractions/Plugins/BasePlugin.cs | 14 +- .../Plugins/SchemaValidationCache.cs | 57 ++++++ DevProxy.Abstractions/Utils/ProxyUtils.cs | 175 ++++++++++++++++- .../Behavior/GenericErrorResponsesLoader.cs | 2 +- ...geModelRateLimitingCustomResponseLoader.cs | 2 +- .../RateLimitingCustomResponseLoader.cs | 2 +- .../Inspection/LanguageModelPricingLoader.cs | 2 +- .../Manipulation/RewritesLoader.cs | 2 +- DevProxy.Plugins/Mocking/CrudApiDataLoader.cs | 11 +- .../Mocking/CrudApiDefinitionLoader.cs | 2 +- DevProxy.Plugins/Mocking/MockRequestLoader.cs | 2 +- .../Mocking/MockResponsesLoader.cs | 2 +- .../Mocking/MockStdioResponsesLoader.cs | 2 +- .../Mocking/WebSocketMockResponsesLoader.cs | 2 +- .../Reporting/CsomTypesDefinitionLoader.cs | 2 +- .../BaseLoaderSchemaValidationTests.cs | 161 ++++++++++++++++ DevProxy.Tests/Fakes.cs | 2 +- 19 files changed, 626 insertions(+), 50 deletions(-) create mode 100644 DevProxy.Abstractions/Plugins/SchemaValidationCache.cs create mode 100644 DevProxy.Tests/BaseLoaderSchemaValidationTests.cs diff --git a/DevProxy.Abstractions.Tests/Utils/ProxyUtilsTests.cs b/DevProxy.Abstractions.Tests/Utils/ProxyUtilsTests.cs index 6016c6870..d870c8c73 100644 --- a/DevProxy.Abstractions.Tests/Utils/ProxyUtilsTests.cs +++ b/DevProxy.Abstractions.Tests/Utils/ProxyUtilsTests.cs @@ -98,4 +98,60 @@ public void SerializeBody_ObjectIsSerializedAsJson() using var doc = JsonDocument.Parse(body); Assert.Equal("hello", doc.RootElement.GetProperty("message").GetString()); } + + [Theory] + [InlineData("""{ "$schema": "https://example.test/schema.json", "mocks": [] }""")] + [InlineData("""{ "mocks": [{ "$schema": "nested" }], "$schema": "https://example.test/schema.json" }""")] + [InlineData(""" + // comment + { + "mocks": [], + "$schema": "https://example.test/schema.json", + } + """)] + public void ReadSchemaReference_ReturnsTopLevelSchema(string json) + { + using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)); + Assert.Equal("https://example.test/schema.json", ProxyUtils.ReadSchemaReference(stream)); + } + + [Theory] + [InlineData("""{ "mocks": [{ "$schema": "nested" }] }""")] + [InlineData("""[{ "$schema": "https://example.test/schema.json" }]""")] + [InlineData("""{ "$schema": null }""")] + public void ReadSchemaReference_ReturnsNullWithoutTopLevelSchema(string json) + { + using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)); + Assert.Null(ProxyUtils.ReadSchemaReference(stream)); + } + + [Fact] + public void ReadSchemaReference_StopsReadingAfterSchema() + { + using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes( + """{ "$schema": "https://example.test/schema.json", "mocks": [ invalid""")); + Assert.Equal("https://example.test/schema.json", ProxyUtils.ReadSchemaReference(stream)); + } + + [Fact] + public void ReadSchemaReference_ReadsTokensLargerThanBufferInSmallChunks() + { + var json = $$"""{ "body": "{{new string('a', 20_000)}}", "$schema": "https://example.test/schema.json" }"""; + var bytes = System.Text.Encoding.UTF8.GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(json)).ToArray(); + using var stream = new OneByteStream(bytes); + Assert.Equal("https://example.test/schema.json", ProxyUtils.ReadSchemaReference(stream)); + } + + [Fact] + public void ReadSchemaReference_ThrowsOnInvalidJsonBeforeSchema() + { + using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("""{ "mocks": [ invalid ], "$schema": "x" }""")); + Assert.ThrowsAny(() => ProxyUtils.ReadSchemaReference(stream)); + } + + private sealed class OneByteStream(byte[] bytes) : MemoryStream(bytes) + { + public override int Read(byte[] buffer, int offset, int count) => base.Read(buffer, offset, Math.Min(count, 1)); + public override int Read(Span buffer) => base.Read(buffer[..Math.Min(buffer.Length, 1)]); + } } diff --git a/DevProxy.Abstractions/Plugins/BaseLoader.cs b/DevProxy.Abstractions/Plugins/BaseLoader.cs index 8bd505f99..9ba2e4778 100644 --- a/DevProxy.Abstractions/Plugins/BaseLoader.cs +++ b/DevProxy.Abstractions/Plugins/BaseLoader.cs @@ -5,7 +5,10 @@ using DevProxy.Abstractions.Proxy; using DevProxy.Abstractions.Utils; using Microsoft.Extensions.Logging; -using System.Text.Json; +using System.Buffers; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; namespace DevProxy.Abstractions.Plugins; @@ -61,7 +64,26 @@ public async Task InitFileWatcherAsync(CancellationToken cancellationToken) await LoadFileContentsAsync(cancellationToken); } - protected abstract void LoadData(string fileContents); + /// + /// Loads the data from the file contents as a JSON string. YAML files are + /// converted to JSON first. Override this method or . + /// + protected virtual void LoadData(string fileContents) => + throw new NotImplementedException($"Override {nameof(LoadData)}(string) or {nameof(LoadData)}(Stream) in {GetType().Name}"); + + /// + /// Loads the data from the file contents as a UTF-8 JSON stream. YAML files + /// are converted to JSON first. Override this method instead of + /// to avoid materializing the whole file + /// as a string. The default implementation reads the stream into a string + /// and calls . The stream is disposed after + /// this method returns. + /// + protected virtual void LoadData(Stream fileContents) + { + using var reader = new StreamReader(fileContents, leaveOpen: true); + LoadData(reader.ReadToEnd()); + } protected virtual void Dispose(bool disposing) { @@ -80,22 +102,29 @@ protected virtual void Dispose(bool disposing) } } - private async Task ValidateFileContentsAsync(string fileContents, CancellationToken cancellationToken) + private async Task ValidateFileContentsAsync(Stream fileContents, SchemaValidationCache.FileVersion? fileVersion, CancellationToken cancellationToken) { - using var document = JsonDocument.Parse(fileContents, ProxyUtils.JsonDocumentOptions); - var root = document.RootElement; + var schemaUrl = ProxyUtils.ReadSchemaReference(fileContents); + fileContents.Position = 0; - // Schema validation only applies to JSON objects, not arrays - if (root.ValueKind != JsonValueKind.Object || - !root.TryGetProperty("$schema", out var schemaUrlElement)) + if (string.IsNullOrEmpty(schemaUrl)) { Logger.LogDebug("Schema reference not found in file {File}. Skipping schema validation", FilePath); return true; } - var schemaUrl = schemaUrlElement.GetString() ?? ""; ProxyUtils.ValidateSchemaVersion(schemaUrl, Logger); + + var cacheKey = SchemaValidationCache.CreateKey(FilePath, schemaUrl); + if (SchemaValidationCache.HasPassed(cacheKey, fileVersion)) + { + Logger.LogDebug("File {File} hasn't changed since it passed schema validation. Skipping schema validation", FilePath); + return true; + } + var (IsValid, ValidationErrors) = await ProxyUtils.ValidateJsonAsync(fileContents, schemaUrl, _httpClient, Logger, cancellationToken); + fileContents.Position = 0; + SchemaValidationCache.SetResult(cacheKey, fileVersion, IsValid); if (!IsValid) { @@ -123,41 +152,130 @@ private async Task LoadFileContentsAsync(CancellationToken cancellationToken) try { + // read before the contents so that a change while loading isn't missed + var fileVersion = SchemaValidationCache.GetFileVersion(FilePath); + using var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - using var reader = new StreamReader(stream); - var fileContents = await reader.ReadToEndAsync(cancellationToken); + if (!ProxyYaml.IsYamlFile(FilePath) && CanLoadFromFileStream(stream)) + { + stream.Position = 0; + await LoadJsonAsync(stream, fileVersion, cancellationToken); + return; + } - // Convert YAML to JSON if needed - string jsonContents; - if (ProxyYaml.IsYamlFile(FilePath)) + stream.Position = 0; + var jsonContents = await ReadJsonContentsAsync(stream, cancellationToken); + if (jsonContents is null) { - if (!ProxyYaml.TryConvertYamlToJson(fileContents, out var converted, out var error)) - { - Logger.LogError("Failed to parse YAML file {File}: {Error}", FilePath, error); - return; - } - jsonContents = converted!; + return; + } + + using var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonContents.Value.Json), writable: false); + await LoadJsonAsync(jsonStream, fileVersion is { } version ? version with { ContentHash = jsonContents.Value.ContentHash } : null, cancellationToken); + } + catch (Exception ex) + { + Logger.LogError(ex, "An error has occurred while reading {File}:", FilePath); + } + } + + private async Task LoadJsonAsync(Stream jsonContents, SchemaValidationCache.FileVersion? fileVersion, CancellationToken cancellationToken) + { + if (!_validateSchemas || await ValidateFileContentsAsync(jsonContents, fileVersion, cancellationToken)) + { + LoadData(jsonContents); + } + } + + /// + /// Reads the file as a string, converts YAML to JSON, and resolves environment variable placeholders. + /// + /// The JSON and, if placeholders changed the contents, a hash of the resolved JSON. + /// null if the YAML couldn't be converted. + private async Task<(string Json, string? ContentHash)?> ReadJsonContentsAsync(Stream stream, CancellationToken cancellationToken) + { + using var reader = new StreamReader(stream, leaveOpen: true); + var fileContents = await reader.ReadToEndAsync(cancellationToken); + + // Convert YAML to JSON if needed + string jsonContents; + if (ProxyYaml.IsYamlFile(FilePath)) + { + if (!ProxyYaml.TryConvertYamlToJson(fileContents, out var converted, out var error)) + { + Logger.LogError("Failed to parse YAML file {File}: {Error}", FilePath, error); + return null; + } + jsonContents = converted!; + } + else + { + jsonContents = fileContents; + } + + string? contentHash = null; + if (ResolveEnvironmentVariables) + { + var unresolvedVariables = new List(); + var resolvedContents = EnvironmentVariablePlaceholders.ResolveInJson(jsonContents, unresolvedVariables); + EnvironmentVariablePlaceholders.LogUnresolvedVariables(Logger, unresolvedVariables, FilePath); + + // the validated contents depend on environment variables, not only on the file + if (!ReferenceEquals(resolvedContents, jsonContents)) + { + contentHash = Convert.ToHexString(SHA256.HashData(MemoryMarshal.AsBytes(resolvedContents.AsSpan()))); + jsonContents = resolvedContents; } - else + } + + return (jsonContents, contentHash); + } + + /// + /// Returns true if the JSON file can be loaded as-is, without reading it into a string: + /// it's not UTF-16 or UTF-32 encoded, and (if placeholders are resolved) it doesn't + /// contain anything that could be a placeholder (${ or a \u escape). + /// + private bool CanLoadFromFileStream(Stream stream) + { + var buffer = ArrayPool.Shared.Rent(16 * 1024); + try + { + var read = stream.ReadAtLeast(buffer, 4, throwOnEndOfStream: false); + var start = buffer.AsSpan(0, read); + if (start.StartsWith((ReadOnlySpan)[0xFF, 0xFE]) || + start.StartsWith((ReadOnlySpan)[0xFE, 0xFF]) || + start.StartsWith((ReadOnlySpan)[0x00, 0x00, 0xFE, 0xFF])) { - jsonContents = fileContents; + return false; } - if (ResolveEnvironmentVariables) + if (!ResolveEnvironmentVariables) { - var unresolvedVariables = new List(); - jsonContents = EnvironmentVariablePlaceholders.ResolveInJson(jsonContents, unresolvedVariables); - EnvironmentVariablePlaceholders.LogUnresolvedVariables(Logger, unresolvedVariables, FilePath); + return true; } - if (!_validateSchemas || await ValidateFileContentsAsync(jsonContents, cancellationToken)) + byte previous = 0; + while (read > 0) { - LoadData(jsonContents); + foreach (var current in buffer.AsSpan(0, read)) + { + if ((previous == (byte)'$' && current == (byte)'{') || + (previous == (byte)'\\' && current == (byte)'u')) + { + return false; + } + // an escaped backslash can't start an escape sequence + previous = previous == (byte)'\\' && current == (byte)'\\' ? (byte)0 : current; + } + read = stream.Read(buffer); } + + return true; } - catch (Exception ex) + finally { - Logger.LogError(ex, "An error has occurred while reading {File}:", FilePath); + ArrayPool.Shared.Return(buffer); } } diff --git a/DevProxy.Abstractions/Plugins/BasePlugin.cs b/DevProxy.Abstractions/Plugins/BasePlugin.cs index 7f47ce16f..ac42b037a 100644 --- a/DevProxy.Abstractions/Plugins/BasePlugin.cs +++ b/DevProxy.Abstractions/Plugins/BasePlugin.cs @@ -201,6 +201,16 @@ public override async Task InitializeAsync(InitArgs e, CancellationToken cancell } var configSectionName = ConfigurationSection.Key; + var cacheKey = SchemaValidationCache.CreateKey(ProxyConfiguration.ConfigFile, schemaUrl, configSectionName); + // read before the contents so that a change while validating isn't missed + var fileVersion = SchemaValidationCache.GetFileVersion(ProxyConfiguration.ConfigFile); + if (SchemaValidationCache.HasPassed(cacheKey, fileVersion)) + { + ProxyUtils.ValidateSchemaVersion(schemaUrl, Logger); + Logger.LogDebug("Configuration section {SectionName} hasn't changed since it passed schema validation. Skipping schema validation", configSectionName); + return (true, []); + } + var configFile = await File.ReadAllTextAsync(ProxyConfiguration.ConfigFile, cancellationToken); using var document = JsonDocument.Parse(configFile, ProxyUtils.JsonDocumentOptions); @@ -213,7 +223,9 @@ public override async Task InitializeAsync(InitArgs e, CancellationToken cancell } ProxyUtils.ValidateSchemaVersion(schemaUrl, Logger); - return await ProxyUtils.ValidateJsonAsync(configSection.GetRawText(), schemaUrl, _httpClient, Logger, cancellationToken); + var result = await ProxyUtils.ValidateJsonAsync(configSection.GetRawText(), schemaUrl, _httpClient, Logger, cancellationToken); + SchemaValidationCache.SetResult(cacheKey, fileVersion, result.IsValid); + return result; } catch (Exception ex) { diff --git a/DevProxy.Abstractions/Plugins/SchemaValidationCache.cs b/DevProxy.Abstractions/Plugins/SchemaValidationCache.cs new file mode 100644 index 000000000..a64c2f7fd --- /dev/null +++ b/DevProxy.Abstractions/Plugins/SchemaValidationCache.cs @@ -0,0 +1,57 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Concurrent; + +namespace DevProxy.Abstractions.Plugins; + +/// +/// Remembers, per process, which files passed schema validation so that +/// unchanged files aren't validated again on every load or hot reload. +/// Only passes are stored. A file is considered unchanged when its size, +/// last write time and (optionally) a hash of the validated contents match. +/// +internal static class SchemaValidationCache +{ + internal readonly record struct Key(string FilePath, string SchemaUrl, string? Section); + internal readonly record struct FileVersion(long Length, long LastWriteTimeUtcTicks, string? ContentHash); + + // one entry per file, schema and section, so the cache doesn't grow when files change + private static readonly ConcurrentDictionary _passed = new(); + + public static Key CreateKey(string filePath, string schemaUrl, string? section = null) => + new(Path.GetFullPath(filePath), schemaUrl, section); + + public static FileVersion? GetFileVersion(string filePath, string? contentHash = null) + { + var fileInfo = new FileInfo(filePath); + return fileInfo.Exists + ? new(fileInfo.Length, fileInfo.LastWriteTimeUtc.Ticks, contentHash) + : null; + } + + public static bool HasPassed(Key key, FileVersion? version) => + version is not null && + _passed.TryGetValue(key, out var passedVersion) && + passedVersion == version; + + /// + /// Records the validation result. A pass is stored only if the file didn't + /// change while it was being validated ( is + /// read before reading the file and compared with the current version). + /// + public static void SetResult(Key key, FileVersion? versionBefore, bool isValid) + { + if (isValid && + versionBefore is { } before && + GetFileVersion(key.FilePath, before.ContentHash) == before) + { + _passed[key] = before; + } + else + { + _ = _passed.TryRemove(key, out _); + } + } +} diff --git a/DevProxy.Abstractions/Utils/ProxyUtils.cs b/DevProxy.Abstractions/Utils/ProxyUtils.cs index 7c5af6808..31e232066 100644 --- a/DevProxy.Abstractions/Utils/ProxyUtils.cs +++ b/DevProxy.Abstractions/Utils/ProxyUtils.cs @@ -8,6 +8,8 @@ using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Schema; +using System.Buffers; +using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.Reflection; using System.Text.Encodings.Web; @@ -28,6 +30,9 @@ sealed class ParsedSample public static class ProxyUtils { + private static readonly ConcurrentDictionary _schemaCache = new(StringComparer.Ordinal); + private static readonly byte[] _utf8Bom = [0xEF, 0xBB, 0xBF]; + private static readonly Regex itemPathRegex = new(@"(?:\/)[\w]+:[\w\/.]+(:(?=\/)|$)"); private static readonly Regex sanitizedItemPathRegex = new("^[a-z]+:$", RegexOptions.IgnoreCase); private static readonly Regex entityNameRegex = new("^((microsoft.graph(.[a-z]+)+)|[a-z]+)$", RegexOptions.IgnoreCase); @@ -292,11 +297,7 @@ public static string SanitizeUrl(string absoluteUrl) } ArgumentNullException.ThrowIfNull(httpClient); - logger.LogDebug("Downloading schema from {SchemaUrl}", schemaUrl); - var schemaContents = await httpClient.GetStringAsync(schemaUrl, cancellationToken); - - logger.LogDebug("Parsing schema"); - var schema = JSchema.Parse(schemaContents); + var schema = await GetSchemaAsync(schemaUrl, httpClient, logger, cancellationToken); logger.LogDebug("Parsing JSON"); var token = JToken.Parse(json); @@ -312,6 +313,170 @@ public static string SanitizeUrl(string absoluteUrl) } } + /// + /// Validates UTF-8 JSON read from against the schema at . + /// The stream is read from its current position and isn't disposed. + /// + public static async Task<(bool IsValid, IEnumerable ValidationErrors)> ValidateJsonAsync(Stream json, string? schemaUrl, HttpClient httpClient, ILogger logger, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(json); + ArgumentNullException.ThrowIfNull(logger); + + try + { + logger.LogDebug("Validating JSON against schema {SchemaUrl}", schemaUrl); + + if (json.CanSeek && json.Length - json.Position == 0) + { + logger.LogDebug("JSON is empty, skipping validation"); + return (true, []); + } + if (string.IsNullOrEmpty(schemaUrl)) + { + logger.LogDebug("Schema URL is empty, skipping validation"); + return (true, []); + } + ArgumentNullException.ThrowIfNull(httpClient); + + var schema = await GetSchemaAsync(schemaUrl, httpClient, logger, cancellationToken); + logger.LogDebug("Parsing JSON"); + JToken token; + // the JSON is read from a local or in-memory stream, where sync reads are cheaper than async ones +#pragma warning disable CA1849 + using (var streamReader = new StreamReader(json, leaveOpen: true)) + using (var jsonReader = new Newtonsoft.Json.JsonTextReader(streamReader)) + { + token = JToken.Load(jsonReader); + // same as JToken.Parse: fail on anything other than comments after the root value + while (jsonReader.Read()) + { + } + } +#pragma warning restore CA1849 + + logger.LogDebug("Validating JSON"); + var isValid = token.IsValid(schema, out IList errorMessages); + + return (isValid, errorMessages); + } + catch (Exception ex) + { + logger.LogDebug(ex, "Error validating JSON"); + return (false, [ex.Message]); + } + } + + // Schemas are downloaded once per process. Changes to a schema + // published online are picked up the next time Dev Proxy starts. + private static async Task GetSchemaAsync(string schemaUrl, HttpClient httpClient, ILogger logger, CancellationToken cancellationToken) + { + if (_schemaCache.TryGetValue(schemaUrl, out var cachedSchema)) + { + logger.LogDebug("Using cached schema {SchemaUrl}", schemaUrl); + return cachedSchema; + } + + logger.LogDebug("Downloading schema from {SchemaUrl}", schemaUrl); + var schemaContents = await httpClient.GetStringAsync(schemaUrl, cancellationToken); + + logger.LogDebug("Parsing schema"); + var schema = JSchema.Parse(schemaContents); + return _schemaCache.GetOrAdd(schemaUrl, schema); + } + + /// + /// Reads the value of the top-level $schema property from UTF-8 JSON without + /// parsing the whole document. Reading stops as soon as the property is found. + /// The stream is read from its current position and isn't disposed. + /// + /// The schema URL, or null if the root isn't an object or doesn't have a $schema property. + /// The JSON is invalid before the $schema property is found. + /// The $schema property isn't a string. + public static string? ReadSchemaReference(Stream utf8Json) + { + ArgumentNullException.ThrowIfNull(utf8Json); + + var buffer = ArrayPool.Shared.Rent(4096); + try + { + var state = new JsonReaderState(new JsonReaderOptions + { + AllowTrailingCommas = JsonDocumentOptions.AllowTrailingCommas, + CommentHandling = JsonDocumentOptions.CommentHandling + }); + + var dataLength = utf8Json.ReadAtLeast(buffer, _utf8Bom.Length, throwOnEndOfStream: false); + var isFinalBlock = dataLength < _utf8Bom.Length; + if (buffer.AsSpan(0, dataLength).StartsWith(_utf8Bom)) + { + buffer.AsSpan(_utf8Bom.Length, dataLength - _utf8Bom.Length).CopyTo(buffer); + dataLength -= _utf8Bom.Length; + } + + var isSchemaValue = false; + while (true) + { + if (!isFinalBlock && dataLength < buffer.Length) + { + var read = utf8Json.Read(buffer, dataLength, buffer.Length - dataLength); + isFinalBlock = read == 0; + dataLength += read; + } + + var reader = new Utf8JsonReader(buffer.AsSpan(0, dataLength), isFinalBlock, state); + while (reader.Read()) + { + if (isSchemaValue) + { + return reader.TokenType switch + { + JsonTokenType.String => reader.GetString(), + JsonTokenType.Null => null, + _ => throw new InvalidOperationException("The $schema property must be a string") + }; + } + + if (reader.CurrentDepth == 0) + { + if (reader.TokenType != JsonTokenType.StartObject) + { + return null; + } + } + else if (reader.CurrentDepth == 1 && + reader.TokenType == JsonTokenType.PropertyName && + reader.ValueTextEquals("$schema"u8)) + { + isSchemaValue = true; + } + } + + if (isFinalBlock) + { + return null; + } + + state = reader.CurrentState; + var consumed = (int)reader.BytesConsumed; + buffer.AsSpan(consumed, dataLength - consumed).CopyTo(buffer); + dataLength -= consumed; + + // a single token doesn't fit in the buffer + if (dataLength == buffer.Length) + { + var largerBuffer = ArrayPool.Shared.Rent(buffer.Length * 2); + buffer.AsSpan(0, dataLength).CopyTo(largerBuffer); + ArrayPool.Shared.Return(buffer); + buffer = largerBuffer; + } + } + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + public static string ReplaceVariables(string s, Dictionary variables, Func? formatVariableRef = null) { ArgumentNullException.ThrowIfNull(s); diff --git a/DevProxy.Plugins/Behavior/GenericErrorResponsesLoader.cs b/DevProxy.Plugins/Behavior/GenericErrorResponsesLoader.cs index a37d14aa9..16fe5dae5 100644 --- a/DevProxy.Plugins/Behavior/GenericErrorResponsesLoader.cs +++ b/DevProxy.Plugins/Behavior/GenericErrorResponsesLoader.cs @@ -21,7 +21,7 @@ internal sealed class GenericErrorResponsesLoader( protected override string FilePath => _configuration.ErrorsFile; - protected override void LoadData(string fileContents) + protected override void LoadData(Stream fileContents) { try { diff --git a/DevProxy.Plugins/Behavior/LanguageModelRateLimitingCustomResponseLoader.cs b/DevProxy.Plugins/Behavior/LanguageModelRateLimitingCustomResponseLoader.cs index cb5f3860a..31e797bc1 100644 --- a/DevProxy.Plugins/Behavior/LanguageModelRateLimitingCustomResponseLoader.cs +++ b/DevProxy.Plugins/Behavior/LanguageModelRateLimitingCustomResponseLoader.cs @@ -22,7 +22,7 @@ internal sealed class LanguageModelRateLimitingCustomResponseLoader( protected override string FilePath => _configuration.CustomResponseFile; - protected override void LoadData(string fileContents) + protected override void LoadData(Stream fileContents) { try { diff --git a/DevProxy.Plugins/Behavior/RateLimitingCustomResponseLoader.cs b/DevProxy.Plugins/Behavior/RateLimitingCustomResponseLoader.cs index 1a913045f..4b3d267d6 100644 --- a/DevProxy.Plugins/Behavior/RateLimitingCustomResponseLoader.cs +++ b/DevProxy.Plugins/Behavior/RateLimitingCustomResponseLoader.cs @@ -22,7 +22,7 @@ internal sealed class RateLimitingCustomResponseLoader( protected override string FilePath => _configuration.CustomResponseFile; - protected override void LoadData(string fileContents) + protected override void LoadData(Stream fileContents) { try { diff --git a/DevProxy.Plugins/Inspection/LanguageModelPricingLoader.cs b/DevProxy.Plugins/Inspection/LanguageModelPricingLoader.cs index bee49a763..d437482f1 100644 --- a/DevProxy.Plugins/Inspection/LanguageModelPricingLoader.cs +++ b/DevProxy.Plugins/Inspection/LanguageModelPricingLoader.cs @@ -22,7 +22,7 @@ internal sealed class LanguageModelPricesLoader( protected override string FilePath => _configuration.PricesFile ?? throw new ArgumentNullException(nameof(_configuration.PricesFile), "Prices file path must be set in the configuration."); - protected override void LoadData(string fileContents) + protected override void LoadData(Stream fileContents) { try { diff --git a/DevProxy.Plugins/Manipulation/RewritesLoader.cs b/DevProxy.Plugins/Manipulation/RewritesLoader.cs index a9bf172de..619060f0d 100644 --- a/DevProxy.Plugins/Manipulation/RewritesLoader.cs +++ b/DevProxy.Plugins/Manipulation/RewritesLoader.cs @@ -24,7 +24,7 @@ internal sealed class RewritesLoader( // as-is. RewritePlugin resolves ${env:NAME} per request. protected override bool ResolveEnvironmentVariables => false; - protected override void LoadData(string fileContents) + protected override void LoadData(Stream fileContents) { try { diff --git a/DevProxy.Plugins/Mocking/CrudApiDataLoader.cs b/DevProxy.Plugins/Mocking/CrudApiDataLoader.cs index b34e9a2c5..2d123b663 100644 --- a/DevProxy.Plugins/Mocking/CrudApiDataLoader.cs +++ b/DevProxy.Plugins/Mocking/CrudApiDataLoader.cs @@ -6,6 +6,7 @@ using DevProxy.Abstractions.Proxy; using DevProxy.Abstractions.Utils; using Microsoft.Extensions.Logging; +using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace DevProxy.Plugins.Mocking; @@ -27,11 +28,17 @@ internal sealed class CrudApiDataLoader( Path.GetDirectoryName(_configuration.ApiFile) ?? string.Empty ); - protected override void LoadData(string fileContents) + protected override void LoadData(Stream fileContents) { try { - var data = JArray.Parse(fileContents); + using var streamReader = new StreamReader(fileContents, leaveOpen: true); + using var jsonReader = new JsonTextReader(streamReader); + var data = JArray.Load(jsonReader); + // same as JArray.Parse: fail on anything other than comments after the array + while (jsonReader.Read()) + { + } _onDataLoaded(data); Logger.LogInformation( "Data for CRUD API loaded from {DataFile} for API {ApiFile}", diff --git a/DevProxy.Plugins/Mocking/CrudApiDefinitionLoader.cs b/DevProxy.Plugins/Mocking/CrudApiDefinitionLoader.cs index e268acfa1..c0c3b1bb7 100644 --- a/DevProxy.Plugins/Mocking/CrudApiDefinitionLoader.cs +++ b/DevProxy.Plugins/Mocking/CrudApiDefinitionLoader.cs @@ -21,7 +21,7 @@ internal sealed class CrudApiDefinitionLoader( protected override string FilePath => _configuration.ApiFile; - protected override void LoadData(string fileContents) + protected override void LoadData(Stream fileContents) { try { diff --git a/DevProxy.Plugins/Mocking/MockRequestLoader.cs b/DevProxy.Plugins/Mocking/MockRequestLoader.cs index 357ce10c7..6ff402889 100644 --- a/DevProxy.Plugins/Mocking/MockRequestLoader.cs +++ b/DevProxy.Plugins/Mocking/MockRequestLoader.cs @@ -21,7 +21,7 @@ internal sealed class MockRequestLoader( protected override string FilePath => _configuration.MockFile; - protected override void LoadData(string fileContents) + protected override void LoadData(Stream fileContents) { try { diff --git a/DevProxy.Plugins/Mocking/MockResponsesLoader.cs b/DevProxy.Plugins/Mocking/MockResponsesLoader.cs index bb56e1167..86302de49 100644 --- a/DevProxy.Plugins/Mocking/MockResponsesLoader.cs +++ b/DevProxy.Plugins/Mocking/MockResponsesLoader.cs @@ -21,7 +21,7 @@ internal sealed class MockResponsesLoader( protected override string FilePath => _configuration.MocksFile; - protected override void LoadData(string fileContents) + protected override void LoadData(Stream fileContents) { try { diff --git a/DevProxy.Plugins/Mocking/MockStdioResponsesLoader.cs b/DevProxy.Plugins/Mocking/MockStdioResponsesLoader.cs index f99aff97e..0c46c2bc9 100644 --- a/DevProxy.Plugins/Mocking/MockStdioResponsesLoader.cs +++ b/DevProxy.Plugins/Mocking/MockStdioResponsesLoader.cs @@ -21,7 +21,7 @@ internal sealed class MockStdioResponsesLoader( protected override string FilePath => _configuration.MocksFile; - protected override void LoadData(string fileContents) + protected override void LoadData(Stream fileContents) { try { diff --git a/DevProxy.Plugins/Mocking/WebSocketMockResponsesLoader.cs b/DevProxy.Plugins/Mocking/WebSocketMockResponsesLoader.cs index 7c2347420..963fab201 100644 --- a/DevProxy.Plugins/Mocking/WebSocketMockResponsesLoader.cs +++ b/DevProxy.Plugins/Mocking/WebSocketMockResponsesLoader.cs @@ -25,7 +25,7 @@ internal sealed class WebSocketMockResponsesLoader( protected override string FilePath => _configuration.MocksFile; - protected override void LoadData(string fileContents) + protected override void LoadData(Stream fileContents) { try { diff --git a/DevProxy.Plugins/Reporting/CsomTypesDefinitionLoader.cs b/DevProxy.Plugins/Reporting/CsomTypesDefinitionLoader.cs index 67e5083ee..e812759bc 100644 --- a/DevProxy.Plugins/Reporting/CsomTypesDefinitionLoader.cs +++ b/DevProxy.Plugins/Reporting/CsomTypesDefinitionLoader.cs @@ -22,7 +22,7 @@ internal sealed class CsomTypesDefinitionLoader( protected override string FilePath => _configuration.TypesFilePath!; - protected override void LoadData(string fileContents) + protected override void LoadData(Stream fileContents) { try { diff --git a/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs b/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs new file mode 100644 index 000000000..abdacf982 --- /dev/null +++ b/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs @@ -0,0 +1,161 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Concurrent; +using System.Net; +using DevProxy.Abstractions.Plugins; +using Microsoft.Extensions.Logging; +using Xunit; + +namespace DevProxy.Tests; + +public sealed class BaseLoaderSchemaValidationTests : IDisposable +{ + private const string Variable = "DEVPROXY_TEST_LOADER_SCHEMA_NAME"; + private const string Schema = """ + { + "type": "object", + "properties": { "name": { "type": "string", "maxLength": 5 } }, + "required": ["name"] + } + """; + private readonly string _folder = Directory.CreateTempSubdirectory("devproxy-loader-schema").FullName; + // unique per test so that the per-process schema and validation caches don't leak between tests + private readonly string _schemaUrl = $"https://schemas.example.test/{Guid.NewGuid()}/schema.json"; + private readonly SchemaHandler _handler = new(Schema); + private readonly HttpClient _httpClient; + private readonly TestLogger _logger = new(); + + public BaseLoaderSchemaValidationTests() => _httpClient = new(_handler); + + public void Dispose() + { + Environment.SetEnvironmentVariable(Variable, null); + _httpClient.Dispose(); + _handler.Dispose(); + Directory.Delete(_folder, true); + } + + [Fact] + public async Task DoesNotValidateUnchangedFileAgain() + { + var path = await WriteFileAsync("mocks.json", """{ "$schema": "{schema}", "name": "abc" }"""); + + var first = await LoadAsync(path); + var second = await LoadAsync(path); + + Assert.NotNull(first.Contents); + Assert.NotNull(second.Contents); + Assert.Equal(1, _logger.ValidationCount); + Assert.Equal(1, _handler.RequestCount); + } + + [Fact] + public async Task ValidatesChangedFileAgainWithCachedSchema() + { + var path = await WriteFileAsync("mocks.json", """{ "$schema": "{schema}", "name": "abc" }"""); + _ = await LoadAsync(path); + + _ = await WriteFileAsync("mocks.json", """{ "$schema": "{schema}", "name": "toolong" }"""); + var loader = await LoadAsync(path); + + Assert.Null(loader.Contents); + Assert.Equal(2, _logger.ValidationCount); + Assert.Equal(1, _handler.RequestCount); + } + + [Fact] + public async Task DoesNotCacheFailedValidation() + { + var path = await WriteFileAsync("mocks.json", """{ "$schema": "{schema}", "name": "toolong" }"""); + + var first = await LoadAsync(path); + var second = await LoadAsync(path); + + Assert.Null(first.Contents); + Assert.Null(second.Contents); + Assert.Equal(2, _logger.ValidationCount); + } + + [Fact] + public async Task ValidatesAgainWhenResolvedPlaceholdersChange() + { + var path = await WriteFileAsync("mocks.json", $$"""{ "$schema": "{schema}", "name": "${{{Variable}}}" }"""); + + Environment.SetEnvironmentVariable(Variable, "abc"); + var first = await LoadAsync(path); + Environment.SetEnvironmentVariable(Variable, "toolong"); + var second = await LoadAsync(path); + + Assert.NotNull(first.Contents); + Assert.Null(second.Contents); + Assert.Equal(2, _logger.ValidationCount); + } + + [Fact] + public async Task DoesNotValidateUnchangedYamlFileAgain() + { + var path = await WriteFileAsync("mocks.yaml", """ + $schema: "{schema}" + name: abc + """); + + var first = await LoadAsync(path); + var second = await LoadAsync(path); + + Assert.Contains("\"abc\"", first.Contents, StringComparison.Ordinal); + Assert.NotNull(second.Contents); + Assert.Equal(1, _logger.ValidationCount); + } + + private async Task WriteFileAsync(string fileName, string contents) + { + var path = Path.Combine(_folder, fileName); + await File.WriteAllTextAsync(path, contents.Replace("{schema}", _schemaUrl, StringComparison.Ordinal)); + return path; + } + + private async Task LoadAsync(string path) + { + var loader = new TestLoader(_httpClient, _logger, path); + await loader.InitFileWatcherAsync(CancellationToken.None); + loader.Dispose(); + return loader; + } + + private sealed class TestLoader(HttpClient httpClient, ILogger logger, string filePath) : + BaseLoader(httpClient, logger, new FakeProxyConfiguration { ValidateSchemas = true }) + { + public string? Contents { get; private set; } + protected override string FilePath => filePath; + protected override void LoadData(Stream fileContents) + { + using var reader = new StreamReader(fileContents); + Contents = reader.ReadToEnd(); + } + } + + private sealed class SchemaHandler(string schema) : HttpMessageHandler + { + private int _requestCount; + public int RequestCount => _requestCount; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + _ = Interlocked.Increment(ref _requestCount); + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(schema) }); + } + } + + private sealed class TestLogger : ILogger + { + private readonly ConcurrentQueue _messages = new(); + public int ValidationCount => _messages.Count(m => m.StartsWith("Validating JSON against schema", StringComparison.Ordinal)); + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel logLevel) => true; + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + _messages.Enqueue(formatter(state, exception)); + } +} diff --git a/DevProxy.Tests/Fakes.cs b/DevProxy.Tests/Fakes.cs index 39447f292..a9db7132f 100644 --- a/DevProxy.Tests/Fakes.cs +++ b/DevProxy.Tests/Fakes.cs @@ -87,7 +87,7 @@ internal sealed class FakeProxyConfiguration : IProxyConfiguration, IProcessTree public bool Record { get; set; } public bool ShowTimestamps => false; public long? TimeoutSeconds { get; set; } - public bool ValidateSchemas => false; + public bool ValidateSchemas { get; set; } public IEnumerable WatchPids { get; set; } = []; public IEnumerable WatchProcessNames { get; set; } = []; public bool WatchProcessTree { get; set; } From 884f59242c837343768d8e092bac8d3f3fee02e6 Mon Sep 17 00:00:00 2001 From: waldekmastykarz Date: Sat, 21 Nov 2026 15:05:25 +0100 Subject: [PATCH 2/8] Validate and load data files from a single snapshot Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Abstractions/Plugins/BaseLoader.cs | 82 ++++++++++----------- 1 file changed, 40 insertions(+), 42 deletions(-) diff --git a/DevProxy.Abstractions/Plugins/BaseLoader.cs b/DevProxy.Abstractions/Plugins/BaseLoader.cs index 9ba2e4778..1c62afbce 100644 --- a/DevProxy.Abstractions/Plugins/BaseLoader.cs +++ b/DevProxy.Abstractions/Plugins/BaseLoader.cs @@ -5,7 +5,6 @@ using DevProxy.Abstractions.Proxy; using DevProxy.Abstractions.Utils; using Microsoft.Extensions.Logging; -using System.Buffers; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; @@ -155,16 +154,20 @@ private async Task LoadFileContentsAsync(CancellationToken cancellationToken) // read before the contents so that a change while loading isn't missed var fileVersion = SchemaValidationCache.GetFileVersion(FilePath); - using var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - if (!ProxyYaml.IsYamlFile(FilePath) && CanLoadFromFileStream(stream)) + (string Json, string? ContentHash)? jsonContents; + // validate and load the same snapshot, so that a change to the file while + // loading can't publish contents that weren't validated + using (var snapshot = await ReadFileAsync(cancellationToken)) { - stream.Position = 0; - await LoadJsonAsync(stream, fileVersion, cancellationToken); - return; + if (!ProxyYaml.IsYamlFile(FilePath) && CanLoadAsIs(snapshot.GetBuffer().AsSpan(0, (int)snapshot.Length))) + { + await LoadJsonAsync(snapshot, fileVersion, cancellationToken); + return; + } + + jsonContents = await ReadJsonContentsAsync(snapshot, cancellationToken); } - stream.Position = 0; - var jsonContents = await ReadJsonContentsAsync(stream, cancellationToken); if (jsonContents is null) { return; @@ -231,52 +234,47 @@ private async Task LoadJsonAsync(Stream jsonContents, SchemaValidationCache.File return (jsonContents, contentHash); } + private async Task ReadFileAsync(CancellationToken cancellationToken) + { + using var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize: 0); + var snapshot = new MemoryStream((int)Math.Min(stream.Length, Array.MaxLength)); + await stream.CopyToAsync(snapshot, cancellationToken); + snapshot.Position = 0; + return snapshot; + } + /// /// Returns true if the JSON file can be loaded as-is, without reading it into a string: /// it's not UTF-16 or UTF-32 encoded, and (if placeholders are resolved) it doesn't /// contain anything that could be a placeholder (${ or a \u escape). /// - private bool CanLoadFromFileStream(Stream stream) + private bool CanLoadAsIs(ReadOnlySpan fileContents) { - var buffer = ArrayPool.Shared.Rent(16 * 1024); - try + if (fileContents.StartsWith((ReadOnlySpan)[0xFF, 0xFE]) || + fileContents.StartsWith((ReadOnlySpan)[0xFE, 0xFF]) || + fileContents.StartsWith((ReadOnlySpan)[0x00, 0x00, 0xFE, 0xFF])) { - var read = stream.ReadAtLeast(buffer, 4, throwOnEndOfStream: false); - var start = buffer.AsSpan(0, read); - if (start.StartsWith((ReadOnlySpan)[0xFF, 0xFE]) || - start.StartsWith((ReadOnlySpan)[0xFE, 0xFF]) || - start.StartsWith((ReadOnlySpan)[0x00, 0x00, 0xFE, 0xFF])) - { - return false; - } - - if (!ResolveEnvironmentVariables) - { - return true; - } - - byte previous = 0; - while (read > 0) - { - foreach (var current in buffer.AsSpan(0, read)) - { - if ((previous == (byte)'$' && current == (byte)'{') || - (previous == (byte)'\\' && current == (byte)'u')) - { - return false; - } - // an escaped backslash can't start an escape sequence - previous = previous == (byte)'\\' && current == (byte)'\\' ? (byte)0 : current; - } - read = stream.Read(buffer); - } + return false; + } + if (!ResolveEnvironmentVariables) + { return true; } - finally + + byte previous = 0; + foreach (var current in fileContents) { - ArrayPool.Shared.Return(buffer); + if ((previous == (byte)'$' && current == (byte)'{') || + (previous == (byte)'\\' && current == (byte)'u')) + { + return false; + } + // an escaped backslash can't start an escape sequence + previous = previous == (byte)'\\' && current == (byte)'\\' ? (byte)0 : current; } + + return true; } private void File_Changed(object sender, FileSystemEventArgs e) From 1826e2478191cae27c1694b941801365362337e3 Mon Sep 17 00:00:00 2001 From: waldekmastykarz Date: Sat, 21 Nov 2026 15:10:27 +0100 Subject: [PATCH 3/8] Recheck the file version before accepting a cached validation Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Plugins/SchemaValidationCache.cs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/DevProxy.Abstractions/Plugins/SchemaValidationCache.cs b/DevProxy.Abstractions/Plugins/SchemaValidationCache.cs index a64c2f7fd..4f31ebf86 100644 --- a/DevProxy.Abstractions/Plugins/SchemaValidationCache.cs +++ b/DevProxy.Abstractions/Plugins/SchemaValidationCache.cs @@ -31,10 +31,17 @@ public static Key CreateKey(string filePath, string schemaUrl, string? section = : null; } - public static bool HasPassed(Key key, FileVersion? version) => - version is not null && + /// + /// Returns true if the contents read after was + /// taken already passed validation. Call after reading the contents: the file + /// must still match , so that an edit made while + /// it was being read isn't mistaken for the version that passed. + /// + public static bool HasPassed(Key key, FileVersion? versionBefore) => + versionBefore is { } before && _passed.TryGetValue(key, out var passedVersion) && - passedVersion == version; + passedVersion == before && + GetFileVersion(key.FilePath, before.ContentHash) == before; /// /// Records the validation result. A pass is stored only if the file didn't From 7c7f168b92a0809f0ff8583478b6e4b864ef07b4 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 26 Nov 2026 14:54:23 +0100 Subject: [PATCH 4/8] Fix CA1068 in BaseLoaderSchemaValidationTests Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/BaseLoaderSchemaValidationTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs b/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs index 120eacc0d..668a53565 100644 --- a/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs +++ b/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs @@ -53,7 +53,7 @@ public async Task DoesNotLoadFileWhenCanceledWhileRetrievingSchema() { cts.Cancel(); throw new OperationCanceledException(cts.Token); - }, logger, cts.Token); + }, logger, cancellationToken: cts.Token); Assert.Null(loader.Contents); Assert.DoesNotContain(logger.Messages, m => m.LogLevel >= LogLevel.Warning); @@ -125,7 +125,7 @@ public async Task DoesNotLoadInvalidJsonWithoutSchemaReference(string contents) Assert.Contains(logger.Messages, m => m.LogLevel == LogLevel.Error); } - private async Task LoadAsync(Func sendSchemaRequest, ILogger logger, CancellationToken cancellationToken = default, string? contents = null) + private async Task LoadAsync(Func sendSchemaRequest, ILogger logger, string? contents = null, CancellationToken cancellationToken = default) { var path = Path.Combine(_folder, "mocks.json"); await File.WriteAllTextAsync(path, contents ?? Contents, CancellationToken.None); From 28bcd393480cc6e53b1f8e6d247a019862113340 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 26 Nov 2026 14:58:51 +0100 Subject: [PATCH 5/8] Throw on canceled token before schema cache lookup; test plugin section validation cache Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Utils/ProxyUtilsTests.cs | 11 +++ DevProxy.Abstractions/Utils/ProxyUtils.cs | 2 + .../BasePluginSchemaValidationTests.cs | 78 +++++++++++++++++++ 3 files changed, 91 insertions(+) diff --git a/DevProxy.Abstractions.Tests/Utils/ProxyUtilsTests.cs b/DevProxy.Abstractions.Tests/Utils/ProxyUtilsTests.cs index 2ffc854b9..e1d928017 100644 --- a/DevProxy.Abstractions.Tests/Utils/ProxyUtilsTests.cs +++ b/DevProxy.Abstractions.Tests/Utils/ProxyUtilsTests.cs @@ -38,6 +38,17 @@ public async Task ValidateJsonAgainstSchemaAsync_Canceled_Throws() ProxyUtils.ValidateJsonAgainstSchemaAsync("""{ "name": 1 }""", _schemaUrl, httpClient, NullLogger.Instance, new CancellationToken(true))); } + [Fact] + public async Task ValidateJsonAgainstSchemaAsync_CanceledWithCachedSchema_Throws() + { + using var handler = new StubHttpMessageHandler(_ => new(HttpStatusCode.OK) { Content = new StringContent(Schema) }); + using var httpClient = new HttpClient(handler); + _ = await ProxyUtils.ValidateJsonAgainstSchemaAsync("""{ "name": "a" }""", _schemaUrl, httpClient, NullLogger.Instance, CancellationToken.None); + + _ = await Assert.ThrowsAnyAsync(() => + ProxyUtils.ValidateJsonAgainstSchemaAsync("""{ "name": "a" }""", _schemaUrl, httpClient, NullLogger.Instance, new CancellationToken(true))); + } + [Fact] public async Task ValidateJsonAsync_Canceled_ReturnsInvalid() { diff --git a/DevProxy.Abstractions/Utils/ProxyUtils.cs b/DevProxy.Abstractions/Utils/ProxyUtils.cs index a89864edf..18d676e7f 100644 --- a/DevProxy.Abstractions/Utils/ProxyUtils.cs +++ b/DevProxy.Abstractions/Utils/ProxyUtils.cs @@ -432,6 +432,8 @@ public static async Task ValidateJsonAgainstSchemaAsync( // published online are picked up the next time Dev Proxy starts. private static async Task GetSchemaAsync(string schemaUrl, HttpClient httpClient, ILogger logger, CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); + if (_schemaCache.TryGetValue(schemaUrl, out var cachedSchema)) { logger.LogDebug("Using cached schema {SchemaUrl}", schemaUrl); diff --git a/DevProxy.Tests/BasePluginSchemaValidationTests.cs b/DevProxy.Tests/BasePluginSchemaValidationTests.cs index 4bece78b3..d62f08dc5 100644 --- a/DevProxy.Tests/BasePluginSchemaValidationTests.cs +++ b/DevProxy.Tests/BasePluginSchemaValidationTests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Net; using DevProxy.Abstractions.Plugins; using DevProxy.Abstractions.Proxy; using Microsoft.Extensions.Configuration; @@ -13,7 +14,15 @@ namespace DevProxy.Tests; public sealed class BasePluginSchemaValidationTests : IDisposable { + private const string Schema = """ + { + "type": "object", + "properties": { "name": { "type": "string", "maxLength": 5 } } + } + """; private readonly string _folder = Directory.CreateTempSubdirectory("devproxy-plugin").FullName; + // unique per test so that the per-process schema and validation caches don't leak between tests + private readonly string _schemaUrl = $"https://schemas.example.test/plugin-{Guid.NewGuid()}.json"; public void Dispose() => Directory.Delete(_folder, true); @@ -36,6 +45,75 @@ public async Task InitializeAsync_SchemaCannotBeRetrieved_LogsWarningInsteadOfEr Assert.DoesNotContain(logger.Messages, m => m.LogLevel >= LogLevel.Error); } + [Fact] + public async Task InitializeAsync_UnchangedSection_SkipsValidation() + { + var configFile = await WriteConfigAsync("""{ "testPlugin": { "$schema": "{schema}", "name": "abc" } }"""); + + var first = await InitializeAsync(configFile, "testPlugin"); + var second = await InitializeAsync(configFile, "testPlugin"); + + Assert.Equal(1, ValidationCount(first)); + Assert.Equal(0, ValidationCount(second)); + Assert.DoesNotContain(second.Messages, m => m.LogLevel >= LogLevel.Warning); + } + + [Fact] + public async Task InitializeAsync_SectionChangedToInvalid_ValidatesAgain() + { + var configFile = await WriteConfigAsync("""{ "testPlugin": { "$schema": "{schema}", "name": "abc" } }"""); + _ = await InitializeAsync(configFile, "testPlugin"); + + _ = await WriteConfigAsync("""{ "testPlugin": { "$schema": "{schema}", "name": "toolong" } }"""); + var logger = await InitializeAsync(configFile, "testPlugin"); + + Assert.Equal(1, ValidationCount(logger)); + Assert.Contains(logger.Messages, m => m.LogLevel == LogLevel.Error && m.Message.Contains("validation failed", StringComparison.Ordinal)); + } + + [Fact] + public async Task InitializeAsync_SectionsSharingSchema_AreCachedIndependently() + { + var configFile = await WriteConfigAsync(""" + { + "validPlugin": { "$schema": "{schema}", "name": "abc" }, + "invalidPlugin": { "$schema": "{schema}", "name": "toolong" } + } + """); + _ = await InitializeAsync(configFile, "validPlugin"); + + var invalid = await InitializeAsync(configFile, "invalidPlugin"); + var valid = await InitializeAsync(configFile, "validPlugin"); + + Assert.Equal(1, ValidationCount(invalid)); + Assert.Contains(invalid.Messages, m => m.LogLevel == LogLevel.Error && m.Message.Contains("validation failed", StringComparison.Ordinal)); + Assert.Equal(0, ValidationCount(valid)); + } + + private static int ValidationCount(RecordingLogger logger) => + logger.Messages.Count(m => m.Message.StartsWith("Validating JSON against schema", StringComparison.Ordinal)); + + private async Task WriteConfigAsync(string contents) + { + var configFile = Path.Combine(_folder, "devproxyrc.json"); + await File.WriteAllTextAsync(configFile, contents.Replace("{schema}", _schemaUrl, StringComparison.Ordinal)); + return configFile; + } + + private static async Task InitializeAsync(string configFile, string sectionName) + { + var configurationSection = new ConfigurationBuilder().AddJsonFile(configFile).Build().GetSection(sectionName); + var proxyConfiguration = new FakeProxyConfiguration { ConfigFile = configFile, ValidateSchemas = true }; + var logger = new RecordingLogger(); + using var handler = new FakeHttpMessageHandler(_ => new(HttpStatusCode.OK) { Content = new StringContent(Schema) }); + using var httpClient = new HttpClient(handler); + using var plugin = new TestPlugin(httpClient, logger, proxyConfiguration, configurationSection); + using var serviceProvider = new ServiceCollection().BuildServiceProvider(); + + await plugin.InitializeAsync(new() { ServiceProvider = serviceProvider }, CancellationToken.None); + return logger; + } + private sealed class TestPlugin(HttpClient httpClient, ILogger logger, IProxyConfiguration proxyConfiguration, IConfigurationSection configurationSection) : BasePlugin(httpClient, logger, new HashSet(), proxyConfiguration, configurationSection) { From 056c963458d9dc070b6b9ce37de2c1b57d289b70 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 26 Nov 2026 15:33:20 +0100 Subject: [PATCH 6/8] Test that a malformed reload keeps previously loaded data Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../BaseLoaderSchemaValidationTests.cs | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs b/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs index 668a53565..a4e7184d5 100644 --- a/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs +++ b/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs @@ -125,6 +125,28 @@ public async Task DoesNotLoadInvalidJsonWithoutSchemaReference(string contents) Assert.Contains(logger.Messages, m => m.LogLevel == LogLevel.Error); } + [Fact] + public async Task KeepsLoadedDataWhenReloadedFileIsInvalidJson() + { + var timeout = TimeSpan.FromSeconds(10); + const string validContents = """[{ "id": 2, "name": "reloaded" }]"""; + var path = Path.Combine(_folder, "items.json"); + await File.WriteAllTextAsync(path, validContents, CancellationToken.None); + using var handler = new FakeHttpMessageHandler(_ => new(HttpStatusCode.OK) { Content = new StringContent(Schema) }); + using var httpClient = new HttpClient(handler); + var errorLogged = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var logger = new ErrorSignalingLogger(errorLogged); + using var loader = new TestLoader(httpClient, logger, path); + await loader.InitFileWatcherAsync(CancellationToken.None); + Assert.Equal(validContents, loader.Contents); + + await File.WriteAllTextAsync(path, """[{ "id": 3, "name": "invalid" }] { "extra": true }""", CancellationToken.None); + await errorLogged.Task.WaitAsync(timeout); + + Assert.Equal(validContents, loader.Contents); + Assert.Equal([validContents], loader.LoadedContents); + } + private async Task LoadAsync(Func sendSchemaRequest, ILogger logger, string? contents = null, CancellationToken cancellationToken = default) { var path = Path.Combine(_folder, "mocks.json"); @@ -203,6 +225,21 @@ protected override void LoadData(string fileContents) } } + private sealed class ErrorSignalingLogger(TaskCompletionSource errorLogged) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + if (logLevel >= LogLevel.Error) + { + _ = errorLogged.TrySetResult(); + } + } + } + private sealed class AsyncHttpMessageHandler(Func> send) : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => From 155050d257b748f2a1c2025f2e8c218922eed326 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Fri, 27 Nov 2026 10:03:35 +0100 Subject: [PATCH 7/8] Reject malformed JSON on schema fallback paths and keep stream validation overload internal - Fully check JSON syntax before loading when $schema is null/empty or the schema can't be retrieved - Make ValidateJsonAgainstSchemaAsync(Stream, ...) internal to avoid ambiguous null calls Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Abstractions/Plugins/BaseLoader.cs | 10 +++++++ DevProxy.Abstractions/Utils/ProxyUtils.cs | 26 ++++++++++++++++--- .../BaseLoaderSchemaValidationTests.cs | 24 +++++++++++++++++ 3 files changed, 56 insertions(+), 4 deletions(-) diff --git a/DevProxy.Abstractions/Plugins/BaseLoader.cs b/DevProxy.Abstractions/Plugins/BaseLoader.cs index 4b2fd63e0..6a2c9e51f 100644 --- a/DevProxy.Abstractions/Plugins/BaseLoader.cs +++ b/DevProxy.Abstractions/Plugins/BaseLoader.cs @@ -127,6 +127,7 @@ private async Task ValidateFileContentsAsync(Stream fileContents, SchemaVa if (string.IsNullOrEmpty(schemaUrl)) { Logger.LogDebug("Schema reference not found in file {File}. Skipping schema validation", FilePath); + EnsureValidJson(fileContents); return true; } @@ -150,6 +151,7 @@ private async Task ValidateFileContentsAsync(Stream fileContents, SchemaVa { Logger.LogWarning("Skipping schema validation for {File} because the schema {SchemaUrl} could not be retrieved: {Error}", FilePath, schemaUrl, string.Join(", ", result.Errors)); } + EnsureValidJson(fileContents); return true; } @@ -165,6 +167,14 @@ private async Task ValidateFileContentsAsync(Stream fileContents, SchemaVa return true; } + // Without schema validation, JSON that's invalid after the $schema property + // must still be rejected, so that it doesn't replace previously loaded data + private static void EnsureValidJson(Stream fileContents) + { + ProxyUtils.EnsureValidJson(fileContents); + fileContents.Position = 0; + } + private async Task LoadFileContentsAsync(CancellationToken cancellationToken) { if (_isDisposed) diff --git a/DevProxy.Abstractions/Utils/ProxyUtils.cs b/DevProxy.Abstractions/Utils/ProxyUtils.cs index 62ac0dd9a..a1170f5fd 100644 --- a/DevProxy.Abstractions/Utils/ProxyUtils.cs +++ b/DevProxy.Abstractions/Utils/ProxyUtils.cs @@ -482,7 +482,7 @@ SchemaValidationResult Validate(JSchema schema) /// so that callers can skip validation instead of treating the document as invalid. /// /// was canceled. - public static Task ValidateJsonAgainstSchemaAsync(Stream json, string? schemaUrl, HttpClient httpClient, ILogger logger, CancellationToken cancellationToken) => + internal static Task ValidateJsonAgainstSchemaAsync(Stream json, string? schemaUrl, HttpClient httpClient, ILogger logger, CancellationToken cancellationToken) => ValidateJsonAgainstSchemaAsync(json, schemaUrl, httpClient, logger, Path.Combine(AppFolder ?? string.Empty, "schemas"), NormalizeVersion(ProductVersion), remoteSchemaFallbackTimeout, cancellationToken); internal static Task ValidateJsonAgainstSchemaAsync(Stream json, string? schemaUrl, HttpClient httpClient, ILogger logger, string? localSchemasFolder, string currentVersion, TimeSpan remoteSchemaFallbackTimeout, CancellationToken cancellationToken) @@ -551,7 +551,18 @@ private static async Task GetSchemaAsync(string schemaUrl, HttpClient h /// The schema URL, or null if the root isn't an object or doesn't have a $schema property. /// The JSON is invalid before the $schema property is found. /// The $schema property isn't a string. - public static string? ReadSchemaReference(Stream utf8Json) + public static string? ReadSchemaReference(Stream utf8Json) => + ReadSchemaReference(utf8Json, readToEnd: false); + + /// + /// Reads UTF-8 JSON to the end without materializing it, to check that it's valid JSON. + /// The stream is read from its current position and isn't disposed. + /// + /// The JSON is invalid. + internal static void EnsureValidJson(Stream utf8Json) => + _ = ReadSchemaReference(utf8Json, readToEnd: true); + + private static string? ReadSchemaReference(Stream utf8Json, bool readToEnd) { ArgumentNullException.ThrowIfNull(utf8Json); @@ -573,6 +584,7 @@ private static async Task GetSchemaAsync(string schemaUrl, HttpClient h } var isSchemaValue = false; + string? schemaUrl = null; bool? isRootObject = null; while (true) { @@ -588,12 +600,18 @@ private static async Task GetSchemaAsync(string schemaUrl, HttpClient h { if (isSchemaValue) { - return reader.TokenType switch + isSchemaValue = false; + schemaUrl = reader.TokenType switch { JsonTokenType.String => reader.GetString(), JsonTokenType.Null => null, _ => throw new InvalidOperationException("The $schema property must be a string") }; + if (!readToEnd) + { + return schemaUrl; + } + continue; } // keep reading a root that isn't an object, so that invalid JSON is reported @@ -609,7 +627,7 @@ private static async Task GetSchemaAsync(string schemaUrl, HttpClient h if (isFinalBlock) { - return null; + return schemaUrl; } state = reader.CurrentState; diff --git a/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs b/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs index a4e7184d5..0d9d8af3d 100644 --- a/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs +++ b/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs @@ -125,6 +125,30 @@ public async Task DoesNotLoadInvalidJsonWithoutSchemaReference(string contents) Assert.Contains(logger.Messages, m => m.LogLevel == LogLevel.Error); } + [Theory] + [InlineData("""{ "$schema": null, "name": }""")] + [InlineData("""{ "$schema": "", "name": }""")] + public async Task DoesNotLoadInvalidJsonAfterEmptySchemaReference(string contents) + { + var logger = new RecordingLogger(); + + var loader = await LoadAsync(_ => new(HttpStatusCode.OK) { Content = new StringContent(Schema) }, logger, contents: contents); + + Assert.Null(loader.Contents); + Assert.Contains(logger.Messages, m => m.LogLevel == LogLevel.Error); + } + + [Fact] + public async Task DoesNotLoadInvalidJsonWhenSchemaCannotBeRetrieved() + { + var logger = new RecordingLogger(); + + var loader = await LoadAsync(_ => throw new HttpRequestException("Connection refused"), logger, contents: $$"""{ "$schema": "{{_schemaUrl}}", "name": }"""); + + Assert.Null(loader.Contents); + Assert.Contains(logger.Messages, m => m.LogLevel == LogLevel.Error); + } + [Fact] public async Task KeepsLoadedDataWhenReloadedFileIsInvalidJson() { From f9ac1901cc74fcdd35e845413d9000786e8635e4 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Fri, 27 Nov 2026 13:25:54 +0100 Subject: [PATCH 8/8] Reject malformed JSON before schema validation in loaders The schema validator accepts JSON that System.Text.Json rejects, such as single-quoted strings, which let malformed data be loaded and cached as a successful validation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Abstractions/Plugins/BaseLoader.cs | 8 ++++--- .../BaseLoaderSchemaValidationCacheTests.cs | 23 ++++++++++++++++++- .../BaseLoaderSchemaValidationTests.cs | 21 +++++++++++++++++ 3 files changed, 48 insertions(+), 4 deletions(-) diff --git a/DevProxy.Abstractions/Plugins/BaseLoader.cs b/DevProxy.Abstractions/Plugins/BaseLoader.cs index 6a2c9e51f..4bb1a3783 100644 --- a/DevProxy.Abstractions/Plugins/BaseLoader.cs +++ b/DevProxy.Abstractions/Plugins/BaseLoader.cs @@ -140,6 +140,9 @@ private async Task ValidateFileContentsAsync(Stream fileContents, SchemaVa return true; } + // the schema validator accepts JSON that System.Text.Json rejects, such as + // single-quoted strings, so check the syntax first to not load or cache it + EnsureValidJson(fileContents); var result = await ProxyUtils.ValidateJsonAgainstSchemaAsync(fileContents, schemaUrl, _httpClient, Logger, cancellationToken); fileContents.Position = 0; // a pass without a schema isn't cached, so that the file is validated once the schema is available @@ -151,7 +154,6 @@ private async Task ValidateFileContentsAsync(Stream fileContents, SchemaVa { Logger.LogWarning("Skipping schema validation for {File} because the schema {SchemaUrl} could not be retrieved: {Error}", FilePath, schemaUrl, string.Join(", ", result.Errors)); } - EnsureValidJson(fileContents); return true; } @@ -167,8 +169,8 @@ private async Task ValidateFileContentsAsync(Stream fileContents, SchemaVa return true; } - // Without schema validation, JSON that's invalid after the $schema property - // must still be rejected, so that it doesn't replace previously loaded data + // JSON that's invalid after the $schema property must be rejected, + // so that it doesn't replace previously loaded data private static void EnsureValidJson(Stream fileContents) { ProxyUtils.EnsureValidJson(fileContents); diff --git a/DevProxy.Tests/BaseLoaderSchemaValidationCacheTests.cs b/DevProxy.Tests/BaseLoaderSchemaValidationCacheTests.cs index f453dc6f0..7eb88489e 100644 --- a/DevProxy.Tests/BaseLoaderSchemaValidationCacheTests.cs +++ b/DevProxy.Tests/BaseLoaderSchemaValidationCacheTests.cs @@ -78,6 +78,19 @@ public async Task DoesNotCacheFailedValidation() Assert.Equal(2, _logger.ValidationCount); } + [Fact] + public async Task DoesNotLoadOrCacheInvalidJsonThatMatchesSchema() + { + var path = await WriteFileAsync("mocks.json", """{ "$schema": "{schema}", "name": 'abc' }"""); + + var first = await LoadAsync(path); + var second = await LoadAsync(path); + + Assert.Null(first.Contents); + Assert.Null(second.Contents); + Assert.Equal(2, _logger.ErrorCount); + } + [Fact] public async Task ValidatesAgainWhenResolvedPlaceholdersChange() { @@ -151,11 +164,19 @@ protected override Task SendAsync(HttpRequestMessage reques private sealed class TestLogger : ILogger { private readonly ConcurrentQueue _messages = new(); + private int _errorCount; public int ValidationCount => _messages.Count(m => m.StartsWith("Validating JSON against schema", StringComparison.Ordinal)); + public int ErrorCount => _errorCount; public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + if (logLevel == LogLevel.Error) + { + _ = Interlocked.Increment(ref _errorCount); + } _messages.Enqueue(formatter(state, exception)); + } } } diff --git a/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs b/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs index 0d9d8af3d..e6d3aef02 100644 --- a/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs +++ b/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs @@ -171,6 +171,27 @@ public async Task KeepsLoadedDataWhenReloadedFileIsInvalidJson() Assert.Equal([validContents], loader.LoadedContents); } + [Fact] + public async Task KeepsLoadedDataWhenReloadedFileIsInvalidJsonThatMatchesSchema() + { + var timeout = TimeSpan.FromSeconds(10); + var validContents = $$"""{ "$schema": "{{_schemaUrl}}", "name": "previous" }"""; + var path = Path.Combine(_folder, "mocks.json"); + await File.WriteAllTextAsync(path, validContents, CancellationToken.None); + using var handler = new FakeHttpMessageHandler(_ => new(HttpStatusCode.OK) { Content = new StringContent(Schema) }); + using var httpClient = new HttpClient(handler); + var errorLogged = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var logger = new ErrorSignalingLogger(errorLogged); + using var loader = new TestLoader(httpClient, logger, path); + await loader.InitFileWatcherAsync(CancellationToken.None); + Assert.Equal(validContents, loader.Contents); + + await File.WriteAllTextAsync(path, $$"""{ "$schema": "{{_schemaUrl}}", "name": 'malformed' }""", CancellationToken.None); + await errorLogged.Task.WaitAsync(timeout); + + Assert.Equal([validContents], loader.LoadedContents); + } + private async Task LoadAsync(Func sendSchemaRequest, ILogger logger, string? contents = null, CancellationToken cancellationToken = default) { var path = Path.Combine(_folder, "mocks.json");