diff --git a/DevProxy.Abstractions.Tests/Utils/ProxyUtilsSchemaValidationTests.cs b/DevProxy.Abstractions.Tests/Utils/ProxyUtilsSchemaValidationTests.cs index 188ebeda9..1714ef954 100644 --- a/DevProxy.Abstractions.Tests/Utils/ProxyUtilsSchemaValidationTests.cs +++ b/DevProxy.Abstractions.Tests/Utils/ProxyUtilsSchemaValidationTests.cs @@ -19,6 +19,11 @@ public sealed class ProxyUtilsSchemaValidationTests : IDisposable private const string JsonWithoutName = """{ "other": 1 }"""; private readonly string _schemasFolder = Directory.CreateTempSubdirectory("devproxy-schemas-").FullName; + // unique per test, because downloaded schemas are cached per process + private readonly string _schemaFile = $"{Guid.NewGuid()}.schema.json"; + + private string UniqueSchemaUrl(string version = CurrentVersion) => + $"https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v{version}/{_schemaFile}"; public void Dispose() => Directory.Delete(_schemasFolder, true); @@ -32,7 +37,7 @@ public sealed class ProxyUtilsSchemaValidationTests : IDisposable [InlineData("", false)] public void GetLocalSchemaPath_MapsOnlyCurrentVersionDevProxySchemas(string schemaUrl, bool expectLocal) { - WriteLocalSchema(AllowAnythingSchema); + File.WriteAllText(Path.Combine(_schemasFolder, SchemaFile), AllowAnythingSchema); var localPath = ProxyUtils.GetLocalSchemaPath(schemaUrl, CurrentVersion, _schemasFolder); @@ -52,7 +57,7 @@ public async Task ValidateJsonAgainstSchemaAsync_LocalSchemaValid_DoesNotDownloa WriteLocalSchema(AllowAnythingSchema); using var handler = new FakeHandler(_ => throw new InvalidOperationException("Unexpected HTTP call")); - var (isValid, errors) = await ValidateAsync(JsonWithoutName, SchemaUrl, handler); + var (isValid, errors) = await ValidateAsync(JsonWithoutName, UniqueSchemaUrl(), handler); Assert.True(isValid); Assert.Empty(errors); @@ -65,7 +70,7 @@ public async Task ValidateJsonAgainstSchemaAsync_LocalSchemaInvalid_UsesRemoteSc WriteLocalSchema(RequireNameSchema); using var handler = new FakeHandler(_ => Ok(AllowAnythingSchema)); - var (isValid, _) = await ValidateAsync(JsonWithoutName, SchemaUrl, handler); + var (isValid, _) = await ValidateAsync(JsonWithoutName, UniqueSchemaUrl(), handler); Assert.True(isValid); Assert.Equal(1, handler.CallCount); @@ -77,7 +82,7 @@ public async Task ValidateJsonAgainstSchemaAsync_LocalSchemaInvalidAndRemoteUnav WriteLocalSchema(RequireNameSchema); using var handler = new FakeHandler(_ => throw new HttpRequestException("offline")); - var (isValid, errors) = await ValidateAsync(JsonWithoutName, SchemaUrl, handler); + var (isValid, errors) = await ValidateAsync(JsonWithoutName, UniqueSchemaUrl(), handler); Assert.False(isValid); Assert.Contains(errors, e => e.Contains("name", StringComparison.Ordinal)); @@ -94,7 +99,7 @@ public async Task ValidateJsonAgainstSchemaAsync_LocalSchemaInvalidAndRemoteTime return await Ok(AllowAnythingSchema); }); - var (isValid, _) = await ValidateAsync(JsonWithoutName, SchemaUrl, handler, TimeSpan.FromMilliseconds(50)); + var (isValid, _) = await ValidateAsync(JsonWithoutName, UniqueSchemaUrl(), handler, TimeSpan.FromMilliseconds(50)); Assert.False(isValid); } @@ -102,7 +107,7 @@ public async Task ValidateJsonAgainstSchemaAsync_LocalSchemaInvalidAndRemoteTime [Fact] public async Task ValidateJsonAgainstSchemaAsync_NoLocalSchema_DownloadsSchema() { - const string otherVersionUrl = "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v4.0.0/test.schema.json"; + var otherVersionUrl = UniqueSchemaUrl("4.0.0"); WriteLocalSchema(AllowAnythingSchema); using var handler = new FakeHandler(_ => Ok(RequireNameSchema)); @@ -112,8 +117,40 @@ public async Task ValidateJsonAgainstSchemaAsync_NoLocalSchema_DownloadsSchema() Assert.Equal(1, handler.CallCount); } + [Fact] + public async Task ValidateJsonAgainstSchemaAsync_StreamWithLocalSchema_DoesNotDownloadSchema() + { + WriteLocalSchema(RequireNameSchema); + using var handler = new FakeHandler(_ => throw new InvalidOperationException("Unexpected HTTP call")); + using var httpClient = new HttpClient(handler, false); + using var json = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("""{ "name": "a" }""")); + + var result = await ProxyUtils.ValidateJsonAgainstSchemaAsync(json, UniqueSchemaUrl(), httpClient, NullLogger.Instance, _schemasFolder, CurrentVersion, TimeSpan.FromSeconds(5), CancellationToken.None); + + Assert.Equal(SchemaValidationStatus.Valid, result.Status); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task ValidateJsonAgainstSchemaAsync_StreamLocalSchemaInvalid_ValidatesAgainstRemoteSchemaOncePerProcess() + { + WriteLocalSchema(RequireNameSchema); + using var handler = new FakeHandler(_ => Ok(AllowAnythingSchema)); + using var httpClient = new HttpClient(handler, false); + var schemaUrl = UniqueSchemaUrl(); + + for (var i = 0; i < 2; i++) + { + using var json = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(JsonWithoutName)); + var result = await ProxyUtils.ValidateJsonAgainstSchemaAsync(json, schemaUrl, httpClient, NullLogger.Instance, _schemasFolder, CurrentVersion, TimeSpan.FromSeconds(5), CancellationToken.None); + Assert.Equal(SchemaValidationStatus.Valid, result.Status); + } + + Assert.Equal(1, handler.CallCount); + } + private void WriteLocalSchema(string contents) => - File.WriteAllText(Path.Combine(_schemasFolder, SchemaFile), contents); + File.WriteAllText(Path.Combine(_schemasFolder, _schemaFile), contents); private async Task<(bool IsValid, IEnumerable ValidationErrors)> ValidateAsync(string json, string schemaUrl, FakeHandler handler, TimeSpan? timeout = null) { diff --git a/DevProxy.Abstractions.Tests/Utils/ProxyUtilsTests.cs b/DevProxy.Abstractions.Tests/Utils/ProxyUtilsTests.cs index 3713e5ef3..e1d928017 100644 --- a/DevProxy.Abstractions.Tests/Utils/ProxyUtilsTests.cs +++ b/DevProxy.Abstractions.Tests/Utils/ProxyUtilsTests.cs @@ -12,7 +12,8 @@ namespace DevProxy.Abstractions.Tests.Utils; public class ProxyUtilsTests { - private const string SchemaUrl = "https://schemas.example.test/schema.json"; + // unique per test, because downloaded schemas are cached per process + private readonly string _schemaUrl = $"https://schemas.example.test/{Guid.NewGuid()}.json"; private const string Schema = """{ "properties": { "name": { "type": "string" } } }"""; [Fact] @@ -21,7 +22,7 @@ public async Task ValidateJsonAgainstSchemaAsync_SchemaDownloadFails_ReturnsSche using var handler = new StubHttpMessageHandler(_ => throw new HttpRequestException("Connection refused")); using var httpClient = new HttpClient(handler); - var result = await ProxyUtils.ValidateJsonAgainstSchemaAsync("""{ "name": 1 }""", SchemaUrl, httpClient, NullLogger.Instance, CancellationToken.None); + var result = await ProxyUtils.ValidateJsonAgainstSchemaAsync("""{ "name": 1 }""", _schemaUrl, httpClient, NullLogger.Instance, CancellationToken.None); Assert.Equal(SchemaValidationStatus.SchemaUnavailable, result.Status); Assert.Equal(["Connection refused"], result.Errors); @@ -34,7 +35,18 @@ public async Task ValidateJsonAgainstSchemaAsync_Canceled_Throws() using var httpClient = new HttpClient(handler); _ = await Assert.ThrowsAnyAsync(() => - ProxyUtils.ValidateJsonAgainstSchemaAsync("""{ "name": 1 }""", SchemaUrl, httpClient, NullLogger.Instance, new CancellationToken(true))); + 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] @@ -43,7 +55,7 @@ public async Task ValidateJsonAsync_Canceled_ReturnsInvalid() using var handler = new StubHttpMessageHandler(_ => new(HttpStatusCode.OK) { Content = new StringContent(Schema) }); using var httpClient = new HttpClient(handler); - var (isValid, errors) = await ProxyUtils.ValidateJsonAsync("""{ "name": "a" }""", SchemaUrl, httpClient, NullLogger.Instance, new CancellationToken(true)); + var (isValid, errors) = await ProxyUtils.ValidateJsonAsync("""{ "name": "a" }""", _schemaUrl, httpClient, NullLogger.Instance, new CancellationToken(true)); Assert.False(isValid); Assert.NotEmpty(errors); @@ -57,7 +69,7 @@ public async Task ValidateJsonAgainstSchemaAsync_ResponseIsNotSchema_ReturnsSche using var handler = new StubHttpMessageHandler(_ => new(statusCode) { Content = new StringContent(content) }); using var httpClient = new HttpClient(handler); - var result = await ProxyUtils.ValidateJsonAgainstSchemaAsync("""{ "name": 1 }""", SchemaUrl, httpClient, NullLogger.Instance, CancellationToken.None); + var result = await ProxyUtils.ValidateJsonAgainstSchemaAsync("""{ "name": 1 }""", _schemaUrl, httpClient, NullLogger.Instance, CancellationToken.None); Assert.Equal(SchemaValidationStatus.SchemaUnavailable, result.Status); } @@ -70,7 +82,7 @@ public async Task ValidateJsonAgainstSchemaAsync_SchemaRetrieved_ValidatesJson(s using var handler = new StubHttpMessageHandler(_ => new(HttpStatusCode.OK) { Content = new StringContent(Schema) }); using var httpClient = new HttpClient(handler); - var result = await ProxyUtils.ValidateJsonAgainstSchemaAsync(json, SchemaUrl, httpClient, NullLogger.Instance, CancellationToken.None); + var result = await ProxyUtils.ValidateJsonAgainstSchemaAsync(json, _schemaUrl, httpClient, NullLogger.Instance, CancellationToken.None); Assert.Equal(expectedStatus, result.Status); } @@ -164,6 +176,71 @@ public void SerializeBody_ObjectIsSerializedAsJson() 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)); + } + + [Theory] + [InlineData("""[{ "id": 1 }] { "extra": true }""")] + [InlineData("""{ "mocks": [] } { "extra": true }""")] + public void ReadSchemaReference_ThrowsOnInvalidJsonWithoutSchema(string json) + { + using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)); + Assert.ThrowsAny(() => 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)]); + } + private sealed class StubHttpMessageHandler(Func send) : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => diff --git a/DevProxy.Abstractions/Plugins/BaseLoader.cs b/DevProxy.Abstractions/Plugins/BaseLoader.cs index 34a46dc76..4bb1a3783 100644 --- a/DevProxy.Abstractions/Plugins/BaseLoader.cs +++ b/DevProxy.Abstractions/Plugins/BaseLoader.cs @@ -5,7 +5,9 @@ using DevProxy.Abstractions.Proxy; using DevProxy.Abstractions.Utils; using Microsoft.Extensions.Logging; -using System.Text.Json; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; namespace DevProxy.Abstractions.Plugins; @@ -66,7 +68,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()); + } /// /// Removes null entries from non-nullable collections and dictionaries in the @@ -98,22 +119,34 @@ 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); + EnsureValidJson(fileContents); 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; + } + + // 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 + SchemaValidationCache.SetResult(cacheKey, fileVersion, result.Status == SchemaValidationStatus.Valid); if (result.Status == SchemaValidationStatus.SchemaUnavailable) { @@ -136,6 +169,14 @@ private async Task ValidateFileContentsAsync(string fileContents, Cancella return true; } + // 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); + fileContents.Position = 0; + } + private async Task LoadFileContentsAsync(CancellationToken cancellationToken) { if (_isDisposed) @@ -166,37 +207,30 @@ private async Task LoadFileContentsAsync(CancellationToken cancellationToken) return; } - using var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - using var reader = new StreamReader(stream); - var fileContents = await reader.ReadToEndAsync(cancellationToken); + // read before the contents so that a change while loading isn't missed + var fileVersion = SchemaValidationCache.GetFileVersion(FilePath); - // Convert YAML to JSON if needed - string jsonContents; - if (ProxyYaml.IsYamlFile(FilePath)) + (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)) { - if (!ProxyYaml.TryConvertYamlToJson(fileContents, out var converted, out var error)) + if (!ProxyYaml.IsYamlFile(FilePath) && CanLoadAsIs(snapshot.GetBuffer().AsSpan(0, (int)snapshot.Length))) { - Logger.LogError("Failed to parse YAML file {File}: {Error}", FilePath, error); + await LoadJsonAsync(snapshot, fileVersion, cancellationToken); return; } - jsonContents = converted!; - } - else - { - jsonContents = fileContents; - } - if (ResolveEnvironmentVariables) - { - var unresolvedVariables = new List(); - jsonContents = EnvironmentVariablePlaceholders.ResolveInJson(jsonContents, unresolvedVariables); - EnvironmentVariablePlaceholders.LogUnresolvedVariables(Logger, unresolvedVariables, FilePath); + jsonContents = await ReadJsonContentsAsync(snapshot, cancellationToken); } - if (!_validateSchemas || await ValidateFileContentsAsync(jsonContents, cancellationToken)) + if (jsonContents is null) { - LoadData(jsonContents); + 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 (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -212,6 +246,101 @@ private async Task LoadFileContentsAsync(CancellationToken cancellationToken) } } + 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; + } + } + + 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 CanLoadAsIs(ReadOnlySpan fileContents) + { + if (fileContents.StartsWith((ReadOnlySpan)[0xFF, 0xFE]) || + fileContents.StartsWith((ReadOnlySpan)[0xFE, 0xFF]) || + fileContents.StartsWith((ReadOnlySpan)[0x00, 0x00, 0xFE, 0xFF])) + { + return false; + } + + if (!ResolveEnvironmentVariables) + { + return true; + } + + byte previous = 0; + foreach (var current in fileContents) + { + 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) { // Don't process file changes if this loader has been disposed diff --git a/DevProxy.Abstractions/Plugins/BasePlugin.cs b/DevProxy.Abstractions/Plugins/BasePlugin.cs index 8adc35883..92503aaf0 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); @@ -214,6 +224,8 @@ public override async Task InitializeAsync(InitArgs e, CancellationToken cancell ProxyUtils.ValidateSchemaVersion(schemaUrl, Logger); var result = await ProxyUtils.ValidateJsonAgainstSchemaAsync(configSection.GetRawText(), schemaUrl, _httpClient, Logger, cancellationToken); + // a pass without a schema isn't cached, so that the section is validated once the schema is available + SchemaValidationCache.SetResult(cacheKey, fileVersion, result.Status == SchemaValidationStatus.Valid); if (result.Status == SchemaValidationStatus.SchemaUnavailable) { if (Logger.IsEnabled(LogLevel.Warning)) diff --git a/DevProxy.Abstractions/Plugins/SchemaValidationCache.cs b/DevProxy.Abstractions/Plugins/SchemaValidationCache.cs new file mode 100644 index 000000000..4f31ebf86 --- /dev/null +++ b/DevProxy.Abstractions/Plugins/SchemaValidationCache.cs @@ -0,0 +1,64 @@ +// 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; + } + + /// + /// 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 == before && + GetFileVersion(key.FilePath, before.ContentHash) == before; + + /// + /// 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 3e026aa61..a1170f5fd 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); @@ -313,51 +318,22 @@ public static string SanitizeUrl(string absoluteUrl) public static Task ValidateJsonAgainstSchemaAsync(string? 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 async Task ValidateJsonAgainstSchemaAsync(string? json, string? schemaUrl, HttpClient httpClient, ILogger logger, string? localSchemasFolder, string currentVersion, TimeSpan remoteSchemaFallbackTimeout, CancellationToken cancellationToken) + internal static Task ValidateJsonAgainstSchemaAsync(string? json, string? schemaUrl, HttpClient httpClient, ILogger logger, string? localSchemasFolder, string currentVersion, TimeSpan remoteSchemaFallbackTimeout, CancellationToken cancellationToken) { logger.LogDebug("Validating JSON against schema {SchemaUrl}", schemaUrl); if (string.IsNullOrEmpty(json)) { logger.LogDebug("JSON is empty, skipping validation"); - return new(SchemaValidationStatus.Valid, []); + return Task.FromResult(new SchemaValidationResult(SchemaValidationStatus.Valid, [])); } if (string.IsNullOrEmpty(schemaUrl)) { logger.LogDebug("Schema URL is empty, skipping validation"); - return new(SchemaValidationStatus.Valid, []); - } - - var localSchema = await LoadLocalSchemaAsync(schemaUrl, logger, localSchemasFolder, currentVersion, cancellationToken); - if (localSchema is not null) - { - var localResult = ValidateJson(json, localSchema, logger); - if (localResult.Status == SchemaValidationStatus.Valid) - { - return localResult; - } - - // The schema might have been fixed after the release, so check - // the latest version online before reporting the document as invalid - return await ValidateJsonAgainstRemoteSchemaAsync(json, schemaUrl, httpClient, logger, localResult, remoteSchemaFallbackTimeout, cancellationToken); - } - - JSchema schema; - try - { - schema = await DownloadSchemaAsync(schemaUrl, httpClient, logger, cancellationToken); - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - throw; - } - catch (Exception ex) - { - logger.LogDebug(ex, "Error retrieving schema {SchemaUrl}", schemaUrl); - return new(SchemaValidationStatus.SchemaUnavailable, [ex.Message]); + return Task.FromResult(new SchemaValidationResult(SchemaValidationStatus.Valid, [])); } - return ValidateJson(json, schema, logger); + return ValidateAgainstSchemaAsync(() => JToken.Parse(json), schemaUrl, httpClient, logger, localSchemasFolder, currentVersion, remoteSchemaFallbackTimeout, cancellationToken); } /// @@ -385,6 +361,94 @@ internal static async Task ValidateJsonAgainstSchemaAsyn return File.Exists(localSchemaPath) ? localSchemaPath : null; } + private static async Task ValidateAgainstSchemaAsync(Func parseJson, string schemaUrl, HttpClient httpClient, ILogger logger, string? localSchemasFolder, string currentVersion, TimeSpan remoteSchemaFallbackTimeout, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + // parse the JSON at most once, because a stream can only be read once + JToken? token = null; + Exception? parseError = null; + SchemaValidationResult Validate(JSchema schema) + { + if (token is null && parseError is null) + { + try + { + logger.LogDebug("Parsing JSON"); + token = parseJson(); + } + catch (Exception ex) + { + parseError = ex; + } + } + + if (parseError is not null) + { + logger.LogDebug(parseError, "Error validating JSON"); + return new(SchemaValidationStatus.Invalid, [parseError.Message]); + } + + try + { + logger.LogDebug("Validating JSON"); + var isValid = token!.IsValid(schema, out IList errorMessages); + return new(isValid ? SchemaValidationStatus.Valid : SchemaValidationStatus.Invalid, errorMessages); + } + catch (Exception ex) + { + logger.LogDebug(ex, "Error validating JSON"); + return new(SchemaValidationStatus.Invalid, [ex.Message]); + } + } + + var localSchema = await LoadLocalSchemaAsync(schemaUrl, logger, localSchemasFolder, currentVersion, cancellationToken); + if (localSchema is not null) + { + var localResult = Validate(localSchema); + // an updated schema can't fix JSON that can't be parsed + if (localResult.Status == SchemaValidationStatus.Valid || parseError is not null) + { + return localResult; + } + + // The schema might have been fixed after the release, so check + // the latest version online before reporting the document as invalid + JSchema remoteSchema; + try + { + logger.LogDebug("JSON doesn't match the local schema. Checking the online schema for updates"); + using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeoutCts.CancelAfter(remoteSchemaFallbackTimeout); + remoteSchema = await GetSchemaAsync(schemaUrl, httpClient, logger, timeoutCts.Token); + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + logger.LogDebug(ex, "Couldn't retrieve schema {SchemaUrl}. Using the local schema validation result", schemaUrl); + return localResult; + } + + return Validate(remoteSchema); + } + + JSchema schema; + try + { + schema = await GetSchemaAsync(schemaUrl, httpClient, logger, cancellationToken); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + logger.LogDebug(ex, "Error retrieving schema {SchemaUrl}", schemaUrl); + return new(SchemaValidationStatus.SchemaUnavailable, [ex.Message]); + } + + return Validate(schema); + } + private static async Task LoadLocalSchemaAsync(string schemaUrl, ILogger logger, string? localSchemasFolder, string currentVersion, CancellationToken cancellationToken) { var localSchemaPath = GetLocalSchemaPath(schemaUrl, currentVersion, localSchemasFolder); @@ -406,52 +470,184 @@ internal static async Task ValidateJsonAgainstSchemaAsyn } } - private static async Task ValidateJsonAgainstRemoteSchemaAsync(string json, string schemaUrl, HttpClient httpClient, ILogger logger, SchemaValidationResult localResult, TimeSpan timeout, CancellationToken cancellationToken) + /// + /// Validates UTF-8 JSON read from against the schema at . + /// The stream is read from its current position and isn't disposed. + /// Schemas for the current Dev Proxy version are loaded from the schemas shipped with + /// Dev Proxy, and only downloaded when the document doesn't match the local schema. + /// + /// + /// The validation result. If the schema can't be loaded, downloaded or parsed, for example when + /// there's no network connection, the status is + /// so that callers can skip validation instead of treating the document as invalid. + /// + /// was canceled. + 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) { - JSchema schema; - try + ArgumentNullException.ThrowIfNull(json); + ArgumentNullException.ThrowIfNull(logger); + + logger.LogDebug("Validating JSON against schema {SchemaUrl}", schemaUrl); + + if (json.CanSeek && json.Length - json.Position == 0) { - logger.LogDebug("JSON doesn't match the local schema. Checking the online schema for updates"); - using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - timeoutCts.CancelAfter(timeout); - schema = await DownloadSchemaAsync(schemaUrl, httpClient, logger, timeoutCts.Token); + logger.LogDebug("JSON is empty, skipping validation"); + return Task.FromResult(new SchemaValidationResult(SchemaValidationStatus.Valid, [])); } - catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + if (string.IsNullOrEmpty(schemaUrl)) { - logger.LogDebug(ex, "Couldn't retrieve schema {SchemaUrl}. Using the local schema validation result", schemaUrl); - return localResult; + logger.LogDebug("Schema URL is empty, skipping validation"); + return Task.FromResult(new SchemaValidationResult(SchemaValidationStatus.Valid, [])); } - return ValidateJson(json, schema, logger); + return ValidateAgainstSchemaAsync(() => ParseJson(json), schemaUrl, httpClient, logger, localSchemasFolder, currentVersion, remoteSchemaFallbackTimeout, cancellationToken); } - private static async Task DownloadSchemaAsync(string schemaUrl, HttpClient httpClient, ILogger logger, CancellationToken cancellationToken) + private static JToken ParseJson(Stream json) + { + // 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); + var 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 + return token; + } + + // Downloaded schemas are cached 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) { ArgumentNullException.ThrowIfNull(httpClient); + cancellationToken.ThrowIfCancellationRequested(); + + 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"); - return JSchema.Parse(schemaContents); + var schema = JSchema.Parse(schemaContents); + return _schemaCache.GetOrAdd(schemaUrl, schema); } - private static SchemaValidationResult ValidateJson(string json, JSchema schema, ILogger logger) + /// + /// 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. If the + /// document doesn't have the property, it's read to the end, which checks that it's valid JSON. + /// 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) => + 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); + + var buffer = ArrayPool.Shared.Rent(4096); try { - logger.LogDebug("Parsing JSON"); - var token = JToken.Parse(json); + var state = new JsonReaderState(new JsonReaderOptions + { + AllowTrailingCommas = JsonDocumentOptions.AllowTrailingCommas, + CommentHandling = JsonDocumentOptions.CommentHandling + }); - logger.LogDebug("Validating JSON"); - var isValid = token.IsValid(schema, out IList errorMessages); + 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; + } - return new(isValid ? SchemaValidationStatus.Valid : SchemaValidationStatus.Invalid, errorMessages); + var isSchemaValue = false; + string? schemaUrl = null; + bool? isRootObject = null; + 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) + { + 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 + isRootObject ??= reader.TokenType == JsonTokenType.StartObject; + if (isRootObject == true && + reader.CurrentDepth == 1 && + reader.TokenType == JsonTokenType.PropertyName && + reader.ValueTextEquals("$schema"u8)) + { + isSchemaValue = true; + } + } + + if (isFinalBlock) + { + return schemaUrl; + } + + 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; + } + } } - catch (Exception ex) + finally { - logger.LogDebug(ex, "Error validating JSON"); - return new(SchemaValidationStatus.Invalid, [ex.Message]); + ArrayPool.Shared.Return(buffer); } } diff --git a/DevProxy.Plugins/Behavior/GenericErrorResponsesLoader.cs b/DevProxy.Plugins/Behavior/GenericErrorResponsesLoader.cs index 0df1c40cb..36430968b 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 e20a5c905..740d80bf8 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 3b8fe4271..5943fed00 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 b60a0ca50..5cf21262e 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 b2a778087..19ff4d36b 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 95639e637..41456d559 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()) + { + } for (var i = data.Count - 1; i >= 0; i--) { if (data[i].Type == JTokenType.Null) diff --git a/DevProxy.Plugins/Mocking/CrudApiDefinitionLoader.cs b/DevProxy.Plugins/Mocking/CrudApiDefinitionLoader.cs index c08d451ca..b513c98dc 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 80e7459ac..246ff0b9f 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 f720fbde7..9e86910fc 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 98a70b502..45faef2ca 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 921e943d8..b608a274c 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 f9e5b805d..53db30d43 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/BaseLoaderSchemaValidationCacheTests.cs b/DevProxy.Tests/BaseLoaderSchemaValidationCacheTests.cs new file mode 100644 index 000000000..7eb88489e --- /dev/null +++ b/DevProxy.Tests/BaseLoaderSchemaValidationCacheTests.cs @@ -0,0 +1,182 @@ +// 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 BaseLoaderSchemaValidationCacheTests : 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/schema-{Guid.NewGuid()}.json"; + private readonly SchemaHandler _handler = new(Schema); + private readonly HttpClient _httpClient; + private readonly TestLogger _logger = new(); + + public BaseLoaderSchemaValidationCacheTests() => _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 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() + { + 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(); + 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) + { + 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 7189cd48c..e6d3aef02 100644 --- a/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs +++ b/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs @@ -11,10 +11,11 @@ namespace DevProxy.Tests; public sealed class BaseLoaderSchemaValidationTests : IDisposable { - private const string SchemaUrl = "https://schemas.example.test/mocks.schema.json"; private const string Schema = """{ "properties": { "name": { "type": "string" } } }"""; + // unique per test, because downloaded schemas are cached per process + private readonly string _schemaUrl = $"https://schemas.example.test/mocks-{Guid.NewGuid()}.schema.json"; // Doesn't match the schema, which requires name to be a string - private const string Contents = $$"""{ "$schema": "{{SchemaUrl}}", "name": 1 }"""; + private string Contents => $$"""{ "$schema": "{{_schemaUrl}}", "name": 1 }"""; private readonly string _folder = Directory.CreateTempSubdirectory("devproxy-loader").FullName; public void Dispose() => Directory.Delete(_folder, true); @@ -52,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); @@ -64,8 +65,8 @@ public async Task DoesNotLoadFileWhenCanceledWhileRetrievingSchema() public async Task AppliesNewestDataWhenFileChangesWhileRetrievingSchema(bool schemaAvailable) { var timeout = TimeSpan.FromSeconds(10); - var initialContents = $$"""{ "$schema": "{{SchemaUrl}}", "name": "initial" }"""; - var updatedContents = $$"""{ "$schema": "{{SchemaUrl}}", "name": "updated" }"""; + var initialContents = $$"""{ "$schema": "{{_schemaUrl}}", "name": "initial" }"""; + var updatedContents = $$"""{ "$schema": "{{_schemaUrl}}", "name": "updated" }"""; var path = Path.Combine(_folder, "mocks.json"); await File.WriteAllTextAsync(path, initialContents, CancellationToken.None); @@ -111,10 +112,90 @@ public async Task AppliesNewestDataWhenFileChangesWhileRetrievingSchema(bool sch Assert.Equal([initialContents, updatedContents], loader.LoadedContents); } - private async Task LoadAsync(Func sendSchemaRequest, ILogger logger, CancellationToken cancellationToken = default) + [Theory] + [InlineData("""[{ "id": 3 }] { "extra": true }""")] + [InlineData("""{ "name": "a" } { "extra": true }""")] + public async Task DoesNotLoadInvalidJsonWithoutSchemaReference(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); + } + + [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() + { + 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); + } + + [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"); - await File.WriteAllTextAsync(path, Contents, CancellationToken.None); + await File.WriteAllTextAsync(path, contents ?? Contents, CancellationToken.None); using var handler = new FakeHttpMessageHandler(sendSchemaRequest); using var httpClient = new HttpClient(handler); var loader = new TestLoader(httpClient, logger, path); @@ -189,6 +270,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) => 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) {