From e4b31eed780bed5b31212c60fddb9f09b9b8748b Mon Sep 17 00:00:00 2001 From: waldekmastykarz Date: Sun, 15 Nov 2026 13:15:03 +0100 Subject: [PATCH 1/5] Add support for .NET 11. Closes #2112 - Build Dev Proxy, plugins and tests on net11.0 and update EF Core and Microsoft.Extensions.* packages to 11.0.0 - Multi-target DevProxy.Abstractions to net10.0 and net11.0 so existing plugin projects keep working - Fix new analyzer errors (CA1307, CA2016, CA2027) - Pin AnalysisLevel to 11.0 so new SDKs don't break the build - Update hard-coded net10.0 paths, CI SDK versions and release workflow (sign, zip and upload both Abstractions targets) - Run tests in CI - Document plugin reference requirements in the Abstractions README Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/codeql-analysis.yml | 2 +- .github/workflows/create-release.yml | 26 +- .github/workflows/dotnet.yml | 7 +- .vscode/launch.json | 4 +- .../DevProxy.Abstractions.Tests.csproj | 2 +- .../DevProxy.Abstractions.csproj | 27 +- .../Proxy/WatchedHostExtractor.cs | 4 +- DevProxy.Abstractions/README.md | 21 + DevProxy.Abstractions/Utils/ProxyUtils.cs | 1666 +++++++-------- DevProxy.Abstractions/packages.lock.json | 233 +++ .../CommandExitCodeTests.cs | 2 +- .../DevProxy.Integration.Tests.csproj | 4 +- .../EngineInactivityTimeoutTests.cs | 6 +- .../ProcessSmokeTests.cs | 2 +- DevProxy.Plugins/ApiCenter/ApiCenterClient.cs | 398 ++-- .../Behavior/GenericRandomErrorPlugin.cs | 776 +++---- DevProxy.Plugins/DevProxy.Plugins.csproj | 8 +- .../Generation/ApiCenterOnboardingPlugin.cs | 828 ++++---- .../Generation/OpenApiSpecGeneratorPlugin.cs | 1682 ++++++++-------- .../Generation/TypeSpecGeneratorPlugin.cs | 2 +- .../Mocking/MockResponsePlugin.cs | 2 +- .../Mocking/MockStdioResponsePlugin.cs | 2 +- DevProxy.Plugins/packages.lock.json | 295 +-- .../DevProxy.Proxy.Kestrel.Tests.csproj | 2 +- .../DevProxy.Proxy.Kestrel.csproj | 2 +- .../Internal/ConnectAuthorityParser.cs | 2 +- DevProxy.Proxy.Kestrel/packages.lock.json | 94 +- DevProxy.Tests/DevProxy.Tests.csproj | 2 +- DevProxy/Commands/ApiCommand.cs | 8 +- DevProxy/Commands/ConfigCommand.cs | 1794 ++++++++--------- DevProxy/Commands/DevProxyCommand.cs | 1626 +++++++-------- DevProxy/Commands/LogsCommand.cs | 2 +- DevProxy/Commands/StdioCommand.cs | 6 +- DevProxy/DevProxy.csproj | 4 +- DevProxy/Logging/JsonConsoleFormatter.cs | 6 +- DevProxy/Logging/ProxyConsoleFormatter.cs | 666 +++--- DevProxy/Plugins/PluginServiceExtensions.cs | 514 ++--- DevProxy/packages.lock.json | 96 +- Directory.Build.props | 4 + WINDOWS-VERIFICATION.md | 4 +- scripts/local-build.ps1 | 2 +- 41 files changed, 5510 insertions(+), 5323 deletions(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index af64ce689..bd9415c1b 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -49,7 +49,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/create-release.yml b/.github/workflows/create-release.yml index 4c05a45aa..c777be4cb 100644 --- a/.github/workflows/create-release.yml +++ b/.github/workflows/create-release.yml @@ -35,7 +35,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Rename executable for prerelease if: contains(github.ref_name, '-beta') || contains(github.ref_name, '-alpha') run: | @@ -60,7 +60,7 @@ jobs: if: matrix.architecture == 'win-x64' run: dotnet build ./DevProxy.Abstractions/DevProxy.Abstractions.csproj -p:InformationalVersion=$("${{ github.ref_name }}".Substring(1)) -c Release --no-self-contained - name: Add plugins to output - run: cp ./DevProxy/bin/Release/net10.0/${{ matrix.architecture }}/plugins ./${{ env.release }} -r + run: cp ./DevProxy/bin/Release/net11.0/${{ matrix.architecture }}/plugins ./${{ env.release }} -r - name: Remove unnecessary files run: | pushd @@ -110,10 +110,11 @@ jobs: path: ./${{ env.release }}.zip - name: Sign abstractions if: matrix.architecture == 'win-x64' + working-directory: ./DevProxy.Abstractions/bin/Release shell: pwsh run: > - ./sign code azure-key-vault - ./DevProxy.Abstractions/bin/Release/net10.0/DevProxy.Abstractions.dll + ../../../sign code azure-key-vault + **/DevProxy.Abstractions.dll --publisher-name "${{ env.APP_PUBLISHER }}" --description "${{ env.APP_DESCRIPTION }}" --description-url "${{ env.APP_DESCRIPTION_URL }}" @@ -123,19 +124,28 @@ jobs: --azure-key-vault-url "${{ secrets.DOTNET_VAULT_URL }}" --timestamp-url http://timestamp.digicert.com --verbosity Debug - - name: Archive abstractions + - name: Archive abstractions (net10.0) if: matrix.architecture == 'win-x64' uses: thedoctor0/zip-release@b57d897cb5d60cb78b51a507f63fa184cfe35554 # master with: - filename: '../../../../DevProxy.Abstractions-${{ github.ref_name }}.zip' + filename: '../../../../DevProxy.Abstractions-${{ github.ref_name }}-net10.0.zip' directory: './DevProxy.Abstractions/bin/Release/net10.0' exclusions: '*.json' + - name: Archive abstractions (net11.0) + if: matrix.architecture == 'win-x64' + uses: thedoctor0/zip-release@b57d897cb5d60cb78b51a507f63fa184cfe35554 # master + with: + filename: '../../../../DevProxy.Abstractions-${{ github.ref_name }}-net11.0.zip' + directory: './DevProxy.Abstractions/bin/Release/net11.0' + exclusions: '*.json' - name: Upload abstractions if: matrix.architecture == 'win-x64' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: binaries-dev-proxy-abstractions-${{ github.ref_name }} - path: ./DevProxy.Abstractions-${{ github.ref_name }}.zip + path: | + ./DevProxy.Abstractions-${{ github.ref_name }}-net10.0.zip + ./DevProxy.Abstractions-${{ github.ref_name }}-net11.0.zip - name: Add installer icon if: contains(matrix.architecture, 'win-') run: | @@ -208,7 +218,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Get version from tag id: get_version run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index ab74d5e0f..e0624db8b 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -22,15 +22,16 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Restore workloads run: dotnet workload restore - name: Restore dependencies run: dotnet restore DevProxy.sln --locked-mode - name: Build run: dotnet build DevProxy.sln --no-restore - # We really should have tests, putting these steps here for when we have a build process - # - name: Test + - name: Test + run: dotnet test DevProxy.sln --no-build + # - name: Test with coverage # run: dotnet test DevProxy.sln --no-build --verbosity normal --collect:"XPlat Code Coverage" # - name: Install report generator # run: dotnet tool install --global dotnet-reportgenerator-globaltool diff --git a/.vscode/launch.json b/.vscode/launch.json index 9252a22ff..eed2498b4 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -10,9 +10,9 @@ "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/DevProxy/bin/Debug/net10.0/devproxy.dll", + "program": "${workspaceFolder}/DevProxy/bin/Debug/net11.0/devproxy.dll", "args": [], - "cwd": "${workspaceFolder}/DevProxy/bin/Debug/net10.0", + "cwd": "${workspaceFolder}/DevProxy/bin/Debug/net11.0", // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console "console": "integratedTerminal", "stopAtEntry": false, diff --git a/DevProxy.Abstractions.Tests/DevProxy.Abstractions.Tests.csproj b/DevProxy.Abstractions.Tests/DevProxy.Abstractions.Tests.csproj index 988daa360..f3af15df6 100644 --- a/DevProxy.Abstractions.Tests/DevProxy.Abstractions.Tests.csproj +++ b/DevProxy.Abstractions.Tests/DevProxy.Abstractions.Tests.csproj @@ -1,7 +1,7 @@ - net10.0 + net11.0 enable enable false diff --git a/DevProxy.Abstractions/DevProxy.Abstractions.csproj b/DevProxy.Abstractions/DevProxy.Abstractions.csproj index 64f10a3d3..88d3d5dab 100644 --- a/DevProxy.Abstractions/DevProxy.Abstractions.csproj +++ b/DevProxy.Abstractions/DevProxy.Abstractions.csproj @@ -1,7 +1,8 @@ - net10.0 + + net10.0;net11.0 DevProxy.Abstractions enable enable @@ -33,12 +34,6 @@ - - - - - - @@ -47,4 +42,22 @@ + + + + + + + + + + + + + + + + + + diff --git a/DevProxy.Abstractions/Proxy/WatchedHostExtractor.cs b/DevProxy.Abstractions/Proxy/WatchedHostExtractor.cs index 205b931f6..1c029e3ac 100644 --- a/DevProxy.Abstractions/Proxy/WatchedHostExtractor.cs +++ b/DevProxy.Abstractions/Proxy/WatchedHostExtractor.cs @@ -95,7 +95,7 @@ public static bool IsHostWide(Regex urlRegex) return true; } - var pathStart = pattern.IndexOf('/', scheme + 3); - return pathStart < 0 || pattern[pathStart..] is "/" or "/*"; + var pathOffset = pattern.AsSpan(scheme + 3).IndexOf('/'); + return pathOffset < 0 || pattern[(scheme + 3 + pathOffset)..] is "/" or "/*"; } } diff --git a/DevProxy.Abstractions/README.md b/DevProxy.Abstractions/README.md index 6e41bd969..73d1dd2cb 100644 --- a/DevProxy.Abstractions/README.md +++ b/DevProxy.Abstractions/README.md @@ -39,4 +39,25 @@ public class MyPlugin( } ``` +## Target framework + +This package targets `net10.0` and `net11.0`. Target the same .NET version as the Dev Proxy release that runs your plugin, or an earlier one. Dev Proxy can load a plugin built for an earlier .NET version, but not for a later one. + +## Don't ship shared assemblies with your plugin + +Dev Proxy already loads `DevProxy.Abstractions` and the `Microsoft.Extensions.*` packages that it depends on. If your plugin ships its own copy of these assemblies, Dev Proxy loads a second copy, and your plugin's types won't match Dev Proxy's types. To avoid this, reference `DevProxy.Abstractions` and the shared packages with `Private=false` and `ExcludeAssets=runtime`: + +```xml + + + false + runtime + + + false + runtime + + +``` + For more information, see the [Dev Proxy documentation](https://aka.ms/devproxy/docs). diff --git a/DevProxy.Abstractions/Utils/ProxyUtils.cs b/DevProxy.Abstractions/Utils/ProxyUtils.cs index 7c5af6808..c4835e174 100644 --- a/DevProxy.Abstractions/Utils/ProxyUtils.cs +++ b/DevProxy.Abstractions/Utils/ProxyUtils.cs @@ -1,833 +1,833 @@ -// 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 DevProxy.Abstractions.Models; -using DevProxy.Abstractions.Proxy; -using DevProxy.Abstractions.Proxy.Http; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Schema; -using System.Collections.ObjectModel; -using System.Reflection; -using System.Text.Encodings.Web; -using System.Runtime.InteropServices; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Text.RegularExpressions; - -namespace DevProxy.Abstractions.Utils; - -sealed class ParsedSample -{ - public string QueryVersion { get; set; } = string.Empty; - public string RequestUrl { get; set; } = string.Empty; - public string SampleUrl { get; set; } = string.Empty; - public string Search { get; set; } = string.Empty; -} - -public static class ProxyUtils -{ - 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); - // all alpha must include 2 to allow for oauth2PermissionScopes - private static readonly Regex allAlphaRegex = new("^[a-z2]+$", RegexOptions.IgnoreCase); - private static readonly Regex deprecationRegex = new("^[a-z]+_v2$", RegexOptions.IgnoreCase); - private static readonly Regex functionCallRegex = new(@"^[a-z]+\(.*\)$", RegexOptions.IgnoreCase); - - private static Assembly? _assembly; - private static string _productVersion = string.Empty; - - public static readonly string ReportsKey = "Reports"; - - // doesn't end with a path separator - public static string? AppFolder => Path.GetDirectoryName(AppContext.BaseDirectory); - - /// - /// Gets the path to the user data folder for Dev Proxy. - /// On macOS: ~/Library/Application Support/dev-proxy/ - /// On Linux: ~/.config/dev-proxy/ (or $XDG_CONFIG_HOME/dev-proxy/) - /// On Windows: %LocalAppData%\dev-proxy\ - /// - public static string DataFolder - { - get - { - var basePath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) - ? Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) - : Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); - return Path.Combine(basePath, "dev-proxy"); - } - } - public static JsonSerializerOptions JsonSerializerOptions { get; } = new() - { - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, - Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - PropertyNameCaseInsensitive = true, - ReadCommentHandling = JsonCommentHandling.Skip, - WriteIndented = true - }; - public static JsonDocumentOptions JsonDocumentOptions { get; } = new() - { - AllowTrailingCommas = true, - CommentHandling = JsonCommentHandling.Skip - }; - public static string ProductVersion - { - get - { - if (string.IsNullOrEmpty(_productVersion)) - { - var assembly = GetAssembly(); - var assemblyVersionAttribute = assembly.GetCustomAttribute(); - - if (assemblyVersionAttribute is null) - { - _productVersion = assembly.GetName().Version?.ToString() ?? ""; - } - else - { - _productVersion = assemblyVersionAttribute.InformationalVersion; - } - } - - - return _productVersion; - } - } - - static ProxyUtils() - { - // convert enum values to camelCase - JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); - } - - /// - /// Converts a configured response body to the string sent to the client. - /// String bodies are returned as-is; other values are serialized as JSON. - /// - public static string SerializeBody(object? body) => body switch - { - null => string.Empty, - string s => s, - JsonElement { ValueKind: JsonValueKind.String } el => el.GetString() ?? string.Empty, - JValue { Type: JTokenType.String } jv => jv.Value() ?? string.Empty, - _ => JsonSerializer.Serialize(body, JsonSerializerOptions) - }; - - public static bool IsGraphRequest(IHttpRequest request) - { - ArgumentNullException.ThrowIfNull(request); - - return IsGraphUrl(request.RequestUri); - } - - public static bool IsGraphUrl(Uri uri) - { - ArgumentNullException.ThrowIfNull(uri); - - return uri.Host.StartsWith("graph.microsoft.", StringComparison.OrdinalIgnoreCase) || - uri.Host.StartsWith("microsoftgraph.", StringComparison.OrdinalIgnoreCase); - } - - public static bool IsGraphBatchUrl(Uri uri) - { - ArgumentNullException.ThrowIfNull(uri); - - return uri.AbsoluteUri.EndsWith("/$batch", StringComparison.OrdinalIgnoreCase); - } - - public static Uri GetAbsoluteRequestUrlFromBatch(Uri batchRequestUri, string relativeRequestUrl) - { - ArgumentNullException.ThrowIfNull(batchRequestUri); - - var hostName = batchRequestUri.Host; - var graphVersion = batchRequestUri.Segments[1].TrimEnd('/'); - var absoluteRequestUrl = new Uri($"https://{hostName}/{graphVersion}{relativeRequestUrl}"); - return absoluteRequestUrl; - } - - public static bool IsSdkRequest(IHttpRequest request) - { - ArgumentNullException.ThrowIfNull(request); - - return request.Headers.Contains("SdkVersion"); - } - - public static bool IsGraphBetaRequest(IHttpRequest request) - { - ArgumentNullException.ThrowIfNull(request); - - return IsGraphRequest(request) && - IsGraphBetaUrl(request.RequestUri); - } - - public static bool IsGraphBetaUrl(Uri uri) - { - ArgumentNullException.ThrowIfNull(uri); - - return uri.AbsolutePath.Contains("/beta/", StringComparison.OrdinalIgnoreCase); - } - - /// - /// Utility to build HTTP response headers consistent with Microsoft Graph - /// - /// The http request for which response headers are being constructed - /// string a guid representing the a unique identifier for the request - /// string representation of the date and time the request was made - /// IList with defaults consistent with Microsoft Graph. Automatically adds CORS headers when the Origin header is present - public static IList BuildGraphResponseHeaders(IHttpRequest request, string requestId, string requestDate) - { - ArgumentNullException.ThrowIfNull(request); - - if (!IsGraphRequest(request)) - { - return []; - } - - var hasOrigin = request.Headers.FirstOrDefault((h) => h.Name.Equals("Origin", StringComparison.OrdinalIgnoreCase)) is not null; - return BuildGraphResponseHeadersCore(hasOrigin, requestId, requestDate); - } - - private static List BuildGraphResponseHeadersCore(bool hasOriginHeader, string requestId, string requestDate) - { - var headers = new List - { - new ("Cache-Control", "no-store"), - new ("x-ms-ags-diagnostic", ""), - new ("Strict-Transport-Security", ""), - new ("request-id", requestId), - new ("client-request-id", requestId), - new ("Date", requestDate), - new ("Content-Type", "application/json") - }; - if (hasOriginHeader) - { - headers.Add(new("Access-Control-Allow-Origin", "*")); - headers.Add(new("Access-Control-Expose-Headers", "ETag, Location, Preference-Applied, Content-Range, request-id, client-request-id, ReadWriteConsistencyToken, SdkVersion, WWW-Authenticate, x-ms-client-gcc-tenant, Retry-After")); - } - return headers; - } - - public static string ReplacePathTokens(string? path) - { - if (string.IsNullOrEmpty(path)) - { - return path ?? string.Empty; - } - - path = ExpandHomeDirectory(path); - path = path.Replace("~dataFolder", DataFolder, StringComparison.OrdinalIgnoreCase); - return path.Replace("~appFolder", AppFolder, StringComparison.OrdinalIgnoreCase); - } - - private static string ExpandHomeDirectory(string path) - { - if (path.Length < 2 || path[0] != '~' || - (path[1] != '/' && !(OperatingSystem.IsWindows() && path[1] == '\\'))) - { - return path; - } - - var homeFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - if (string.IsNullOrEmpty(homeFolder)) - { - return path; - } - - return Path.Join(homeFolder, path[2..]); - } - - public static string GetFullPath(string? path, string? basePath) => - Path.GetFullPath(ReplacePathTokens(path), Path.GetDirectoryName(basePath) ?? string.Empty); - - // from: https://github.com/microsoftgraph/microsoft-graph-explorer-v4/blob/db86b903f36ef1b882996d46aee52cd49ed4444b/src/app/utils/query-url-sanitization.ts -#pragma warning disable CA1055 - public static string SanitizeUrl(string absoluteUrl) -#pragma warning restore CA1055 - { - absoluteUrl = Uri.UnescapeDataString(absoluteUrl); - var uri = new Uri(absoluteUrl); - - var parsedSample = ParseSampleUrl(absoluteUrl); - var queryString = !string.IsNullOrEmpty(parsedSample.Search) ? $"?{SanitizeQueryParameters(parsedSample.Search)}" : ""; - - // Sanitize item path specified in query url - var resourceUrl = parsedSample.RequestUrl; - if (!string.IsNullOrEmpty(resourceUrl)) - { - resourceUrl = itemPathRegex.Replace(parsedSample.RequestUrl, match => - { - return $"{match.Value[..match.Value.IndexOf(':', StringComparison.OrdinalIgnoreCase)]}:"; - }); - // Split requestUrl into segments that can be sanitized individually - var urlSegments = resourceUrl.Split('/'); - for (var i = 0; i < urlSegments.Length; i++) - { - var segment = urlSegments[i]; - var sanitizedSegment = SanitizePathSegment(i < 1 ? "" : urlSegments[i - 1], segment); - resourceUrl = resourceUrl.Replace(segment, sanitizedSegment, StringComparison.OrdinalIgnoreCase); - } - } - return $"{uri.GetLeftPart(UriPartial.Authority)}/{parsedSample.QueryVersion}/{resourceUrl}{queryString}"; - } - - public static async Task<(bool IsValid, IEnumerable ValidationErrors)> ValidateJsonAsync(string? json, string? schemaUrl, HttpClient httpClient, ILogger logger, CancellationToken cancellationToken) - { - try - { - logger.LogDebug("Validating JSON against schema {SchemaUrl}", schemaUrl); - - if (string.IsNullOrEmpty(json)) - { - 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); - - logger.LogDebug("Downloading schema from {SchemaUrl}", schemaUrl); - var schemaContents = await httpClient.GetStringAsync(schemaUrl, cancellationToken); - - logger.LogDebug("Parsing schema"); - var schema = JSchema.Parse(schemaContents); - logger.LogDebug("Parsing JSON"); - var token = JToken.Parse(json); - - 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]); - } - } - - public static string ReplaceVariables(string s, Dictionary variables, Func? formatVariableRef = null) - { - ArgumentNullException.ThrowIfNull(s); - ArgumentNullException.ThrowIfNull(variables); - - formatVariableRef ??= v => $"@{v}"; - - var s1 = s; - - foreach (var variable in variables) - { - s1 = s1.Replace(formatVariableRef(variable.Key), variable.Value, StringComparison.OrdinalIgnoreCase); - } - - return s1; - } - - public static void ValidateSchemaVersion(string schemaUrl, ILogger logger) - { - if (string.IsNullOrWhiteSpace(schemaUrl)) - { - logger.LogDebug("Schema is empty, skipping schema version validation."); - return; - } - - var warning = GetSchemaVersionMismatchWarning(schemaUrl); - if (warning is not null) - { - logger.LogWarning("{Warning}", warning); - } - } - - /// - /// Checks if the schema URL version matches the current Dev Proxy version. - /// Returns a warning message if versions don't match, or null if they match - /// or the schema URL cannot be parsed. - /// - public static string? GetSchemaVersionMismatchWarning(string schemaUrl) - { - if (string.IsNullOrWhiteSpace(schemaUrl)) - { - return null; - } - - try - { - var uri = new Uri(schemaUrl); - if (uri.Segments.Length > 2) - { - var schemaVersion = uri.Segments[^2] - .TrimStart('v') - .TrimEnd('/'); - var currentVersion = NormalizeVersion(ProductVersion); - if (CompareSemVer(currentVersion, schemaVersion) != 0) - { - var currentSchemaUrl = uri.ToString().Replace($"/v{schemaVersion}/", $"/v{currentVersion}/", StringComparison.OrdinalIgnoreCase); - return $"The version of schema does not match the installed Dev Proxy version, the expected schema is {currentSchemaUrl}"; - } - } - } - catch - { - return $"The $schema value '{schemaUrl}' is not a valid URL. Schema version could not be validated."; - } - - return null; - } - - /// - /// Returns the ordered list of config file paths to search. - /// The first existing file in the list should be used. - /// - public static IEnumerable GetConfigFileCandidates(string? userConfigFile) - { - return [ - // config file specified by the user takes precedence - // null if not specified - userConfigFile, - // current directory - JSON/JSONC files - "devproxyrc.jsonc", - "devproxyrc.json", - // current directory - YAML files - "devproxyrc.yaml", - "devproxyrc.yml", - // .devproxy subdirectory - JSON/JSONC files - Path.Combine(".devproxy", "devproxyrc.jsonc"), - Path.Combine(".devproxy", "devproxyrc.json"), - // .devproxy subdirectory - YAML files - Path.Combine(".devproxy", "devproxyrc.yaml"), - Path.Combine(".devproxy", "devproxyrc.yml"), - // app folder - JSON/JSONC files - Path.Combine(AppFolder ?? "", "devproxyrc.jsonc"), - Path.Combine(AppFolder ?? "", "devproxyrc.json"), - // app folder - YAML files - Path.Combine(AppFolder ?? "", "devproxyrc.yaml"), - Path.Combine(AppFolder ?? "", "devproxyrc.yml") - ]; - } - - /// - /// Compares two semantic versions strings. - /// - /// ver1 - /// ver2 - /// - /// Returns 0 if the versions are equal, -1 if a is less than b, and 1 if a is greater than b. - /// An invalid argument is "rounded" to a minimal version. - /// - public static int CompareSemVer(string? a, string? b) - { - if (string.IsNullOrWhiteSpace(a) && string.IsNullOrWhiteSpace(b)) - { - return 0; - } - else if (string.IsNullOrWhiteSpace(a)) - { - return -1; - } - else if (string.IsNullOrWhiteSpace(b)) - { - return 1; - } - - a = a.TrimStart('v'); - b = b.TrimStart('v'); - - var aParts = a.Split('-'); - var bParts = b.Split('-'); - - var aParsed = Version.TryParse(aParts[0], out var aVersion); - var bParsed = Version.TryParse(bParts[0], out var bVersion); - if (!aParsed && !bParsed) - { - return 0; - } - else if (!aParsed) - { - return -1; - } - else if (!bParsed) - { - return 1; - } - - var compare = aVersion!.CompareTo(bVersion); - if (compare != 0) - { - // if the versions are different, return the comparison result - return compare; - } - - // if the versions are the same, compare the prerelease tags - if (aParts.Length == 1 && bParts.Length == 1) - { - // if both versions are stable, they are equal - return 0; - } - else if (aParts.Length == 1) - { - // if a is stable and b is not, a is greater - return 1; - } - else if (bParts.Length == 1) - { - // if b is stable and a is not, b is greater - return -1; - } - else if (aParts[1] == bParts[1]) - { - // if both versions are prerelease and the tags are the same, they are equal - return 0; - } - else - { - // if both versions are prerelease, b is greater - return -1; - } - } - - /// - /// Produces major.minor.patch version dropping a pre-release suffix. - /// - /// A version looks like "0.28.1", "0.28.1-alpha", "0.28.10-beta.1", "0.28.10-rc.1", or "0.28.0-preview-1", etc. - public static string NormalizeVersion(string version) - { - if (string.IsNullOrWhiteSpace(version)) - { - return version; - } - - return version.Split('-', StringSplitOptions.None)[0]; - } - - public static string GetGraphVersion(string url) - { - var uri = new Uri(url); - return uri.Segments[1].Replace("/", "", StringComparison.OrdinalIgnoreCase); - } - - public static void MergeHeaders(IList allHeaders, IList headersToAdd) - { - ArgumentNullException.ThrowIfNull(allHeaders); - ArgumentNullException.ThrowIfNull(headersToAdd); - - foreach (var header in headersToAdd) - { - var existingHeader = allHeaders.FirstOrDefault(h => h.Name.Equals(header.Name, StringComparison.OrdinalIgnoreCase)); - if (existingHeader is not null) - { - if (header.Name.Equals("Access-Control-Expose-Headers", StringComparison.OrdinalIgnoreCase) || - header.Name.Equals("Access-Control-Allow-Headers", StringComparison.OrdinalIgnoreCase)) - { - var existingValues = existingHeader.Value.Split(',').Select(v => v.Trim()); - var newValues = header.Value.Split(',').Select(v => v.Trim()); - var allValues = existingValues.Union(newValues).Distinct(); - _ = allHeaders.Remove(existingHeader); - allHeaders.Add(new(header.Name, string.Join(", ", allValues))); - continue; - } - - // don't remove headers that we've just added - if (!headersToAdd.Contains(existingHeader)) - { - _ = allHeaders.Remove(existingHeader); - } - } - - allHeaders.Add(header); - } - } - - public static bool MatchesUrlToWatch(ISet watchedUrls, string url, bool evaluateWildcards = false) - { - ArgumentNullException.ThrowIfNull(watchedUrls); - ArgumentNullException.ThrowIfNull(url); - - if (evaluateWildcards && url.Contains('*', StringComparison.OrdinalIgnoreCase)) - { - // url contains a wildcard, so convert it to regex and compare - var match = watchedUrls.FirstOrDefault(r => - { - var pattern = RegexToPattern(r.Url); - var result = UrlRegexComparer.CompareRegexPatterns(pattern, url); - return result != UrlRegexComparisonResult.PatternsMutuallyExclusive; - }); - return match is not null && !match.Exclude; - } - else - { - var match = watchedUrls.FirstOrDefault(r => r.Url.IsMatch(url)); - return match is not null && !match.Exclude; - } - } - - public static string PatternToRegex(string pattern) - { - return $"^{Regex.Escape(pattern).Replace("\\*", ".*", StringComparison.OrdinalIgnoreCase)}$"; - } - - /// - /// Normalizes a WebSocket URL scheme to its HTTP equivalent (wss:// → - /// https://, ws:// → http://), leaving any other scheme untouched. - /// - /// - /// The proxy engine reports an intercepted WebSocket upgrade with an http(s) - /// scheme (a ws(s) connection is an HTTP Upgrade on the wire). Authors, - /// however, naturally write wss://host/* in urlsToWatch and mock URLs. - /// Normalizing both sides to http(s) before matching lets either form work. - /// - /// - public static string NormalizeWebSocketScheme(string url) - { - ArgumentNullException.ThrowIfNull(url); - - if (url.StartsWith("wss://", StringComparison.OrdinalIgnoreCase)) - { - return string.Concat("https://", url.AsSpan("wss://".Length)); - } - if (url.StartsWith("ws://", StringComparison.OrdinalIgnoreCase)) - { - return string.Concat("http://", url.AsSpan("ws://".Length)); - } - return url; - } - - public static string RegexToPattern(Regex regex) - { - ArgumentNullException.ThrowIfNull(regex); - - return Regex.Unescape(regex.ToString()) - .Trim('^', '$') - .Replace(".*", "*", StringComparison.OrdinalIgnoreCase); - } - - public static IEnumerable GetWildcardPatterns(ReadOnlyCollection urls) - { - return [.. urls - .GroupBy(url => - { - if (url.Contains('*', StringComparison.OrdinalIgnoreCase)) - { - return url; - } - - var uri = new Uri(url); - return $"{uri.Scheme}://{uri.Host}"; - }) - .Select(group => - { - if (group.Count() == 1) - { - var url = group.First(); - if (url.Contains('*', StringComparison.OrdinalIgnoreCase)) - { - return url; - } - - // For single URLs, use the URL up to the last segment - var uri = new Uri(url); - var path = uri.AbsolutePath; - var lastSlashIndex = path.LastIndexOf('/'); - return $"{group.Key}{path[..lastSlashIndex]}/*"; - } - - // For multiple URLs, find the common prefix - var paths = group.Select(url => - { - return url.Contains('*', StringComparison.OrdinalIgnoreCase) ? url : new Uri(url).AbsolutePath; - }).ToList(); - var commonPrefix = GetCommonPrefix(paths); - return $"{group.Key}{commonPrefix}*"; - }) - .OrderBy(x => x)]; - } - -#pragma warning disable CA1055 - public static string UrlWithParametersToRegex(string urlWithParameters) -#pragma warning restore CA1055 - { - ArgumentNullException.ThrowIfNull(urlWithParameters); - - return $"^{Regex.Replace(Regex.Escape(urlWithParameters), "\\\\{[^}]+}", ".*")}"; - } - - internal static Assembly GetAssembly() - => _assembly ??= (Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly()); - - /** - * Skipped segments: - * - Entities, entity sets and navigation properties, expected to contain alphabetic letters only - * - Deprecated entities in the form _v2 - * The remaining URL segments are assumed to be variables that need to be sanitized - * @param segment - */ - private static string SanitizePathSegment(string previousSegment, string segment) - { - var segmentsToIgnore = new[] { "$value", "$count", "$ref", "$batch" }; - - if (IsAllAlpha(segment) || - IsDeprecation(segment) || - sanitizedItemPathRegex.IsMatch(segment) || - segmentsToIgnore.Contains(segment.ToLowerInvariant()) || - entityNameRegex.IsMatch(segment)) - { - return segment; - } - - // Check if segment is in this form: users('|') and transform to users() - if (IsFunctionCall(segment)) - { - var openingBracketIndex = segment.IndexOf('(', StringComparison.OrdinalIgnoreCase); - var textWithinBrackets = segment.Substring( - openingBracketIndex + 1, - segment.Length - 2 - ); - var sanitizedText = string.Join(',', textWithinBrackets - .Split(',') - .Select(text => - { - if (text.Contains('=', StringComparison.OrdinalIgnoreCase)) - { - var key = text.Split('=')[0]; - key = !IsAllAlpha(key) ? "" : key; - return $"{key}="; - } - return ""; - })); - - return $"{segment[..openingBracketIndex]}({sanitizedText})"; - } - - if (IsPlaceHolderSegment(segment)) - { - return segment; - } - - if (!IsAllAlpha(previousSegment) && !IsDeprecation(previousSegment)) - { - previousSegment = "unknown"; - } - - return $"{{{previousSegment}-id}}"; - } - - private static string SanitizeQueryParameters(string queryString) - { - // remove leading ? from query string and decode - queryString = Uri.UnescapeDataString( - new Regex(@"\+").Replace(queryString[1..], " ") - ); - return string.Join('&', queryString.Split('&').Select(s => s)); - } - - private static bool IsAllAlpha(string value) => allAlphaRegex.IsMatch(value); - - private static bool IsDeprecation(string value) => deprecationRegex.IsMatch(value); - - private static bool IsFunctionCall(string value) => functionCallRegex.IsMatch(value); - - private static bool IsPlaceHolderSegment(string segment) - { - return segment.StartsWith('{') && segment.EndsWith('}'); - } - - private static ParsedSample ParseSampleUrl(string url, string? version = null) - { - var parsedSample = new ParsedSample(); - - if (!string.IsNullOrEmpty(url)) - { - try - { - url = RemoveExtraSlashesFromUrl(url); - parsedSample.QueryVersion = version ?? GetGraphVersion(url); - parsedSample.RequestUrl = GetRequestUrl(url, parsedSample.QueryVersion); - parsedSample.Search = GenerateSearchParameters(url, ""); - parsedSample.SampleUrl = GenerateSampleUrl(url, parsedSample.QueryVersion, parsedSample.RequestUrl, parsedSample.Search); - } - catch (Exception) { } - } - - return parsedSample; - } - - private static string RemoveExtraSlashesFromUrl(string url) - { - return new Regex(@"([^:]\/)\/+").Replace(url, "$1"); - } - - private static string GetRequestUrl(string url, string version) - { - var uri = new Uri(url); - var versionToReplace = uri.AbsolutePath.StartsWith($"/{version}", StringComparison.OrdinalIgnoreCase) - ? version - : GetGraphVersion(url); - var requestContent = uri.AbsolutePath.Split(versionToReplace).LastOrDefault() ?? ""; - return Uri.UnescapeDataString(requestContent.TrimEnd('/')).TrimStart('/'); - } - - private static string GenerateSearchParameters(string url, string search) - { - var uri = new Uri(url); - - if (!string.IsNullOrEmpty(uri.Query)) - { - try - { - search = Uri.UnescapeDataString(uri.Query); - } - catch (Exception) - { - search = uri.Query; - } - } - - return new Regex(@"\s").Replace(search, "+"); - } - - private static string GenerateSampleUrl( - string url, - string queryVersion, - string requestUrl, - string search - ) - { - var uri = new Uri(url); - var origin = uri.GetLeftPart(UriPartial.Authority); - return RemoveExtraSlashesFromUrl($"{origin}/{queryVersion}/{requestUrl + search}"); - } - - private static string GetCommonPrefix(List paths) - { - if (paths.Count == 0) - { - return string.Empty; - } - - var firstPath = paths[0]; - var commonPrefixLength = firstPath.Length; - - for (var i = 1; i < paths.Count; i++) - { - commonPrefixLength = Math.Min(commonPrefixLength, paths[i].Length); - for (var j = 0; j < commonPrefixLength; j++) - { - if (firstPath[j] != paths[i][j]) - { - commonPrefixLength = j; - break; - } - } - } - - // Find the last complete path segment - var prefix = firstPath[..commonPrefixLength]; - var lastSlashIndex = prefix.LastIndexOf('/'); - return lastSlashIndex >= 0 ? prefix[..(lastSlashIndex + 1)] : prefix; - } -} +// 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 DevProxy.Abstractions.Models; +using DevProxy.Abstractions.Proxy; +using DevProxy.Abstractions.Proxy.Http; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Schema; +using System.Collections.ObjectModel; +using System.Reflection; +using System.Text.Encodings.Web; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; + +namespace DevProxy.Abstractions.Utils; + +sealed class ParsedSample +{ + public string QueryVersion { get; set; } = string.Empty; + public string RequestUrl { get; set; } = string.Empty; + public string SampleUrl { get; set; } = string.Empty; + public string Search { get; set; } = string.Empty; +} + +public static class ProxyUtils +{ + 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); + // all alpha must include 2 to allow for oauth2PermissionScopes + private static readonly Regex allAlphaRegex = new("^[a-z2]+$", RegexOptions.IgnoreCase); + private static readonly Regex deprecationRegex = new("^[a-z]+_v2$", RegexOptions.IgnoreCase); + private static readonly Regex functionCallRegex = new(@"^[a-z]+\(.*\)$", RegexOptions.IgnoreCase); + + private static Assembly? _assembly; + private static string _productVersion = string.Empty; + + public static readonly string ReportsKey = "Reports"; + + // doesn't end with a path separator + public static string? AppFolder => Path.GetDirectoryName(AppContext.BaseDirectory); + + /// + /// Gets the path to the user data folder for Dev Proxy. + /// On macOS: ~/Library/Application Support/dev-proxy/ + /// On Linux: ~/.config/dev-proxy/ (or $XDG_CONFIG_HOME/dev-proxy/) + /// On Windows: %LocalAppData%\dev-proxy\ + /// + public static string DataFolder + { + get + { + var basePath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + ? Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + : Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + return Path.Combine(basePath, "dev-proxy"); + } + } + public static JsonSerializerOptions JsonSerializerOptions { get; } = new() + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true, + ReadCommentHandling = JsonCommentHandling.Skip, + WriteIndented = true + }; + public static JsonDocumentOptions JsonDocumentOptions { get; } = new() + { + AllowTrailingCommas = true, + CommentHandling = JsonCommentHandling.Skip + }; + public static string ProductVersion + { + get + { + if (string.IsNullOrEmpty(_productVersion)) + { + var assembly = GetAssembly(); + var assemblyVersionAttribute = assembly.GetCustomAttribute(); + + if (assemblyVersionAttribute is null) + { + _productVersion = assembly.GetName().Version?.ToString() ?? ""; + } + else + { + _productVersion = assemblyVersionAttribute.InformationalVersion; + } + } + + + return _productVersion; + } + } + + static ProxyUtils() + { + // convert enum values to camelCase + JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); + } + + /// + /// Converts a configured response body to the string sent to the client. + /// String bodies are returned as-is; other values are serialized as JSON. + /// + public static string SerializeBody(object? body) => body switch + { + null => string.Empty, + string s => s, + JsonElement { ValueKind: JsonValueKind.String } el => el.GetString() ?? string.Empty, + JValue { Type: JTokenType.String } jv => jv.Value() ?? string.Empty, + _ => JsonSerializer.Serialize(body, JsonSerializerOptions) + }; + + public static bool IsGraphRequest(IHttpRequest request) + { + ArgumentNullException.ThrowIfNull(request); + + return IsGraphUrl(request.RequestUri); + } + + public static bool IsGraphUrl(Uri uri) + { + ArgumentNullException.ThrowIfNull(uri); + + return uri.Host.StartsWith("graph.microsoft.", StringComparison.OrdinalIgnoreCase) || + uri.Host.StartsWith("microsoftgraph.", StringComparison.OrdinalIgnoreCase); + } + + public static bool IsGraphBatchUrl(Uri uri) + { + ArgumentNullException.ThrowIfNull(uri); + + return uri.AbsoluteUri.EndsWith("/$batch", StringComparison.OrdinalIgnoreCase); + } + + public static Uri GetAbsoluteRequestUrlFromBatch(Uri batchRequestUri, string relativeRequestUrl) + { + ArgumentNullException.ThrowIfNull(batchRequestUri); + + var hostName = batchRequestUri.Host; + var graphVersion = batchRequestUri.Segments[1].TrimEnd('/'); + var absoluteRequestUrl = new Uri($"https://{hostName}/{graphVersion}{relativeRequestUrl}"); + return absoluteRequestUrl; + } + + public static bool IsSdkRequest(IHttpRequest request) + { + ArgumentNullException.ThrowIfNull(request); + + return request.Headers.Contains("SdkVersion"); + } + + public static bool IsGraphBetaRequest(IHttpRequest request) + { + ArgumentNullException.ThrowIfNull(request); + + return IsGraphRequest(request) && + IsGraphBetaUrl(request.RequestUri); + } + + public static bool IsGraphBetaUrl(Uri uri) + { + ArgumentNullException.ThrowIfNull(uri); + + return uri.AbsolutePath.Contains("/beta/", StringComparison.OrdinalIgnoreCase); + } + + /// + /// Utility to build HTTP response headers consistent with Microsoft Graph + /// + /// The http request for which response headers are being constructed + /// string a guid representing the a unique identifier for the request + /// string representation of the date and time the request was made + /// IList with defaults consistent with Microsoft Graph. Automatically adds CORS headers when the Origin header is present + public static IList BuildGraphResponseHeaders(IHttpRequest request, string requestId, string requestDate) + { + ArgumentNullException.ThrowIfNull(request); + + if (!IsGraphRequest(request)) + { + return []; + } + + var hasOrigin = request.Headers.FirstOrDefault((h) => h.Name.Equals("Origin", StringComparison.OrdinalIgnoreCase)) is not null; + return BuildGraphResponseHeadersCore(hasOrigin, requestId, requestDate); + } + + private static List BuildGraphResponseHeadersCore(bool hasOriginHeader, string requestId, string requestDate) + { + var headers = new List + { + new ("Cache-Control", "no-store"), + new ("x-ms-ags-diagnostic", ""), + new ("Strict-Transport-Security", ""), + new ("request-id", requestId), + new ("client-request-id", requestId), + new ("Date", requestDate), + new ("Content-Type", "application/json") + }; + if (hasOriginHeader) + { + headers.Add(new("Access-Control-Allow-Origin", "*")); + headers.Add(new("Access-Control-Expose-Headers", "ETag, Location, Preference-Applied, Content-Range, request-id, client-request-id, ReadWriteConsistencyToken, SdkVersion, WWW-Authenticate, x-ms-client-gcc-tenant, Retry-After")); + } + return headers; + } + + public static string ReplacePathTokens(string? path) + { + if (string.IsNullOrEmpty(path)) + { + return path ?? string.Empty; + } + + path = ExpandHomeDirectory(path); + path = path.Replace("~dataFolder", DataFolder, StringComparison.OrdinalIgnoreCase); + return path.Replace("~appFolder", AppFolder, StringComparison.OrdinalIgnoreCase); + } + + private static string ExpandHomeDirectory(string path) + { + if (path.Length < 2 || path[0] != '~' || + (path[1] != '/' && !(OperatingSystem.IsWindows() && path[1] == '\\'))) + { + return path; + } + + var homeFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + if (string.IsNullOrEmpty(homeFolder)) + { + return path; + } + + return Path.Join(homeFolder, path[2..]); + } + + public static string GetFullPath(string? path, string? basePath) => + Path.GetFullPath(ReplacePathTokens(path), Path.GetDirectoryName(basePath) ?? string.Empty); + + // from: https://github.com/microsoftgraph/microsoft-graph-explorer-v4/blob/db86b903f36ef1b882996d46aee52cd49ed4444b/src/app/utils/query-url-sanitization.ts +#pragma warning disable CA1055 + public static string SanitizeUrl(string absoluteUrl) +#pragma warning restore CA1055 + { + absoluteUrl = Uri.UnescapeDataString(absoluteUrl); + var uri = new Uri(absoluteUrl); + + var parsedSample = ParseSampleUrl(absoluteUrl); + var queryString = !string.IsNullOrEmpty(parsedSample.Search) ? $"?{SanitizeQueryParameters(parsedSample.Search)}" : ""; + + // Sanitize item path specified in query url + var resourceUrl = parsedSample.RequestUrl; + if (!string.IsNullOrEmpty(resourceUrl)) + { + resourceUrl = itemPathRegex.Replace(parsedSample.RequestUrl, match => + { + return $"{match.Value[..match.Value.IndexOf(':', StringComparison.OrdinalIgnoreCase)]}:"; + }); + // Split requestUrl into segments that can be sanitized individually + var urlSegments = resourceUrl.Split('/'); + for (var i = 0; i < urlSegments.Length; i++) + { + var segment = urlSegments[i]; + var sanitizedSegment = SanitizePathSegment(i < 1 ? "" : urlSegments[i - 1], segment); + resourceUrl = resourceUrl.Replace(segment, sanitizedSegment, StringComparison.OrdinalIgnoreCase); + } + } + return $"{uri.GetLeftPart(UriPartial.Authority)}/{parsedSample.QueryVersion}/{resourceUrl}{queryString}"; + } + + public static async Task<(bool IsValid, IEnumerable ValidationErrors)> ValidateJsonAsync(string? json, string? schemaUrl, HttpClient httpClient, ILogger logger, CancellationToken cancellationToken) + { + try + { + logger.LogDebug("Validating JSON against schema {SchemaUrl}", schemaUrl); + + if (string.IsNullOrEmpty(json)) + { + 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); + + logger.LogDebug("Downloading schema from {SchemaUrl}", schemaUrl); + var schemaContents = await httpClient.GetStringAsync(schemaUrl, cancellationToken); + + logger.LogDebug("Parsing schema"); + var schema = JSchema.Parse(schemaContents); + logger.LogDebug("Parsing JSON"); + var token = JToken.Parse(json); + + 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]); + } + } + + public static string ReplaceVariables(string s, Dictionary variables, Func? formatVariableRef = null) + { + ArgumentNullException.ThrowIfNull(s); + ArgumentNullException.ThrowIfNull(variables); + + formatVariableRef ??= v => $"@{v}"; + + var s1 = s; + + foreach (var variable in variables) + { + s1 = s1.Replace(formatVariableRef(variable.Key), variable.Value, StringComparison.OrdinalIgnoreCase); + } + + return s1; + } + + public static void ValidateSchemaVersion(string schemaUrl, ILogger logger) + { + if (string.IsNullOrWhiteSpace(schemaUrl)) + { + logger.LogDebug("Schema is empty, skipping schema version validation."); + return; + } + + var warning = GetSchemaVersionMismatchWarning(schemaUrl); + if (warning is not null) + { + logger.LogWarning("{Warning}", warning); + } + } + + /// + /// Checks if the schema URL version matches the current Dev Proxy version. + /// Returns a warning message if versions don't match, or null if they match + /// or the schema URL cannot be parsed. + /// + public static string? GetSchemaVersionMismatchWarning(string schemaUrl) + { + if (string.IsNullOrWhiteSpace(schemaUrl)) + { + return null; + } + + try + { + var uri = new Uri(schemaUrl); + if (uri.Segments.Length > 2) + { + var schemaVersion = uri.Segments[^2] + .TrimStart('v') + .TrimEnd('/'); + var currentVersion = NormalizeVersion(ProductVersion); + if (CompareSemVer(currentVersion, schemaVersion) != 0) + { + var currentSchemaUrl = uri.ToString().Replace($"/v{schemaVersion}/", $"/v{currentVersion}/", StringComparison.OrdinalIgnoreCase); + return $"The version of schema does not match the installed Dev Proxy version, the expected schema is {currentSchemaUrl}"; + } + } + } + catch + { + return $"The $schema value '{schemaUrl}' is not a valid URL. Schema version could not be validated."; + } + + return null; + } + + /// + /// Returns the ordered list of config file paths to search. + /// The first existing file in the list should be used. + /// + public static IEnumerable GetConfigFileCandidates(string? userConfigFile) + { + return [ + // config file specified by the user takes precedence + // null if not specified + userConfigFile, + // current directory - JSON/JSONC files + "devproxyrc.jsonc", + "devproxyrc.json", + // current directory - YAML files + "devproxyrc.yaml", + "devproxyrc.yml", + // .devproxy subdirectory - JSON/JSONC files + Path.Combine(".devproxy", "devproxyrc.jsonc"), + Path.Combine(".devproxy", "devproxyrc.json"), + // .devproxy subdirectory - YAML files + Path.Combine(".devproxy", "devproxyrc.yaml"), + Path.Combine(".devproxy", "devproxyrc.yml"), + // app folder - JSON/JSONC files + Path.Combine(AppFolder ?? "", "devproxyrc.jsonc"), + Path.Combine(AppFolder ?? "", "devproxyrc.json"), + // app folder - YAML files + Path.Combine(AppFolder ?? "", "devproxyrc.yaml"), + Path.Combine(AppFolder ?? "", "devproxyrc.yml") + ]; + } + + /// + /// Compares two semantic versions strings. + /// + /// ver1 + /// ver2 + /// + /// Returns 0 if the versions are equal, -1 if a is less than b, and 1 if a is greater than b. + /// An invalid argument is "rounded" to a minimal version. + /// + public static int CompareSemVer(string? a, string? b) + { + if (string.IsNullOrWhiteSpace(a) && string.IsNullOrWhiteSpace(b)) + { + return 0; + } + else if (string.IsNullOrWhiteSpace(a)) + { + return -1; + } + else if (string.IsNullOrWhiteSpace(b)) + { + return 1; + } + + a = a.TrimStart('v'); + b = b.TrimStart('v'); + + var aParts = a.Split('-'); + var bParts = b.Split('-'); + + var aParsed = Version.TryParse(aParts[0], out var aVersion); + var bParsed = Version.TryParse(bParts[0], out var bVersion); + if (!aParsed && !bParsed) + { + return 0; + } + else if (!aParsed) + { + return -1; + } + else if (!bParsed) + { + return 1; + } + + var compare = aVersion!.CompareTo(bVersion); + if (compare != 0) + { + // if the versions are different, return the comparison result + return compare; + } + + // if the versions are the same, compare the prerelease tags + if (aParts.Length == 1 && bParts.Length == 1) + { + // if both versions are stable, they are equal + return 0; + } + else if (aParts.Length == 1) + { + // if a is stable and b is not, a is greater + return 1; + } + else if (bParts.Length == 1) + { + // if b is stable and a is not, b is greater + return -1; + } + else if (aParts[1] == bParts[1]) + { + // if both versions are prerelease and the tags are the same, they are equal + return 0; + } + else + { + // if both versions are prerelease, b is greater + return -1; + } + } + + /// + /// Produces major.minor.patch version dropping a pre-release suffix. + /// + /// A version looks like "0.28.1", "0.28.1-alpha", "0.28.10-beta.1", "0.28.10-rc.1", or "0.28.0-preview-1", etc. + public static string NormalizeVersion(string version) + { + if (string.IsNullOrWhiteSpace(version)) + { + return version; + } + + return version.Split('-', StringSplitOptions.None)[0]; + } + + public static string GetGraphVersion(string url) + { + var uri = new Uri(url); + return uri.Segments[1].Replace("/", "", StringComparison.OrdinalIgnoreCase); + } + + public static void MergeHeaders(IList allHeaders, IList headersToAdd) + { + ArgumentNullException.ThrowIfNull(allHeaders); + ArgumentNullException.ThrowIfNull(headersToAdd); + + foreach (var header in headersToAdd) + { + var existingHeader = allHeaders.FirstOrDefault(h => h.Name.Equals(header.Name, StringComparison.OrdinalIgnoreCase)); + if (existingHeader is not null) + { + if (header.Name.Equals("Access-Control-Expose-Headers", StringComparison.OrdinalIgnoreCase) || + header.Name.Equals("Access-Control-Allow-Headers", StringComparison.OrdinalIgnoreCase)) + { + var existingValues = existingHeader.Value.Split(',').Select(v => v.Trim()); + var newValues = header.Value.Split(',').Select(v => v.Trim()); + var allValues = existingValues.Union(newValues).Distinct(); + _ = allHeaders.Remove(existingHeader); + allHeaders.Add(new(header.Name, string.Join(", ", allValues))); + continue; + } + + // don't remove headers that we've just added + if (!headersToAdd.Contains(existingHeader)) + { + _ = allHeaders.Remove(existingHeader); + } + } + + allHeaders.Add(header); + } + } + + public static bool MatchesUrlToWatch(ISet watchedUrls, string url, bool evaluateWildcards = false) + { + ArgumentNullException.ThrowIfNull(watchedUrls); + ArgumentNullException.ThrowIfNull(url); + + if (evaluateWildcards && url.Contains('*', StringComparison.OrdinalIgnoreCase)) + { + // url contains a wildcard, so convert it to regex and compare + var match = watchedUrls.FirstOrDefault(r => + { + var pattern = RegexToPattern(r.Url); + var result = UrlRegexComparer.CompareRegexPatterns(pattern, url); + return result != UrlRegexComparisonResult.PatternsMutuallyExclusive; + }); + return match is not null && !match.Exclude; + } + else + { + var match = watchedUrls.FirstOrDefault(r => r.Url.IsMatch(url)); + return match is not null && !match.Exclude; + } + } + + public static string PatternToRegex(string pattern) + { + return $"^{Regex.Escape(pattern).Replace("\\*", ".*", StringComparison.OrdinalIgnoreCase)}$"; + } + + /// + /// Normalizes a WebSocket URL scheme to its HTTP equivalent (wss:// → + /// https://, ws:// → http://), leaving any other scheme untouched. + /// + /// + /// The proxy engine reports an intercepted WebSocket upgrade with an http(s) + /// scheme (a ws(s) connection is an HTTP Upgrade on the wire). Authors, + /// however, naturally write wss://host/* in urlsToWatch and mock URLs. + /// Normalizing both sides to http(s) before matching lets either form work. + /// + /// + public static string NormalizeWebSocketScheme(string url) + { + ArgumentNullException.ThrowIfNull(url); + + if (url.StartsWith("wss://", StringComparison.OrdinalIgnoreCase)) + { + return string.Concat("https://", url.AsSpan("wss://".Length)); + } + if (url.StartsWith("ws://", StringComparison.OrdinalIgnoreCase)) + { + return string.Concat("http://", url.AsSpan("ws://".Length)); + } + return url; + } + + public static string RegexToPattern(Regex regex) + { + ArgumentNullException.ThrowIfNull(regex); + + return Regex.Unescape(regex.ToString()) + .Trim('^', '$') + .Replace(".*", "*", StringComparison.OrdinalIgnoreCase); + } + + public static IEnumerable GetWildcardPatterns(ReadOnlyCollection urls) + { + return [.. urls + .GroupBy(url => + { + if (url.Contains('*', StringComparison.OrdinalIgnoreCase)) + { + return url; + } + + var uri = new Uri(url); + return $"{uri.Scheme}://{uri.Host}"; + }) + .Select(group => + { + if (group.Count() == 1) + { + var url = group.First(); + if (url.Contains('*', StringComparison.OrdinalIgnoreCase)) + { + return url; + } + + // For single URLs, use the URL up to the last segment + var uri = new Uri(url); + var path = uri.AbsolutePath; + var lastSlashIndex = path.AsSpan().LastIndexOf('/'); + return $"{group.Key}{path[..lastSlashIndex]}/*"; + } + + // For multiple URLs, find the common prefix + var paths = group.Select(url => + { + return url.Contains('*', StringComparison.OrdinalIgnoreCase) ? url : new Uri(url).AbsolutePath; + }).ToList(); + var commonPrefix = GetCommonPrefix(paths); + return $"{group.Key}{commonPrefix}*"; + }) + .OrderBy(x => x)]; + } + +#pragma warning disable CA1055 + public static string UrlWithParametersToRegex(string urlWithParameters) +#pragma warning restore CA1055 + { + ArgumentNullException.ThrowIfNull(urlWithParameters); + + return $"^{Regex.Replace(Regex.Escape(urlWithParameters), "\\\\{[^}]+}", ".*")}"; + } + + internal static Assembly GetAssembly() + => _assembly ??= (Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly()); + + /** + * Skipped segments: + * - Entities, entity sets and navigation properties, expected to contain alphabetic letters only + * - Deprecated entities in the form _v2 + * The remaining URL segments are assumed to be variables that need to be sanitized + * @param segment + */ + private static string SanitizePathSegment(string previousSegment, string segment) + { + var segmentsToIgnore = new[] { "$value", "$count", "$ref", "$batch" }; + + if (IsAllAlpha(segment) || + IsDeprecation(segment) || + sanitizedItemPathRegex.IsMatch(segment) || + segmentsToIgnore.Contains(segment.ToLowerInvariant()) || + entityNameRegex.IsMatch(segment)) + { + return segment; + } + + // Check if segment is in this form: users('|') and transform to users() + if (IsFunctionCall(segment)) + { + var openingBracketIndex = segment.IndexOf('(', StringComparison.OrdinalIgnoreCase); + var textWithinBrackets = segment.Substring( + openingBracketIndex + 1, + segment.Length - 2 + ); + var sanitizedText = string.Join(',', textWithinBrackets + .Split(',') + .Select(text => + { + if (text.Contains('=', StringComparison.OrdinalIgnoreCase)) + { + var key = text.Split('=')[0]; + key = !IsAllAlpha(key) ? "" : key; + return $"{key}="; + } + return ""; + })); + + return $"{segment[..openingBracketIndex]}({sanitizedText})"; + } + + if (IsPlaceHolderSegment(segment)) + { + return segment; + } + + if (!IsAllAlpha(previousSegment) && !IsDeprecation(previousSegment)) + { + previousSegment = "unknown"; + } + + return $"{{{previousSegment}-id}}"; + } + + private static string SanitizeQueryParameters(string queryString) + { + // remove leading ? from query string and decode + queryString = Uri.UnescapeDataString( + new Regex(@"\+").Replace(queryString[1..], " ") + ); + return string.Join('&', queryString.Split('&').Select(s => s)); + } + + private static bool IsAllAlpha(string value) => allAlphaRegex.IsMatch(value); + + private static bool IsDeprecation(string value) => deprecationRegex.IsMatch(value); + + private static bool IsFunctionCall(string value) => functionCallRegex.IsMatch(value); + + private static bool IsPlaceHolderSegment(string segment) + { + return segment is ['{', .., '}']; + } + + private static ParsedSample ParseSampleUrl(string url, string? version = null) + { + var parsedSample = new ParsedSample(); + + if (!string.IsNullOrEmpty(url)) + { + try + { + url = RemoveExtraSlashesFromUrl(url); + parsedSample.QueryVersion = version ?? GetGraphVersion(url); + parsedSample.RequestUrl = GetRequestUrl(url, parsedSample.QueryVersion); + parsedSample.Search = GenerateSearchParameters(url, ""); + parsedSample.SampleUrl = GenerateSampleUrl(url, parsedSample.QueryVersion, parsedSample.RequestUrl, parsedSample.Search); + } + catch (Exception) { } + } + + return parsedSample; + } + + private static string RemoveExtraSlashesFromUrl(string url) + { + return new Regex(@"([^:]\/)\/+").Replace(url, "$1"); + } + + private static string GetRequestUrl(string url, string version) + { + var uri = new Uri(url); + var versionToReplace = uri.AbsolutePath.StartsWith($"/{version}", StringComparison.OrdinalIgnoreCase) + ? version + : GetGraphVersion(url); + var requestContent = uri.AbsolutePath.Split(versionToReplace).LastOrDefault() ?? ""; + return Uri.UnescapeDataString(requestContent.TrimEnd('/')).TrimStart('/'); + } + + private static string GenerateSearchParameters(string url, string search) + { + var uri = new Uri(url); + + if (!string.IsNullOrEmpty(uri.Query)) + { + try + { + search = Uri.UnescapeDataString(uri.Query); + } + catch (Exception) + { + search = uri.Query; + } + } + + return new Regex(@"\s").Replace(search, "+"); + } + + private static string GenerateSampleUrl( + string url, + string queryVersion, + string requestUrl, + string search + ) + { + var uri = new Uri(url); + var origin = uri.GetLeftPart(UriPartial.Authority); + return RemoveExtraSlashesFromUrl($"{origin}/{queryVersion}/{requestUrl + search}"); + } + + private static string GetCommonPrefix(List paths) + { + if (paths.Count == 0) + { + return string.Empty; + } + + var firstPath = paths[0]; + var commonPrefixLength = firstPath.Length; + + for (var i = 1; i < paths.Count; i++) + { + commonPrefixLength = Math.Min(commonPrefixLength, paths[i].Length); + for (var j = 0; j < commonPrefixLength; j++) + { + if (firstPath[j] != paths[i][j]) + { + commonPrefixLength = j; + break; + } + } + } + + // Find the last complete path segment + var prefix = firstPath[..commonPrefixLength]; + var lastSlashIndex = prefix.AsSpan().LastIndexOf('/'); + return lastSlashIndex >= 0 ? prefix[..(lastSlashIndex + 1)] : prefix; + } +} diff --git a/DevProxy.Abstractions/packages.lock.json b/DevProxy.Abstractions/packages.lock.json index 33fc00a2d..20a0450ac 100644 --- a/DevProxy.Abstractions/packages.lock.json +++ b/DevProxy.Abstractions/packages.lock.json @@ -304,6 +304,239 @@ "SQLitePCLRaw.core": "2.1.13" } } + }, + "net11.0": { + "Markdig": { + "type": "Direct", + "requested": "[1.6.0, )", + "resolved": "1.6.0", + "contentHash": "rJEpDfPM8wrfXUgkNejjg2bJN9bciy44uVyRwKUI+92CnSmbaLeJTLPYcCdvgM4RFsKrhs8d2H2hO78yZpMl3g==" + }, + "Microsoft.EntityFrameworkCore.Sqlite": { + "type": "Direct", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "12olimxsnuTo+9jsQvbS9fF/FXUhW7AHaXFcK/TgpND3Ki53CBvXnvT+AnPnk6d6f02D5NBdmBcZzfAynBgkRw==", + "dependencies": { + "Microsoft.EntityFrameworkCore.Sqlite.Core": "[11.0.0, 12.0.0-a)", + "Microsoft.Extensions.Caching.Memory": "11.0.0", + "Microsoft.Extensions.DependencyModel": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "SQLitePCLRaw.bundle_e_sqlite3": "3.0.5", + "SQLitePCLRaw.core": "3.0.5" + } + }, + "Microsoft.Extensions.Configuration": { + "type": "Direct", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==" + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Direct", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Json": { + "type": "Direct", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "WsNcEnVlq43lXBHAXtQg1b7job819SUf9BPtJrq44vhthL9Ijl2mkRBx5L3hIU1p2AN+wiRg47yhYj+vQxEgeQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.FileExtensions": "11.0.0" + } + }, + "Microsoft.Extensions.FileSystemGlobbing": { + "type": "Direct", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Ycwu/y22NK/ZyJpaFRJc4FB88mjOnsttk2AVHaKgEeShq0vodXZ4FJErpMM2Jju3r3t/2VYWrcHuIxj3ZT/aow==" + }, + "Microsoft.OpenApi": { + "type": "Direct", + "requested": "[3.11.0, )", + "resolved": "3.11.0", + "contentHash": "kvQz+mL/fnDw2VaE8zMyQhbMv7FmOYUydIhCVNKxQdrLu9XiMT/07DHwJ5YkRO2uzcxTFvMAKFKKywxoyLKHcA==" + }, + "Microsoft.OpenApi.YamlReader": { + "type": "Direct", + "requested": "[3.11.0, )", + "resolved": "3.11.0", + "contentHash": "AM3Me+AzT9g123P9mc8Po5auLbYE9MeBW42TkR0T/NWelJuy2CqAR7eGpkdeP4lL7FCDZFW2dEdeQTBY+QxmWQ==", + "dependencies": { + "Microsoft.OpenApi": "3.11.0", + "SharpYaml": "2.1.5" + } + }, + "Newtonsoft.Json.Schema": { + "type": "Direct", + "requested": "[4.0.2, )", + "resolved": "4.0.2", + "contentHash": "+Kyhf67t35xoUycpSkaaxGeBaTLz/sZOPEW94HCVM/WJFVJooIsIHGUV7hS8xSvT1Ci78XwN4Fr57927OGYE6w==", + "dependencies": { + "Newtonsoft.Json": "13.0.4" + } + }, + "Scriban": { + "type": "Direct", + "requested": "[7.5.3, )", + "resolved": "7.5.3", + "contentHash": "yeusmR5XJYfGJ2Wj8I92TagqV3n6dggeurnq+cfYPZ4YMFmZMuAG8YSLqExrB9Z9Gx99YGR4ABzVkAHcLlTOmw==" + }, + "System.CommandLine": { + "type": "Direct", + "requested": "[2.0.14, )", + "resolved": "2.0.14", + "contentHash": "15fyVO4aG6poR6IKmhM74zf7PUzaU6FZAGm2d3SQSO9yIyGAeo44e6t9qeKjjaqyMEqYdqcb2G1B0gpLoDU2cA==" + }, + "YamlDotNet": { + "type": "Direct", + "requested": "[18.1.0, )", + "resolved": "18.1.0", + "contentHash": "5K+9KFg2TdTl7VXv88Qzi/0lqK6JFoNP3lRuImPYGRV7K/QYklDyTrj4+A+KAki1JsQi6qKY+hDyY7d6WRqjrw==" + }, + "Microsoft.Data.Sqlite.Core": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "aWaF2LDjuFZwE9UsAGRYGNyS48xqaXoKPAjwpJI85fsaM/43s5NTRnl4xtqbTGKq8of2M/W8mo7DJk7v4zzHGQ==", + "dependencies": { + "SQLitePCLRaw.core": "3.0.5" + } + }, + "Microsoft.EntityFrameworkCore": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "1zGKYhZMHG9gIfC89cC2QKM6DpNotDglm+UzYEV9dAWyLwJI8kLx+yfjAQVpC83iUzvr9y+1HJ0HZ8cOaosBXA==", + "dependencies": { + "Microsoft.EntityFrameworkCore.Abstractions": "[11.0.0, 12.0.0-a)", + "Microsoft.EntityFrameworkCore.Analyzers": "[11.0.0, 12.0.0-a)", + "Microsoft.Extensions.Caching.Memory": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0" + } + }, + "Microsoft.EntityFrameworkCore.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "iL0D3Dohk6bNYIHSM3VhvDXrJ+WXs7yMBVv+4L1ozxbsDmohG0T3ogd0mLgWBofu49BHGOgfFKgSGLsOirsjoQ==" + }, + "Microsoft.EntityFrameworkCore.Analyzers": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "R7QxcmtQLP5np732En6eyzv2DjKevbrRxUUY9jPRQwuLzOSbyDowE5l0KyqdEEySvdHbrdRILg99FlaJTwcPbQ==" + }, + "Microsoft.EntityFrameworkCore.Relational": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "yGS+J269mYUl8V17rHWaeFDySoUnGdiugIzszlNZr0F2+JirFatQyw2s2He92wyYIuy/Y3Yv3QLdq/HdTSj7cA==", + "dependencies": { + "Microsoft.EntityFrameworkCore": "[11.0.0, 12.0.0-a)", + "Microsoft.Extensions.Caching.Memory": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0" + } + }, + "Microsoft.EntityFrameworkCore.Sqlite.Core": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "7u0jhtUY4GXr2MRsvSzemUpgf2znOCf8+3VLYxYNthIU5rIKk5Y+9EvS+yAlLIBL2218LeahsHYKA0MWKBYo5Q==", + "dependencies": { + "Microsoft.Data.Sqlite.Core": "[11.0.0, 12.0.0-a)", + "Microsoft.EntityFrameworkCore.Relational": "[11.0.0, 12.0.0-a)", + "Microsoft.Extensions.Caching.Memory": "11.0.0", + "Microsoft.Extensions.DependencyModel": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "SQLitePCLRaw.core": "3.0.5" + } + }, + "Microsoft.Extensions.Caching.Memory": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "w0nn5qRLxZC2T3sSmXj5PhrBFpGFCSFxg7E/zBi4lne0wZcZPY8of3qQDowqGobMZ3PW5qJnM1Q8fmGjL2B6Iw==" + }, + "Microsoft.Extensions.Configuration.FileExtensions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "ViBZDt2Y7TfVIxiWG5HKfP1KHTzsxn7a31ikZSg/1mdOfGyGAPj278v63NOU+n4UqvaOR43t9MOCUfadSohjQA==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.FileProviders.Physical": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==" + }, + "Microsoft.Extensions.DependencyModel": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "K6M9zulTQ3OU0myKAcBb/Gbfw/aTKa3wlxyDhwfOmT7Wavoxe0lzAkeDjS5+/1dqcgGDUZtIykJIo3T4W7zKbQ==" + }, + "Microsoft.Extensions.FileProviders.Physical": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "lHezhjI8zoTpltXwNy6QMr4/6lIhbXsAYZnCrgRDNNzMHCKvh+x95mkBVXLMzs8axrw7J5Cy21K8lM5YHCfgAw==", + "dependencies": { + "Microsoft.Extensions.FileSystemGlobbing": "11.0.0" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "11.0.0" + } + }, + "Newtonsoft.Json": { + "type": "Transitive", + "resolved": "13.0.4", + "contentHash": "pdgNNMai3zv51W5aq268sujXUyx7SNdE2bj1wZcWjAQrKMFZV260lbqYop1d2GM67JI1huLRwxo9ZqnfF/lC6A==" + }, + "SharpYaml": { + "type": "Transitive", + "resolved": "2.1.5", + "contentHash": "1pNSpfXxNAgCQ9sacKKpEWO2DxTefoLEjw0v1nWMvyJScUWacoHvjXr4LfcUkhm0qYgNYripFFiUeEzW4tdXIQ==" + }, + "SQLite": { + "type": "Transitive", + "resolved": "3.53.4", + "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" + }, + "SQLitePCLRaw.bundle_e_sqlite3": { + "type": "Transitive", + "resolved": "3.0.5", + "contentHash": "SW8iASIyWMrLzqabUHYQRvALhvD4ylSBsj4PgEVGwc36kQjc9xT5kSV/XQ9rU7nIpBWD+LPyX3Hlw5FzyUzGeQ==", + "dependencies": { + "SQLite": "3.53.4", + "SQLitePCLRaw.config.e_sqlite3": "3.0.5" + } + }, + "SQLitePCLRaw.config.e_sqlite3": { + "type": "Transitive", + "resolved": "3.0.5", + "contentHash": "aSk8WE5tF2MybESMgtZAEyMVCAWA0nBqOMc48HFoa9UoSdtm3goDXVzNRnefeKIwE6bV9NaNXptn1F9ReMQI0Q==", + "dependencies": { + "SQLitePCLRaw.provider.e_sqlite3": "3.0.5" + } + }, + "SQLitePCLRaw.core": { + "type": "Transitive", + "resolved": "3.0.5", + "contentHash": "k81AYXXRCw3Zj8rOhyBoCsx/U97KYDFI2CSKr/ijl5BwpsW/hX/4kBiDmerFaoust8nxBwa0IHQFw8MmSHRtnQ==" + }, + "SQLitePCLRaw.provider.e_sqlite3": { + "type": "Transitive", + "resolved": "3.0.5", + "contentHash": "um8YSWduhhuskTG2bHfZrBqMNQOydfU8pcseT+cu5RivOGyoUbCrGXxgoRNTmRYw2VbMWnEZVVFcneZT/5dsBg==", + "dependencies": { + "SQLitePCLRaw.core": "3.0.5" + } + } } } } \ No newline at end of file diff --git a/DevProxy.Integration.Tests/CommandExitCodeTests.cs b/DevProxy.Integration.Tests/CommandExitCodeTests.cs index fde028164..56db128b4 100644 --- a/DevProxy.Integration.Tests/CommandExitCodeTests.cs +++ b/DevProxy.Integration.Tests/CommandExitCodeTests.cs @@ -188,7 +188,7 @@ private static string LocateHostDll() var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir is not null) { - var candidate = Path.Combine(dir.FullName, "DevProxy", "bin", config, "net10.0", "DevProxy.dll"); + var candidate = Path.Combine(dir.FullName, "DevProxy", "bin", config, "net11.0", "DevProxy.dll"); if (File.Exists(candidate)) { return candidate; diff --git a/DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj b/DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj index c2cb9f1cd..fdef79781 100644 --- a/DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj +++ b/DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj @@ -1,7 +1,7 @@ - net10.0 + net11.0 enable enable false @@ -26,7 +26,7 @@ this test host must itself supply the runtime assemblies, mirroring DevProxy.csproj. --> - + diff --git a/DevProxy.Integration.Tests/EngineInactivityTimeoutTests.cs b/DevProxy.Integration.Tests/EngineInactivityTimeoutTests.cs index 5d0ff3714..e7882929f 100644 --- a/DevProxy.Integration.Tests/EngineInactivityTimeoutTests.cs +++ b/DevProxy.Integration.Tests/EngineInactivityTimeoutTests.cs @@ -28,8 +28,7 @@ public async Task ExecuteAsync_WithTimeout_StopsApplicationWhenIdle() await RunEngineAsync(configuration, lifetime, async () => { - var stopped = await Task.WhenAny(lifetime.StopRequested.Task, Task.Delay(10_000)); - Assert.Same(lifetime.StopRequested.Task, stopped); + await lifetime.StopRequested.Task.WaitAsync(TimeSpan.FromSeconds(10)); }); } @@ -77,8 +76,7 @@ await RunEngineAsync(configuration, lifetime, async () => await Task.Delay(400); } - var stopped = await Task.WhenAny(lifetime.StopRequested.Task, Task.Delay(10_000)); - Assert.Same(lifetime.StopRequested.Task, stopped); + await lifetime.StopRequested.Task.WaitAsync(TimeSpan.FromSeconds(10)); }); } diff --git a/DevProxy.Integration.Tests/ProcessSmokeTests.cs b/DevProxy.Integration.Tests/ProcessSmokeTests.cs index 75ea5ae26..fb907c2b3 100644 --- a/DevProxy.Integration.Tests/ProcessSmokeTests.cs +++ b/DevProxy.Integration.Tests/ProcessSmokeTests.cs @@ -638,7 +638,7 @@ private static string LocateHostDll() var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir is not null) { - var candidate = Path.Combine(dir.FullName, "DevProxy", "bin", config, "net10.0", "devproxy.dll"); + var candidate = Path.Combine(dir.FullName, "DevProxy", "bin", config, "net11.0", "devproxy.dll"); if (File.Exists(candidate)) { return candidate; diff --git a/DevProxy.Plugins/ApiCenter/ApiCenterClient.cs b/DevProxy.Plugins/ApiCenter/ApiCenterClient.cs index 7cb5fd027..2b54f9b2d 100644 --- a/DevProxy.Plugins/ApiCenter/ApiCenterClient.cs +++ b/DevProxy.Plugins/ApiCenter/ApiCenterClient.cs @@ -1,200 +1,200 @@ -// 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 Azure.Core; -using Azure.Core.Diagnostics; -using Azure.Identity; -using DevProxy.Abstractions.Utils; -using DevProxy.Plugins.Handlers; -using DevProxy.Plugins.Models.ApiCenter; -using Microsoft.Extensions.Logging; -using System.Diagnostics.Tracing; -using System.Net.Http.Json; -using System.Text; -using System.Text.Json; - -namespace DevProxy.Plugins.ApiCenter; - -internal sealed class ApiCenterClientConfiguration -{ - public string ResourceGroupName { get; set; } = ""; - public string ServiceName { get; set; } = ""; - public string SubscriptionId { get; set; } = ""; - public string WorkspaceName { get; set; } = "default"; -} - -internal sealed class ApiCenterClient : IDisposable -{ - private readonly AuthenticationDelegatingHandler _authenticationHandler; - private readonly ApiCenterClientConfiguration _configuration; - private readonly TokenCredential _credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() - { - ExcludeInteractiveBrowserCredential = true - }); - private readonly HttpClient _httpClient; - private readonly ILogger _logger; - private readonly string[] _scopes = ["https://management.azure.com/.default"]; - - internal ApiCenterClient(ApiCenterClientConfiguration configuration, ILogger logger) - { - if (string.IsNullOrEmpty(configuration.SubscriptionId)) - { - throw new ArgumentException("Specify subscriptionId in the configuration."); - } - if (string.IsNullOrEmpty(configuration.ResourceGroupName)) - { - throw new ArgumentException("Specify resourceGroupName in the configuration."); - } - if (string.IsNullOrEmpty(configuration.ServiceName)) - { - throw new ArgumentException("Specify serviceName in the configuration."); - } - if (string.IsNullOrEmpty(configuration.WorkspaceName)) - { - throw new ArgumentException("Specify workspaceName in the configuration."); - } - - // load configuration from env vars - configuration.SubscriptionId = ResolveEnvironmentVariable(configuration.SubscriptionId, "subscriptionId"); - configuration.ResourceGroupName = ResolveEnvironmentVariable(configuration.ResourceGroupName, "resourceGroupName"); - configuration.ServiceName = ResolveEnvironmentVariable(configuration.ServiceName, "serviceName"); - configuration.WorkspaceName = ResolveEnvironmentVariable(configuration.WorkspaceName, "workspaceName"); - - _configuration = configuration; - _logger = logger; - - _authenticationHandler = new(_credential, _scopes) - { - InnerHandler = new TracingDelegatingHandler(logger) - { - InnerHandler = new HttpClientHandler() - } - }; - _httpClient = new HttpClient(_authenticationHandler); - - if (_logger.IsEnabled(LogLevel.Debug)) - { - using var azureLogger = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Verbose); - } - } - - private static string ResolveEnvironmentVariable(string value, string settingName) - { - if (!value.StartsWith('@')) - { - return value; - } - - var variableName = value[1..]; - var variableValue = Environment.GetEnvironmentVariable(variableName); - return string.IsNullOrEmpty(variableValue) - ? throw new ArgumentException($"Environment variable {variableName} referenced by {settingName} isn't set.") - : variableValue; - } - - internal Task GetAccessTokenAsync(CancellationToken cancellationToken) => - _authenticationHandler.GetAccessTokenAsync(cancellationToken); - - internal async Task GetApisAsync() - { - _logger.LogInformation("Loading APIs from API Center..."); - - var res = await _httpClient.GetStringAsync($"https://management.azure.com/subscriptions/{_configuration.SubscriptionId}/resourceGroups/{_configuration.ResourceGroupName}/providers/Microsoft.ApiCenter/services/{_configuration.ServiceName}/workspaces/{_configuration.WorkspaceName}/apis?api-version=2024-03-01"); - var collection = JsonSerializer.Deserialize>(res, ProxyUtils.JsonSerializerOptions); - return collection?.Value; - } - - internal async Task GetDefinitionAsync(string definitionId, CancellationToken cancellationToken) - { - _logger.LogDebug("Loading API definition {Id}...", definitionId); - - var res = await _httpClient.GetStringAsync($"https://management.azure.com{definitionId}?api-version=2024-03-01", cancellationToken); - return JsonSerializer.Deserialize(res, ProxyUtils.JsonSerializerOptions); - } - - internal async Task GetDefinitionsAsync(string versionId, CancellationToken cancellationToken) - { - _logger.LogDebug("Loading API definitions for version {Id}...", versionId); - - var res = await _httpClient.GetStringAsync($"https://management.azure.com{versionId}/definitions?api-version=2024-03-01", cancellationToken); - var collection = JsonSerializer.Deserialize>(res, ProxyUtils.JsonSerializerOptions); - return collection?.Value; - } - - internal async Task GetDeploymentsAsync(string apiId, CancellationToken cancellationToken) - { - _logger.LogDebug("Loading API deployments for {ApiName}...", apiId); - - var res = await _httpClient.GetStringAsync($"https://management.azure.com{apiId}/deployments?api-version=2024-03-01", cancellationToken); - var collection = JsonSerializer.Deserialize>(res, ProxyUtils.JsonSerializerOptions); - return collection?.Value; - } - - internal async Task GetVersionsAsync(string apiId, CancellationToken cancellationToken) - { - _logger.LogDebug("Loading API versions for {ApiName}...", apiId); - - var res = await _httpClient.GetStringAsync($"https://management.azure.com{apiId}/versions?api-version=2024-03-01", cancellationToken); - var collection = JsonSerializer.Deserialize>(res, ProxyUtils.JsonSerializerOptions); - return collection?.Value; - } - - internal async Task PostExportSpecificationAsync(string definitionId, CancellationToken cancellationToken) - { - var definitionRes = await _httpClient.PostAsync($"https://management.azure.com{definitionId}/exportSpecification?api-version=2024-03-01", null, cancellationToken); - return await definitionRes.Content.ReadFromJsonAsync(ProxyUtils.JsonSerializerOptions, cancellationToken); - } - - internal async Task PostImportSpecificationAsync(ApiSpecImport apiSpecImport, string definitionId, CancellationToken cancellationToken) - { - using var content = new StringContent(JsonSerializer.Serialize(apiSpecImport, ProxyUtils.JsonSerializerOptions), Encoding.UTF8, "application/json"); - return await _httpClient.PostAsync($"https://management.azure.com{definitionId}/importSpecification?api-version=2024-03-01", content, cancellationToken); - } - - internal async Task PutApiAsync(Api api, string apiName, CancellationToken cancellationToken) - { - using var content = new StringContent(JsonSerializer.Serialize(api, ProxyUtils.JsonSerializerOptions), Encoding.UTF8, "application/json"); - var res = await _httpClient.PutAsync($"https://management.azure.com/subscriptions/{_configuration.SubscriptionId}/resourceGroups/{_configuration.ResourceGroupName}/providers/Microsoft.ApiCenter/services/{_configuration.ServiceName}/workspaces/{_configuration.WorkspaceName}/apis/{apiName}?api-version=2024-03-01", content, cancellationToken); - - var resContent = await res.Content.ReadAsStringAsync(cancellationToken); - _logger.LogDebug("{Response}", resContent); - - return res.IsSuccessStatusCode ? - JsonSerializer.Deserialize(resContent, ProxyUtils.JsonSerializerOptions) : - null; - } - - internal async Task PutVersionAsync(ApiVersion apiVersion, string apiId, string apiName, CancellationToken cancellationToken) - { - using var content = new StringContent(JsonSerializer.Serialize(apiVersion, ProxyUtils.JsonSerializerOptions), Encoding.UTF8, "application/json"); - var res = await _httpClient.PutAsync($"https://management.azure.com{apiId}/versions/{apiName}?api-version=2024-03-01", content, cancellationToken); - - var resContent = await res.Content.ReadAsStringAsync(cancellationToken); - _logger.LogDebug("{Response}", resContent); - - return res.IsSuccessStatusCode ? - JsonSerializer.Deserialize(resContent, ProxyUtils.JsonSerializerOptions) : - null; - } - - internal async Task PutDefinitionAsync(ApiDefinition apiDefinition, string apiVersionId, string definitionName, CancellationToken cancellationToken) - { - using var content = new StringContent(JsonSerializer.Serialize(apiDefinition, ProxyUtils.JsonSerializerOptions), Encoding.UTF8, "application/json"); - var res = await _httpClient.PutAsync($"https://management.azure.com{apiVersionId}/definitions/{definitionName}?api-version=2024-03-01", content, cancellationToken); - - var resContent = await res.Content.ReadAsStringAsync(cancellationToken); - _logger.LogDebug("{Response}", resContent); - - return res.IsSuccessStatusCode ? - JsonSerializer.Deserialize(resContent, ProxyUtils.JsonSerializerOptions) : - null; - } - - public void Dispose() - { - _httpClient.Dispose(); - _authenticationHandler.Dispose(); - GC.SuppressFinalize(this); - } +// 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 Azure.Core; +using Azure.Core.Diagnostics; +using Azure.Identity; +using DevProxy.Abstractions.Utils; +using DevProxy.Plugins.Handlers; +using DevProxy.Plugins.Models.ApiCenter; +using Microsoft.Extensions.Logging; +using System.Diagnostics.Tracing; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; + +namespace DevProxy.Plugins.ApiCenter; + +internal sealed class ApiCenterClientConfiguration +{ + public string ResourceGroupName { get; set; } = ""; + public string ServiceName { get; set; } = ""; + public string SubscriptionId { get; set; } = ""; + public string WorkspaceName { get; set; } = "default"; +} + +internal sealed class ApiCenterClient : IDisposable +{ + private readonly AuthenticationDelegatingHandler _authenticationHandler; + private readonly ApiCenterClientConfiguration _configuration; + private readonly TokenCredential _credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() + { + ExcludeInteractiveBrowserCredential = true + }); + private readonly HttpClient _httpClient; + private readonly ILogger _logger; + private readonly string[] _scopes = ["https://management.azure.com/.default"]; + + internal ApiCenterClient(ApiCenterClientConfiguration configuration, ILogger logger) + { + if (string.IsNullOrEmpty(configuration.SubscriptionId)) + { + throw new ArgumentException("Specify subscriptionId in the configuration."); + } + if (string.IsNullOrEmpty(configuration.ResourceGroupName)) + { + throw new ArgumentException("Specify resourceGroupName in the configuration."); + } + if (string.IsNullOrEmpty(configuration.ServiceName)) + { + throw new ArgumentException("Specify serviceName in the configuration."); + } + if (string.IsNullOrEmpty(configuration.WorkspaceName)) + { + throw new ArgumentException("Specify workspaceName in the configuration."); + } + + // load configuration from env vars + configuration.SubscriptionId = ResolveEnvironmentVariable(configuration.SubscriptionId, "subscriptionId"); + configuration.ResourceGroupName = ResolveEnvironmentVariable(configuration.ResourceGroupName, "resourceGroupName"); + configuration.ServiceName = ResolveEnvironmentVariable(configuration.ServiceName, "serviceName"); + configuration.WorkspaceName = ResolveEnvironmentVariable(configuration.WorkspaceName, "workspaceName"); + + _configuration = configuration; + _logger = logger; + + _authenticationHandler = new(_credential, _scopes) + { + InnerHandler = new TracingDelegatingHandler(logger) + { + InnerHandler = new HttpClientHandler() + } + }; + _httpClient = new HttpClient(_authenticationHandler); + + if (_logger.IsEnabled(LogLevel.Debug)) + { + using var azureLogger = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Verbose); + } + } + + private static string ResolveEnvironmentVariable(string value, string settingName) + { + if (!value.StartsWith('@', StringComparison.Ordinal)) + { + return value; + } + + var variableName = value[1..]; + var variableValue = Environment.GetEnvironmentVariable(variableName); + return string.IsNullOrEmpty(variableValue) + ? throw new ArgumentException($"Environment variable {variableName} referenced by {settingName} isn't set.") + : variableValue; + } + + internal Task GetAccessTokenAsync(CancellationToken cancellationToken) => + _authenticationHandler.GetAccessTokenAsync(cancellationToken); + + internal async Task GetApisAsync() + { + _logger.LogInformation("Loading APIs from API Center..."); + + var res = await _httpClient.GetStringAsync($"https://management.azure.com/subscriptions/{_configuration.SubscriptionId}/resourceGroups/{_configuration.ResourceGroupName}/providers/Microsoft.ApiCenter/services/{_configuration.ServiceName}/workspaces/{_configuration.WorkspaceName}/apis?api-version=2024-03-01"); + var collection = JsonSerializer.Deserialize>(res, ProxyUtils.JsonSerializerOptions); + return collection?.Value; + } + + internal async Task GetDefinitionAsync(string definitionId, CancellationToken cancellationToken) + { + _logger.LogDebug("Loading API definition {Id}...", definitionId); + + var res = await _httpClient.GetStringAsync($"https://management.azure.com{definitionId}?api-version=2024-03-01", cancellationToken); + return JsonSerializer.Deserialize(res, ProxyUtils.JsonSerializerOptions); + } + + internal async Task GetDefinitionsAsync(string versionId, CancellationToken cancellationToken) + { + _logger.LogDebug("Loading API definitions for version {Id}...", versionId); + + var res = await _httpClient.GetStringAsync($"https://management.azure.com{versionId}/definitions?api-version=2024-03-01", cancellationToken); + var collection = JsonSerializer.Deserialize>(res, ProxyUtils.JsonSerializerOptions); + return collection?.Value; + } + + internal async Task GetDeploymentsAsync(string apiId, CancellationToken cancellationToken) + { + _logger.LogDebug("Loading API deployments for {ApiName}...", apiId); + + var res = await _httpClient.GetStringAsync($"https://management.azure.com{apiId}/deployments?api-version=2024-03-01", cancellationToken); + var collection = JsonSerializer.Deserialize>(res, ProxyUtils.JsonSerializerOptions); + return collection?.Value; + } + + internal async Task GetVersionsAsync(string apiId, CancellationToken cancellationToken) + { + _logger.LogDebug("Loading API versions for {ApiName}...", apiId); + + var res = await _httpClient.GetStringAsync($"https://management.azure.com{apiId}/versions?api-version=2024-03-01", cancellationToken); + var collection = JsonSerializer.Deserialize>(res, ProxyUtils.JsonSerializerOptions); + return collection?.Value; + } + + internal async Task PostExportSpecificationAsync(string definitionId, CancellationToken cancellationToken) + { + var definitionRes = await _httpClient.PostAsync($"https://management.azure.com{definitionId}/exportSpecification?api-version=2024-03-01", null, cancellationToken); + return await definitionRes.Content.ReadFromJsonAsync(ProxyUtils.JsonSerializerOptions, cancellationToken); + } + + internal async Task PostImportSpecificationAsync(ApiSpecImport apiSpecImport, string definitionId, CancellationToken cancellationToken) + { + using var content = new StringContent(JsonSerializer.Serialize(apiSpecImport, ProxyUtils.JsonSerializerOptions), Encoding.UTF8, "application/json"); + return await _httpClient.PostAsync($"https://management.azure.com{definitionId}/importSpecification?api-version=2024-03-01", content, cancellationToken); + } + + internal async Task PutApiAsync(Api api, string apiName, CancellationToken cancellationToken) + { + using var content = new StringContent(JsonSerializer.Serialize(api, ProxyUtils.JsonSerializerOptions), Encoding.UTF8, "application/json"); + var res = await _httpClient.PutAsync($"https://management.azure.com/subscriptions/{_configuration.SubscriptionId}/resourceGroups/{_configuration.ResourceGroupName}/providers/Microsoft.ApiCenter/services/{_configuration.ServiceName}/workspaces/{_configuration.WorkspaceName}/apis/{apiName}?api-version=2024-03-01", content, cancellationToken); + + var resContent = await res.Content.ReadAsStringAsync(cancellationToken); + _logger.LogDebug("{Response}", resContent); + + return res.IsSuccessStatusCode ? + JsonSerializer.Deserialize(resContent, ProxyUtils.JsonSerializerOptions) : + null; + } + + internal async Task PutVersionAsync(ApiVersion apiVersion, string apiId, string apiName, CancellationToken cancellationToken) + { + using var content = new StringContent(JsonSerializer.Serialize(apiVersion, ProxyUtils.JsonSerializerOptions), Encoding.UTF8, "application/json"); + var res = await _httpClient.PutAsync($"https://management.azure.com{apiId}/versions/{apiName}?api-version=2024-03-01", content, cancellationToken); + + var resContent = await res.Content.ReadAsStringAsync(cancellationToken); + _logger.LogDebug("{Response}", resContent); + + return res.IsSuccessStatusCode ? + JsonSerializer.Deserialize(resContent, ProxyUtils.JsonSerializerOptions) : + null; + } + + internal async Task PutDefinitionAsync(ApiDefinition apiDefinition, string apiVersionId, string definitionName, CancellationToken cancellationToken) + { + using var content = new StringContent(JsonSerializer.Serialize(apiDefinition, ProxyUtils.JsonSerializerOptions), Encoding.UTF8, "application/json"); + var res = await _httpClient.PutAsync($"https://management.azure.com{apiVersionId}/definitions/{definitionName}?api-version=2024-03-01", content, cancellationToken); + + var resContent = await res.Content.ReadAsStringAsync(cancellationToken); + _logger.LogDebug("{Response}", resContent); + + return res.IsSuccessStatusCode ? + JsonSerializer.Deserialize(resContent, ProxyUtils.JsonSerializerOptions) : + null; + } + + public void Dispose() + { + _httpClient.Dispose(); + _authenticationHandler.Dispose(); + GC.SuppressFinalize(this); + } } \ No newline at end of file diff --git a/DevProxy.Plugins/Behavior/GenericRandomErrorPlugin.cs b/DevProxy.Plugins/Behavior/GenericRandomErrorPlugin.cs index cea63ec85..f837f5916 100644 --- a/DevProxy.Plugins/Behavior/GenericRandomErrorPlugin.cs +++ b/DevProxy.Plugins/Behavior/GenericRandomErrorPlugin.cs @@ -1,388 +1,388 @@ -// 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 DevProxy.Abstractions.Plugins; -using DevProxy.Abstractions.Proxy; -using DevProxy.Abstractions.Proxy.Http; -using DevProxy.Abstractions.Utils; -using DevProxy.Plugins.Models; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using System.CommandLine.Parsing; -using System.CommandLine; -using System.Globalization; -using System.Net; -using System.Text.Json; -using System.Text.RegularExpressions; - -namespace DevProxy.Plugins.Behavior; - -enum GenericRandomErrorFailMode -{ - Throttled, - Random, - PassThru -} - -public sealed class GenericRandomErrorConfiguration -{ - public IEnumerable Errors { get; set; } = []; - public string ErrorsFile { get; set; } = "errors.json"; - public int Rate { get; set; } = 50; - public int RetryAfterInSeconds { get; set; } = 5; -} - -public sealed class GenericRandomErrorPlugin( - HttpClient httpClient, - ILogger logger, - ISet urlsToWatch, - IProxyConfiguration proxyConfiguration, - IConfigurationSection pluginConfigurationSection) : - BasePlugin( - httpClient, - logger, - urlsToWatch, - proxyConfiguration, - pluginConfigurationSection) -{ - private const string _rateOptionName = "--failure-rate"; - - private readonly Random _random = new(); - private GenericErrorResponsesLoader? _loader; - - public override string Name => nameof(GenericRandomErrorPlugin); - - public override async Task InitializeAsync(InitArgs e, CancellationToken cancellationToken) - { - ArgumentNullException.ThrowIfNull(e); - - await base.InitializeAsync(e, cancellationToken); - - Configuration.ErrorsFile = ProxyUtils.GetFullPath(Configuration.ErrorsFile, ProxyConfiguration.ConfigFile); - - _loader = ActivatorUtilities.CreateInstance(e.ServiceProvider, Configuration); - await _loader.InitFileWatcherAsync(cancellationToken); - - ValidateErrors(); - } - - public override Option[] GetOptions() - { - var _rateOption = new Option(_rateOptionName, "-f") - { - Description = "The percentage of chance that a request will fail", - HelpName = "failure-rate" - }; - _rateOption.Validators.Add((input) => - { - try - { - var value = input.GetValue(_rateOption); - if (value.HasValue && (value < 0 || value > 100)) - { - input.AddError($"{value} is not a valid failure rate. Specify a number between 0 and 100"); - } - } - catch (InvalidOperationException ex) - { - input.AddError(ex.Message); - } - }); - - return [_rateOption]; - } - - public override void OptionsLoaded(OptionsLoadedArgs e) - { - ArgumentNullException.ThrowIfNull(e); - - base.OptionsLoaded(e); - - var rate = e.ParseResult.GetValueOrDefault(_rateOptionName); - if (rate is not null) - { - Configuration.Rate = rate.Value; - } - } - - public override Task BeforeRequestAsync(ProxyRequestArgs e, CancellationToken cancellationToken) - { - Logger.LogTrace("{Method} called", nameof(BeforeRequestAsync)); - - ArgumentNullException.ThrowIfNull(e); - - if (!e.HasRequestUrlMatch(UrlsToWatch)) - { - Logger.LogRequest("URL not matched", MessageType.Skipped, new LoggingContext(e.ProxySession)); - return Task.CompletedTask; - } - if (e.ResponseState.HasBeenSet) - { - Logger.LogRequest("Response already set", MessageType.Skipped, new LoggingContext(e.ProxySession)); - return Task.CompletedTask; - } - - var failMode = ShouldFail(); - - if (failMode == GenericRandomErrorFailMode.PassThru && Configuration.Rate != 100) - { - Logger.LogRequest("Pass through", MessageType.Skipped, new LoggingContext(e.ProxySession)); - return Task.CompletedTask; - } - FailResponse(e); - - Logger.LogTrace("Left {Name}", nameof(BeforeRequestAsync)); - return Task.CompletedTask; - } - - // uses config to determine if a request should be failed - private GenericRandomErrorFailMode ShouldFail() => _random.Next(0, 100) < Configuration.Rate ? GenericRandomErrorFailMode.Random : GenericRandomErrorFailMode.PassThru; - - private void FailResponse(ProxyRequestArgs e) - { - var matchingResponse = GetMatchingErrorResponse(e.ProxySession.Request); - if (matchingResponse is not null && - matchingResponse.Responses is not null) - { - // pick a random error response for the current request - var error = matchingResponse.Responses.ElementAt(_random.Next(0, matchingResponse.Responses.Count())); - UpdateProxyResponse(e, error); - } - else - { - Logger.LogRequest("No matching error response found", MessageType.Skipped, new LoggingContext(e.ProxySession)); - } - } - - private static ThrottlingInfo ShouldThrottle(IHttpRequest request, string throttlingKey, int retryAfterInSeconds) - { - var throttleKeyForRequest = BuildThrottleKey(request); - return new(throttleKeyForRequest == throttlingKey ? retryAfterInSeconds : 0, "Retry-After"); - } - - private GenericErrorResponse? GetMatchingErrorResponse(IHttpRequest request) - { - if (Configuration.Errors is null || - !Configuration.Errors.Any()) - { - return null; - } - - var errorResponse = Configuration.Errors.FirstOrDefault(errorResponse => - { - if (errorResponse.Request is null) - { - return false; - } - - if (errorResponse.Responses is null) - { - return false; - } - - if (errorResponse.Request.Method is not null && - errorResponse.Request.Method != request.Method) - { - return false; - } - - if (string.Equals(errorResponse.Request.Url, request.Url, StringComparison.OrdinalIgnoreCase) && - HasMatchingBody(errorResponse, request)) - { - return true; - } - - // check if the URL contains a wildcard - // if it doesn't, it's not a match for the current request for sure - if (!errorResponse.Request.Url.Contains('*', StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - // turn mock URL with wildcard into a regex and match against the request URL - var errorResponseUrlRegex = Regex.Escape(errorResponse.Request.Url).Replace("\\*", ".*", StringComparison.OrdinalIgnoreCase); - return Regex.IsMatch(request.Url, $"^{errorResponseUrlRegex}$", RegexOptions.IgnoreCase) && - HasMatchingBody(errorResponse, request); - }); - - return errorResponse; - } - - private void UpdateProxyResponse(ProxyRequestArgs e, GenericErrorResponseResponse error) - { - var request = e.ProxySession.Request; - var headers = new List(); - if (error.Headers is not null) - { - headers.AddRange(error.Headers); - } - - // Retry-After can be sent with any status code (eg. 429, 503, 529), - // so resolve @dynamic regardless of the status code - if (error.Headers is not null) - { - var retryAfterHeader = error.Headers.FirstOrDefault(h => string.Equals(h.Name, "Retry-After", StringComparison.OrdinalIgnoreCase)); - if (retryAfterHeader?.Value is not null && retryAfterHeader.Value.StartsWith("@dynamic", StringComparison.OrdinalIgnoreCase)) - { - // Parse @dynamic or @dynamic=value syntax - var retryAfterInSeconds = Configuration.RetryAfterInSeconds; - if (retryAfterHeader.Value.StartsWith("@dynamic=", StringComparison.OrdinalIgnoreCase)) - { - var valueStr = retryAfterHeader.Value["@dynamic=".Length..]; - if (int.TryParse(valueStr, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedValue)) - { - if (parsedValue < 0) - { - Logger.LogWarning("Negative @dynamic value '{Value}' for Retry-After header is not allowed. Using default value {Default}.", valueStr, Configuration.RetryAfterInSeconds); - } - else - { - retryAfterInSeconds = parsedValue; - } - } - else - { - Logger.LogWarning("Invalid @dynamic value '{Value}' for Retry-After header. Using default value {Default}.", valueStr, Configuration.RetryAfterInSeconds); - } - } - - var retryAfterDate = DateTime.Now.AddSeconds(retryAfterInSeconds); - if (!e.GlobalData.TryGetValue(RetryAfterPlugin.ThrottledRequestsKey, out var value)) - { - value = new List(); - e.GlobalData.Add(RetryAfterPlugin.ThrottledRequestsKey, value); - } - var throttledRequests = value as List; - var throttleKey = BuildThrottleKey(request); - throttledRequests?.Add(new(throttleKey, (req, key) => ShouldThrottle(req, key, retryAfterInSeconds), retryAfterDate)); - // replace the header with the @dynamic value with the actual value - var h = headers.First(h => string.Equals(h.Name, "Retry-After", StringComparison.OrdinalIgnoreCase)); - _ = headers.Remove(h); - headers.Add(new("Retry-After", retryAfterInSeconds.ToString(CultureInfo.InvariantCulture))); - } - } - - // default the content type to application/json unless set in the error response - if (error.Body is not null && - !headers.Any(h => string.Equals(h.Name, "Content-Type", StringComparison.OrdinalIgnoreCase))) - { - headers.Add(new("Content-Type", "application/json")); - } - - var statusCode = (HttpStatusCode)(error.StatusCode ?? 400); - string body = ProxyUtils.SerializeBody(error.Body); - if (body.StartsWith('@')) - { - // we've got a mock body starting with @-token which means we're sending - // a response from a file on disk - // if we can read the file, we can immediately send the response and - // skip the rest of the logic in this method - var filePath = Path.Combine(Path.GetDirectoryName(Configuration.ErrorsFile) ?? "", ProxyUtils.ReplacePathTokens(body[1..])); - if (!File.Exists(filePath)) - { - Logger.LogError("File {FilePath} not found. Serving file path in the mock response", (string?)filePath); - e.ProxySession.Respond(body, statusCode, headers.Select(h => new HttpHeader(h.Name, h.Value))); - } - else - { - var bodyBytes = File.ReadAllBytes(filePath); - e.ProxySession.Respond(bodyBytes, statusCode, headers.Select(h => new HttpHeader(h.Name, h.Value))); - } - } - else - { - e.ProxySession.Respond(body, statusCode, headers.Select(h => new HttpHeader(h.Name, h.Value))); - } - e.ResponseState.HasBeenSet = true; - Logger.LogRequest($"{error.StatusCode} {statusCode}", MessageType.Chaos, new LoggingContext(e.ProxySession)); - } - - private void ValidateErrors() - { - Logger.LogDebug("Validating error responses"); - - if (Configuration.Errors is null || - !Configuration.Errors.Any()) - { - Logger.LogDebug("No error responses defined"); - return; - } - - var unmatchedErrorUrls = new List(); - - foreach (var error in Configuration.Errors) - { - if (error.Request is null) - { - Logger.LogDebug("Error response is missing a request"); - continue; - } - - if (string.IsNullOrEmpty(error.Request.Url)) - { - Logger.LogDebug("Error response is missing a URL"); - continue; - } - - if (!ProxyUtils.MatchesUrlToWatch(UrlsToWatch, error.Request.Url, true)) - { - unmatchedErrorUrls.Add(error.Request.Url); - } - } - - if (unmatchedErrorUrls.Count == 0) - { - Logger.LogDebug("All error response URLs are matched"); - return; - } - - var suggestedWildcards = ProxyUtils.GetWildcardPatterns(unmatchedErrorUrls.AsReadOnly()); - if (Logger.IsEnabled(LogLevel.Warning)) - { - Logger.LogWarning( - "The following URLs in {ErrorsFile} don't match any URL to watch: {UnmatchedMocks}. Add the following URLs to URLs to watch: {UrlsToWatch}", - Configuration.ErrorsFile, - string.Join(", ", unmatchedErrorUrls), - string.Join(", ", suggestedWildcards) - ); - } - } - - private static bool HasMatchingBody(GenericErrorResponse errorResponse, IHttpRequest request) - { - if (request.Method == "GET") - { - // GET requests don't have a body so we can't match on it - return true; - } - - if (errorResponse.Request?.BodyFragment is null) - { - // no body fragment to match on - return true; - } - - if (!request.HasBody || string.IsNullOrEmpty(request.BodyString)) - { - // error response defines a body fragment but the request has no body - // so it can't match - return false; - } - - return request.BodyString.Contains(errorResponse.Request.BodyFragment, StringComparison.OrdinalIgnoreCase); - } - - // throttle requests per host - private static string BuildThrottleKey(IHttpRequest r) => r.RequestUri.Host; - - protected override void Dispose(bool disposing) - { - if (disposing) - { - _loader?.Dispose(); - } - base.Dispose(disposing); - } -} +// 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 DevProxy.Abstractions.Plugins; +using DevProxy.Abstractions.Proxy; +using DevProxy.Abstractions.Proxy.Http; +using DevProxy.Abstractions.Utils; +using DevProxy.Plugins.Models; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System.CommandLine.Parsing; +using System.CommandLine; +using System.Globalization; +using System.Net; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace DevProxy.Plugins.Behavior; + +enum GenericRandomErrorFailMode +{ + Throttled, + Random, + PassThru +} + +public sealed class GenericRandomErrorConfiguration +{ + public IEnumerable Errors { get; set; } = []; + public string ErrorsFile { get; set; } = "errors.json"; + public int Rate { get; set; } = 50; + public int RetryAfterInSeconds { get; set; } = 5; +} + +public sealed class GenericRandomErrorPlugin( + HttpClient httpClient, + ILogger logger, + ISet urlsToWatch, + IProxyConfiguration proxyConfiguration, + IConfigurationSection pluginConfigurationSection) : + BasePlugin( + httpClient, + logger, + urlsToWatch, + proxyConfiguration, + pluginConfigurationSection) +{ + private const string _rateOptionName = "--failure-rate"; + + private readonly Random _random = new(); + private GenericErrorResponsesLoader? _loader; + + public override string Name => nameof(GenericRandomErrorPlugin); + + public override async Task InitializeAsync(InitArgs e, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(e); + + await base.InitializeAsync(e, cancellationToken); + + Configuration.ErrorsFile = ProxyUtils.GetFullPath(Configuration.ErrorsFile, ProxyConfiguration.ConfigFile); + + _loader = ActivatorUtilities.CreateInstance(e.ServiceProvider, Configuration); + await _loader.InitFileWatcherAsync(cancellationToken); + + ValidateErrors(); + } + + public override Option[] GetOptions() + { + var _rateOption = new Option(_rateOptionName, "-f") + { + Description = "The percentage of chance that a request will fail", + HelpName = "failure-rate" + }; + _rateOption.Validators.Add((input) => + { + try + { + var value = input.GetValue(_rateOption); + if (value.HasValue && (value < 0 || value > 100)) + { + input.AddError($"{value} is not a valid failure rate. Specify a number between 0 and 100"); + } + } + catch (InvalidOperationException ex) + { + input.AddError(ex.Message); + } + }); + + return [_rateOption]; + } + + public override void OptionsLoaded(OptionsLoadedArgs e) + { + ArgumentNullException.ThrowIfNull(e); + + base.OptionsLoaded(e); + + var rate = e.ParseResult.GetValueOrDefault(_rateOptionName); + if (rate is not null) + { + Configuration.Rate = rate.Value; + } + } + + public override Task BeforeRequestAsync(ProxyRequestArgs e, CancellationToken cancellationToken) + { + Logger.LogTrace("{Method} called", nameof(BeforeRequestAsync)); + + ArgumentNullException.ThrowIfNull(e); + + if (!e.HasRequestUrlMatch(UrlsToWatch)) + { + Logger.LogRequest("URL not matched", MessageType.Skipped, new LoggingContext(e.ProxySession)); + return Task.CompletedTask; + } + if (e.ResponseState.HasBeenSet) + { + Logger.LogRequest("Response already set", MessageType.Skipped, new LoggingContext(e.ProxySession)); + return Task.CompletedTask; + } + + var failMode = ShouldFail(); + + if (failMode == GenericRandomErrorFailMode.PassThru && Configuration.Rate != 100) + { + Logger.LogRequest("Pass through", MessageType.Skipped, new LoggingContext(e.ProxySession)); + return Task.CompletedTask; + } + FailResponse(e); + + Logger.LogTrace("Left {Name}", nameof(BeforeRequestAsync)); + return Task.CompletedTask; + } + + // uses config to determine if a request should be failed + private GenericRandomErrorFailMode ShouldFail() => _random.Next(0, 100) < Configuration.Rate ? GenericRandomErrorFailMode.Random : GenericRandomErrorFailMode.PassThru; + + private void FailResponse(ProxyRequestArgs e) + { + var matchingResponse = GetMatchingErrorResponse(e.ProxySession.Request); + if (matchingResponse is not null && + matchingResponse.Responses is not null) + { + // pick a random error response for the current request + var error = matchingResponse.Responses.ElementAt(_random.Next(0, matchingResponse.Responses.Count())); + UpdateProxyResponse(e, error); + } + else + { + Logger.LogRequest("No matching error response found", MessageType.Skipped, new LoggingContext(e.ProxySession)); + } + } + + private static ThrottlingInfo ShouldThrottle(IHttpRequest request, string throttlingKey, int retryAfterInSeconds) + { + var throttleKeyForRequest = BuildThrottleKey(request); + return new(throttleKeyForRequest == throttlingKey ? retryAfterInSeconds : 0, "Retry-After"); + } + + private GenericErrorResponse? GetMatchingErrorResponse(IHttpRequest request) + { + if (Configuration.Errors is null || + !Configuration.Errors.Any()) + { + return null; + } + + var errorResponse = Configuration.Errors.FirstOrDefault(errorResponse => + { + if (errorResponse.Request is null) + { + return false; + } + + if (errorResponse.Responses is null) + { + return false; + } + + if (errorResponse.Request.Method is not null && + errorResponse.Request.Method != request.Method) + { + return false; + } + + if (string.Equals(errorResponse.Request.Url, request.Url, StringComparison.OrdinalIgnoreCase) && + HasMatchingBody(errorResponse, request)) + { + return true; + } + + // check if the URL contains a wildcard + // if it doesn't, it's not a match for the current request for sure + if (!errorResponse.Request.Url.Contains('*', StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + // turn mock URL with wildcard into a regex and match against the request URL + var errorResponseUrlRegex = Regex.Escape(errorResponse.Request.Url).Replace("\\*", ".*", StringComparison.OrdinalIgnoreCase); + return Regex.IsMatch(request.Url, $"^{errorResponseUrlRegex}$", RegexOptions.IgnoreCase) && + HasMatchingBody(errorResponse, request); + }); + + return errorResponse; + } + + private void UpdateProxyResponse(ProxyRequestArgs e, GenericErrorResponseResponse error) + { + var request = e.ProxySession.Request; + var headers = new List(); + if (error.Headers is not null) + { + headers.AddRange(error.Headers); + } + + // Retry-After can be sent with any status code (eg. 429, 503, 529), + // so resolve @dynamic regardless of the status code + if (error.Headers is not null) + { + var retryAfterHeader = error.Headers.FirstOrDefault(h => string.Equals(h.Name, "Retry-After", StringComparison.OrdinalIgnoreCase)); + if (retryAfterHeader?.Value is not null && retryAfterHeader.Value.StartsWith("@dynamic", StringComparison.OrdinalIgnoreCase)) + { + // Parse @dynamic or @dynamic=value syntax + var retryAfterInSeconds = Configuration.RetryAfterInSeconds; + if (retryAfterHeader.Value.StartsWith("@dynamic=", StringComparison.OrdinalIgnoreCase)) + { + var valueStr = retryAfterHeader.Value["@dynamic=".Length..]; + if (int.TryParse(valueStr, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedValue)) + { + if (parsedValue < 0) + { + Logger.LogWarning("Negative @dynamic value '{Value}' for Retry-After header is not allowed. Using default value {Default}.", valueStr, Configuration.RetryAfterInSeconds); + } + else + { + retryAfterInSeconds = parsedValue; + } + } + else + { + Logger.LogWarning("Invalid @dynamic value '{Value}' for Retry-After header. Using default value {Default}.", valueStr, Configuration.RetryAfterInSeconds); + } + } + + var retryAfterDate = DateTime.Now.AddSeconds(retryAfterInSeconds); + if (!e.GlobalData.TryGetValue(RetryAfterPlugin.ThrottledRequestsKey, out var value)) + { + value = new List(); + e.GlobalData.Add(RetryAfterPlugin.ThrottledRequestsKey, value); + } + var throttledRequests = value as List; + var throttleKey = BuildThrottleKey(request); + throttledRequests?.Add(new(throttleKey, (req, key) => ShouldThrottle(req, key, retryAfterInSeconds), retryAfterDate)); + // replace the header with the @dynamic value with the actual value + var h = headers.First(h => string.Equals(h.Name, "Retry-After", StringComparison.OrdinalIgnoreCase)); + _ = headers.Remove(h); + headers.Add(new("Retry-After", retryAfterInSeconds.ToString(CultureInfo.InvariantCulture))); + } + } + + // default the content type to application/json unless set in the error response + if (error.Body is not null && + !headers.Any(h => string.Equals(h.Name, "Content-Type", StringComparison.OrdinalIgnoreCase))) + { + headers.Add(new("Content-Type", "application/json")); + } + + var statusCode = (HttpStatusCode)(error.StatusCode ?? 400); + string body = ProxyUtils.SerializeBody(error.Body); + if (body.StartsWith('@', StringComparison.Ordinal)) + { + // we've got a mock body starting with @-token which means we're sending + // a response from a file on disk + // if we can read the file, we can immediately send the response and + // skip the rest of the logic in this method + var filePath = Path.Combine(Path.GetDirectoryName(Configuration.ErrorsFile) ?? "", ProxyUtils.ReplacePathTokens(body[1..])); + if (!File.Exists(filePath)) + { + Logger.LogError("File {FilePath} not found. Serving file path in the mock response", (string?)filePath); + e.ProxySession.Respond(body, statusCode, headers.Select(h => new HttpHeader(h.Name, h.Value))); + } + else + { + var bodyBytes = File.ReadAllBytes(filePath); + e.ProxySession.Respond(bodyBytes, statusCode, headers.Select(h => new HttpHeader(h.Name, h.Value))); + } + } + else + { + e.ProxySession.Respond(body, statusCode, headers.Select(h => new HttpHeader(h.Name, h.Value))); + } + e.ResponseState.HasBeenSet = true; + Logger.LogRequest($"{error.StatusCode} {statusCode}", MessageType.Chaos, new LoggingContext(e.ProxySession)); + } + + private void ValidateErrors() + { + Logger.LogDebug("Validating error responses"); + + if (Configuration.Errors is null || + !Configuration.Errors.Any()) + { + Logger.LogDebug("No error responses defined"); + return; + } + + var unmatchedErrorUrls = new List(); + + foreach (var error in Configuration.Errors) + { + if (error.Request is null) + { + Logger.LogDebug("Error response is missing a request"); + continue; + } + + if (string.IsNullOrEmpty(error.Request.Url)) + { + Logger.LogDebug("Error response is missing a URL"); + continue; + } + + if (!ProxyUtils.MatchesUrlToWatch(UrlsToWatch, error.Request.Url, true)) + { + unmatchedErrorUrls.Add(error.Request.Url); + } + } + + if (unmatchedErrorUrls.Count == 0) + { + Logger.LogDebug("All error response URLs are matched"); + return; + } + + var suggestedWildcards = ProxyUtils.GetWildcardPatterns(unmatchedErrorUrls.AsReadOnly()); + if (Logger.IsEnabled(LogLevel.Warning)) + { + Logger.LogWarning( + "The following URLs in {ErrorsFile} don't match any URL to watch: {UnmatchedMocks}. Add the following URLs to URLs to watch: {UrlsToWatch}", + Configuration.ErrorsFile, + string.Join(", ", unmatchedErrorUrls), + string.Join(", ", suggestedWildcards) + ); + } + } + + private static bool HasMatchingBody(GenericErrorResponse errorResponse, IHttpRequest request) + { + if (request.Method == "GET") + { + // GET requests don't have a body so we can't match on it + return true; + } + + if (errorResponse.Request?.BodyFragment is null) + { + // no body fragment to match on + return true; + } + + if (!request.HasBody || string.IsNullOrEmpty(request.BodyString)) + { + // error response defines a body fragment but the request has no body + // so it can't match + return false; + } + + return request.BodyString.Contains(errorResponse.Request.BodyFragment, StringComparison.OrdinalIgnoreCase); + } + + // throttle requests per host + private static string BuildThrottleKey(IHttpRequest r) => r.RequestUri.Host; + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _loader?.Dispose(); + } + base.Dispose(disposing); + } +} diff --git a/DevProxy.Plugins/DevProxy.Plugins.csproj b/DevProxy.Plugins/DevProxy.Plugins.csproj index 87ede89b9..6c902ee5f 100644 --- a/DevProxy.Plugins/DevProxy.Plugins.csproj +++ b/DevProxy.Plugins/DevProxy.Plugins.csproj @@ -1,6 +1,6 @@  - net10.0 + net11.0 DevProxy.Plugins enable enable @@ -21,15 +21,15 @@ false runtime - + false runtime - + false runtime - + false runtime diff --git a/DevProxy.Plugins/Generation/ApiCenterOnboardingPlugin.cs b/DevProxy.Plugins/Generation/ApiCenterOnboardingPlugin.cs index ed6dbcbdc..f9e7f27a8 100644 --- a/DevProxy.Plugins/Generation/ApiCenterOnboardingPlugin.cs +++ b/DevProxy.Plugins/Generation/ApiCenterOnboardingPlugin.cs @@ -1,414 +1,414 @@ -// 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 DevProxy.Abstractions.Plugins; -using DevProxy.Abstractions.Proxy; -using DevProxy.Abstractions.Utils; -using DevProxy.Plugins.ApiCenter; -using DevProxy.Plugins.Models.ApiCenter; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.OpenApi; -using System.Diagnostics; - -namespace DevProxy.Plugins.Generation; - -public sealed class ApiCenterOnboardingPluginConfiguration -{ - public bool CreateApicEntryForNewApis { get; set; } = true; - public string ResourceGroupName { get; set; } = ""; - public string ServiceName { get; set; } = ""; - public string SubscriptionId { get; set; } = ""; - public string WorkspaceName { get; set; } = "default"; -} - -public sealed class ApiCenterOnboardingPlugin( - HttpClient httpClient, - ILogger logger, - ISet urlsToWatch, - IProxyConfiguration proxyConfiguration, - IConfigurationSection pluginConfigurationSection) : - BaseReportingPlugin( - httpClient, - logger, - urlsToWatch, - proxyConfiguration, - pluginConfigurationSection) -{ - private ApiCenterClient? _apiCenterClient; - private Api[]? _apis; - private Dictionary? _apiDefinitionsByUrl; - - public override string Name => nameof(ApiCenterOnboardingPlugin); - - public override async Task InitializeAsync(InitArgs e, CancellationToken cancellationToken) - { - ArgumentNullException.ThrowIfNull(e); - - await base.InitializeAsync(e, cancellationToken); - - try - { - _apiCenterClient = ActivatorUtilities.CreateInstance(e.ServiceProvider, - new ApiCenterClientConfiguration - { - SubscriptionId = Configuration.SubscriptionId, - ResourceGroupName = Configuration.ResourceGroupName, - ServiceName = Configuration.ServiceName, - WorkspaceName = Configuration.WorkspaceName - } - ); - } - catch (Exception ex) - { - Logger.LogError(ex, "Failed to create API Center client. The {Plugin} will not be used.", Name); - Enabled = false; - return; - } - - Logger.LogInformation("Plugin {Plugin} connecting to Azure...", Name); - try - { - _ = await _apiCenterClient.GetAccessTokenAsync(cancellationToken); - } - catch (Exception ex) - { - Logger.LogError(ex, "Failed to authenticate with Azure. The {Plugin} will not be used.", Name); - Enabled = false; - return; - } - Logger.LogDebug("Plugin {Plugin} auth confirmed...", Name); - } - - public override async Task AfterRecordingStopAsync(RecordingArgs e, CancellationToken cancellationToken) - { - Logger.LogTrace("{Method} called", nameof(AfterRecordingStopAsync)); - - ArgumentNullException.ThrowIfNull(e); - - if (!e.RequestLogs.Any()) - { - Logger.LogDebug("No requests to process"); - return; - } - - Logger.LogInformation("Checking if recorded API requests belong to APIs in API Center..."); - - Debug.Assert(_apiCenterClient is not null); - - _apis ??= await _apiCenterClient.GetApisAsync(); - - if (_apis == null || _apis.Length == 0) - { - Logger.LogInformation("No APIs found in API Center"); - return; - } - - _apiDefinitionsByUrl ??= await _apis.GetApiDefinitionsByUrlAsync(_apiCenterClient, Logger, cancellationToken); - - var newApis = new List<(string method, string url)>(); - var interceptedRequests = e.RequestLogs - .Where(l => l.MessageType == MessageType.InterceptedRequest) - .Select(request => - { - var methodAndUrl = request.Message.Split(' '); - return (method: methodAndUrl[0], url: methodAndUrl[1]); - }) - .Where(r => !r.method.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase) && - ProxyUtils.MatchesUrlToWatch(UrlsToWatch, r.url)) - .Distinct(); - - var existingApis = new List(); - - foreach (var request in interceptedRequests) - { - cancellationToken.ThrowIfCancellationRequested(); - - var (method, url) = request; - - Logger.LogDebug("Processing request {Method} {Url}...", method, url); - - var apiDefinition = _apiDefinitionsByUrl.FirstOrDefault(x => - url.StartsWith(x.Key, StringComparison.OrdinalIgnoreCase)).Value; - if (apiDefinition is null || - apiDefinition.Id is null) - { - Logger.LogDebug("No matching API definition not found for {Url}. Adding new API...", url); - newApis.Add((method, url)); - continue; - } - - await apiDefinition.LoadOpenApiDefinitionAsync(_apiCenterClient, Logger, cancellationToken); - - if (apiDefinition.Definition is null) - { - Logger.LogDebug("API definition not found for {Url} so nothing to compare to. Adding new API...", url); - newApis.Add(new(method, url)); - continue; - } - - var pathItem = apiDefinition.Definition.FindMatchingPathItem(url, Logger); - if (pathItem is null) - { - Logger.LogDebug("No matching path found for {Url}. Adding new API...", url); - newApis.Add(new(method, url)); - continue; - } - - var operation = pathItem.Value.Value.Operations?.FirstOrDefault(x => - x.Key.Method.Equals(method, StringComparison.OrdinalIgnoreCase)); - if (operation is null || operation.Value.Value is null) - { - Logger.LogDebug("No matching operation found for {Method} {Url}. Adding new API...", method, url); - newApis.Add(new(method, url)); - continue; - } - - existingApis.Add(new() - { - MethodAndUrl = $"{method} {url}", - ApiDefinitionId = apiDefinition.Id, - OperationId = operation.Value.Value.OperationId ?? "" - }); - } - - if (newApis.Count == 0) - { - Logger.LogInformation("No new APIs found"); - StoreReport(new ApiCenterOnboardingPluginReport - { - ExistingApis = [.. existingApis], - NewApis = [] - }, e); - return; - } - - // dedupe newApis - newApis = [.. newApis.Distinct()]; - - StoreReport(new ApiCenterOnboardingPluginReport - { - ExistingApis = [.. existingApis], - NewApis = [.. newApis.Select(a => new ApiCenterOnboardingPluginReportNewApiInfo - { - Method = a.method, - Url = a.url - })] - }, e); - - var apisPerSchemeAndHost = newApis.GroupBy(x => - { - var u = new Uri(x.url); - return u.GetLeftPart(UriPartial.Authority); - }); - - var newApisMessageChunks = new List(["New APIs that aren't registered in Azure API Center:", ""]); - foreach (var apiPerHost in apisPerSchemeAndHost) - { - newApisMessageChunks.Add($"{apiPerHost.Key}:"); - newApisMessageChunks.AddRange(apiPerHost.Select(a => $" {a.method} {a.url}")); - } - - if (Logger.IsEnabled(LogLevel.Information)) - { - Logger.LogInformation("{NewApis}", string.Join(Environment.NewLine, newApisMessageChunks)); - } - - if (!Configuration.CreateApicEntryForNewApis) - { - return; - } - - var generatedOpenApiSpecs = e.GlobalData.TryGetValue(OpenApiSpecGeneratorPlugin.GeneratedOpenApiSpecsKey, out var specs) ? specs as Dictionary : []; - await CreateApisInApiCenterAsync(apisPerSchemeAndHost, generatedOpenApiSpecs!, cancellationToken); - - Logger.LogTrace("Left {Name}", nameof(AfterRecordingStopAsync)); - } - - async Task CreateApisInApiCenterAsync( - IEnumerable> apisPerHost, - Dictionary generatedOpenApiSpecs, - CancellationToken cancellationToken) - { - Logger.LogInformation("Creating new API entries in API Center..."); - - foreach (var apiPerHost in apisPerHost) - { - var schemeAndHost = apiPerHost.Key; - - var api = await CreateApiAsync(schemeAndHost, apiPerHost, cancellationToken); - if (api is null) - { - continue; - } - - Debug.Assert(api.Id is not null); - - if (!generatedOpenApiSpecs.TryGetValue(schemeAndHost, out var openApiSpecFilePath)) - { - Logger.LogDebug("No OpenAPI spec found for {Host}", schemeAndHost); - continue; - } - - var apiVersion = await CreateApiVersionAsync(api.Id, cancellationToken); - if (apiVersion is null) - { - continue; - } - - Debug.Assert(apiVersion.Id is not null); - - var apiDefinition = await CreateApiDefinitionAsync(apiVersion.Id, cancellationToken); - if (apiDefinition is null) - { - continue; - } - - Debug.Assert(apiDefinition.Id is not null); - - await ImportApiDefinitionAsync(apiDefinition.Id, openApiSpecFilePath, cancellationToken); - } - } - - async Task CreateApiAsync(string schemeAndHost, IEnumerable<(string method, string url)> apiRequests, CancellationToken cancellationToken) - { - Debug.Assert(_apiCenterClient is not null); - - // trim to 50 chars which is max length for API name - var apiName = $"new-{schemeAndHost - .Replace(".", "-", StringComparison.OrdinalIgnoreCase) - .Replace("http://", "", StringComparison.OrdinalIgnoreCase) - .Replace("https://", "", StringComparison.OrdinalIgnoreCase)}-{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}".MaxLength(50); - Logger.LogInformation(" Creating API {ApiName} for {Host}...", apiName, schemeAndHost); - - var title = $"New APIs: {schemeAndHost}"; - var description = new List(["New APIs discovered by Dev Proxy", ""]); - description.AddRange([.. apiRequests.Select(a => $" {a.method} {a.url}")]); - var api = new Api - { - Properties = new() - { - Title = title, - Description = string.Join(Environment.NewLine, description), - Kind = ApiKind.REST - } - }; - - var newApi = await _apiCenterClient.PutApiAsync(api, apiName, cancellationToken); - if (newApi is not null) - { - Logger.LogDebug("API created successfully"); - } - else - { - Logger.LogError("Failed to create API {ApiName} for {Host}", apiName, schemeAndHost); - } - - return newApi; - } - - async Task CreateApiVersionAsync(string apiId, CancellationToken cancellationToken) - { - Debug.Assert(_apiCenterClient is not null); - - Logger.LogDebug(" Creating API version for {Api}...", apiId); - - var apiVersion = new ApiVersion - { - Properties = new() - { - Title = "v1.0", - LifecycleStage = ApiLifecycleStage.Production - } - }; - - var newApiVersion = await _apiCenterClient.PutVersionAsync(apiVersion, apiId, "v1-0", cancellationToken); - if (newApiVersion is not null) - { - Logger.LogDebug("API version created successfully"); - } - else - { - if (Logger.IsEnabled(LogLevel.Error)) - { - Logger.LogError("Failed to create API version for {Api}", apiId[apiId.LastIndexOf('/')..]); - } - } - - return newApiVersion; - } - - async Task CreateApiDefinitionAsync(string apiVersionId, CancellationToken cancellationToken) - { - Debug.Assert(_apiCenterClient is not null); - - Logger.LogDebug(" Creating API definition for {Api}...", apiVersionId); - - var apiDefinition = new ApiDefinition - { - Properties = new() - { - Title = "OpenAPI" - } - }; - var newApiDefinition = await _apiCenterClient.PutDefinitionAsync(apiDefinition, apiVersionId, "openapi", cancellationToken); - if (newApiDefinition is not null) - { - Logger.LogDebug("API definition created successfully"); - } - else - { - Logger.LogError("Failed to create API definition for {ApiVersion}", apiVersionId); - } - - return newApiDefinition; - } - - async Task ImportApiDefinitionAsync(string apiDefinitionId, string openApiSpecFilePath, CancellationToken cancellationToken) - { - Debug.Assert(_apiCenterClient is not null); - - Logger.LogDebug(" Importing API definition for {Api}...", apiDefinitionId); - - var openApiSpec = await File.ReadAllTextAsync(openApiSpecFilePath, cancellationToken); - var apiSpecImport = new ApiSpecImport - { - Format = ApiSpecImportResultFormat.Inline, - Value = openApiSpec, - Specification = new() - { - Name = "openapi", - Version = "3.0.1" - } - }; - var res = await _apiCenterClient.PostImportSpecificationAsync(apiSpecImport, apiDefinitionId, cancellationToken); - if (res.IsSuccessStatusCode) - { - Logger.LogDebug("API definition imported successfully"); - } - else - { - var resContent = res.ReasonPhrase; - try - { - resContent = await res.Content.ReadAsStringAsync(cancellationToken); - } - catch - { - } - - Logger.LogError("Failed to import API definition for {ApiDefinition}. Status: {Status}, reason: {Reason}", apiDefinitionId, res.StatusCode, resContent); - } - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - _apiCenterClient?.Dispose(); - } - base.Dispose(disposing); - } -} +// 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 DevProxy.Abstractions.Plugins; +using DevProxy.Abstractions.Proxy; +using DevProxy.Abstractions.Utils; +using DevProxy.Plugins.ApiCenter; +using DevProxy.Plugins.Models.ApiCenter; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.OpenApi; +using System.Diagnostics; + +namespace DevProxy.Plugins.Generation; + +public sealed class ApiCenterOnboardingPluginConfiguration +{ + public bool CreateApicEntryForNewApis { get; set; } = true; + public string ResourceGroupName { get; set; } = ""; + public string ServiceName { get; set; } = ""; + public string SubscriptionId { get; set; } = ""; + public string WorkspaceName { get; set; } = "default"; +} + +public sealed class ApiCenterOnboardingPlugin( + HttpClient httpClient, + ILogger logger, + ISet urlsToWatch, + IProxyConfiguration proxyConfiguration, + IConfigurationSection pluginConfigurationSection) : + BaseReportingPlugin( + httpClient, + logger, + urlsToWatch, + proxyConfiguration, + pluginConfigurationSection) +{ + private ApiCenterClient? _apiCenterClient; + private Api[]? _apis; + private Dictionary? _apiDefinitionsByUrl; + + public override string Name => nameof(ApiCenterOnboardingPlugin); + + public override async Task InitializeAsync(InitArgs e, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(e); + + await base.InitializeAsync(e, cancellationToken); + + try + { + _apiCenterClient = ActivatorUtilities.CreateInstance(e.ServiceProvider, + new ApiCenterClientConfiguration + { + SubscriptionId = Configuration.SubscriptionId, + ResourceGroupName = Configuration.ResourceGroupName, + ServiceName = Configuration.ServiceName, + WorkspaceName = Configuration.WorkspaceName + } + ); + } + catch (Exception ex) + { + Logger.LogError(ex, "Failed to create API Center client. The {Plugin} will not be used.", Name); + Enabled = false; + return; + } + + Logger.LogInformation("Plugin {Plugin} connecting to Azure...", Name); + try + { + _ = await _apiCenterClient.GetAccessTokenAsync(cancellationToken); + } + catch (Exception ex) + { + Logger.LogError(ex, "Failed to authenticate with Azure. The {Plugin} will not be used.", Name); + Enabled = false; + return; + } + Logger.LogDebug("Plugin {Plugin} auth confirmed...", Name); + } + + public override async Task AfterRecordingStopAsync(RecordingArgs e, CancellationToken cancellationToken) + { + Logger.LogTrace("{Method} called", nameof(AfterRecordingStopAsync)); + + ArgumentNullException.ThrowIfNull(e); + + if (!e.RequestLogs.Any()) + { + Logger.LogDebug("No requests to process"); + return; + } + + Logger.LogInformation("Checking if recorded API requests belong to APIs in API Center..."); + + Debug.Assert(_apiCenterClient is not null); + + _apis ??= await _apiCenterClient.GetApisAsync(); + + if (_apis == null || _apis.Length == 0) + { + Logger.LogInformation("No APIs found in API Center"); + return; + } + + _apiDefinitionsByUrl ??= await _apis.GetApiDefinitionsByUrlAsync(_apiCenterClient, Logger, cancellationToken); + + var newApis = new List<(string method, string url)>(); + var interceptedRequests = e.RequestLogs + .Where(l => l.MessageType == MessageType.InterceptedRequest) + .Select(request => + { + var methodAndUrl = request.Message.Split(' '); + return (method: methodAndUrl[0], url: methodAndUrl[1]); + }) + .Where(r => !r.method.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase) && + ProxyUtils.MatchesUrlToWatch(UrlsToWatch, r.url)) + .Distinct(); + + var existingApis = new List(); + + foreach (var request in interceptedRequests) + { + cancellationToken.ThrowIfCancellationRequested(); + + var (method, url) = request; + + Logger.LogDebug("Processing request {Method} {Url}...", method, url); + + var apiDefinition = _apiDefinitionsByUrl.FirstOrDefault(x => + url.StartsWith(x.Key, StringComparison.OrdinalIgnoreCase)).Value; + if (apiDefinition is null || + apiDefinition.Id is null) + { + Logger.LogDebug("No matching API definition not found for {Url}. Adding new API...", url); + newApis.Add((method, url)); + continue; + } + + await apiDefinition.LoadOpenApiDefinitionAsync(_apiCenterClient, Logger, cancellationToken); + + if (apiDefinition.Definition is null) + { + Logger.LogDebug("API definition not found for {Url} so nothing to compare to. Adding new API...", url); + newApis.Add(new(method, url)); + continue; + } + + var pathItem = apiDefinition.Definition.FindMatchingPathItem(url, Logger); + if (pathItem is null) + { + Logger.LogDebug("No matching path found for {Url}. Adding new API...", url); + newApis.Add(new(method, url)); + continue; + } + + var operation = pathItem.Value.Value.Operations?.FirstOrDefault(x => + x.Key.Method.Equals(method, StringComparison.OrdinalIgnoreCase)); + if (operation is null || operation.Value.Value is null) + { + Logger.LogDebug("No matching operation found for {Method} {Url}. Adding new API...", method, url); + newApis.Add(new(method, url)); + continue; + } + + existingApis.Add(new() + { + MethodAndUrl = $"{method} {url}", + ApiDefinitionId = apiDefinition.Id, + OperationId = operation.Value.Value.OperationId ?? "" + }); + } + + if (newApis.Count == 0) + { + Logger.LogInformation("No new APIs found"); + StoreReport(new ApiCenterOnboardingPluginReport + { + ExistingApis = [.. existingApis], + NewApis = [] + }, e); + return; + } + + // dedupe newApis + newApis = [.. newApis.Distinct()]; + + StoreReport(new ApiCenterOnboardingPluginReport + { + ExistingApis = [.. existingApis], + NewApis = [.. newApis.Select(a => new ApiCenterOnboardingPluginReportNewApiInfo + { + Method = a.method, + Url = a.url + })] + }, e); + + var apisPerSchemeAndHost = newApis.GroupBy(x => + { + var u = new Uri(x.url); + return u.GetLeftPart(UriPartial.Authority); + }); + + var newApisMessageChunks = new List(["New APIs that aren't registered in Azure API Center:", ""]); + foreach (var apiPerHost in apisPerSchemeAndHost) + { + newApisMessageChunks.Add($"{apiPerHost.Key}:"); + newApisMessageChunks.AddRange(apiPerHost.Select(a => $" {a.method} {a.url}")); + } + + if (Logger.IsEnabled(LogLevel.Information)) + { + Logger.LogInformation("{NewApis}", string.Join(Environment.NewLine, newApisMessageChunks)); + } + + if (!Configuration.CreateApicEntryForNewApis) + { + return; + } + + var generatedOpenApiSpecs = e.GlobalData.TryGetValue(OpenApiSpecGeneratorPlugin.GeneratedOpenApiSpecsKey, out var specs) ? specs as Dictionary : []; + await CreateApisInApiCenterAsync(apisPerSchemeAndHost, generatedOpenApiSpecs!, cancellationToken); + + Logger.LogTrace("Left {Name}", nameof(AfterRecordingStopAsync)); + } + + async Task CreateApisInApiCenterAsync( + IEnumerable> apisPerHost, + Dictionary generatedOpenApiSpecs, + CancellationToken cancellationToken) + { + Logger.LogInformation("Creating new API entries in API Center..."); + + foreach (var apiPerHost in apisPerHost) + { + var schemeAndHost = apiPerHost.Key; + + var api = await CreateApiAsync(schemeAndHost, apiPerHost, cancellationToken); + if (api is null) + { + continue; + } + + Debug.Assert(api.Id is not null); + + if (!generatedOpenApiSpecs.TryGetValue(schemeAndHost, out var openApiSpecFilePath)) + { + Logger.LogDebug("No OpenAPI spec found for {Host}", schemeAndHost); + continue; + } + + var apiVersion = await CreateApiVersionAsync(api.Id, cancellationToken); + if (apiVersion is null) + { + continue; + } + + Debug.Assert(apiVersion.Id is not null); + + var apiDefinition = await CreateApiDefinitionAsync(apiVersion.Id, cancellationToken); + if (apiDefinition is null) + { + continue; + } + + Debug.Assert(apiDefinition.Id is not null); + + await ImportApiDefinitionAsync(apiDefinition.Id, openApiSpecFilePath, cancellationToken); + } + } + + async Task CreateApiAsync(string schemeAndHost, IEnumerable<(string method, string url)> apiRequests, CancellationToken cancellationToken) + { + Debug.Assert(_apiCenterClient is not null); + + // trim to 50 chars which is max length for API name + var apiName = $"new-{schemeAndHost + .Replace(".", "-", StringComparison.OrdinalIgnoreCase) + .Replace("http://", "", StringComparison.OrdinalIgnoreCase) + .Replace("https://", "", StringComparison.OrdinalIgnoreCase)}-{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}".MaxLength(50); + Logger.LogInformation(" Creating API {ApiName} for {Host}...", apiName, schemeAndHost); + + var title = $"New APIs: {schemeAndHost}"; + var description = new List(["New APIs discovered by Dev Proxy", ""]); + description.AddRange([.. apiRequests.Select(a => $" {a.method} {a.url}")]); + var api = new Api + { + Properties = new() + { + Title = title, + Description = string.Join(Environment.NewLine, description), + Kind = ApiKind.REST + } + }; + + var newApi = await _apiCenterClient.PutApiAsync(api, apiName, cancellationToken); + if (newApi is not null) + { + Logger.LogDebug("API created successfully"); + } + else + { + Logger.LogError("Failed to create API {ApiName} for {Host}", apiName, schemeAndHost); + } + + return newApi; + } + + async Task CreateApiVersionAsync(string apiId, CancellationToken cancellationToken) + { + Debug.Assert(_apiCenterClient is not null); + + Logger.LogDebug(" Creating API version for {Api}...", apiId); + + var apiVersion = new ApiVersion + { + Properties = new() + { + Title = "v1.0", + LifecycleStage = ApiLifecycleStage.Production + } + }; + + var newApiVersion = await _apiCenterClient.PutVersionAsync(apiVersion, apiId, "v1-0", cancellationToken); + if (newApiVersion is not null) + { + Logger.LogDebug("API version created successfully"); + } + else + { + if (Logger.IsEnabled(LogLevel.Error)) + { + Logger.LogError("Failed to create API version for {Api}", apiId[apiId.LastIndexOf('/', StringComparison.Ordinal)..]); + } + } + + return newApiVersion; + } + + async Task CreateApiDefinitionAsync(string apiVersionId, CancellationToken cancellationToken) + { + Debug.Assert(_apiCenterClient is not null); + + Logger.LogDebug(" Creating API definition for {Api}...", apiVersionId); + + var apiDefinition = new ApiDefinition + { + Properties = new() + { + Title = "OpenAPI" + } + }; + var newApiDefinition = await _apiCenterClient.PutDefinitionAsync(apiDefinition, apiVersionId, "openapi", cancellationToken); + if (newApiDefinition is not null) + { + Logger.LogDebug("API definition created successfully"); + } + else + { + Logger.LogError("Failed to create API definition for {ApiVersion}", apiVersionId); + } + + return newApiDefinition; + } + + async Task ImportApiDefinitionAsync(string apiDefinitionId, string openApiSpecFilePath, CancellationToken cancellationToken) + { + Debug.Assert(_apiCenterClient is not null); + + Logger.LogDebug(" Importing API definition for {Api}...", apiDefinitionId); + + var openApiSpec = await File.ReadAllTextAsync(openApiSpecFilePath, cancellationToken); + var apiSpecImport = new ApiSpecImport + { + Format = ApiSpecImportResultFormat.Inline, + Value = openApiSpec, + Specification = new() + { + Name = "openapi", + Version = "3.0.1" + } + }; + var res = await _apiCenterClient.PostImportSpecificationAsync(apiSpecImport, apiDefinitionId, cancellationToken); + if (res.IsSuccessStatusCode) + { + Logger.LogDebug("API definition imported successfully"); + } + else + { + var resContent = res.ReasonPhrase; + try + { + resContent = await res.Content.ReadAsStringAsync(cancellationToken); + } + catch + { + } + + Logger.LogError("Failed to import API definition for {ApiDefinition}. Status: {Status}, reason: {Reason}", apiDefinitionId, res.StatusCode, resContent); + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _apiCenterClient?.Dispose(); + } + base.Dispose(disposing); + } +} diff --git a/DevProxy.Plugins/Generation/OpenApiSpecGeneratorPlugin.cs b/DevProxy.Plugins/Generation/OpenApiSpecGeneratorPlugin.cs index e65bc5786..eb84da6c0 100644 --- a/DevProxy.Plugins/Generation/OpenApiSpecGeneratorPlugin.cs +++ b/DevProxy.Plugins/Generation/OpenApiSpecGeneratorPlugin.cs @@ -1,841 +1,841 @@ -// 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 DevProxy.Abstractions.LanguageModel; -using DevProxy.Abstractions.Plugins; -using DevProxy.Abstractions.Proxy; -using DevProxy.Abstractions.Proxy.Http; -using DevProxy.Abstractions.Utils; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using Microsoft.OpenApi; -using System.Text.Json.Nodes; -using System.Collections.Specialized; -using System.Globalization; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Web; - -namespace DevProxy.Plugins.Generation; - -sealed class GeneratedByOpenApiExtension : IOpenApiExtension -{ - public void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) - { - writer.WriteStartObject(); - writer.WriteProperty("toolName", "Dev Proxy"); - writer.WriteProperty("toolVersion", ProxyUtils.ProductVersion); - writer.WriteEndObject(); - } -} - -[JsonConverter(typeof(JsonStringEnumConverter))] -public enum SpecVersion -{ -#pragma warning disable CA1707 - v2_0, - v3_0, - v3_1, - v3_2 -#pragma warning restore CA1707 -} - -[JsonConverter(typeof(JsonStringEnumConverter))] -public enum SpecFormat -{ - Json, - Yaml -} - -public sealed class OpenApiSpecGeneratorPluginConfiguration -{ - public bool IncludeOptionsRequests { get; set; } - public SpecFormat SpecFormat { get; set; } = SpecFormat.Json; - public SpecVersion SpecVersion { get; set; } = SpecVersion.v3_0; - public bool IgnoreResponseTypes { get; set; } - public IEnumerable IncludeParameters { get; set; } = []; -} - -public sealed class OpenApiSpecGeneratorPlugin( - HttpClient httpClient, - ILogger logger, - ISet urlsToWatch, - ILanguageModelClient languageModelClient, - IProxyConfiguration proxyConfiguration, - IConfigurationSection pluginConfigurationSection) : - BaseReportingPlugin( - httpClient, - logger, - urlsToWatch, - proxyConfiguration, - pluginConfigurationSection) -{ - public static readonly string GeneratedOpenApiSpecsKey = "GeneratedOpenApiSpecs"; - - public override string Name => nameof(OpenApiSpecGeneratorPlugin); - - public override async Task AfterRecordingStopAsync(RecordingArgs e, CancellationToken cancellationToken) - { - Logger.LogTrace("{Method} called", nameof(AfterRecordingStopAsync)); - - ArgumentNullException.ThrowIfNull(e); - - if (!e.RequestLogs.Any()) - { - Logger.LogDebug("No requests to process"); - return; - } - - Logger.LogInformation("Creating OpenAPI spec from recorded requests..."); - - var openApiDocs = new List(); - - foreach (var request in e.RequestLogs) - { - cancellationToken.ThrowIfCancellationRequested(); - - if (request.MessageType != MessageType.InterceptedResponse || - request.Context is null || - request.Context.Session is null || - !ProxyUtils.MatchesUrlToWatch(UrlsToWatch, request.Context.Session.Request.RequestUri.AbsoluteUri)) - { - continue; - } - - if (!Configuration.IncludeOptionsRequests && - string.Equals(request.Context.Session.Request.Method, "OPTIONS", StringComparison.OrdinalIgnoreCase)) - { - Logger.LogDebug("Skipping OPTIONS request {Url}...", request.Context.Session.Request.RequestUri); - continue; - } - - var methodAndUrlString = request.Message; - Logger.LogDebug("Processing request {MethodAndUrlString}...", methodAndUrlString); - - try - { - var pathItem = GetOpenApiPathItem(request.Context.Session); - var parametrizedPath = ParametrizePath(pathItem, request.Context.Session.Request.RequestUri); - if (pathItem.Operations is null) - { - Logger.LogDebug("No operations found for request {MethodAndUrlString}. Skipping...", methodAndUrlString); - continue; - } - var operationInfo = pathItem.Operations.First(); - operationInfo.Value.OperationId = await GetOperationIdAsync( - operationInfo.Key.ToString(), - request.Context.Session.Request.RequestUri.GetLeftPart(UriPartial.Authority), - parametrizedPath, - cancellationToken - ); - operationInfo.Value.Description = await GetOperationDescriptionAsync( - operationInfo.Key.ToString(), - request.Context.Session.Request.RequestUri.GetLeftPart(UriPartial.Authority), - parametrizedPath, - cancellationToken - ); - AddOrMergePathItem(openApiDocs, pathItem, request.Context.Session.Request.RequestUri, parametrizedPath); - } - catch (Exception ex) - { - Logger.LogError(ex, "Error processing request {MethodAndUrl}", methodAndUrlString); - } - } - - Logger.LogDebug("Serializing OpenAPI docs..."); - var generatedOpenApiSpecs = new Dictionary(); - foreach (var openApiDoc in openApiDocs) - { - if (openApiDoc.Servers is null || openApiDoc.Servers.Count == 0) - { - Logger.LogDebug("OpenAPI doc has no servers. Skipping..."); - continue; - } - var server = openApiDoc.Servers.First(); - if (string.IsNullOrEmpty(server.Url)) - { - Logger.LogDebug("Server URL is null or empty. Skipping..."); - continue; - } - var fileName = GetFileNameFromServerUrl(server.Url, Configuration.SpecFormat); - - var openApiSpecVersion = Configuration.SpecVersion switch - { - SpecVersion.v2_0 => OpenApiSpecVersion.OpenApi2_0, - SpecVersion.v3_0 => OpenApiSpecVersion.OpenApi3_0, - SpecVersion.v3_1 => OpenApiSpecVersion.OpenApi3_1, - SpecVersion.v3_2 => OpenApiSpecVersion.OpenApi3_2, - _ => OpenApiSpecVersion.OpenApi3_0 - }; - - var docString = Configuration.SpecFormat switch - { - SpecFormat.Json => await openApiDoc.SerializeAsJsonAsync(openApiSpecVersion, cancellationToken), - SpecFormat.Yaml => await openApiDoc.SerializeAsYamlAsync(openApiSpecVersion, cancellationToken), - _ => await openApiDoc.SerializeAsJsonAsync(openApiSpecVersion, cancellationToken) - }; - - Logger.LogDebug(" Writing OpenAPI spec to {FileName}...", fileName); - await File.WriteAllTextAsync(fileName, docString, cancellationToken); - - generatedOpenApiSpecs.Add(server.Url, fileName); - - Logger.LogInformation("Created OpenAPI spec file {FileName}", fileName); - } - - StoreReport(new OpenApiSpecGeneratorPluginReport( - generatedOpenApiSpecs - .Select(kvp => new OpenApiSpecGeneratorPluginReportItem - { - ServerUrl = kvp.Key, - FileName = kvp.Value - })), e); - - // store the generated OpenAPI specs in the global data - // for use by other plugins - e.GlobalData[GeneratedOpenApiSpecsKey] = generatedOpenApiSpecs; - - Logger.LogTrace("Left {Name}", nameof(AfterRecordingStopAsync)); - } - - private async Task GetOperationIdAsync(string method, string serverUrl, string parametrizedPath, CancellationToken cancellationToken) - { - var id = await languageModelClient.GenerateChatCompletionAsync("api_operation_id", new() - { - { "request", $"{method.ToUpperInvariant()} {serverUrl}{parametrizedPath}" } - }, cancellationToken); - return id?.Response ?? $"{method}{parametrizedPath.Replace('/', '.')}"; - } - - private async Task GetOperationDescriptionAsync(string method, string serverUrl, string parametrizedPath, CancellationToken cancellationToken) - { - var description = await languageModelClient.GenerateChatCompletionAsync("api_operation_description", new() - { - { "request", $"{method.ToUpperInvariant()} {serverUrl}{parametrizedPath}" } - }, - cancellationToken); - return description?.Response ?? $"{method} {parametrizedPath}"; - } - - /** - * Creates an OpenAPI PathItem from an intercepted request and response pair. - * @param session The intercepted session. - */ - private OpenApiPathItem GetOpenApiPathItem(IProxySession session) - { - var request = session.Request; - var response = session.Response!; - - var resource = GetLastNonTokenSegment(request.RequestUri.Segments); - var path = new OpenApiPathItem - { - Operations = [] - }; - - var method = request.Method?.ToUpperInvariant() switch - { - "DELETE" => HttpMethod.Delete, - "GET" => HttpMethod.Get, - "HEAD" => HttpMethod.Head, - "OPTIONS" => HttpMethod.Options, - "PATCH" => HttpMethod.Patch, - "POST" => HttpMethod.Post, - "PUT" => HttpMethod.Put, - "QUERY" => HttpMethod.Query, - "TRACE" => HttpMethod.Trace, - _ => throw new NotSupportedException($"Method {request.Method} is not supported") - }; - var operation = new OpenApiOperation - { - // will be replaced later after the path has been parametrized - Description = $"{method} {resource}", - // will be replaced later after the path has been parametrized - OperationId = $"{method}.{resource}" - }; - SetParametersFromQueryString(operation, HttpUtility.ParseQueryString(request.RequestUri.Query)); - SetParametersFromRequestHeaders(operation, request.Headers); - SetRequestBody(operation, request); - SetResponseFromSession(operation, response); - - path.Operations?.Add(method, operation); - - return path; - } - - private void SetRequestBody(OpenApiOperation operation, IHttpRequest request) - { - if (!request.HasBody) - { - Logger.LogDebug(" Request has no body"); - return; - } - - if (request.ContentType is null) - { - Logger.LogDebug(" Request has no content type"); - return; - } - - Logger.LogDebug(" Processing request body..."); - operation.RequestBody = new OpenApiRequestBody - { - Content = new Dictionary - { - { - GetMediaType(request.ContentType), - new OpenApiMediaType - { - Schema = GetSchemaFromBody(GetMediaType(request.ContentType), request.BodyString) - } - } - } - }; - } - - private void SetParametersFromRequestHeaders(OpenApiOperation operation, IHeaderCollection headers) - { - if (headers is null || - headers.Count == 0) - { - Logger.LogDebug(" Request has no headers"); - return; - } - - Logger.LogDebug(" Processing request headers..."); - foreach (var header in headers) - { - var lowerCaseHeaderName = header.Name.ToLowerInvariant(); - if (Models.Http.StandardHeaders.Contains(lowerCaseHeaderName)) - { - Logger.LogDebug(" Skipping standard header {HeaderName}", header.Name); - continue; - } - - if (Models.Http.AuthHeaders.Contains(lowerCaseHeaderName)) - { - Logger.LogDebug(" Skipping auth header {HeaderName}", header.Name); - continue; - } - - operation.Parameters?.Add(new OpenApiParameter() - { - Name = header.Name, - In = ParameterLocation.Header, - Required = false, - Schema = new OpenApiSchema() { Type = JsonSchemaType.String } - }); - Logger.LogDebug(" Added header {HeaderName}", header.Name); - } - } - - private void SetParametersFromQueryString(OpenApiOperation operation, NameValueCollection queryParams) - { - if (queryParams.AllKeys is null || - queryParams.AllKeys.Length == 0) - { - Logger.LogDebug(" Request has no query string parameters"); - return; - } - - Logger.LogDebug(" Processing query string parameters..."); - var dictionary = queryParams.AllKeys - .Where(k => k is not null).Cast() - .ToDictionary(k => k, k => queryParams[k] as object); - - foreach (var (key, value) in dictionary) - { - var isRequired = Configuration.IncludeParameters.Any(p => string.Equals(p, key, StringComparison.Ordinal)); - - OpenApiParameter parameter = new() - { - Name = key, - In = ParameterLocation.Query, - Required = isRequired, - Schema = new OpenApiSchema() { Type = JsonSchemaType.String } - }; - SetParameterDefault(parameter, value); - - operation.Parameters?.Add(parameter); - Logger.LogDebug(" Added query string parameter {ParameterKey}", key); - } - } - - private static void SetParameterDefault(OpenApiParameter parameter, object? value) - { - if (!parameter.Required || value is null) - { - return; - } - if (parameter.Schema is OpenApiSchema schema) - { - schema.Default = JsonValue.Create(value.ToString()); - } - } - - private void SetResponseFromSession(OpenApiOperation operation, IHttpResponse response) - { - if (response is null) - { - Logger.LogDebug(" No response to process"); - return; - } - - Logger.LogDebug(" Processing response..."); - - var openApiResponse = new OpenApiResponse - { - Description = response.StatusDescription - }; - var responseCode = ((int)response.StatusCode).ToString(CultureInfo.InvariantCulture); - if (response.HasBody) - { - Logger.LogDebug(" Response has body"); - - openApiResponse.Content?.Add(GetMediaType(response.ContentType), new OpenApiMediaType() - { - Schema = GetSchemaFromBody(GetMediaType(response.ContentType), response.BodyString) - }); - } - else - { - Logger.LogDebug(" Response doesn't have body"); - } - - if (response.Headers is not null && response.Headers.Count > 0) - { - Logger.LogDebug(" Response has headers"); - - foreach (var header in response.Headers) - { - var lowerCaseHeaderName = header.Name.ToLowerInvariant(); - if (Models.Http.StandardHeaders.Contains(lowerCaseHeaderName)) - { - Logger.LogDebug(" Skipping standard header {HeaderName}", header.Name); - continue; - } - - if (Models.Http.AuthHeaders.Contains(lowerCaseHeaderName)) - { - Logger.LogDebug(" Skipping auth header {HeaderName}", header.Name); - continue; - } - - if (openApiResponse.Headers?.ContainsKey(header.Name) == true) - { - Logger.LogDebug(" Header {HeaderName} already exists in response", header.Name); - continue; - } - - openApiResponse.Headers?.Add(header.Name, new OpenApiHeader() - { - Schema = new OpenApiSchema() { Type = JsonSchemaType.String } - }); - Logger.LogDebug(" Added header {HeaderName}", header.Name); - } - } - else - { - Logger.LogDebug(" Response doesn't have headers"); - } - - operation.Responses?.Add(responseCode, openApiResponse); - } - - private OpenApiSchema? GetSchemaFromBody(string? contentType, string body) - { - if (contentType is null) - { - Logger.LogDebug(" No content type to process"); - return null; - } - - if (contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) - { - Logger.LogDebug(" Processing JSON body..."); - if (Configuration.IgnoreResponseTypes) - { - Logger.LogDebug(" Ignoring response types"); - return new() - { - Type = JsonSchemaType.String - }; - } - - return GetSchemaFromJsonString(body); - } - - return null; - } - - private void AddOrMergePathItem(List openApiDocs, OpenApiPathItem pathItem, Uri requestUri, string parametrizedPath) - { - var serverUrl = requestUri.GetLeftPart(UriPartial.Authority); - var openApiDoc = openApiDocs.FirstOrDefault(d => d.Servers?.Any(s => s.Url == serverUrl) == true); - - if (openApiDoc is null) - { - Logger.LogDebug(" Creating OpenAPI spec for {ServerUrl}...", serverUrl); - - openApiDoc = new OpenApiDocument - { - Info = new() - { - Version = "v1.0", - Title = $"{serverUrl} API", - Description = $"{serverUrl} API", - }, - Servers = - [ - new() { Url = serverUrl } - ], - Paths = [], - Extensions = new Dictionary - { - { "x-ms-generated-by", new GeneratedByOpenApiExtension() } - } - }; - openApiDocs.Add(openApiDoc); - } - else - { - Logger.LogDebug(" Found OpenAPI spec for {ServerUrl}...", serverUrl); - } - - if (!openApiDoc.Paths.TryGetValue(parametrizedPath, out var value)) - { - Logger.LogDebug(" Adding path {ParametrizedPath} to OpenAPI spec...", parametrizedPath); - value = pathItem; - openApiDoc.Paths.Add(parametrizedPath, value); - // since we've just added the path, we're done - return; - } - - Logger.LogDebug(" Merging path {ParametrizedPath} into OpenAPI spec...", parametrizedPath); - var operation = pathItem.Operations?.First(); - if (operation is not null) - { - AddOrMergeOperation((OpenApiPathItem)value, operation.Value.Key, operation.Value.Value); - } - } - - private void AddOrMergeOperation(OpenApiPathItem pathItem, HttpMethod httpMethod, OpenApiOperation apiOperation) - { - if (pathItem.Operations?.TryGetValue(httpMethod, out var value) != true) - { - Logger.LogDebug(" Adding operation {OperationType} to path...", httpMethod); - - pathItem.AddOperation(httpMethod, apiOperation); - // since we've just added the operation, we're done - return; - } - - Logger.LogDebug(" Merging operation {OperationType} into path...", httpMethod); - - var operation = value!; - - AddOrMergeParameters(operation, apiOperation.Parameters); - AddOrMergeRequestBody(operation, (OpenApiRequestBody?)apiOperation.RequestBody); - AddOrMergeResponse(operation, apiOperation.Responses); - } - - private void AddOrMergeParameters(OpenApiOperation operation, IList? parameters) - { - if (parameters is null || parameters.Count == 0) - { - Logger.LogDebug(" No parameters to process"); - return; - } - - Logger.LogDebug(" Processing parameters for operation..."); - - foreach (var parameter in parameters) - { - var paramFromOperation = operation.Parameters?.FirstOrDefault(p => p.Name == parameter.Name && p.In == parameter.In); - if (paramFromOperation is null) - { - Logger.LogDebug(" Adding parameter {ParameterName} to operation...", parameter.Name); - operation.Parameters?.Add(parameter); - continue; - } - - Logger.LogDebug(" Merging parameter {ParameterName}...", parameter.Name); - MergeSchema(parameter?.Schema, paramFromOperation.Schema); - } - } - - private void MergeSchema(IOpenApiSchema? source, IOpenApiSchema? target) - { - if (source is null || target is null) - { - Logger.LogDebug(" Source or target is null. Skipping..."); - return; - } - - if (source.Type != JsonSchemaType.Object || target.Type != JsonSchemaType.Object) - { - Logger.LogDebug(" Source or target schema is not an object. Skipping..."); - return; - } - - if (source.Properties is null || source.Properties.Count == 0) - { - Logger.LogDebug(" Source has no properties. Skipping..."); - return; - } - - if (target.Properties is null || target.Properties.Count == 0) - { - Logger.LogDebug(" Target has no properties. Skipping..."); - return; - } - - foreach (var property in source.Properties) - { - var propertyFromTarget = target.Properties.FirstOrDefault(p => p.Key == property.Key); - if (propertyFromTarget.Value is null) - { - Logger.LogDebug(" Adding property {PropertyKey} to schema...", property.Key); - target.Properties.Add(property); - continue; - } - - if (property.Value.Type != JsonSchemaType.Object) - { - Logger.LogDebug(" Property already found but is not an object. Skipping..."); - continue; - } - - Logger.LogDebug(" Merging property {PropertyKey}...", property.Key); - MergeSchema(property.Value, propertyFromTarget.Value); - } - } - - private void AddOrMergeRequestBody(OpenApiOperation operation, OpenApiRequestBody? requestBody) - { - if (requestBody is null || requestBody.Content is null || requestBody.Content.Count == 0) - { - Logger.LogDebug(" No request body to process"); - return; - } - - var requestBodyType = requestBody.Content.FirstOrDefault().Key; - IOpenApiMediaType? bodyFromOperation = null; - if (operation.RequestBody?.Content is not null) - { - _ = operation.RequestBody.Content.TryGetValue(requestBodyType, out bodyFromOperation); - } - - if (bodyFromOperation is null) - { - Logger.LogDebug(" Adding request body to operation..."); - - operation.RequestBody ??= new OpenApiRequestBody - { - Content = new Dictionary() - }; - operation.RequestBody.Content!.Add(requestBody.Content.FirstOrDefault()); - // since we've just added the request body, we're done - return; - } - - Logger.LogDebug(" Merging request body into operation..."); - MergeSchema(bodyFromOperation.Schema, requestBody.Content.FirstOrDefault().Value.Schema); - } - - private void AddOrMergeResponse(OpenApiOperation operation, OpenApiResponses? apiResponses) - { - if (apiResponses is null) - { - Logger.LogDebug(" No response to process"); - return; - } - - var apiResponseInfo = apiResponses.FirstOrDefault(); - var apiResponseStatusCode = apiResponseInfo.Key; - var apiResponse = apiResponseInfo.Value; - IOpenApiResponse? responseFromOperation = null; - if (operation.Responses is not null) - { - _ = operation.Responses.TryGetValue(apiResponseStatusCode, out responseFromOperation); - } - - if (responseFromOperation is null) - { - Logger.LogDebug(" Adding response {ApiResponseStatusCode} to operation...", apiResponseStatusCode); - - operation.Responses?.Add(apiResponseStatusCode, apiResponse); - // since we've just added the response, we're done - return; - } - - if (apiResponse.Content is null || apiResponse.Content.Count == 0) - { - Logger.LogDebug(" No response content to process"); - return; - } - - var apiResponseContentType = apiResponse.Content.First().Key; - IOpenApiMediaType? contentFromOperation = null; - if (responseFromOperation.Content is not null) - { - _ = responseFromOperation.Content.TryGetValue(apiResponseContentType, out contentFromOperation); - } - - if (contentFromOperation is null) - { - Logger.LogDebug(" Adding response {ApiResponseContentType} to {ApiResponseStatusCode} to response...", apiResponseContentType, apiResponseStatusCode); - - responseFromOperation.Content?.Add(apiResponse.Content.First()); - // since we've just added the content, we're done - return; - } - - Logger.LogDebug(" Merging response {ApiResponseStatusCode}/{ApiResponseContentType} into operation...", apiResponseStatusCode, apiResponseContentType); - MergeSchema(contentFromOperation.Schema, apiResponse.Content.First().Value.Schema); - } - - /** - * Replaces segments in the request URI, that match predefined patters, - * with parameters and adds them to the OpenAPI PathItem. - * @param pathItem The OpenAPI PathItem to parametrize. - * @param requestUri The request URI. - * @returns The parametrized server-relative URL - */ - private static string ParametrizePath(OpenApiPathItem pathItem, Uri requestUri) - { - var segments = requestUri.Segments; - var previousSegment = "item"; - - for (var i = 0; i < segments.Length; i++) - { - var segment = requestUri.Segments[i].Trim('/'); - if (string.IsNullOrEmpty(segment)) - { - continue; - } - - if (IsParametrizable(segment)) - { - var parameterName = $"{previousSegment}-id"; - segments[i] = $"{{{parameterName}}}{(requestUri.Segments[i].EndsWith('/') ? "/" : "")}"; - - pathItem.Parameters?.Add(new OpenApiParameter - { - Name = parameterName, - In = ParameterLocation.Path, - Required = true, - Schema = new OpenApiSchema { Type = JsonSchemaType.String } - }); - } - else - { - previousSegment = segment; - } - } - - return string.Join(string.Empty, segments); - } - - private static bool IsParametrizable(string segment) - { - return Guid.TryParse(segment.Trim('/'), out _) || - int.TryParse(segment.Trim('/'), out _); - } - - private static string GetLastNonTokenSegment(string[] segments) - { - for (var i = segments.Length - 1; i >= 0; i--) - { - var segment = segments[i].Trim('/'); - if (string.IsNullOrEmpty(segment)) - { - continue; - } - - if (!IsParametrizable(segment)) - { - return segment; - } - } - - return "item"; - } - - private static string GetMediaType(string? contentType) - { - if (string.IsNullOrEmpty(contentType)) - { - return contentType ?? ""; - } - - var mediaType = contentType.Split(';').First().Trim(); - return mediaType; - } - - private static string GetFileNameFromServerUrl(string serverUrl, SpecFormat format) - { - var uri = new Uri(serverUrl); - var ext = format switch - { - SpecFormat.Json => "json", - SpecFormat.Yaml => "yaml", - _ => "json" - }; - var fileName = $"{uri.Host}-{uri.Port}-{DateTime.Now:yyyyMMddHHmmss}.{ext}"; - return fileName; - } - - private static OpenApiSchema GetSchemaFromJsonString(string jsonString) - { - try - { - using var doc = JsonDocument.Parse(jsonString, ProxyUtils.JsonDocumentOptions); - var root = doc.RootElement; - var schema = GetSchemaFromJsonElement(root); - return schema; - } - catch - { - return new() - { - Type = JsonSchemaType.Object - }; - } - } - - private static OpenApiSchema GetSchemaFromJsonElement(JsonElement jsonElement) - { - var schema = new OpenApiSchema(); - -#pragma warning disable IDE0010 - switch (jsonElement.ValueKind) -#pragma warning restore IDE0010 - { - case JsonValueKind.String: - schema.Type = JsonSchemaType.String; - break; - case JsonValueKind.Number: - schema.Type = JsonSchemaType.Number; - break; - case JsonValueKind.True: - case JsonValueKind.False: - schema.Type = JsonSchemaType.Boolean; - break; - case JsonValueKind.Object: - schema.Type = JsonSchemaType.Object; - schema.Properties = jsonElement.EnumerateObject() - .ToDictionary(p => p.Name, p => (IOpenApiSchema)GetSchemaFromJsonElement(p.Value)); - break; - case JsonValueKind.Array: - schema.Type = JsonSchemaType.Array; - schema.Items = GetSchemaFromJsonElement(jsonElement.EnumerateArray().FirstOrDefault()); - break; - default: - schema.Type = JsonSchemaType.Object; - break; - } - - return schema; - } -} +// 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 DevProxy.Abstractions.LanguageModel; +using DevProxy.Abstractions.Plugins; +using DevProxy.Abstractions.Proxy; +using DevProxy.Abstractions.Proxy.Http; +using DevProxy.Abstractions.Utils; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.OpenApi; +using System.Text.Json.Nodes; +using System.Collections.Specialized; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Web; + +namespace DevProxy.Plugins.Generation; + +sealed class GeneratedByOpenApiExtension : IOpenApiExtension +{ + public void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) + { + writer.WriteStartObject(); + writer.WriteProperty("toolName", "Dev Proxy"); + writer.WriteProperty("toolVersion", ProxyUtils.ProductVersion); + writer.WriteEndObject(); + } +} + +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum SpecVersion +{ +#pragma warning disable CA1707 + v2_0, + v3_0, + v3_1, + v3_2 +#pragma warning restore CA1707 +} + +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum SpecFormat +{ + Json, + Yaml +} + +public sealed class OpenApiSpecGeneratorPluginConfiguration +{ + public bool IncludeOptionsRequests { get; set; } + public SpecFormat SpecFormat { get; set; } = SpecFormat.Json; + public SpecVersion SpecVersion { get; set; } = SpecVersion.v3_0; + public bool IgnoreResponseTypes { get; set; } + public IEnumerable IncludeParameters { get; set; } = []; +} + +public sealed class OpenApiSpecGeneratorPlugin( + HttpClient httpClient, + ILogger logger, + ISet urlsToWatch, + ILanguageModelClient languageModelClient, + IProxyConfiguration proxyConfiguration, + IConfigurationSection pluginConfigurationSection) : + BaseReportingPlugin( + httpClient, + logger, + urlsToWatch, + proxyConfiguration, + pluginConfigurationSection) +{ + public static readonly string GeneratedOpenApiSpecsKey = "GeneratedOpenApiSpecs"; + + public override string Name => nameof(OpenApiSpecGeneratorPlugin); + + public override async Task AfterRecordingStopAsync(RecordingArgs e, CancellationToken cancellationToken) + { + Logger.LogTrace("{Method} called", nameof(AfterRecordingStopAsync)); + + ArgumentNullException.ThrowIfNull(e); + + if (!e.RequestLogs.Any()) + { + Logger.LogDebug("No requests to process"); + return; + } + + Logger.LogInformation("Creating OpenAPI spec from recorded requests..."); + + var openApiDocs = new List(); + + foreach (var request in e.RequestLogs) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (request.MessageType != MessageType.InterceptedResponse || + request.Context is null || + request.Context.Session is null || + !ProxyUtils.MatchesUrlToWatch(UrlsToWatch, request.Context.Session.Request.RequestUri.AbsoluteUri)) + { + continue; + } + + if (!Configuration.IncludeOptionsRequests && + string.Equals(request.Context.Session.Request.Method, "OPTIONS", StringComparison.OrdinalIgnoreCase)) + { + Logger.LogDebug("Skipping OPTIONS request {Url}...", request.Context.Session.Request.RequestUri); + continue; + } + + var methodAndUrlString = request.Message; + Logger.LogDebug("Processing request {MethodAndUrlString}...", methodAndUrlString); + + try + { + var pathItem = GetOpenApiPathItem(request.Context.Session); + var parametrizedPath = ParametrizePath(pathItem, request.Context.Session.Request.RequestUri); + if (pathItem.Operations is null) + { + Logger.LogDebug("No operations found for request {MethodAndUrlString}. Skipping...", methodAndUrlString); + continue; + } + var operationInfo = pathItem.Operations.First(); + operationInfo.Value.OperationId = await GetOperationIdAsync( + operationInfo.Key.ToString(), + request.Context.Session.Request.RequestUri.GetLeftPart(UriPartial.Authority), + parametrizedPath, + cancellationToken + ); + operationInfo.Value.Description = await GetOperationDescriptionAsync( + operationInfo.Key.ToString(), + request.Context.Session.Request.RequestUri.GetLeftPart(UriPartial.Authority), + parametrizedPath, + cancellationToken + ); + AddOrMergePathItem(openApiDocs, pathItem, request.Context.Session.Request.RequestUri, parametrizedPath); + } + catch (Exception ex) + { + Logger.LogError(ex, "Error processing request {MethodAndUrl}", methodAndUrlString); + } + } + + Logger.LogDebug("Serializing OpenAPI docs..."); + var generatedOpenApiSpecs = new Dictionary(); + foreach (var openApiDoc in openApiDocs) + { + if (openApiDoc.Servers is null || openApiDoc.Servers.Count == 0) + { + Logger.LogDebug("OpenAPI doc has no servers. Skipping..."); + continue; + } + var server = openApiDoc.Servers.First(); + if (string.IsNullOrEmpty(server.Url)) + { + Logger.LogDebug("Server URL is null or empty. Skipping..."); + continue; + } + var fileName = GetFileNameFromServerUrl(server.Url, Configuration.SpecFormat); + + var openApiSpecVersion = Configuration.SpecVersion switch + { + SpecVersion.v2_0 => OpenApiSpecVersion.OpenApi2_0, + SpecVersion.v3_0 => OpenApiSpecVersion.OpenApi3_0, + SpecVersion.v3_1 => OpenApiSpecVersion.OpenApi3_1, + SpecVersion.v3_2 => OpenApiSpecVersion.OpenApi3_2, + _ => OpenApiSpecVersion.OpenApi3_0 + }; + + var docString = Configuration.SpecFormat switch + { + SpecFormat.Json => await openApiDoc.SerializeAsJsonAsync(openApiSpecVersion, cancellationToken), + SpecFormat.Yaml => await openApiDoc.SerializeAsYamlAsync(openApiSpecVersion, cancellationToken), + _ => await openApiDoc.SerializeAsJsonAsync(openApiSpecVersion, cancellationToken) + }; + + Logger.LogDebug(" Writing OpenAPI spec to {FileName}...", fileName); + await File.WriteAllTextAsync(fileName, docString, cancellationToken); + + generatedOpenApiSpecs.Add(server.Url, fileName); + + Logger.LogInformation("Created OpenAPI spec file {FileName}", fileName); + } + + StoreReport(new OpenApiSpecGeneratorPluginReport( + generatedOpenApiSpecs + .Select(kvp => new OpenApiSpecGeneratorPluginReportItem + { + ServerUrl = kvp.Key, + FileName = kvp.Value + })), e); + + // store the generated OpenAPI specs in the global data + // for use by other plugins + e.GlobalData[GeneratedOpenApiSpecsKey] = generatedOpenApiSpecs; + + Logger.LogTrace("Left {Name}", nameof(AfterRecordingStopAsync)); + } + + private async Task GetOperationIdAsync(string method, string serverUrl, string parametrizedPath, CancellationToken cancellationToken) + { + var id = await languageModelClient.GenerateChatCompletionAsync("api_operation_id", new() + { + { "request", $"{method.ToUpperInvariant()} {serverUrl}{parametrizedPath}" } + }, cancellationToken); + return id?.Response ?? $"{method}{parametrizedPath.Replace('/', '.')}"; + } + + private async Task GetOperationDescriptionAsync(string method, string serverUrl, string parametrizedPath, CancellationToken cancellationToken) + { + var description = await languageModelClient.GenerateChatCompletionAsync("api_operation_description", new() + { + { "request", $"{method.ToUpperInvariant()} {serverUrl}{parametrizedPath}" } + }, + cancellationToken); + return description?.Response ?? $"{method} {parametrizedPath}"; + } + + /** + * Creates an OpenAPI PathItem from an intercepted request and response pair. + * @param session The intercepted session. + */ + private OpenApiPathItem GetOpenApiPathItem(IProxySession session) + { + var request = session.Request; + var response = session.Response!; + + var resource = GetLastNonTokenSegment(request.RequestUri.Segments); + var path = new OpenApiPathItem + { + Operations = [] + }; + + var method = request.Method?.ToUpperInvariant() switch + { + "DELETE" => HttpMethod.Delete, + "GET" => HttpMethod.Get, + "HEAD" => HttpMethod.Head, + "OPTIONS" => HttpMethod.Options, + "PATCH" => HttpMethod.Patch, + "POST" => HttpMethod.Post, + "PUT" => HttpMethod.Put, + "QUERY" => HttpMethod.Query, + "TRACE" => HttpMethod.Trace, + _ => throw new NotSupportedException($"Method {request.Method} is not supported") + }; + var operation = new OpenApiOperation + { + // will be replaced later after the path has been parametrized + Description = $"{method} {resource}", + // will be replaced later after the path has been parametrized + OperationId = $"{method}.{resource}" + }; + SetParametersFromQueryString(operation, HttpUtility.ParseQueryString(request.RequestUri.Query)); + SetParametersFromRequestHeaders(operation, request.Headers); + SetRequestBody(operation, request); + SetResponseFromSession(operation, response); + + path.Operations?.Add(method, operation); + + return path; + } + + private void SetRequestBody(OpenApiOperation operation, IHttpRequest request) + { + if (!request.HasBody) + { + Logger.LogDebug(" Request has no body"); + return; + } + + if (request.ContentType is null) + { + Logger.LogDebug(" Request has no content type"); + return; + } + + Logger.LogDebug(" Processing request body..."); + operation.RequestBody = new OpenApiRequestBody + { + Content = new Dictionary + { + { + GetMediaType(request.ContentType), + new OpenApiMediaType + { + Schema = GetSchemaFromBody(GetMediaType(request.ContentType), request.BodyString) + } + } + } + }; + } + + private void SetParametersFromRequestHeaders(OpenApiOperation operation, IHeaderCollection headers) + { + if (headers is null || + headers.Count == 0) + { + Logger.LogDebug(" Request has no headers"); + return; + } + + Logger.LogDebug(" Processing request headers..."); + foreach (var header in headers) + { + var lowerCaseHeaderName = header.Name.ToLowerInvariant(); + if (Models.Http.StandardHeaders.Contains(lowerCaseHeaderName)) + { + Logger.LogDebug(" Skipping standard header {HeaderName}", header.Name); + continue; + } + + if (Models.Http.AuthHeaders.Contains(lowerCaseHeaderName)) + { + Logger.LogDebug(" Skipping auth header {HeaderName}", header.Name); + continue; + } + + operation.Parameters?.Add(new OpenApiParameter() + { + Name = header.Name, + In = ParameterLocation.Header, + Required = false, + Schema = new OpenApiSchema() { Type = JsonSchemaType.String } + }); + Logger.LogDebug(" Added header {HeaderName}", header.Name); + } + } + + private void SetParametersFromQueryString(OpenApiOperation operation, NameValueCollection queryParams) + { + if (queryParams.AllKeys is null || + queryParams.AllKeys.Length == 0) + { + Logger.LogDebug(" Request has no query string parameters"); + return; + } + + Logger.LogDebug(" Processing query string parameters..."); + var dictionary = queryParams.AllKeys + .Where(k => k is not null).Cast() + .ToDictionary(k => k, k => queryParams[k] as object); + + foreach (var (key, value) in dictionary) + { + var isRequired = Configuration.IncludeParameters.Any(p => string.Equals(p, key, StringComparison.Ordinal)); + + OpenApiParameter parameter = new() + { + Name = key, + In = ParameterLocation.Query, + Required = isRequired, + Schema = new OpenApiSchema() { Type = JsonSchemaType.String } + }; + SetParameterDefault(parameter, value); + + operation.Parameters?.Add(parameter); + Logger.LogDebug(" Added query string parameter {ParameterKey}", key); + } + } + + private static void SetParameterDefault(OpenApiParameter parameter, object? value) + { + if (!parameter.Required || value is null) + { + return; + } + if (parameter.Schema is OpenApiSchema schema) + { + schema.Default = JsonValue.Create(value.ToString()); + } + } + + private void SetResponseFromSession(OpenApiOperation operation, IHttpResponse response) + { + if (response is null) + { + Logger.LogDebug(" No response to process"); + return; + } + + Logger.LogDebug(" Processing response..."); + + var openApiResponse = new OpenApiResponse + { + Description = response.StatusDescription + }; + var responseCode = ((int)response.StatusCode).ToString(CultureInfo.InvariantCulture); + if (response.HasBody) + { + Logger.LogDebug(" Response has body"); + + openApiResponse.Content?.Add(GetMediaType(response.ContentType), new OpenApiMediaType() + { + Schema = GetSchemaFromBody(GetMediaType(response.ContentType), response.BodyString) + }); + } + else + { + Logger.LogDebug(" Response doesn't have body"); + } + + if (response.Headers is not null && response.Headers.Count > 0) + { + Logger.LogDebug(" Response has headers"); + + foreach (var header in response.Headers) + { + var lowerCaseHeaderName = header.Name.ToLowerInvariant(); + if (Models.Http.StandardHeaders.Contains(lowerCaseHeaderName)) + { + Logger.LogDebug(" Skipping standard header {HeaderName}", header.Name); + continue; + } + + if (Models.Http.AuthHeaders.Contains(lowerCaseHeaderName)) + { + Logger.LogDebug(" Skipping auth header {HeaderName}", header.Name); + continue; + } + + if (openApiResponse.Headers?.ContainsKey(header.Name) == true) + { + Logger.LogDebug(" Header {HeaderName} already exists in response", header.Name); + continue; + } + + openApiResponse.Headers?.Add(header.Name, new OpenApiHeader() + { + Schema = new OpenApiSchema() { Type = JsonSchemaType.String } + }); + Logger.LogDebug(" Added header {HeaderName}", header.Name); + } + } + else + { + Logger.LogDebug(" Response doesn't have headers"); + } + + operation.Responses?.Add(responseCode, openApiResponse); + } + + private OpenApiSchema? GetSchemaFromBody(string? contentType, string body) + { + if (contentType is null) + { + Logger.LogDebug(" No content type to process"); + return null; + } + + if (contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) + { + Logger.LogDebug(" Processing JSON body..."); + if (Configuration.IgnoreResponseTypes) + { + Logger.LogDebug(" Ignoring response types"); + return new() + { + Type = JsonSchemaType.String + }; + } + + return GetSchemaFromJsonString(body); + } + + return null; + } + + private void AddOrMergePathItem(List openApiDocs, OpenApiPathItem pathItem, Uri requestUri, string parametrizedPath) + { + var serverUrl = requestUri.GetLeftPart(UriPartial.Authority); + var openApiDoc = openApiDocs.FirstOrDefault(d => d.Servers?.Any(s => s.Url == serverUrl) == true); + + if (openApiDoc is null) + { + Logger.LogDebug(" Creating OpenAPI spec for {ServerUrl}...", serverUrl); + + openApiDoc = new OpenApiDocument + { + Info = new() + { + Version = "v1.0", + Title = $"{serverUrl} API", + Description = $"{serverUrl} API", + }, + Servers = + [ + new() { Url = serverUrl } + ], + Paths = [], + Extensions = new Dictionary + { + { "x-ms-generated-by", new GeneratedByOpenApiExtension() } + } + }; + openApiDocs.Add(openApiDoc); + } + else + { + Logger.LogDebug(" Found OpenAPI spec for {ServerUrl}...", serverUrl); + } + + if (!openApiDoc.Paths.TryGetValue(parametrizedPath, out var value)) + { + Logger.LogDebug(" Adding path {ParametrizedPath} to OpenAPI spec...", parametrizedPath); + value = pathItem; + openApiDoc.Paths.Add(parametrizedPath, value); + // since we've just added the path, we're done + return; + } + + Logger.LogDebug(" Merging path {ParametrizedPath} into OpenAPI spec...", parametrizedPath); + var operation = pathItem.Operations?.First(); + if (operation is not null) + { + AddOrMergeOperation((OpenApiPathItem)value, operation.Value.Key, operation.Value.Value); + } + } + + private void AddOrMergeOperation(OpenApiPathItem pathItem, HttpMethod httpMethod, OpenApiOperation apiOperation) + { + if (pathItem.Operations?.TryGetValue(httpMethod, out var value) != true) + { + Logger.LogDebug(" Adding operation {OperationType} to path...", httpMethod); + + pathItem.AddOperation(httpMethod, apiOperation); + // since we've just added the operation, we're done + return; + } + + Logger.LogDebug(" Merging operation {OperationType} into path...", httpMethod); + + var operation = value!; + + AddOrMergeParameters(operation, apiOperation.Parameters); + AddOrMergeRequestBody(operation, (OpenApiRequestBody?)apiOperation.RequestBody); + AddOrMergeResponse(operation, apiOperation.Responses); + } + + private void AddOrMergeParameters(OpenApiOperation operation, IList? parameters) + { + if (parameters is null || parameters.Count == 0) + { + Logger.LogDebug(" No parameters to process"); + return; + } + + Logger.LogDebug(" Processing parameters for operation..."); + + foreach (var parameter in parameters) + { + var paramFromOperation = operation.Parameters?.FirstOrDefault(p => p.Name == parameter.Name && p.In == parameter.In); + if (paramFromOperation is null) + { + Logger.LogDebug(" Adding parameter {ParameterName} to operation...", parameter.Name); + operation.Parameters?.Add(parameter); + continue; + } + + Logger.LogDebug(" Merging parameter {ParameterName}...", parameter.Name); + MergeSchema(parameter?.Schema, paramFromOperation.Schema); + } + } + + private void MergeSchema(IOpenApiSchema? source, IOpenApiSchema? target) + { + if (source is null || target is null) + { + Logger.LogDebug(" Source or target is null. Skipping..."); + return; + } + + if (source.Type != JsonSchemaType.Object || target.Type != JsonSchemaType.Object) + { + Logger.LogDebug(" Source or target schema is not an object. Skipping..."); + return; + } + + if (source.Properties is null || source.Properties.Count == 0) + { + Logger.LogDebug(" Source has no properties. Skipping..."); + return; + } + + if (target.Properties is null || target.Properties.Count == 0) + { + Logger.LogDebug(" Target has no properties. Skipping..."); + return; + } + + foreach (var property in source.Properties) + { + var propertyFromTarget = target.Properties.FirstOrDefault(p => p.Key == property.Key); + if (propertyFromTarget.Value is null) + { + Logger.LogDebug(" Adding property {PropertyKey} to schema...", property.Key); + target.Properties.Add(property); + continue; + } + + if (property.Value.Type != JsonSchemaType.Object) + { + Logger.LogDebug(" Property already found but is not an object. Skipping..."); + continue; + } + + Logger.LogDebug(" Merging property {PropertyKey}...", property.Key); + MergeSchema(property.Value, propertyFromTarget.Value); + } + } + + private void AddOrMergeRequestBody(OpenApiOperation operation, OpenApiRequestBody? requestBody) + { + if (requestBody is null || requestBody.Content is null || requestBody.Content.Count == 0) + { + Logger.LogDebug(" No request body to process"); + return; + } + + var requestBodyType = requestBody.Content.FirstOrDefault().Key; + IOpenApiMediaType? bodyFromOperation = null; + if (operation.RequestBody?.Content is not null) + { + _ = operation.RequestBody.Content.TryGetValue(requestBodyType, out bodyFromOperation); + } + + if (bodyFromOperation is null) + { + Logger.LogDebug(" Adding request body to operation..."); + + operation.RequestBody ??= new OpenApiRequestBody + { + Content = new Dictionary() + }; + operation.RequestBody.Content!.Add(requestBody.Content.FirstOrDefault()); + // since we've just added the request body, we're done + return; + } + + Logger.LogDebug(" Merging request body into operation..."); + MergeSchema(bodyFromOperation.Schema, requestBody.Content.FirstOrDefault().Value.Schema); + } + + private void AddOrMergeResponse(OpenApiOperation operation, OpenApiResponses? apiResponses) + { + if (apiResponses is null) + { + Logger.LogDebug(" No response to process"); + return; + } + + var apiResponseInfo = apiResponses.FirstOrDefault(); + var apiResponseStatusCode = apiResponseInfo.Key; + var apiResponse = apiResponseInfo.Value; + IOpenApiResponse? responseFromOperation = null; + if (operation.Responses is not null) + { + _ = operation.Responses.TryGetValue(apiResponseStatusCode, out responseFromOperation); + } + + if (responseFromOperation is null) + { + Logger.LogDebug(" Adding response {ApiResponseStatusCode} to operation...", apiResponseStatusCode); + + operation.Responses?.Add(apiResponseStatusCode, apiResponse); + // since we've just added the response, we're done + return; + } + + if (apiResponse.Content is null || apiResponse.Content.Count == 0) + { + Logger.LogDebug(" No response content to process"); + return; + } + + var apiResponseContentType = apiResponse.Content.First().Key; + IOpenApiMediaType? contentFromOperation = null; + if (responseFromOperation.Content is not null) + { + _ = responseFromOperation.Content.TryGetValue(apiResponseContentType, out contentFromOperation); + } + + if (contentFromOperation is null) + { + Logger.LogDebug(" Adding response {ApiResponseContentType} to {ApiResponseStatusCode} to response...", apiResponseContentType, apiResponseStatusCode); + + responseFromOperation.Content?.Add(apiResponse.Content.First()); + // since we've just added the content, we're done + return; + } + + Logger.LogDebug(" Merging response {ApiResponseStatusCode}/{ApiResponseContentType} into operation...", apiResponseStatusCode, apiResponseContentType); + MergeSchema(contentFromOperation.Schema, apiResponse.Content.First().Value.Schema); + } + + /** + * Replaces segments in the request URI, that match predefined patters, + * with parameters and adds them to the OpenAPI PathItem. + * @param pathItem The OpenAPI PathItem to parametrize. + * @param requestUri The request URI. + * @returns The parametrized server-relative URL + */ + private static string ParametrizePath(OpenApiPathItem pathItem, Uri requestUri) + { + var segments = requestUri.Segments; + var previousSegment = "item"; + + for (var i = 0; i < segments.Length; i++) + { + var segment = requestUri.Segments[i].Trim('/'); + if (string.IsNullOrEmpty(segment)) + { + continue; + } + + if (IsParametrizable(segment)) + { + var parameterName = $"{previousSegment}-id"; + segments[i] = $"{{{parameterName}}}{(requestUri.Segments[i].EndsWith('/', StringComparison.Ordinal) ? "/" : "")}"; + + pathItem.Parameters?.Add(new OpenApiParameter + { + Name = parameterName, + In = ParameterLocation.Path, + Required = true, + Schema = new OpenApiSchema { Type = JsonSchemaType.String } + }); + } + else + { + previousSegment = segment; + } + } + + return string.Join(string.Empty, segments); + } + + private static bool IsParametrizable(string segment) + { + return Guid.TryParse(segment.Trim('/'), out _) || + int.TryParse(segment.Trim('/'), out _); + } + + private static string GetLastNonTokenSegment(string[] segments) + { + for (var i = segments.Length - 1; i >= 0; i--) + { + var segment = segments[i].Trim('/'); + if (string.IsNullOrEmpty(segment)) + { + continue; + } + + if (!IsParametrizable(segment)) + { + return segment; + } + } + + return "item"; + } + + private static string GetMediaType(string? contentType) + { + if (string.IsNullOrEmpty(contentType)) + { + return contentType ?? ""; + } + + var mediaType = contentType.Split(';').First().Trim(); + return mediaType; + } + + private static string GetFileNameFromServerUrl(string serverUrl, SpecFormat format) + { + var uri = new Uri(serverUrl); + var ext = format switch + { + SpecFormat.Json => "json", + SpecFormat.Yaml => "yaml", + _ => "json" + }; + var fileName = $"{uri.Host}-{uri.Port}-{DateTime.Now:yyyyMMddHHmmss}.{ext}"; + return fileName; + } + + private static OpenApiSchema GetSchemaFromJsonString(string jsonString) + { + try + { + using var doc = JsonDocument.Parse(jsonString, ProxyUtils.JsonDocumentOptions); + var root = doc.RootElement; + var schema = GetSchemaFromJsonElement(root); + return schema; + } + catch + { + return new() + { + Type = JsonSchemaType.Object + }; + } + } + + private static OpenApiSchema GetSchemaFromJsonElement(JsonElement jsonElement) + { + var schema = new OpenApiSchema(); + +#pragma warning disable IDE0010 + switch (jsonElement.ValueKind) +#pragma warning restore IDE0010 + { + case JsonValueKind.String: + schema.Type = JsonSchemaType.String; + break; + case JsonValueKind.Number: + schema.Type = JsonSchemaType.Number; + break; + case JsonValueKind.True: + case JsonValueKind.False: + schema.Type = JsonSchemaType.Boolean; + break; + case JsonValueKind.Object: + schema.Type = JsonSchemaType.Object; + schema.Properties = jsonElement.EnumerateObject() + .ToDictionary(p => p.Name, p => (IOpenApiSchema)GetSchemaFromJsonElement(p.Value)); + break; + case JsonValueKind.Array: + schema.Type = JsonSchemaType.Array; + schema.Items = GetSchemaFromJsonElement(jsonElement.EnumerateArray().FirstOrDefault()); + break; + default: + schema.Type = JsonSchemaType.Object; + break; + } + + return schema; + } +} diff --git a/DevProxy.Plugins/Generation/TypeSpecGeneratorPlugin.cs b/DevProxy.Plugins/Generation/TypeSpecGeneratorPlugin.cs index 5731ac562..38f0a2dc8 100644 --- a/DevProxy.Plugins/Generation/TypeSpecGeneratorPlugin.cs +++ b/DevProxy.Plugins/Generation/TypeSpecGeneratorPlugin.cs @@ -862,7 +862,7 @@ private async Task MakeSingularAsync(string noun, CancellationToken canc { singular = noun[0..^2]; } - else if (noun.EndsWith('s') && !noun.EndsWith("ss", StringComparison.OrdinalIgnoreCase)) + else if (noun.EndsWith('s', StringComparison.Ordinal) && !noun.EndsWith("ss", StringComparison.OrdinalIgnoreCase)) { singular = noun[0..^1]; } diff --git a/DevProxy.Plugins/Mocking/MockResponsePlugin.cs b/DevProxy.Plugins/Mocking/MockResponsePlugin.cs index 22e36678a..f662eb9f5 100644 --- a/DevProxy.Plugins/Mocking/MockResponsePlugin.cs +++ b/DevProxy.Plugins/Mocking/MockResponsePlugin.cs @@ -406,7 +406,7 @@ private void ProcessMockResponseInternal(ProxyRequestArgs e, MockResponse matchi if (matchingResponse.Response?.Body is not null) { string bodyString = ProxyUtils.SerializeBody(matchingResponse.Response.Body); - if (bodyString.StartsWith('@')) + if (bodyString.StartsWith('@', StringComparison.Ordinal)) { // we've got a mock body starting with @-token which means we're sending // a response from a file on disk diff --git a/DevProxy.Plugins/Mocking/MockStdioResponsePlugin.cs b/DevProxy.Plugins/Mocking/MockStdioResponsePlugin.cs index d1455ea6f..469862874 100644 --- a/DevProxy.Plugins/Mocking/MockStdioResponsePlugin.cs +++ b/DevProxy.Plugins/Mocking/MockStdioResponsePlugin.cs @@ -383,7 +383,7 @@ private string GetMockContent(object? content, string contentType) } // Remove surrounding quotes if present (from JSON string serialization) - if (contentString.StartsWith('"') && contentString.EndsWith('"')) + if (contentString.StartsWith('"', StringComparison.Ordinal) && contentString.EndsWith('"', StringComparison.Ordinal)) { contentString = contentString[1..^1]; // Unescape JSON string diff --git a/DevProxy.Plugins/packages.lock.json b/DevProxy.Plugins/packages.lock.json index 7c3cfb1f5..77c0d1797 100644 --- a/DevProxy.Plugins/packages.lock.json +++ b/DevProxy.Plugins/packages.lock.json @@ -1,7 +1,7 @@ { "version": 1, "dependencies": { - "net10.0": { + "net11.0": { "Azure.Identity": { "type": "Direct", "requested": "[1.21.0, )", @@ -13,34 +13,29 @@ }, "Microsoft.EntityFrameworkCore.Sqlite": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "lxrwnVwvlIfQD4IF4WUVupE6Qxfj3MfFftDVwo7tsGAWCKLL8Ttb8UjIt+gE4e9nRlH7EgdC6TrsArFGnNYREw==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "12olimxsnuTo+9jsQvbS9fF/FXUhW7AHaXFcK/TgpND3Ki53CBvXnvT+AnPnk6d6f02D5NBdmBcZzfAynBgkRw==", "dependencies": { - "Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.14", - "Microsoft.Extensions.Caching.Memory": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyModel": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "SQLitePCLRaw.bundle_e_sqlite3": "2.1.13", - "SQLitePCLRaw.core": "2.1.13" + "Microsoft.EntityFrameworkCore.Sqlite.Core": "[11.0.0, 12.0.0-a)", + "Microsoft.Extensions.Caching.Memory": "11.0.0", + "Microsoft.Extensions.DependencyModel": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "SQLitePCLRaw.bundle_e_sqlite3": "3.0.5", + "SQLitePCLRaw.core": "3.0.5" } }, "Microsoft.Extensions.Configuration": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==" }, "Microsoft.Extensions.FileSystemGlobbing": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "xt6c/PWLL6+CiBiZA3PWRSfkwcPh+HCwiOLrgSUkhzBT7lrT/+QpIKPeuCQyDPspwOuG1q0cbJhuiGpRjr4UNQ==" + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Ycwu/y22NK/ZyJpaFRJc4FB88mjOnsttk2AVHaKgEeShq0vodXZ4FJErpMM2Jju3r3t/2VYWrcHuIxj3ZT/aow==" }, "Microsoft.IdentityModel.Protocols.OpenIdConnect": { "type": "Direct", @@ -81,7 +76,6 @@ "contentHash": "+XDw3fYbiv1a40aFnDJSQleeuUJciXuhoIA19XmcGhT47Hy/xZRqk8NCjHUDKrg72Ixjthicecp8ygBDNeH/Jw==", "dependencies": { "Microsoft.Extensions.Configuration.EnvironmentVariables": "10.0.0", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.0", "Microsoft.Extensions.Logging.Configuration": "10.0.0", "OpenTelemetry.Api.ProviderBuilderExtensions": "1.20.1" } @@ -117,8 +111,6 @@ "contentHash": "x9c/toFMOtRrlTdFuE7rlGCVAduQzWVfKmLz5juj41zJAXEhYD5hluiUyyAEzJ6OxpBnKtiaBztzwpZITAVjtg==", "dependencies": { "Microsoft.Bcl.AsyncInterfaces": "10.0.3", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.3", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.3", "Microsoft.Identity.Client": "4.83.1", "Microsoft.Identity.Client.Extensions.Msal": "4.83.1", "System.ClientModel": "1.10.0", @@ -142,93 +134,67 @@ }, "Microsoft.Data.Sqlite.Core": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1p9rO3Q2X/L/9YrYog3vaDzi8u+WZfJCOkDYoHqmofqYP0DLPLPyZcS2Rnh/79JXAodgbs1AgsaNwLpIvC3Xew==", + "resolved": "11.0.0", + "contentHash": "aWaF2LDjuFZwE9UsAGRYGNyS48xqaXoKPAjwpJI85fsaM/43s5NTRnl4xtqbTGKq8of2M/W8mo7DJk7v4zzHGQ==", "dependencies": { - "SQLitePCLRaw.core": "2.1.13" + "SQLitePCLRaw.core": "3.0.5" } }, "Microsoft.EntityFrameworkCore": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vY3931PYPIDBbKovGHbACmpOWvURvKNyRXfCjMh5yLW+FH6vLWeqUu2xzSCRo4Oz4tgx9GYpd0JlV5LDyAoQdg==", + "resolved": "11.0.0", + "contentHash": "1zGKYhZMHG9gIfC89cC2QKM6DpNotDglm+UzYEV9dAWyLwJI8kLx+yfjAQVpC83iUzvr9y+1HJ0HZ8cOaosBXA==", "dependencies": { - "Microsoft.EntityFrameworkCore.Abstractions": "10.0.14", - "Microsoft.EntityFrameworkCore.Analyzers": "10.0.14", - "Microsoft.Extensions.Caching.Memory": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14" + "Microsoft.EntityFrameworkCore.Abstractions": "[11.0.0, 12.0.0-a)", + "Microsoft.EntityFrameworkCore.Analyzers": "[11.0.0, 12.0.0-a)", + "Microsoft.Extensions.Caching.Memory": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0" } }, "Microsoft.EntityFrameworkCore.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "/SaznoTTFfKzxYEbCPAwwKBR3XT92DZgH4jJ3/cqs2skP3o2D+TL6i9Aaj+8Azwtu6/sRd0ve4P2mN12nfVmCw==" + "resolved": "11.0.0", + "contentHash": "iL0D3Dohk6bNYIHSM3VhvDXrJ+WXs7yMBVv+4L1ozxbsDmohG0T3ogd0mLgWBofu49BHGOgfFKgSGLsOirsjoQ==" }, "Microsoft.EntityFrameworkCore.Analyzers": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "gaANlGNTxkgODX2eeVT8jjd3AmlFilQV4DFf8qoW30+wUCm2o4N7nEHtZvnHIwfhaJni2DqcjE47Au7tC0Q5jA==" + "resolved": "11.0.0", + "contentHash": "R7QxcmtQLP5np732En6eyzv2DjKevbrRxUUY9jPRQwuLzOSbyDowE5l0KyqdEEySvdHbrdRILg99FlaJTwcPbQ==" }, "Microsoft.EntityFrameworkCore.Relational": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "Ut0kgtfoKX9QElQVEXSEAgdQc79jISWStVWSOhfPDDHNSKMwFzSXG3gtdYFTAbsBoV+8NtXdVaj4xwdqeky8UA==", + "resolved": "11.0.0", + "contentHash": "yGS+J269mYUl8V17rHWaeFDySoUnGdiugIzszlNZr0F2+JirFatQyw2s2He92wyYIuy/Y3Yv3QLdq/HdTSj7cA==", "dependencies": { - "Microsoft.EntityFrameworkCore": "10.0.14", - "Microsoft.Extensions.Caching.Memory": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14" + "Microsoft.EntityFrameworkCore": "[11.0.0, 12.0.0-a)", + "Microsoft.Extensions.Caching.Memory": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0" } }, "Microsoft.EntityFrameworkCore.Sqlite.Core": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "08VGlMQ9WbK869as9Ho+VZQbM5Qu6zdorgeh6ShVwQgLYgfUBiaIm02T7spfW7Xc1MBHCvclwPgGWpvx5BYGXQ==", - "dependencies": { - "Microsoft.Data.Sqlite.Core": "10.0.14", - "Microsoft.EntityFrameworkCore.Relational": "10.0.14", - "Microsoft.Extensions.Caching.Memory": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyModel": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "SQLitePCLRaw.core": "2.1.13" - } - }, - "Microsoft.Extensions.Caching.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "enSfqeENnSjGH3YAYKsCtsa5ob0HNiwF2nwJiC2yhilNXTlD/0prxrgPkWjoAp9svJcu04AiEIKtdh/A54P2fA==", + "resolved": "11.0.0", + "contentHash": "7u0jhtUY4GXr2MRsvSzemUpgf2znOCf8+3VLYxYNthIU5rIKk5Y+9EvS+yAlLIBL2218LeahsHYKA0MWKBYo5Q==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Data.Sqlite.Core": "[11.0.0, 12.0.0-a)", + "Microsoft.EntityFrameworkCore.Relational": "[11.0.0, 12.0.0-a)", + "Microsoft.Extensions.Caching.Memory": "11.0.0", + "Microsoft.Extensions.DependencyModel": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "SQLitePCLRaw.core": "3.0.5" } }, "Microsoft.Extensions.Caching.Memory": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "AxK3kyD6sWNpYKf+66huE7wHHjgKHONlD1dUaD/CxjZVBLEpH5N4jaqgszTcZvaM9/XVeXF28K3E0wsTyTA4Xg==", - "dependencies": { - "Microsoft.Extensions.Caching.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" - } + "resolved": "11.0.0", + "contentHash": "w0nn5qRLxZC2T3sSmXj5PhrBFpGFCSFxg7E/zBi4lne0wZcZPY8of3qQDowqGobMZ3PW5qJnM1Q8fmGjL2B6Iw==" }, "Microsoft.Extensions.Configuration.Binder": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0" } }, "Microsoft.Extensions.Configuration.EnvironmentVariables": { @@ -236,106 +202,51 @@ "resolved": "10.0.0", "contentHash": "TmFegsI/uCdwMBD4yKpmO+OkjVNHQL49Dh/ep83NI5rPUEoBK9OdsJo1zURc1A2FuS/R/Pos3wsTjlyLnguBLA==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.0" + "Microsoft.Extensions.Configuration": "10.0.0" } }, "Microsoft.Extensions.Configuration.FileExtensions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "NBIfm8vWNi3UJ9OI9thvREJeV6KzEdPjQ4ONdH+yPWutGBpVnwLbXiEqdEFaGAFYpAluGCfyCwKFgH9pd2scfw==", + "resolved": "11.0.0", + "contentHash": "ViBZDt2Y7TfVIxiWG5HKfP1KHTzsxn7a31ikZSg/1mdOfGyGAPj278v63NOU+n4UqvaOR43t9MOCUfadSohjQA==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.14", - "Microsoft.Extensions.FileProviders.Physical": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.FileProviders.Physical": "11.0.0" } }, "Microsoft.Extensions.Configuration.Json": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4Tn8eNg85x+ICDN4OLC7Dl/xvZNREZIf7VSOAdT4Q4KYf5Ip1zAk+0BAx8BsRTomgEpCYV4kKsNNnP/ZXUbQkw==", + "resolved": "11.0.0", + "contentHash": "WsNcEnVlq43lXBHAXtQg1b7job819SUf9BPtJrq44vhthL9Ijl2mkRBx5L3hIU1p2AN+wiRg47yhYj+vQxEgeQ==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.FileExtensions": "10.0.14", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.FileExtensions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.DependencyInjection.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==" }, "Microsoft.Extensions.DependencyModel": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "N8OcqM0370wSXMJ3ZxO66rSElHrIgxvpfUn0vV7zRj7NvKo0nfwgEoTmC3Yz3860o60IaQ4KIPyeLIGX9EeNWA==" - }, - "Microsoft.Extensions.Diagnostics.Abstractions": { - "type": "Transitive", - "resolved": "10.0.3", - "contentHash": "mQiTzAj7PIJ2A9YXR5QhgulS1fTWhmQc3ckd1Mrf3hKW07d03fBDqx8vVaFw+cRTebDOeB6pNqdWdnRxsi1hBA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.3", - "Microsoft.Extensions.Options": "10.0.3" - } - }, - "Microsoft.Extensions.FileProviders.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "rAqf2Em2ZjLqNbcLJlboQnXNyJP604F960TsCKNiP00Ur6ExIc1mcwmNb8L2eTRT8RC8UKx/GjecoWcW2Sj7bw==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" - } + "resolved": "11.0.0", + "contentHash": "K6M9zulTQ3OU0myKAcBb/Gbfw/aTKa3wlxyDhwfOmT7Wavoxe0lzAkeDjS5+/1dqcgGDUZtIykJIo3T4W7zKbQ==" }, "Microsoft.Extensions.FileProviders.Physical": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "dcp6eCIk6ZpE3CTNmIna0ifgxsPel/MtOc23/Y/AJlD9SZZr7bhlKK2DAXYlrz81yMkMi6el/LHHUFKCZ3ufuQ==", - "dependencies": { - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.14", - "Microsoft.Extensions.FileSystemGlobbing": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Hosting.Abstractions": { - "type": "Transitive", - "resolved": "10.0.3", - "contentHash": "GdMpC10Jf6poxSvUJ4lgYpJ5F/kJeaAoJmrPufjBoPYyCTKKY5Dyl0rZA+LBNvFqTq1cZa/lhlptlUhNvU6xrg==", + "resolved": "11.0.0", + "contentHash": "lHezhjI8zoTpltXwNy6QMr4/6lIhbXsAYZnCrgRDNNzMHCKvh+x95mkBVXLMzs8axrw7J5Cy21K8lM5YHCfgAw==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.3", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.3", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.3", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.3", - "Microsoft.Extensions.Logging.Abstractions": "10.0.3" + "Microsoft.Extensions.FileSystemGlobbing": "11.0.0" } }, "Microsoft.Extensions.Logging": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection": "11.0.0" } }, "Microsoft.Extensions.Logging.Configuration": { @@ -344,41 +255,19 @@ "contentHash": "j8zcwhS6bYB6FEfaY3nYSgHdpiL2T+/V3xjpHtslVAegyI1JUbB9yAt/BFdvZdsNbY0Udm4xFtvfT/hUwcOOOg==", "dependencies": { "Microsoft.Extensions.Configuration": "10.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.0", "Microsoft.Extensions.Configuration.Binder": "10.0.0", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0", "Microsoft.Extensions.Logging": "10.0.0", - "Microsoft.Extensions.Logging.Abstractions": "10.0.0", - "Microsoft.Extensions.Options": "10.0.0", "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.0" } }, - "Microsoft.Extensions.Options": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, "Microsoft.Extensions.Options.ConfigurationExtensions": { "type": "Transitive", "resolved": "10.0.0", "contentHash": "tL9cSl3maS5FPzp/3MtlZI21ExWhni0nnUCF8HY4npTsINw45n9SNDbkKXBMtFyUFGSsQep25fHIDN4f/Vp3AQ==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.0", - "Microsoft.Extensions.Configuration.Binder": "10.0.0", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0", - "Microsoft.Extensions.Options": "10.0.0", - "Microsoft.Extensions.Primitives": "10.0.0" + "Microsoft.Extensions.Configuration.Binder": "10.0.0" } }, - "Microsoft.Extensions.Primitives": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" - }, "Microsoft.Identity.Client": { "type": "Transitive", "resolved": "4.83.1", @@ -431,7 +320,6 @@ "contentHash": "PUowLq8gqICt+oepHWmKBOJmnVmWoQ5dOVn2CgwFMBZZOAEMHgCQLWs8ONYdsjAyjhDHaFy+AAx0OMG/oV06Zw==", "dependencies": { "Microsoft.Bcl.Cryptography": "10.0.2", - "Microsoft.Extensions.Logging.Abstractions": "8.0.0", "Microsoft.IdentityModel.Logging": "8.23.0" } }, @@ -453,7 +341,6 @@ "resolved": "1.20.1", "contentHash": "eDzDY/jTBqRytkYECmVKF7ZP5sKmCIqv1SSnA5BSWltIIvc3931TOMRyCW1qCGNIgmtldtJhISnsmFNxOCfauQ==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0", "OpenTelemetry.Api": "1.20.1" } }, @@ -467,31 +354,39 @@ "resolved": "2.1.5", "contentHash": "1pNSpfXxNAgCQ9sacKKpEWO2DxTefoLEjw0v1nWMvyJScUWacoHvjXr4LfcUkhm0qYgNYripFFiUeEzW4tdXIQ==" }, + "SQLite": { + "type": "Transitive", + "resolved": "3.53.4", + "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" + }, "SQLitePCLRaw.bundle_e_sqlite3": { "type": "Transitive", - "resolved": "2.1.13", - "contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==", + "resolved": "3.0.5", + "contentHash": "SW8iASIyWMrLzqabUHYQRvALhvD4ylSBsj4PgEVGwc36kQjc9xT5kSV/XQ9rU7nIpBWD+LPyX3Hlw5FzyUzGeQ==", "dependencies": { - "SQLitePCLRaw.lib.e_sqlite3": "2.1.13", - "SQLitePCLRaw.provider.e_sqlite3": "2.1.13" + "SQLite": "3.53.4", + "SQLitePCLRaw.config.e_sqlite3": "3.0.5" } }, - "SQLitePCLRaw.core": { + "SQLitePCLRaw.config.e_sqlite3": { "type": "Transitive", - "resolved": "2.1.13", - "contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q==" + "resolved": "3.0.5", + "contentHash": "aSk8WE5tF2MybESMgtZAEyMVCAWA0nBqOMc48HFoa9UoSdtm3goDXVzNRnefeKIwE6bV9NaNXptn1F9ReMQI0Q==", + "dependencies": { + "SQLitePCLRaw.provider.e_sqlite3": "3.0.5" + } }, - "SQLitePCLRaw.lib.e_sqlite3": { + "SQLitePCLRaw.core": { "type": "Transitive", - "resolved": "2.1.13", - "contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A==" + "resolved": "3.0.5", + "contentHash": "k81AYXXRCw3Zj8rOhyBoCsx/U97KYDFI2CSKr/ijl5BwpsW/hX/4kBiDmerFaoust8nxBwa0IHQFw8MmSHRtnQ==" }, "SQLitePCLRaw.provider.e_sqlite3": { "type": "Transitive", - "resolved": "2.1.13", - "contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==", + "resolved": "3.0.5", + "contentHash": "um8YSWduhhuskTG2bHfZrBqMNQOydfU8pcseT+cu5RivOGyoUbCrGXxgoRNTmRYw2VbMWnEZVVFcneZT/5dsBg==", "dependencies": { - "SQLitePCLRaw.core": "2.1.13" + "SQLitePCLRaw.core": "3.0.5" } }, "System.ClientModel": { @@ -499,9 +394,6 @@ "resolved": "1.10.0", "contentHash": "lBEWs54F5Y5pZ9hC+8z4S/X76957ex+DPk7WecRHlbIHtrPfbRMMlOgI3iDn4Jpb3bSxvBnKaaHoD59auFjlBA==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.3", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.3", - "Microsoft.Extensions.Logging.Abstractions": "10.0.3", "System.Memory.Data": "10.0.3" } }, @@ -524,12 +416,11 @@ "type": "Project", "dependencies": { "Markdig": "[1.6.0, )", - "Microsoft.EntityFrameworkCore.Sqlite": "[10.0.14, )", - "Microsoft.Extensions.Configuration": "[10.0.14, )", - "Microsoft.Extensions.Configuration.Binder": "[10.0.14, )", - "Microsoft.Extensions.Configuration.Json": "[10.0.14, )", - "Microsoft.Extensions.FileSystemGlobbing": "[10.0.14, )", - "Microsoft.Extensions.Logging.Abstractions": "[10.0.14, )", + "Microsoft.EntityFrameworkCore.Sqlite": "[11.0.0, )", + "Microsoft.Extensions.Configuration": "[11.0.0, )", + "Microsoft.Extensions.Configuration.Binder": "[11.0.0, )", + "Microsoft.Extensions.Configuration.Json": "[11.0.0, )", + "Microsoft.Extensions.FileSystemGlobbing": "[11.0.0, )", "Microsoft.OpenApi": "[3.11.0, )", "Microsoft.OpenApi.YamlReader": "[3.11.0, )", "Newtonsoft.Json.Schema": "[4.0.2, )", diff --git a/DevProxy.Proxy.Kestrel.Tests/DevProxy.Proxy.Kestrel.Tests.csproj b/DevProxy.Proxy.Kestrel.Tests/DevProxy.Proxy.Kestrel.Tests.csproj index 197fb541a..365f00df3 100644 --- a/DevProxy.Proxy.Kestrel.Tests/DevProxy.Proxy.Kestrel.Tests.csproj +++ b/DevProxy.Proxy.Kestrel.Tests/DevProxy.Proxy.Kestrel.Tests.csproj @@ -1,7 +1,7 @@ - net10.0 + net11.0 enable enable false diff --git a/DevProxy.Proxy.Kestrel/DevProxy.Proxy.Kestrel.csproj b/DevProxy.Proxy.Kestrel/DevProxy.Proxy.Kestrel.csproj index 8ff151f71..cba7191ee 100644 --- a/DevProxy.Proxy.Kestrel/DevProxy.Proxy.Kestrel.csproj +++ b/DevProxy.Proxy.Kestrel/DevProxy.Proxy.Kestrel.csproj @@ -1,7 +1,7 @@ - net10.0 + net11.0 DevProxy.Proxy.Kestrel enable enable diff --git a/DevProxy.Proxy.Kestrel/Internal/ConnectAuthorityParser.cs b/DevProxy.Proxy.Kestrel/Internal/ConnectAuthorityParser.cs index 0929243d3..7399bf49f 100644 --- a/DevProxy.Proxy.Kestrel/Internal/ConnectAuthorityParser.cs +++ b/DevProxy.Proxy.Kestrel/Internal/ConnectAuthorityParser.cs @@ -88,7 +88,7 @@ public static bool TryParse(string authority, int defaultPort, out ConnectAuthor else { var firstColon = authority.IndexOf(':', StringComparison.Ordinal); - var lastColon = authority.LastIndexOf(':'); + var lastColon = authority.LastIndexOf(':', StringComparison.Ordinal); if (firstColon != lastColon) { return false; // multiple colons without brackets (bare IPv6 / garbage) diff --git a/DevProxy.Proxy.Kestrel/packages.lock.json b/DevProxy.Proxy.Kestrel/packages.lock.json index 2d92c82f8..d2fe8c6b9 100644 --- a/DevProxy.Proxy.Kestrel/packages.lock.json +++ b/DevProxy.Proxy.Kestrel/packages.lock.json @@ -1,7 +1,7 @@ { "version": 1, "dependencies": { - "net10.0": { + "net11.0": { "Markdig": { "type": "Transitive", "resolved": "1.6.0", @@ -9,65 +9,65 @@ }, "Microsoft.Data.Sqlite.Core": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1p9rO3Q2X/L/9YrYog3vaDzi8u+WZfJCOkDYoHqmofqYP0DLPLPyZcS2Rnh/79JXAodgbs1AgsaNwLpIvC3Xew==", + "resolved": "11.0.0", + "contentHash": "aWaF2LDjuFZwE9UsAGRYGNyS48xqaXoKPAjwpJI85fsaM/43s5NTRnl4xtqbTGKq8of2M/W8mo7DJk7v4zzHGQ==", "dependencies": { - "SQLitePCLRaw.core": "2.1.13" + "SQLitePCLRaw.core": "3.0.5" } }, "Microsoft.EntityFrameworkCore": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vY3931PYPIDBbKovGHbACmpOWvURvKNyRXfCjMh5yLW+FH6vLWeqUu2xzSCRo4Oz4tgx9GYpd0JlV5LDyAoQdg==", + "resolved": "11.0.0", + "contentHash": "1zGKYhZMHG9gIfC89cC2QKM6DpNotDglm+UzYEV9dAWyLwJI8kLx+yfjAQVpC83iUzvr9y+1HJ0HZ8cOaosBXA==", "dependencies": { - "Microsoft.EntityFrameworkCore.Abstractions": "10.0.14", - "Microsoft.EntityFrameworkCore.Analyzers": "10.0.14" + "Microsoft.EntityFrameworkCore.Abstractions": "[11.0.0, 12.0.0-a)", + "Microsoft.EntityFrameworkCore.Analyzers": "[11.0.0, 12.0.0-a)" } }, "Microsoft.EntityFrameworkCore.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "/SaznoTTFfKzxYEbCPAwwKBR3XT92DZgH4jJ3/cqs2skP3o2D+TL6i9Aaj+8Azwtu6/sRd0ve4P2mN12nfVmCw==" + "resolved": "11.0.0", + "contentHash": "iL0D3Dohk6bNYIHSM3VhvDXrJ+WXs7yMBVv+4L1ozxbsDmohG0T3ogd0mLgWBofu49BHGOgfFKgSGLsOirsjoQ==" }, "Microsoft.EntityFrameworkCore.Analyzers": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "gaANlGNTxkgODX2eeVT8jjd3AmlFilQV4DFf8qoW30+wUCm2o4N7nEHtZvnHIwfhaJni2DqcjE47Au7tC0Q5jA==" + "resolved": "11.0.0", + "contentHash": "R7QxcmtQLP5np732En6eyzv2DjKevbrRxUUY9jPRQwuLzOSbyDowE5l0KyqdEEySvdHbrdRILg99FlaJTwcPbQ==" }, "Microsoft.EntityFrameworkCore.Relational": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "Ut0kgtfoKX9QElQVEXSEAgdQc79jISWStVWSOhfPDDHNSKMwFzSXG3gtdYFTAbsBoV+8NtXdVaj4xwdqeky8UA==", + "resolved": "11.0.0", + "contentHash": "yGS+J269mYUl8V17rHWaeFDySoUnGdiugIzszlNZr0F2+JirFatQyw2s2He92wyYIuy/Y3Yv3QLdq/HdTSj7cA==", "dependencies": { - "Microsoft.EntityFrameworkCore": "10.0.14" + "Microsoft.EntityFrameworkCore": "[11.0.0, 12.0.0-a)" } }, "Microsoft.EntityFrameworkCore.Sqlite": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "lxrwnVwvlIfQD4IF4WUVupE6Qxfj3MfFftDVwo7tsGAWCKLL8Ttb8UjIt+gE4e9nRlH7EgdC6TrsArFGnNYREw==", + "resolved": "11.0.0", + "contentHash": "12olimxsnuTo+9jsQvbS9fF/FXUhW7AHaXFcK/TgpND3Ki53CBvXnvT+AnPnk6d6f02D5NBdmBcZzfAynBgkRw==", "dependencies": { - "Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.14", - "Microsoft.Extensions.DependencyModel": "10.0.14", - "SQLitePCLRaw.bundle_e_sqlite3": "2.1.13", - "SQLitePCLRaw.core": "2.1.13" + "Microsoft.EntityFrameworkCore.Sqlite.Core": "[11.0.0, 12.0.0-a)", + "Microsoft.Extensions.DependencyModel": "11.0.0", + "SQLitePCLRaw.bundle_e_sqlite3": "3.0.5", + "SQLitePCLRaw.core": "3.0.5" } }, "Microsoft.EntityFrameworkCore.Sqlite.Core": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "08VGlMQ9WbK869as9Ho+VZQbM5Qu6zdorgeh6ShVwQgLYgfUBiaIm02T7spfW7Xc1MBHCvclwPgGWpvx5BYGXQ==", + "resolved": "11.0.0", + "contentHash": "7u0jhtUY4GXr2MRsvSzemUpgf2znOCf8+3VLYxYNthIU5rIKk5Y+9EvS+yAlLIBL2218LeahsHYKA0MWKBYo5Q==", "dependencies": { - "Microsoft.Data.Sqlite.Core": "10.0.14", - "Microsoft.EntityFrameworkCore.Relational": "10.0.14", - "Microsoft.Extensions.DependencyModel": "10.0.14", - "SQLitePCLRaw.core": "2.1.13" + "Microsoft.Data.Sqlite.Core": "[11.0.0, 12.0.0-a)", + "Microsoft.EntityFrameworkCore.Relational": "[11.0.0, 12.0.0-a)", + "Microsoft.Extensions.DependencyModel": "11.0.0", + "SQLitePCLRaw.core": "3.0.5" } }, "Microsoft.Extensions.DependencyModel": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "N8OcqM0370wSXMJ3ZxO66rSElHrIgxvpfUn0vV7zRj7NvKo0nfwgEoTmC3Yz3860o60IaQ4KIPyeLIGX9EeNWA==" + "resolved": "11.0.0", + "contentHash": "K6M9zulTQ3OU0myKAcBb/Gbfw/aTKa3wlxyDhwfOmT7Wavoxe0lzAkeDjS5+/1dqcgGDUZtIykJIo3T4W7zKbQ==" }, "Microsoft.OpenApi": { "type": "Transitive", @@ -106,31 +106,39 @@ "resolved": "2.1.5", "contentHash": "1pNSpfXxNAgCQ9sacKKpEWO2DxTefoLEjw0v1nWMvyJScUWacoHvjXr4LfcUkhm0qYgNYripFFiUeEzW4tdXIQ==" }, + "SQLite": { + "type": "Transitive", + "resolved": "3.53.4", + "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" + }, "SQLitePCLRaw.bundle_e_sqlite3": { "type": "Transitive", - "resolved": "2.1.13", - "contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==", + "resolved": "3.0.5", + "contentHash": "SW8iASIyWMrLzqabUHYQRvALhvD4ylSBsj4PgEVGwc36kQjc9xT5kSV/XQ9rU7nIpBWD+LPyX3Hlw5FzyUzGeQ==", "dependencies": { - "SQLitePCLRaw.lib.e_sqlite3": "2.1.13", - "SQLitePCLRaw.provider.e_sqlite3": "2.1.13" + "SQLite": "3.53.4", + "SQLitePCLRaw.config.e_sqlite3": "3.0.5" } }, - "SQLitePCLRaw.core": { + "SQLitePCLRaw.config.e_sqlite3": { "type": "Transitive", - "resolved": "2.1.13", - "contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q==" + "resolved": "3.0.5", + "contentHash": "aSk8WE5tF2MybESMgtZAEyMVCAWA0nBqOMc48HFoa9UoSdtm3goDXVzNRnefeKIwE6bV9NaNXptn1F9ReMQI0Q==", + "dependencies": { + "SQLitePCLRaw.provider.e_sqlite3": "3.0.5" + } }, - "SQLitePCLRaw.lib.e_sqlite3": { + "SQLitePCLRaw.core": { "type": "Transitive", - "resolved": "2.1.13", - "contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A==" + "resolved": "3.0.5", + "contentHash": "k81AYXXRCw3Zj8rOhyBoCsx/U97KYDFI2CSKr/ijl5BwpsW/hX/4kBiDmerFaoust8nxBwa0IHQFw8MmSHRtnQ==" }, "SQLitePCLRaw.provider.e_sqlite3": { "type": "Transitive", - "resolved": "2.1.13", - "contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==", + "resolved": "3.0.5", + "contentHash": "um8YSWduhhuskTG2bHfZrBqMNQOydfU8pcseT+cu5RivOGyoUbCrGXxgoRNTmRYw2VbMWnEZVVFcneZT/5dsBg==", "dependencies": { - "SQLitePCLRaw.core": "2.1.13" + "SQLitePCLRaw.core": "3.0.5" } }, "System.CommandLine": { @@ -147,7 +155,7 @@ "type": "Project", "dependencies": { "Markdig": "[1.6.0, )", - "Microsoft.EntityFrameworkCore.Sqlite": "[10.0.14, )", + "Microsoft.EntityFrameworkCore.Sqlite": "[11.0.0, )", "Microsoft.OpenApi": "[3.11.0, )", "Microsoft.OpenApi.YamlReader": "[3.11.0, )", "Newtonsoft.Json.Schema": "[4.0.2, )", diff --git a/DevProxy.Tests/DevProxy.Tests.csproj b/DevProxy.Tests/DevProxy.Tests.csproj index c2295da3f..8e701be4a 100644 --- a/DevProxy.Tests/DevProxy.Tests.csproj +++ b/DevProxy.Tests/DevProxy.Tests.csproj @@ -1,7 +1,7 @@ - net10.0 + net11.0 enable enable false diff --git a/DevProxy/Commands/ApiCommand.cs b/DevProxy/Commands/ApiCommand.cs index 78119ddce..8fb1295b2 100644 --- a/DevProxy/Commands/ApiCommand.cs +++ b/DevProxy/Commands/ApiCommand.cs @@ -80,10 +80,10 @@ private static async Task PrintTokenAsync(int? pid, OutputFormat outputForm var states = await StateManager.LoadAllStatesAsync(cancellationToken); if (states.Count > 1) { - await Console.Error.WriteLineAsync("Multiple Dev Proxy instances are running. Select one with devproxy api token --pid :"); + await Console.Error.WriteLineAsync("Multiple Dev Proxy instances are running. Select one with devproxy api token --pid :", cancellationToken); foreach (var instance in states.OrderBy(instance => instance.Pid)) { - await Console.Error.WriteLineAsync($" {instance.Pid}: {instance.ApiUrl}"); + await Console.Error.WriteLineAsync($" {instance.Pid}: {instance.ApiUrl}", cancellationToken); } return 1; } @@ -95,7 +95,7 @@ private static async Task PrintTokenAsync(int? pid, OutputFormat outputForm { await Console.Error.WriteLineAsync(pid.HasValue ? $"No running Dev Proxy instance with PID {pid.Value}. Run devproxy status to find an instance." - : "Dev Proxy is not running. Start it with devproxy first."); + : "Dev Proxy is not running. Start it with devproxy first.", cancellationToken); return 1; } @@ -112,7 +112,7 @@ await Console.Error.WriteLineAsync(pid.HasValue } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { - await Console.Error.WriteLineAsync("Unable to read the API token. Restart the selected Dev Proxy instance using the current version and the same user account."); + await Console.Error.WriteLineAsync("Unable to read the API token. Restart the selected Dev Proxy instance using the current version and the same user account.", cancellationToken); return 1; } } diff --git a/DevProxy/Commands/ConfigCommand.cs b/DevProxy/Commands/ConfigCommand.cs index 90bf29ed3..d5113eb9a 100644 --- a/DevProxy/Commands/ConfigCommand.cs +++ b/DevProxy/Commands/ConfigCommand.cs @@ -1,897 +1,897 @@ -// 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 DevProxy.Abstractions.Plugins; -using DevProxy.Abstractions.Proxy; -using DevProxy.Abstractions.Utils; -using DevProxy.Logging; -using DevProxy.Plugins; -using System.CommandLine; -using System.CommandLine.Parsing; -using System.Diagnostics; -using System.Net.Http.Headers; -using System.Reflection; -using System.Text.Json; -using System.Text.RegularExpressions; -using YamlDotNet.Core; - -namespace DevProxy.Commands; - -sealed class ProxyConfigInfo -{ - public IList ConfigFiles { get; set; } = []; - public IList MockFiles { get; set; } = []; -} - -sealed class GitHubTreeResponse -{ - public GitHubTreeItem[] Tree { get; set; } = []; - public bool Truncated { get; set; } -} - -sealed class GitHubTreeItem -{ - public string Path { get; set; } = string.Empty; - public string Type { get; set; } = string.Empty; -} - -sealed class ConfigCommand : Command -{ - private enum ConfigFileFormat - { - Json, - Yaml - } - - private readonly ILogger _logger; - private readonly IProxyConfiguration _proxyConfiguration; - private readonly HttpClient _httpClient; - private const string ConfigTemplatesFolder = "config-templates"; - private static readonly string[] configFilePatterns = ["*.json", "*.yaml", "*.yml"]; - - public ConfigCommand( - HttpClient httpClient, - IProxyConfiguration proxyConfiguration, - ILogger logger) : - base("config", "Manage Dev Proxy configs") - { - _proxyConfiguration = proxyConfiguration; - _logger = logger; - _httpClient = httpClient; - _httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("dev-proxy", ProxyUtils.ProductVersion)); - ConfigureCommand(); - } - - /// - /// Runs config validation standalone, without requiring the full DI container. - /// Used when the proxy is invoked with 'config validate' to allow validating - /// even broken config files. - /// - internal static async Task RunValidateStandaloneAsync(string[] args) - { - string? configFile = null; - var isJsonOutput = false; - - for (var i = 0; i < args.Length; i++) - { - if ((string.Equals(args[i], "--config-file", StringComparison.OrdinalIgnoreCase) || - string.Equals(args[i], "-c", StringComparison.OrdinalIgnoreCase)) && - i + 1 < args.Length) - { - configFile = args[i + 1]; - i++; - } - else if (string.Equals(args[i], DevProxyCommand.OutputOptionName, StringComparison.OrdinalIgnoreCase) && - i + 1 < args.Length) - { - isJsonOutput = string.Equals(args[i + 1], "json", StringComparison.OrdinalIgnoreCase); - i++; - } - } - - using var httpClient = new HttpClient(); - httpClient.DefaultRequestHeaders.UserAgent.Add( - new ProductInfoHeaderValue("dev-proxy", ProxyUtils.ProductVersion)); - - var formatterName = isJsonOutput - ? JsonConsoleFormatter.FormatterName - : ProxyConsoleFormatter.DefaultCategoryName; - - using var loggerFactory = LoggerFactory.Create(builder => - { - _ = builder - .SetMinimumLevel(LogLevel.Information) - .AddConsole(consoleOptions => - { - consoleOptions.FormatterName = formatterName; - consoleOptions.LogToStandardErrorThreshold = LogLevel.Warning; - }) - .AddConsoleFormatter(formatterOptions => - { - formatterOptions.IncludeScopes = false; - formatterOptions.ShowSkipMessages = true; - formatterOptions.ShowTimestamps = false; - }) - .AddConsoleFormatter(formatterOptions => - { - formatterOptions.IncludeScopes = false; - formatterOptions.ShowSkipMessages = true; - formatterOptions.ShowTimestamps = false; - }); - }); - var logger = loggerFactory.CreateLogger(); - - return await ValidateConfigCoreAsync(configFile, isJsonOutput, httpClient, logger, CancellationToken.None); - } - - private void ConfigureCommand() - { - var configGetCommand = new Command("get", "Download the specified config from the Sample Solution Gallery"); - var configIdArgument = new Argument("config-id") - { - Description = "The ID of the config to download" - }; - configGetCommand.Add(configIdArgument); - configGetCommand.SetAction(async (parseResult) => - { - var configId = parseResult.GetValue(configIdArgument); - var outputFormat = parseResult.GetValueOrDefault(DevProxyCommand.OutputOptionName) ?? OutputFormat.Text; - return configId is null ? 1 : await DownloadConfigAsync(configId, outputFormat); - }); - - var configNewCommand = new Command("new", "Create new Dev Proxy configuration file"); - var nameArgument = new Argument("name") - { - Arity = ArgumentArity.ZeroOrOne, - Description = "Name of the configuration file. Defaults to devproxyrc.json (or devproxyrc.yaml with --format yaml)." - }; - var formatOption = new Option("--format") - { - Description = "Configuration format to use (json or yaml)" - }; - configNewCommand.Add(nameArgument); - configNewCommand.Add(formatOption); - configNewCommand.SetAction(async (parseResult) => - { - var format = parseResult.GetValue(formatOption); - var name = parseResult.GetValue(nameArgument) ?? GetDefaultConfigFileName(format); - var outputFormat = parseResult.GetValueOrDefault(DevProxyCommand.OutputOptionName) ?? OutputFormat.Text; - return await CreateConfigFileAsync(name, format, outputFormat); - }); - - var configOpenCommand = new Command("open", "Open devproxyrc.json"); - configOpenCommand.SetAction(parseResult => - { - var cfgPsi = new ProcessStartInfo(_proxyConfiguration.ConfigFile) - { - UseShellExecute = true - }; - _ = Process.Start(cfgPsi); - }); - - var configValidateCommand = new Command("validate", "Validate a Dev Proxy configuration file"); - var validateConfigFileOption = new Option("--config-file", "-c") - { - Description = "The path to the configuration file to validate", - HelpName = "config-file" - }; - configValidateCommand.Add(validateConfigFileOption); - configValidateCommand.SetAction(async (parseResult, cancellationToken) => - { - var configFile = parseResult.GetValue(validateConfigFileOption); - var output = parseResult.GetValueOrDefault(DevProxyCommand.OutputOptionName); - var isJsonOutput = output == OutputFormat.Json; - return await ValidateConfigCoreAsync(configFile, isJsonOutput, _httpClient, _logger, cancellationToken); - }); - - this.AddCommands(new List - { - configGetCommand, - configNewCommand, - configOpenCommand, - configValidateCommand - }.OrderByName()); - - HelpExamples.Add(this, [ - "devproxy config new Create default devproxyrc.json", - "devproxy config new --format yaml Create default devproxyrc.yaml", - "devproxy config new myconfig.json Create named config file", - "devproxy config get Download config from gallery", - "devproxy config open Open config in default editor", - ]); - } - - private async Task DownloadConfigAsync(string configId, OutputFormat outputFormat) - { - try - { - var dataFolder = ProxyUtils.DataFolder; - - var configFolderPath = Path.Combine(dataFolder, "configs"); - _logger.LogDebug("Checking if config folder {ConfigFolderPath} exists...", configFolderPath); - if (!Directory.Exists(configFolderPath)) - { - _logger.LogDebug("Config folder not found, creating it..."); - _ = Directory.CreateDirectory(configFolderPath); - _logger.LogDebug("Config folder created"); - } - - _logger.LogDebug("Getting target folder path for config {ConfigId}...", configId); - var targetFolderPath = GetTargetFolderPath(dataFolder, configId); - _logger.LogDebug("Creating target folder {TargetFolderPath}...", targetFolderPath); - _ = Directory.CreateDirectory(targetFolderPath); - - if (outputFormat == OutputFormat.Text) - { - _logger.LogInformation("Downloading config {ConfigId}...", configId); - } - - var sampleFiles = await GetFilesToDownloadAsync(configId); - if (sampleFiles.Length == 0) - { - if (outputFormat == OutputFormat.Text) - { - _logger.LogError("Config {ConfigId} not found in the samples repo", configId); - } - return 1; - } - foreach (var sampleFile in sampleFiles) - { - await DownloadFileAsync(sampleFile, targetFolderPath, configId); - } - - var configInfo = GetConfigInfo(targetFolderPath); - - if (outputFormat == OutputFormat.Json) - { - var json = JsonSerializer.Serialize(new - { - configId, - path = targetFolderPath, - configFiles = configInfo.ConfigFiles, - mockFiles = configInfo.MockFiles - }, ProxyUtils.JsonSerializerOptions); - _logger.LogStructuredOutput(json); - return 0; - } - - _logger.LogInformation("Config saved in {TargetFolderPath}\r\n", targetFolderPath); - - if (configInfo.ConfigFiles.Count == 0 && configInfo.MockFiles.Count == 0) - { - return 0; - } - - if (configInfo.ConfigFiles.Count > 0) - { - _logger.LogInformation("To start Dev Proxy with the config, run:"); - foreach (var configFile in configInfo.ConfigFiles) - { - if (_logger.IsEnabled(LogLevel.Information)) - { - _logger.LogInformation(" devproxy --config-file \"{ConfigFile}\"", configFile.Replace(dataFolder, "~dataFolder", StringComparison.OrdinalIgnoreCase)); - } - } - } - else - { - _logger.LogInformation("To start Dev Proxy with the mock file, enable the MockResponsePlugin or GraphMockResponsePlugin and run:"); - foreach (var mockFile in configInfo.MockFiles) - { - if (_logger.IsEnabled(LogLevel.Information)) - { - _logger.LogInformation(" devproxy --mock-file \"{MockFile}\"", mockFile.Replace(dataFolder, "~dataFolder", StringComparison.OrdinalIgnoreCase)); - } - } - } - - return 0; - } - catch (Exception ex) - { - if (outputFormat == OutputFormat.Text) - { - _logger.LogError(ex, "Error downloading config"); - } - return 1; - } - } - - /// - /// Returns the list of files that can be used as entry points for the config - /// - /// - /// A sample in the gallery can have multiple entry points. It can - /// contain multiple config files or no config files and a multiple - /// mock files. This method returns the list of files that Dev Proxy - /// can use as entry points. - /// If there's one or more config files, it'll return an array of - /// these file names. If there are no proxy configs, it'll return - /// an array of all the mock files. If there are no mocks, it'll return - /// an empty array indicating that there's no entry point. - /// Files in the .devproxy subfolder are listed before files in the - /// root folder. - /// - /// Full path to the folder with config files - /// Array of files that can be used to start proxy with - private ProxyConfigInfo GetConfigInfo(string configFolder) - { - var configInfo = new ProxyConfigInfo(); - - _logger.LogDebug("Getting list of config files in {ConfigFolder}...", configFolder); - - // Presets in the samples gallery keep their config in a .devproxy - // subfolder, so scan it first, followed by the root folder - var foldersToScan = new[] { Path.Combine(configFolder, ".devproxy"), configFolder } - .Where(Directory.Exists); - var allConfigFiles = foldersToScan - .SelectMany(folder => configFilePatterns - .SelectMany(pattern => Directory.GetFiles(folder, pattern))) - .ToArray(); - - if (allConfigFiles.Length == 0) - { - _logger.LogDebug("No config files found"); - return configInfo; - } - - foreach (var configFile in allConfigFiles) - { - _logger.LogDebug("Reading file {ConfigFile}...", configFile); - - var fileContents = File.ReadAllText(configFile); - - // Check for plugins marker (case-insensitive) - // For JSON: "plugins": - // For YAML: plugins: - if (fileContents.Contains("\"plugins\":", StringComparison.OrdinalIgnoreCase) || - fileContents.Contains("plugins:", StringComparison.OrdinalIgnoreCase)) - { - _logger.LogDebug("File {ConfigFile} contains proxy config", configFile); - configInfo.ConfigFiles.Add(configFile); - continue; - } - - // Check for responses/mocks marker (case-insensitive) - // For JSON: "responses": or "mocks": - // For YAML: responses: or mocks: - if (fileContents.Contains("\"responses\":", StringComparison.OrdinalIgnoreCase) || - fileContents.Contains("\"mocks\":", StringComparison.OrdinalIgnoreCase) || - fileContents.Contains("responses:", StringComparison.OrdinalIgnoreCase) || - fileContents.Contains("mocks:", StringComparison.OrdinalIgnoreCase)) - { - _logger.LogDebug("File {ConfigFile} contains mock data", configFile); - configInfo.MockFiles.Add(configFile); - continue; - } - - _logger.LogDebug("File {ConfigFile} is not a proxy config or mock data", configFile); - } - - if (configInfo.ConfigFiles.Count > 0) - { - if (_logger.IsEnabled(LogLevel.Debug)) - { - _logger.LogDebug("Found {ConfigFilesCount} proxy config files. Clearing mocks...", configInfo.ConfigFiles.Count); - } - configInfo.MockFiles.Clear(); - } - - return configInfo; - } - - private async Task GetFilesToDownloadAsync(string sampleFolderName) - { - _logger.LogDebug("Getting list of files in Dev Proxy samples repo..."); - var url = new Uri($"https://api.github.com/repos/pnp/proxy-samples/git/trees/main?recursive=1"); - var response = await _httpClient.GetAsync(url); - - if (response.IsSuccessStatusCode) - { - var content = await response.Content.ReadAsStringAsync(); - var tree = JsonSerializer.Deserialize(content, ProxyUtils.JsonSerializerOptions) ?? - throw new HttpRequestException("Failed to get list of files from GitHub"); - var samplePath = $"samples/{sampleFolderName}"; - - var filesToDownload = tree.Tree - .Where(f => f.Path.StartsWith(samplePath, StringComparison.OrdinalIgnoreCase) && f.Type == "blob") - .Select(f => f.Path) - .ToArray(); - - foreach (var file in filesToDownload) - { - _logger.LogDebug("Found file {File}", file); - } - - return filesToDownload; - } - else - { - throw new HttpRequestException($"Failed to get list of files from GitHub. Status code: {response.StatusCode}"); - } - } - - private async Task DownloadFileAsync(string filePath, string targetFolderPath, string configId) - { - var url = new Uri($"https://raw.githubusercontent.com/pnp/proxy-samples/main/{filePath.Replace("#", "%23", StringComparison.OrdinalIgnoreCase)}"); - _logger.LogDebug("Downloading file {FilePath}...", filePath); - - var response = await _httpClient.GetAsync(url); - - if (response.IsSuccessStatusCode) - { - var contentStream = await response.Content.ReadAsStreamAsync(); - var filePathInsideSample = Path.GetRelativePath($"samples/{configId}", filePath); - var directoryNameInsideSample = Path.GetDirectoryName(filePathInsideSample); - if (directoryNameInsideSample is not null) - { - _ = Directory.CreateDirectory(Path.Combine(targetFolderPath, directoryNameInsideSample)); - } - var localFilePath = Path.Combine(targetFolderPath, filePathInsideSample); - - using var fileStream = new FileStream(localFilePath, FileMode.Create, FileAccess.Write, FileShare.None); - await contentStream.CopyToAsync(fileStream); - - _logger.LogDebug("File downloaded successfully to {LocalFilePath}", localFilePath); - } - else - { - throw new HttpRequestException($"Failed to download file {url}. Status code: {response.StatusCode}"); - } - } - - private async Task CreateConfigFileAsync(string name, ConfigFileFormat? format, OutputFormat outputFormat) - { - try - { - var selectedFormat = format ?? GetConfigFileFormatFromFileName(name); - var templateFileName = selectedFormat == ConfigFileFormat.Yaml ? "devproxyrc.yaml" : "devproxyrc.json"; - var templateFilePath = Path.Combine(AppContext.BaseDirectory, ConfigTemplatesFolder, templateFileName); - _logger.LogDebug("Reading config template from {TemplateFilePath}...", templateFilePath); - var template = await File.ReadAllTextAsync(templateFilePath); - - var targetFileName = GetTargetFileName(name); - await File.WriteAllTextAsync(targetFileName, template); - - if (outputFormat == OutputFormat.Json) - { - var json = JsonSerializer.Serialize(new - { - path = targetFileName - }, ProxyUtils.JsonSerializerOptions); - _logger.LogStructuredOutput(json); - } - else - { - _logger.LogInformation("Config file created at {TargetFileName}", targetFileName); - } - return 0; - } - catch (Exception ex) - { - if (outputFormat == OutputFormat.Text) - { - _logger.LogError(ex, "Error creating config"); - } - return 1; - } - } - - private static string GetDefaultConfigFileName(ConfigFileFormat? format) => - format == ConfigFileFormat.Yaml ? "devproxyrc.yaml" : "devproxyrc.json"; - - private static ConfigFileFormat GetConfigFileFormatFromFileName(string name) - { - var extension = Path.GetExtension(name).ToLowerInvariant(); - return extension is ".yaml" or ".yml" ? ConfigFileFormat.Yaml : ConfigFileFormat.Json; - } - - private string GetTargetFileName(string name) - { - var originalNameWithoutExtension = Path.GetFileNameWithoutExtension(name); - var originalExtension = Path.GetExtension(name); - var counter = 1; - - while (true) - { - if (!File.Exists(name)) - { - return name; - } - - var newName = $"{originalNameWithoutExtension}-{++counter}{originalExtension}"; - _logger.LogDebug("File {Name} already exists. Trying {NewName}...", name, newName); - name = newName; - } - } - - private static string GetTargetFolderPath(string dataFolder, string configId) - { - var baseFolder = Path.Combine(dataFolder, "configs", configId); - var newFolder = baseFolder; - var i = 1; - while (Directory.Exists(newFolder)) - { - newFolder = baseFolder + i++; - } - - return newFolder; - } - - private static string? ResolveConfigFile(string? configFilePath) - { - if (!string.IsNullOrEmpty(configFilePath)) - { - var resolved = Path.GetFullPath(ProxyUtils.ReplacePathTokens(configFilePath)); - return File.Exists(resolved) ? resolved : null; - } - - foreach (var configFile in ProxyUtils.GetConfigFileCandidates(null)) - { - if (!string.IsNullOrEmpty(configFile) && File.Exists(configFile)) - { - return Path.GetFullPath(configFile); - } - } - - return null; - } - - private static async Task ValidateConfigCoreAsync( - string? configFilePath, - bool isJsonOutput, - HttpClient httpClient, - ILogger logger, - CancellationToken cancellationToken) - { - var errors = new List(); - var warnings = new List(); - var pluginNames = new List(); - var urlPatterns = new List(); - - var resolvedConfigFile = ResolveConfigFile(configFilePath); - if (resolvedConfigFile is null) - { - errors.Add(new("configFile", configFilePath is not null - ? $"Configuration file '{configFilePath}' not found" - : "No configuration file found")); - WriteResults(isJsonOutput, null, errors, warnings, pluginNames, urlPatterns, logger); - return 2; - } - - string configJson; - JsonDocument configDoc; - try - { - var configText = await File.ReadAllTextAsync(resolvedConfigFile, cancellationToken); - - if (ProxyYaml.IsYamlFile(resolvedConfigFile)) - { - if (!ProxyYaml.TryConvertYamlToJson(configText, out var converted, out var yamlError)) - { - throw new JsonException($"Could not convert YAML configuration to JSON: {yamlError}"); - } - configJson = converted!; - } - else - { - configJson = configText; - } - - configDoc = JsonDocument.Parse(configJson, ProxyUtils.JsonDocumentOptions); - } - catch (JsonException ex) - { - errors.Add(new("configFile", $"Invalid configuration: {ex.Message}")); - WriteResults(isJsonOutput, resolvedConfigFile, errors, warnings, pluginNames, urlPatterns, logger); - return 2; - } - catch (YamlException ex) - { - errors.Add(new("configFile", $"Invalid YAML: {ex.Message}")); - WriteResults(isJsonOutput, resolvedConfigFile, errors, warnings, pluginNames, urlPatterns, logger); - return 2; - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - errors.Add(new("configFile", $"Could not read configuration file: {ex.Message}")); - WriteResults(isJsonOutput, resolvedConfigFile, errors, warnings, pluginNames, urlPatterns, logger); - return 2; - } - - using (configDoc) - { - var schemaUrl = configDoc.RootElement.TryGetProperty("$schema", out var schemaProp) - ? schemaProp.GetString() - : null; - if (!string.IsNullOrEmpty(schemaUrl)) - { - try - { - var (isValid, validationErrors) = await ProxyUtils.ValidateJsonAsync( - configJson, schemaUrl, httpClient, logger, cancellationToken); - if (!isValid) - { - foreach (var error in validationErrors) - { - errors.Add(new("schema", error)); - } - } - } - catch (Exception ex) - { - warnings.Add(new("$schema", $"Could not validate schema: {ex.Message}")); - } - - ValidateSchemaVersion(schemaUrl, warnings); - } - else - { - warnings.Add(new("$schema", "No schema URL found, skipping schema validation")); - } - - var configFileDirectory = Path.GetDirectoryName(resolvedConfigFile) ?? "."; - - if (configDoc.RootElement.TryGetProperty("plugins", out var pluginsElement) && - pluginsElement.ValueKind == JsonValueKind.Array) - { - ValidatePlugins(pluginsElement, configFileDirectory, errors, pluginNames); - } - else - { - errors.Add(new("plugins", "No plugins configured")); - } - - if (configDoc.RootElement.TryGetProperty("urlsToWatch", out var urlsElement) && - urlsElement.ValueKind == JsonValueKind.Array) - { - ValidateUrls(urlsElement, errors, warnings, urlPatterns); - } - else - { - warnings.Add(new("urlsToWatch", "No URLs to watch configured")); - } - } - - var isConfigValid = errors.Count == 0; - WriteResults(isJsonOutput, resolvedConfigFile, errors, warnings, pluginNames, urlPatterns, logger); - return isConfigValid ? 0 : 2; - } - - private static void ValidateSchemaVersion(string schemaUrl, List warnings) - { - var warning = ProxyUtils.GetSchemaVersionMismatchWarning(schemaUrl); - if (warning is not null) - { - warnings.Add(new("$schema", warning)); - } - } - - private static void ValidatePlugins( - JsonElement pluginsElement, - string configFileDirectory, - List errors, - List pluginNames) - { - var hasEnabledPlugins = false; - var i = 0; - - foreach (var plugin in pluginsElement.EnumerateArray()) - { - string? name; - bool enabled; - string? pluginPath; - try - { - name = plugin.TryGetProperty("name", out var nameProp) ? nameProp.GetString() : null; - enabled = !plugin.TryGetProperty("enabled", out var enabledProp) || enabledProp.GetBoolean(); - pluginPath = plugin.TryGetProperty("pluginPath", out var pathProp) ? pathProp.GetString() : null; - } - catch (InvalidOperationException ex) - { - errors.Add(new($"plugins[{i}]", $"Invalid plugin definition: {ex.Message}")); - i++; - continue; - } - - if (string.IsNullOrEmpty(name)) - { - errors.Add(new($"plugins[{i}].name", "Plugin name is required")); - i++; - continue; - } - - if (!enabled) - { - i++; - continue; - } - - hasEnabledPlugins = true; - pluginNames.Add(name); - - if (string.IsNullOrEmpty(pluginPath)) - { - errors.Add(new($"plugins[{i}].pluginPath", $"Plugin path is required for '{name}'")); - i++; - continue; - } - - var resolvedPluginPath = Path.GetFullPath( - Path.Combine( - configFileDirectory, - ProxyUtils.ReplacePathTokens(pluginPath.Replace('\\', Path.DirectorySeparatorChar)))); - - if (!File.Exists(resolvedPluginPath)) - { - errors.Add(new($"plugins[{i}].pluginPath", - $"Plugin assembly '{resolvedPluginPath}' not found")); - i++; - continue; - } - - try - { - var pluginLoadContext = new PluginLoadContext(resolvedPluginPath); - var assembly = pluginLoadContext.LoadFromAssemblyName( - new AssemblyName(Path.GetFileNameWithoutExtension(resolvedPluginPath))); - var pluginType = assembly.GetTypes() - .FirstOrDefault(t => t.Name == name && typeof(IPlugin).IsAssignableFrom(t)); - if (pluginType is null) - { - errors.Add(new($"plugins[{i}].name", - $"Plugin '{name}' not found in assembly '{Path.GetFileName(resolvedPluginPath)}'")); - } - } - catch (Exception ex) - { - errors.Add(new($"plugins[{i}]", - $"Failed to load plugin assembly: {ex.Message}")); - } - - i++; - } - - if (!hasEnabledPlugins) - { - errors.Add(new("plugins", "No enabled plugins found")); - } - } - - private static void ValidateUrls( - JsonElement urlsElement, - List errors, - List warnings, - List urlPatterns) - { - var i = 0; - foreach (var url in urlsElement.EnumerateArray()) - { - if (url.ValueKind != JsonValueKind.String) - { - errors.Add(new($"urlsToWatch[{i}]", $"Expected a string but got {url.ValueKind}")); - i++; - continue; - } - - var pattern = url.GetString(); - if (string.IsNullOrEmpty(pattern)) - { - warnings.Add(new($"urlsToWatch[{i}]", "Empty URL pattern")); - } - else - { - urlPatterns.Add(pattern); - try - { - var cleanPattern = pattern.StartsWith('!') ? pattern[1..] : pattern; - _ = new Regex( - $"^{Regex.Escape(cleanPattern).Replace("\\*", ".*", StringComparison.OrdinalIgnoreCase)}$"); - } - catch (ArgumentException ex) - { - errors.Add(new($"urlsToWatch[{i}]", - $"Invalid URL pattern '{pattern}': {ex.Message}")); - } - } - i++; - } - } - - private static void WriteResults( - bool isJsonOutput, - string? configFile, - List errors, - List warnings, - List pluginNames, - List urlPatterns, - ILogger logger) - { - var isValid = errors.Count == 0; - - if (isJsonOutput) - { - WriteJsonResults(configFile, errors, warnings, pluginNames, urlPatterns, isValid, logger); - } - else - { - WriteTextResults(configFile, errors, warnings, pluginNames, urlPatterns, isValid, logger); - } - } - - private static void WriteJsonResults( - string? configFile, - List errors, - List warnings, - List pluginNames, - List urlPatterns, - bool isValid, - ILogger logger) - { - var result = new - { - valid = isValid, - configFile, - plugins = pluginNames, - urlsToWatch = urlPatterns, - errors = errors.Select(e => new { path = e.Path, message = e.Message }), - warnings = warnings.Select(w => new { path = w.Path, message = w.Message }) - }; - - var json = JsonSerializer.Serialize(result, ProxyUtils.JsonSerializerOptions); - logger.LogInformation("{Result}", json); - } - - private static void WriteTextResults( - string? configFile, - List errors, - List warnings, - List pluginNames, - List urlPatterns, - bool isValid, - ILogger logger) - { - if (isValid) - { - logger.LogInformation("\u2713 Configuration is valid"); - } - else - { - logger.LogError("\u2717 Configuration is invalid"); - } - - if (configFile is not null) - { - logger.LogInformation(" Config file: {ConfigFile}", configFile); - } - if (pluginNames.Count > 0) - { - logger.LogInformation(" Plugins: {Count} loaded", pluginNames.Count); - } - if (urlPatterns.Count > 0) - { - logger.LogInformation(" URLs to watch: {Count} pattern{Plural}", urlPatterns.Count, urlPatterns.Count != 1 ? "s" : ""); - } - - if (errors.Count > 0) - { - logger.LogInformation(""); - foreach (var error in errors) - { - logger.LogError(" - {Path}: {Message}", error.Path, error.Message); - } - } - - if (warnings.Count > 0) - { - logger.LogInformation(""); - foreach (var warning in warnings) - { - logger.LogWarning(" - {Path}: {Message}", warning.Path, warning.Message); - } - } - } - - private sealed record ValidationMessage(string Path, string Message); -} +// 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 DevProxy.Abstractions.Plugins; +using DevProxy.Abstractions.Proxy; +using DevProxy.Abstractions.Utils; +using DevProxy.Logging; +using DevProxy.Plugins; +using System.CommandLine; +using System.CommandLine.Parsing; +using System.Diagnostics; +using System.Net.Http.Headers; +using System.Reflection; +using System.Text.Json; +using System.Text.RegularExpressions; +using YamlDotNet.Core; + +namespace DevProxy.Commands; + +sealed class ProxyConfigInfo +{ + public IList ConfigFiles { get; set; } = []; + public IList MockFiles { get; set; } = []; +} + +sealed class GitHubTreeResponse +{ + public GitHubTreeItem[] Tree { get; set; } = []; + public bool Truncated { get; set; } +} + +sealed class GitHubTreeItem +{ + public string Path { get; set; } = string.Empty; + public string Type { get; set; } = string.Empty; +} + +sealed class ConfigCommand : Command +{ + private enum ConfigFileFormat + { + Json, + Yaml + } + + private readonly ILogger _logger; + private readonly IProxyConfiguration _proxyConfiguration; + private readonly HttpClient _httpClient; + private const string ConfigTemplatesFolder = "config-templates"; + private static readonly string[] configFilePatterns = ["*.json", "*.yaml", "*.yml"]; + + public ConfigCommand( + HttpClient httpClient, + IProxyConfiguration proxyConfiguration, + ILogger logger) : + base("config", "Manage Dev Proxy configs") + { + _proxyConfiguration = proxyConfiguration; + _logger = logger; + _httpClient = httpClient; + _httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("dev-proxy", ProxyUtils.ProductVersion)); + ConfigureCommand(); + } + + /// + /// Runs config validation standalone, without requiring the full DI container. + /// Used when the proxy is invoked with 'config validate' to allow validating + /// even broken config files. + /// + internal static async Task RunValidateStandaloneAsync(string[] args) + { + string? configFile = null; + var isJsonOutput = false; + + for (var i = 0; i < args.Length; i++) + { + if ((string.Equals(args[i], "--config-file", StringComparison.OrdinalIgnoreCase) || + string.Equals(args[i], "-c", StringComparison.OrdinalIgnoreCase)) && + i + 1 < args.Length) + { + configFile = args[i + 1]; + i++; + } + else if (string.Equals(args[i], DevProxyCommand.OutputOptionName, StringComparison.OrdinalIgnoreCase) && + i + 1 < args.Length) + { + isJsonOutput = string.Equals(args[i + 1], "json", StringComparison.OrdinalIgnoreCase); + i++; + } + } + + using var httpClient = new HttpClient(); + httpClient.DefaultRequestHeaders.UserAgent.Add( + new ProductInfoHeaderValue("dev-proxy", ProxyUtils.ProductVersion)); + + var formatterName = isJsonOutput + ? JsonConsoleFormatter.FormatterName + : ProxyConsoleFormatter.DefaultCategoryName; + + using var loggerFactory = LoggerFactory.Create(builder => + { + _ = builder + .SetMinimumLevel(LogLevel.Information) + .AddConsole(consoleOptions => + { + consoleOptions.FormatterName = formatterName; + consoleOptions.LogToStandardErrorThreshold = LogLevel.Warning; + }) + .AddConsoleFormatter(formatterOptions => + { + formatterOptions.IncludeScopes = false; + formatterOptions.ShowSkipMessages = true; + formatterOptions.ShowTimestamps = false; + }) + .AddConsoleFormatter(formatterOptions => + { + formatterOptions.IncludeScopes = false; + formatterOptions.ShowSkipMessages = true; + formatterOptions.ShowTimestamps = false; + }); + }); + var logger = loggerFactory.CreateLogger(); + + return await ValidateConfigCoreAsync(configFile, isJsonOutput, httpClient, logger, CancellationToken.None); + } + + private void ConfigureCommand() + { + var configGetCommand = new Command("get", "Download the specified config from the Sample Solution Gallery"); + var configIdArgument = new Argument("config-id") + { + Description = "The ID of the config to download" + }; + configGetCommand.Add(configIdArgument); + configGetCommand.SetAction(async (parseResult) => + { + var configId = parseResult.GetValue(configIdArgument); + var outputFormat = parseResult.GetValueOrDefault(DevProxyCommand.OutputOptionName) ?? OutputFormat.Text; + return configId is null ? 1 : await DownloadConfigAsync(configId, outputFormat); + }); + + var configNewCommand = new Command("new", "Create new Dev Proxy configuration file"); + var nameArgument = new Argument("name") + { + Arity = ArgumentArity.ZeroOrOne, + Description = "Name of the configuration file. Defaults to devproxyrc.json (or devproxyrc.yaml with --format yaml)." + }; + var formatOption = new Option("--format") + { + Description = "Configuration format to use (json or yaml)" + }; + configNewCommand.Add(nameArgument); + configNewCommand.Add(formatOption); + configNewCommand.SetAction(async (parseResult) => + { + var format = parseResult.GetValue(formatOption); + var name = parseResult.GetValue(nameArgument) ?? GetDefaultConfigFileName(format); + var outputFormat = parseResult.GetValueOrDefault(DevProxyCommand.OutputOptionName) ?? OutputFormat.Text; + return await CreateConfigFileAsync(name, format, outputFormat); + }); + + var configOpenCommand = new Command("open", "Open devproxyrc.json"); + configOpenCommand.SetAction(parseResult => + { + var cfgPsi = new ProcessStartInfo(_proxyConfiguration.ConfigFile) + { + UseShellExecute = true + }; + _ = Process.Start(cfgPsi); + }); + + var configValidateCommand = new Command("validate", "Validate a Dev Proxy configuration file"); + var validateConfigFileOption = new Option("--config-file", "-c") + { + Description = "The path to the configuration file to validate", + HelpName = "config-file" + }; + configValidateCommand.Add(validateConfigFileOption); + configValidateCommand.SetAction(async (parseResult, cancellationToken) => + { + var configFile = parseResult.GetValue(validateConfigFileOption); + var output = parseResult.GetValueOrDefault(DevProxyCommand.OutputOptionName); + var isJsonOutput = output == OutputFormat.Json; + return await ValidateConfigCoreAsync(configFile, isJsonOutput, _httpClient, _logger, cancellationToken); + }); + + this.AddCommands(new List + { + configGetCommand, + configNewCommand, + configOpenCommand, + configValidateCommand + }.OrderByName()); + + HelpExamples.Add(this, [ + "devproxy config new Create default devproxyrc.json", + "devproxy config new --format yaml Create default devproxyrc.yaml", + "devproxy config new myconfig.json Create named config file", + "devproxy config get Download config from gallery", + "devproxy config open Open config in default editor", + ]); + } + + private async Task DownloadConfigAsync(string configId, OutputFormat outputFormat) + { + try + { + var dataFolder = ProxyUtils.DataFolder; + + var configFolderPath = Path.Combine(dataFolder, "configs"); + _logger.LogDebug("Checking if config folder {ConfigFolderPath} exists...", configFolderPath); + if (!Directory.Exists(configFolderPath)) + { + _logger.LogDebug("Config folder not found, creating it..."); + _ = Directory.CreateDirectory(configFolderPath); + _logger.LogDebug("Config folder created"); + } + + _logger.LogDebug("Getting target folder path for config {ConfigId}...", configId); + var targetFolderPath = GetTargetFolderPath(dataFolder, configId); + _logger.LogDebug("Creating target folder {TargetFolderPath}...", targetFolderPath); + _ = Directory.CreateDirectory(targetFolderPath); + + if (outputFormat == OutputFormat.Text) + { + _logger.LogInformation("Downloading config {ConfigId}...", configId); + } + + var sampleFiles = await GetFilesToDownloadAsync(configId); + if (sampleFiles.Length == 0) + { + if (outputFormat == OutputFormat.Text) + { + _logger.LogError("Config {ConfigId} not found in the samples repo", configId); + } + return 1; + } + foreach (var sampleFile in sampleFiles) + { + await DownloadFileAsync(sampleFile, targetFolderPath, configId); + } + + var configInfo = GetConfigInfo(targetFolderPath); + + if (outputFormat == OutputFormat.Json) + { + var json = JsonSerializer.Serialize(new + { + configId, + path = targetFolderPath, + configFiles = configInfo.ConfigFiles, + mockFiles = configInfo.MockFiles + }, ProxyUtils.JsonSerializerOptions); + _logger.LogStructuredOutput(json); + return 0; + } + + _logger.LogInformation("Config saved in {TargetFolderPath}\r\n", targetFolderPath); + + if (configInfo.ConfigFiles.Count == 0 && configInfo.MockFiles.Count == 0) + { + return 0; + } + + if (configInfo.ConfigFiles.Count > 0) + { + _logger.LogInformation("To start Dev Proxy with the config, run:"); + foreach (var configFile in configInfo.ConfigFiles) + { + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation(" devproxy --config-file \"{ConfigFile}\"", configFile.Replace(dataFolder, "~dataFolder", StringComparison.OrdinalIgnoreCase)); + } + } + } + else + { + _logger.LogInformation("To start Dev Proxy with the mock file, enable the MockResponsePlugin or GraphMockResponsePlugin and run:"); + foreach (var mockFile in configInfo.MockFiles) + { + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation(" devproxy --mock-file \"{MockFile}\"", mockFile.Replace(dataFolder, "~dataFolder", StringComparison.OrdinalIgnoreCase)); + } + } + } + + return 0; + } + catch (Exception ex) + { + if (outputFormat == OutputFormat.Text) + { + _logger.LogError(ex, "Error downloading config"); + } + return 1; + } + } + + /// + /// Returns the list of files that can be used as entry points for the config + /// + /// + /// A sample in the gallery can have multiple entry points. It can + /// contain multiple config files or no config files and a multiple + /// mock files. This method returns the list of files that Dev Proxy + /// can use as entry points. + /// If there's one or more config files, it'll return an array of + /// these file names. If there are no proxy configs, it'll return + /// an array of all the mock files. If there are no mocks, it'll return + /// an empty array indicating that there's no entry point. + /// Files in the .devproxy subfolder are listed before files in the + /// root folder. + /// + /// Full path to the folder with config files + /// Array of files that can be used to start proxy with + private ProxyConfigInfo GetConfigInfo(string configFolder) + { + var configInfo = new ProxyConfigInfo(); + + _logger.LogDebug("Getting list of config files in {ConfigFolder}...", configFolder); + + // Presets in the samples gallery keep their config in a .devproxy + // subfolder, so scan it first, followed by the root folder + var foldersToScan = new[] { Path.Combine(configFolder, ".devproxy"), configFolder } + .Where(Directory.Exists); + var allConfigFiles = foldersToScan + .SelectMany(folder => configFilePatterns + .SelectMany(pattern => Directory.GetFiles(folder, pattern))) + .ToArray(); + + if (allConfigFiles.Length == 0) + { + _logger.LogDebug("No config files found"); + return configInfo; + } + + foreach (var configFile in allConfigFiles) + { + _logger.LogDebug("Reading file {ConfigFile}...", configFile); + + var fileContents = File.ReadAllText(configFile); + + // Check for plugins marker (case-insensitive) + // For JSON: "plugins": + // For YAML: plugins: + if (fileContents.Contains("\"plugins\":", StringComparison.OrdinalIgnoreCase) || + fileContents.Contains("plugins:", StringComparison.OrdinalIgnoreCase)) + { + _logger.LogDebug("File {ConfigFile} contains proxy config", configFile); + configInfo.ConfigFiles.Add(configFile); + continue; + } + + // Check for responses/mocks marker (case-insensitive) + // For JSON: "responses": or "mocks": + // For YAML: responses: or mocks: + if (fileContents.Contains("\"responses\":", StringComparison.OrdinalIgnoreCase) || + fileContents.Contains("\"mocks\":", StringComparison.OrdinalIgnoreCase) || + fileContents.Contains("responses:", StringComparison.OrdinalIgnoreCase) || + fileContents.Contains("mocks:", StringComparison.OrdinalIgnoreCase)) + { + _logger.LogDebug("File {ConfigFile} contains mock data", configFile); + configInfo.MockFiles.Add(configFile); + continue; + } + + _logger.LogDebug("File {ConfigFile} is not a proxy config or mock data", configFile); + } + + if (configInfo.ConfigFiles.Count > 0) + { + if (_logger.IsEnabled(LogLevel.Debug)) + { + _logger.LogDebug("Found {ConfigFilesCount} proxy config files. Clearing mocks...", configInfo.ConfigFiles.Count); + } + configInfo.MockFiles.Clear(); + } + + return configInfo; + } + + private async Task GetFilesToDownloadAsync(string sampleFolderName) + { + _logger.LogDebug("Getting list of files in Dev Proxy samples repo..."); + var url = new Uri($"https://api.github.com/repos/pnp/proxy-samples/git/trees/main?recursive=1"); + var response = await _httpClient.GetAsync(url); + + if (response.IsSuccessStatusCode) + { + var content = await response.Content.ReadAsStringAsync(); + var tree = JsonSerializer.Deserialize(content, ProxyUtils.JsonSerializerOptions) ?? + throw new HttpRequestException("Failed to get list of files from GitHub"); + var samplePath = $"samples/{sampleFolderName}"; + + var filesToDownload = tree.Tree + .Where(f => f.Path.StartsWith(samplePath, StringComparison.OrdinalIgnoreCase) && f.Type == "blob") + .Select(f => f.Path) + .ToArray(); + + foreach (var file in filesToDownload) + { + _logger.LogDebug("Found file {File}", file); + } + + return filesToDownload; + } + else + { + throw new HttpRequestException($"Failed to get list of files from GitHub. Status code: {response.StatusCode}"); + } + } + + private async Task DownloadFileAsync(string filePath, string targetFolderPath, string configId) + { + var url = new Uri($"https://raw.githubusercontent.com/pnp/proxy-samples/main/{filePath.Replace("#", "%23", StringComparison.OrdinalIgnoreCase)}"); + _logger.LogDebug("Downloading file {FilePath}...", filePath); + + var response = await _httpClient.GetAsync(url); + + if (response.IsSuccessStatusCode) + { + var contentStream = await response.Content.ReadAsStreamAsync(); + var filePathInsideSample = Path.GetRelativePath($"samples/{configId}", filePath); + var directoryNameInsideSample = Path.GetDirectoryName(filePathInsideSample); + if (directoryNameInsideSample is not null) + { + _ = Directory.CreateDirectory(Path.Combine(targetFolderPath, directoryNameInsideSample)); + } + var localFilePath = Path.Combine(targetFolderPath, filePathInsideSample); + + using var fileStream = new FileStream(localFilePath, FileMode.Create, FileAccess.Write, FileShare.None); + await contentStream.CopyToAsync(fileStream); + + _logger.LogDebug("File downloaded successfully to {LocalFilePath}", localFilePath); + } + else + { + throw new HttpRequestException($"Failed to download file {url}. Status code: {response.StatusCode}"); + } + } + + private async Task CreateConfigFileAsync(string name, ConfigFileFormat? format, OutputFormat outputFormat) + { + try + { + var selectedFormat = format ?? GetConfigFileFormatFromFileName(name); + var templateFileName = selectedFormat == ConfigFileFormat.Yaml ? "devproxyrc.yaml" : "devproxyrc.json"; + var templateFilePath = Path.Combine(AppContext.BaseDirectory, ConfigTemplatesFolder, templateFileName); + _logger.LogDebug("Reading config template from {TemplateFilePath}...", templateFilePath); + var template = await File.ReadAllTextAsync(templateFilePath); + + var targetFileName = GetTargetFileName(name); + await File.WriteAllTextAsync(targetFileName, template); + + if (outputFormat == OutputFormat.Json) + { + var json = JsonSerializer.Serialize(new + { + path = targetFileName + }, ProxyUtils.JsonSerializerOptions); + _logger.LogStructuredOutput(json); + } + else + { + _logger.LogInformation("Config file created at {TargetFileName}", targetFileName); + } + return 0; + } + catch (Exception ex) + { + if (outputFormat == OutputFormat.Text) + { + _logger.LogError(ex, "Error creating config"); + } + return 1; + } + } + + private static string GetDefaultConfigFileName(ConfigFileFormat? format) => + format == ConfigFileFormat.Yaml ? "devproxyrc.yaml" : "devproxyrc.json"; + + private static ConfigFileFormat GetConfigFileFormatFromFileName(string name) + { + var extension = Path.GetExtension(name).ToLowerInvariant(); + return extension is ".yaml" or ".yml" ? ConfigFileFormat.Yaml : ConfigFileFormat.Json; + } + + private string GetTargetFileName(string name) + { + var originalNameWithoutExtension = Path.GetFileNameWithoutExtension(name); + var originalExtension = Path.GetExtension(name); + var counter = 1; + + while (true) + { + if (!File.Exists(name)) + { + return name; + } + + var newName = $"{originalNameWithoutExtension}-{++counter}{originalExtension}"; + _logger.LogDebug("File {Name} already exists. Trying {NewName}...", name, newName); + name = newName; + } + } + + private static string GetTargetFolderPath(string dataFolder, string configId) + { + var baseFolder = Path.Combine(dataFolder, "configs", configId); + var newFolder = baseFolder; + var i = 1; + while (Directory.Exists(newFolder)) + { + newFolder = baseFolder + i++; + } + + return newFolder; + } + + private static string? ResolveConfigFile(string? configFilePath) + { + if (!string.IsNullOrEmpty(configFilePath)) + { + var resolved = Path.GetFullPath(ProxyUtils.ReplacePathTokens(configFilePath)); + return File.Exists(resolved) ? resolved : null; + } + + foreach (var configFile in ProxyUtils.GetConfigFileCandidates(null)) + { + if (!string.IsNullOrEmpty(configFile) && File.Exists(configFile)) + { + return Path.GetFullPath(configFile); + } + } + + return null; + } + + private static async Task ValidateConfigCoreAsync( + string? configFilePath, + bool isJsonOutput, + HttpClient httpClient, + ILogger logger, + CancellationToken cancellationToken) + { + var errors = new List(); + var warnings = new List(); + var pluginNames = new List(); + var urlPatterns = new List(); + + var resolvedConfigFile = ResolveConfigFile(configFilePath); + if (resolvedConfigFile is null) + { + errors.Add(new("configFile", configFilePath is not null + ? $"Configuration file '{configFilePath}' not found" + : "No configuration file found")); + WriteResults(isJsonOutput, null, errors, warnings, pluginNames, urlPatterns, logger); + return 2; + } + + string configJson; + JsonDocument configDoc; + try + { + var configText = await File.ReadAllTextAsync(resolvedConfigFile, cancellationToken); + + if (ProxyYaml.IsYamlFile(resolvedConfigFile)) + { + if (!ProxyYaml.TryConvertYamlToJson(configText, out var converted, out var yamlError)) + { + throw new JsonException($"Could not convert YAML configuration to JSON: {yamlError}"); + } + configJson = converted!; + } + else + { + configJson = configText; + } + + configDoc = JsonDocument.Parse(configJson, ProxyUtils.JsonDocumentOptions); + } + catch (JsonException ex) + { + errors.Add(new("configFile", $"Invalid configuration: {ex.Message}")); + WriteResults(isJsonOutput, resolvedConfigFile, errors, warnings, pluginNames, urlPatterns, logger); + return 2; + } + catch (YamlException ex) + { + errors.Add(new("configFile", $"Invalid YAML: {ex.Message}")); + WriteResults(isJsonOutput, resolvedConfigFile, errors, warnings, pluginNames, urlPatterns, logger); + return 2; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + errors.Add(new("configFile", $"Could not read configuration file: {ex.Message}")); + WriteResults(isJsonOutput, resolvedConfigFile, errors, warnings, pluginNames, urlPatterns, logger); + return 2; + } + + using (configDoc) + { + var schemaUrl = configDoc.RootElement.TryGetProperty("$schema", out var schemaProp) + ? schemaProp.GetString() + : null; + if (!string.IsNullOrEmpty(schemaUrl)) + { + try + { + var (isValid, validationErrors) = await ProxyUtils.ValidateJsonAsync( + configJson, schemaUrl, httpClient, logger, cancellationToken); + if (!isValid) + { + foreach (var error in validationErrors) + { + errors.Add(new("schema", error)); + } + } + } + catch (Exception ex) + { + warnings.Add(new("$schema", $"Could not validate schema: {ex.Message}")); + } + + ValidateSchemaVersion(schemaUrl, warnings); + } + else + { + warnings.Add(new("$schema", "No schema URL found, skipping schema validation")); + } + + var configFileDirectory = Path.GetDirectoryName(resolvedConfigFile) ?? "."; + + if (configDoc.RootElement.TryGetProperty("plugins", out var pluginsElement) && + pluginsElement.ValueKind == JsonValueKind.Array) + { + ValidatePlugins(pluginsElement, configFileDirectory, errors, pluginNames); + } + else + { + errors.Add(new("plugins", "No plugins configured")); + } + + if (configDoc.RootElement.TryGetProperty("urlsToWatch", out var urlsElement) && + urlsElement.ValueKind == JsonValueKind.Array) + { + ValidateUrls(urlsElement, errors, warnings, urlPatterns); + } + else + { + warnings.Add(new("urlsToWatch", "No URLs to watch configured")); + } + } + + var isConfigValid = errors.Count == 0; + WriteResults(isJsonOutput, resolvedConfigFile, errors, warnings, pluginNames, urlPatterns, logger); + return isConfigValid ? 0 : 2; + } + + private static void ValidateSchemaVersion(string schemaUrl, List warnings) + { + var warning = ProxyUtils.GetSchemaVersionMismatchWarning(schemaUrl); + if (warning is not null) + { + warnings.Add(new("$schema", warning)); + } + } + + private static void ValidatePlugins( + JsonElement pluginsElement, + string configFileDirectory, + List errors, + List pluginNames) + { + var hasEnabledPlugins = false; + var i = 0; + + foreach (var plugin in pluginsElement.EnumerateArray()) + { + string? name; + bool enabled; + string? pluginPath; + try + { + name = plugin.TryGetProperty("name", out var nameProp) ? nameProp.GetString() : null; + enabled = !plugin.TryGetProperty("enabled", out var enabledProp) || enabledProp.GetBoolean(); + pluginPath = plugin.TryGetProperty("pluginPath", out var pathProp) ? pathProp.GetString() : null; + } + catch (InvalidOperationException ex) + { + errors.Add(new($"plugins[{i}]", $"Invalid plugin definition: {ex.Message}")); + i++; + continue; + } + + if (string.IsNullOrEmpty(name)) + { + errors.Add(new($"plugins[{i}].name", "Plugin name is required")); + i++; + continue; + } + + if (!enabled) + { + i++; + continue; + } + + hasEnabledPlugins = true; + pluginNames.Add(name); + + if (string.IsNullOrEmpty(pluginPath)) + { + errors.Add(new($"plugins[{i}].pluginPath", $"Plugin path is required for '{name}'")); + i++; + continue; + } + + var resolvedPluginPath = Path.GetFullPath( + Path.Combine( + configFileDirectory, + ProxyUtils.ReplacePathTokens(pluginPath.Replace('\\', Path.DirectorySeparatorChar)))); + + if (!File.Exists(resolvedPluginPath)) + { + errors.Add(new($"plugins[{i}].pluginPath", + $"Plugin assembly '{resolvedPluginPath}' not found")); + i++; + continue; + } + + try + { + var pluginLoadContext = new PluginLoadContext(resolvedPluginPath); + var assembly = pluginLoadContext.LoadFromAssemblyName( + new AssemblyName(Path.GetFileNameWithoutExtension(resolvedPluginPath))); + var pluginType = assembly.GetTypes() + .FirstOrDefault(t => t.Name == name && typeof(IPlugin).IsAssignableFrom(t)); + if (pluginType is null) + { + errors.Add(new($"plugins[{i}].name", + $"Plugin '{name}' not found in assembly '{Path.GetFileName(resolvedPluginPath)}'")); + } + } + catch (Exception ex) + { + errors.Add(new($"plugins[{i}]", + $"Failed to load plugin assembly: {ex.Message}")); + } + + i++; + } + + if (!hasEnabledPlugins) + { + errors.Add(new("plugins", "No enabled plugins found")); + } + } + + private static void ValidateUrls( + JsonElement urlsElement, + List errors, + List warnings, + List urlPatterns) + { + var i = 0; + foreach (var url in urlsElement.EnumerateArray()) + { + if (url.ValueKind != JsonValueKind.String) + { + errors.Add(new($"urlsToWatch[{i}]", $"Expected a string but got {url.ValueKind}")); + i++; + continue; + } + + var pattern = url.GetString(); + if (string.IsNullOrEmpty(pattern)) + { + warnings.Add(new($"urlsToWatch[{i}]", "Empty URL pattern")); + } + else + { + urlPatterns.Add(pattern); + try + { + var cleanPattern = pattern.StartsWith('!', StringComparison.Ordinal) ? pattern[1..] : pattern; + _ = new Regex( + $"^{Regex.Escape(cleanPattern).Replace("\\*", ".*", StringComparison.OrdinalIgnoreCase)}$"); + } + catch (ArgumentException ex) + { + errors.Add(new($"urlsToWatch[{i}]", + $"Invalid URL pattern '{pattern}': {ex.Message}")); + } + } + i++; + } + } + + private static void WriteResults( + bool isJsonOutput, + string? configFile, + List errors, + List warnings, + List pluginNames, + List urlPatterns, + ILogger logger) + { + var isValid = errors.Count == 0; + + if (isJsonOutput) + { + WriteJsonResults(configFile, errors, warnings, pluginNames, urlPatterns, isValid, logger); + } + else + { + WriteTextResults(configFile, errors, warnings, pluginNames, urlPatterns, isValid, logger); + } + } + + private static void WriteJsonResults( + string? configFile, + List errors, + List warnings, + List pluginNames, + List urlPatterns, + bool isValid, + ILogger logger) + { + var result = new + { + valid = isValid, + configFile, + plugins = pluginNames, + urlsToWatch = urlPatterns, + errors = errors.Select(e => new { path = e.Path, message = e.Message }), + warnings = warnings.Select(w => new { path = w.Path, message = w.Message }) + }; + + var json = JsonSerializer.Serialize(result, ProxyUtils.JsonSerializerOptions); + logger.LogInformation("{Result}", json); + } + + private static void WriteTextResults( + string? configFile, + List errors, + List warnings, + List pluginNames, + List urlPatterns, + bool isValid, + ILogger logger) + { + if (isValid) + { + logger.LogInformation("\u2713 Configuration is valid"); + } + else + { + logger.LogError("\u2717 Configuration is invalid"); + } + + if (configFile is not null) + { + logger.LogInformation(" Config file: {ConfigFile}", configFile); + } + if (pluginNames.Count > 0) + { + logger.LogInformation(" Plugins: {Count} loaded", pluginNames.Count); + } + if (urlPatterns.Count > 0) + { + logger.LogInformation(" URLs to watch: {Count} pattern{Plural}", urlPatterns.Count, urlPatterns.Count != 1 ? "s" : ""); + } + + if (errors.Count > 0) + { + logger.LogInformation(""); + foreach (var error in errors) + { + logger.LogError(" - {Path}: {Message}", error.Path, error.Message); + } + } + + if (warnings.Count > 0) + { + logger.LogInformation(""); + foreach (var warning in warnings) + { + logger.LogWarning(" - {Path}: {Message}", warning.Path, warning.Message); + } + } + } + + private sealed record ValidationMessage(string Path, string Message); +} diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index e8bfea774..f50274a39 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -1,814 +1,814 @@ -using DevProxy.Abstractions.Plugins; -using DevProxy.Abstractions.Proxy; -using DevProxy.Abstractions.Utils; -using DevProxy.Proxy; -using DevProxy.State; -using Microsoft.AspNetCore.Hosting.Server; -using Microsoft.AspNetCore.Hosting.Server.Features; -using System.CommandLine; -using System.CommandLine.Help; -using System.CommandLine.Invocation; -using System.CommandLine.Parsing; -using System.Globalization; - -namespace DevProxy.Commands; - -sealed class DevProxyCommand : RootCommand -{ - private readonly IServiceProvider _serviceProvider; - private readonly IEnumerable _plugins; - private readonly ILogger _logger; - private readonly IProxyConfiguration _proxyConfiguration; - private readonly ISet _urlsToWatch; - private readonly UpdateNotification _updateNotification; - private WebApplication? _app; - - internal const string PortOptionName = "--port"; - internal const string ApiPortOptionName = "--api-port"; - internal const string ApiIpAddressOptionName = "--api-ip-address"; - internal const string IpAddressOptionName = "--ip-address"; - internal const string LogLevelOptionName = "--log-level"; - internal const string RecordOptionName = "--record"; - internal const string WatchPidsOptionName = "--watch-pids"; - internal const string WatchProcessNamesOptionName = "--watch-process-names"; - internal const string WatchProcessTreeOptionName = "--watch-process-tree"; - internal const string ConfigFileOptionName = "--config-file"; - internal static readonly Option ConfigFileOption = new(ConfigFileOptionName, "-c") - { - HelpName = "config-file", - Description = "Path to config file. If not specified, Dev Proxy searches for devproxyrc.jsonc or devproxyrc.json in the current directory, then in a .devproxy/ directory, then under the ~appFolder location. Supports ~appFolder and ~dataFolder tokens, and a leading ~/ for the home directory." - }; - internal const string NoFirstRunOptionName = "--no-first-run"; - internal const string NoWatchOptionName = "--no-watch"; - internal const string AsSystemProxyOptionName = "--as-system-proxy"; - internal const string InstallCertOptionName = "--install-cert"; - internal const string UrlsToWatchOptionName = "--urls-to-watch"; - internal const string TimeoutOptionName = "--timeout"; - internal const string DiscoverOptionName = "--discover"; - internal const string EnvOptionName = "--env"; - internal const string OutputOptionName = "--output"; - internal const string DetachedOptionName = "--detach"; - internal const string InternalDaemonOptionName = "--_internal-daemon"; - internal const string NoColorOptionName = "--no-color"; - - private static readonly string[] globalOptions = ["--version"]; - private static readonly string[] helpOptions = ["--help", "-h", "/h", "-?", "/?"]; - - private static bool _hasGlobalOptionsResolved; - private static bool _isStdioCommandResolved; - private static bool _isJwtCommandResolved; - private static bool _isRootCommandResolved; - private static bool _isConfigValidateCommandResolved; - private static bool _isDetachedModeResolved; - private static bool _isInternalDaemonResolved; - private static bool _stdioLogFilePathResolved; - private static bool _detachedLogFilePathResolved; - - public static bool HasGlobalOptions - { - get - { - if (_hasGlobalOptionsResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - field = args.Any(arg => globalOptions.Contains(arg)) || - args.Any(arg => helpOptions.Contains(arg)); - _hasGlobalOptionsResolved = true; - return field; - } - } - - public static bool IsStdioCommand - { - get - { - if (_isStdioCommandResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - field = args.Contains("stdio"); - _isStdioCommandResolved = true; - return field; - } - } - - public static bool IsJwtCommand - { - get - { - if (_isJwtCommandResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - field = args.Length > 1 && string.Equals(args[1], "jwt", StringComparison.OrdinalIgnoreCase); - _isJwtCommandResolved = true; - return field; - } - } - - public static bool IsConfigValidateCommand - { - get - { - if (_isConfigValidateCommandResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - field = args.Length > 2 && - string.Equals(args[1], "config", StringComparison.OrdinalIgnoreCase) && - string.Equals(args[2], "validate", StringComparison.OrdinalIgnoreCase) && - !args.Any(arg => helpOptions.Contains(arg)); - _isConfigValidateCommandResolved = true; - return field; - } - } - - public static bool IsDetachedMode - { - get - { - if (_isDetachedModeResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - field = args.Contains("--detach") || args.Contains("-d"); - _isDetachedModeResolved = true; - return field; - } - } - - /// - /// Determines if the root command (proxy itself) is being invoked. - /// Returns true when no subcommand is specified (only options or no args). - /// A subcommand is detected when the first non-program argument doesn't start with '-'. - /// - public static bool IsRootCommand - { - get - { - if (_isRootCommandResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - // Skip the first argument which is the program name - // If there are no more arguments, it's the root command - // If the first argument starts with '-', it's an option (root command) - // Otherwise, it's a subcommand name - field = args.Length <= 1 || args[1].StartsWith('-'); - _isRootCommandResolved = true; - return field; - } - } - - public static bool IsInternalDaemon - { - get - { - if (_isInternalDaemonResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - field = args.Contains("--_internal-daemon"); - _isInternalDaemonResolved = true; - return field; - } - } - - public static string StdioLogFilePath - { - get - { - if (_stdioLogFilePathResolved) - { - return field ?? string.Empty; - } - - field = Path.Combine( - Directory.GetCurrentDirectory(), - $"devproxy-stdio-{DateTime.Now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture)}.log"); - _stdioLogFilePathResolved = true; - return field; - } - } - - public static string DetachedLogFilePath - { - get - { - if (_detachedLogFilePathResolved) - { - return field ?? string.Empty; - } - - field = State.StateManager.GenerateLogFilePath(); - _detachedLogFilePathResolved = true; - return field; - } - } - - public static bool NoColor => ShouldDisableColor( - Environment.GetCommandLineArgs(), - Environment.GetEnvironmentVariable("NO_COLOR"), - Environment.GetEnvironmentVariable("TERM")); - - // Per https://no-color.org, NO_COLOR disables color only when present and not empty. - internal static bool ShouldDisableColor(string[] args, string? noColorEnv, string? termEnv) => - args.Contains(NoColorOptionName) || - !string.IsNullOrEmpty(noColorEnv) || - string.Equals(termEnv, "dumb", StringComparison.OrdinalIgnoreCase); - - public DevProxyCommand( - IEnumerable plugins, - ISet urlsToWatch, - IProxyConfiguration proxyConfiguration, - IServiceProvider serviceProvider, - UpdateNotification updateNotification, - DevProxyConfigOptions options, - ILogger logger) : base($"Start Dev Proxy\n\nAPI:\n Dev Proxy exposes an authenticated REST API for runtime management.\n Use --api-port (default: {proxyConfiguration.ApiPort}) and --api-ip-address (default: 127.0.0.1).\n The API bind address is independent of --ip-address.\n Run 'devproxy status' for the API URL and token, or 'devproxy api show' for endpoints.\n Set the DEV_PROXY_API_TOKEN environment variable (at least 32 characters) to use a fixed API token instead of a generated one.") - { - _serviceProvider = serviceProvider; - _plugins = plugins; - _urlsToWatch = urlsToWatch; - _proxyConfiguration = proxyConfiguration; - _updateNotification = updateNotification; - _logger = logger; - - ConfigureCommand(options); - } - - public async Task InvokeAsync(string[] args, WebApplication app) - { - _app = app; - // Use special parsing for stdio command to disable response file expansion (@file) - // This allows npm package names like @devproxy/mcp to be passed through literally - var parseResult = IsStdioCommand - ? StdioCommand.ParseStdioArgs(this, args) - : Parse(args); - - if (parseResult.Action is ParseErrorAction parseErrorAction) - { - parseErrorAction.ShowHelp = false; - } - - var exitCode = await parseResult.InvokeAsync(null, app.Lifetime.ApplicationStopping); - - // Return exit code 2 for input validation and parse errors to distinguish - // them from runtime errors (exit code 1), following conventions from - // curl, git, and others - if (exitCode != 0 && parseResult.Errors.Count > 0) - { - return 2; - } - - return exitCode; - } - - private async Task InvokeAsync(ParseResult parseResult, CancellationToken cancellationToken) - { - if (_app is null) - { - throw new InvalidOperationException("WebApplication instance is not set. Please provide it when invoking the command."); - } - // Environment overrides from config and --env are applied by now, so this - // validates and pins the effective token before anything reads it. - if (!ApiSecurity.TryInitializeToken(out var tokenError)) - { - _logger.LogError("{TokenError}", tokenError); - return 1; - } - if (!_plugins.Any()) - { - _logger.LogError("You haven't configured any plugins. Please add plugins to your configuration file. Dev Proxy will exit."); - return 1; - } - if (_urlsToWatch.Count == 0) - { - _logger.LogError("You haven't configured any URLs to watch. Please add URLs to your configuration file or use the --urls-to-watch option. Dev Proxy will exit."); - return 1; - } - - ConfigureFromOptions(parseResult); - var optionsLoadedArgs = new OptionsLoadedArgs(parseResult); - foreach (var plugin in _plugins.Where(p => p.Enabled)) - { - plugin.OptionsLoaded(optionsLoadedArgs); - } - - await CheckForNewVersionAsync(); - - try - { - await ApiSecurity.SaveTokenAsync(cancellationToken); - await _app.StartAsync(cancellationToken); - - var serverAddresses = _app.Services.GetRequiredService().Features.Get(); - var serverAddress = serverAddresses?.Addresses.FirstOrDefault(); - var address = ApiSecurity.GetApiUrl(serverAddress ?? - new UriBuilder(Uri.UriSchemeHttp, _proxyConfiguration.ApiIpAddress, _proxyConfiguration.ApiPort).Uri.AbsoluteUri); - _logger.LogInformation("Dev Proxy API listening on {Address}...", address); - - if (_proxyConfiguration.Output != OutputFormat.Json) - { - ApiSecurity.LogTokenOnce(_logger); - } - - if (!System.Net.IPAddress.IsLoopback(System.Net.IPAddress.Parse(_proxyConfiguration.ApiIpAddress))) - { - _logger.LogWarning("The Dev Proxy API is bound to {ApiIpAddress} off-loopback. Bearer tokens are sent over HTTP; use only on trusted networks or through a secure tunnel.", _proxyConfiguration.ApiIpAddress); - } - - await WriteInstanceStateAsync(address); - // Hotkeys write directly to the console, so release them after startup logging is complete. - _app.Services.GetRequiredService().CompleteStartupMessages(); - - await _app.WaitForShutdownAsync(cancellationToken); - - return 0; - } - catch (TaskCanceledException) - { - throw; - } - catch (Exception ex) - { - _logger.LogError(ex, "An error occurred while running Dev Proxy"); - var inner = ex.InnerException; - - while (inner is not null) - { - _logger.LogError(inner, "============ Inner exception ============"); - inner = inner.InnerException; - } -#if DEBUG - throw; // so debug tools go straight to the source of the exception when attached -#else - return 1; -#endif - } - } - - private void ConfigureCommand(DevProxyConfigOptions configOptions) - { - ConfigFileOption.Validators.Clear(); - ConfigFileOption.Validators.Add(input => - { - var filePath = configOptions.ConfigFile ?? ProxyUtils.ReplacePathTokens(input.Tokens[0].Value); - if (string.IsNullOrEmpty(filePath)) - { - return; - } - - if (!File.Exists(filePath)) - { - input.AddError($"Configuration file '{filePath}' does not exist. Check the file path and try again."); - } - }); - - var ipAddressOption = new Option(IpAddressOptionName) - { - Description = "The IP address for the proxy to bind to", - HelpName = "ip-address" - }; - ipAddressOption.Validators.Add(input => - { - if (!System.Net.IPAddress.TryParse(input.Tokens[0].Value, out _)) - { - input.AddError($"'{input.Tokens[0].Value}' is not a valid IP address. Example: 127.0.0.1"); - } - }); - - var urlsToWatchOption = new Option?>(UrlsToWatchOptionName, "-u") - { - AllowMultipleArgumentsPerToken = true, - Arity = ArgumentArity.ZeroOrMore, - Description = "The list of URLs to watch for requests", - HelpName = "urls-to-watch", - }; - - var logLevelOption = new Option(LogLevelOptionName) - { - Description = $"Level of messages to log. Allowed values: {string.Join(", ", Enum.GetNames())}", - HelpName = "log-level", - Recursive = true - }; - logLevelOption.Validators.Add(input => - { - if (!Enum.TryParse(input.Tokens[0].Value, true, out _)) - { - input.AddError($"'{input.Tokens[0].Value}' is not a valid log level. Allowed values: {string.Join(", ", Enum.GetNames())}"); - } - }); - - var portOption = new Option(PortOptionName, "-p") - { - Description = "The port for the proxy to listen on", - HelpName = "port" - }; - - var apiPortOption = new Option(ApiPortOptionName) - { - Description = "The port for the Dev Proxy API to listen on", - HelpName = "api-port" - }; - var apiIpAddressOption = new Option(ApiIpAddressOptionName) - { - Description = "The API bind address (default: 127.0.0.1). Use ::1 for IPv6 loopback. Non-loopback binding requires a trusted network", - HelpName = "api-ip-address" - }; - apiIpAddressOption.Validators.Add(input => - { - if (!System.Net.IPAddress.TryParse(input.Tokens[0].Value, out _)) - { - input.AddError("The API address must be an IP address, for example 127.0.0.1 or ::1."); - } - }); - - var recordOption = new Option(RecordOptionName) - { - Description = "Use this option to record all request logs" - }; - - var watchPidsOption = new Option>(WatchPidsOptionName) - { - AllowMultipleArgumentsPerToken = true, - Description = "The IDs of processes to watch for requests", - HelpName = "pids" - }; - - var watchProcessNamesOption = new Option>(WatchProcessNamesOptionName) - { - AllowMultipleArgumentsPerToken = true, - Description = "The names of processes to watch for requests", - HelpName = "process-names", - }; - - var watchProcessTreeOption = new Option(WatchProcessTreeOptionName) - { - Description = "Also watch descendants of processes selected by --watch-pids or --watch-process-names" - }; - - var noFirstRunOption = new Option(NoFirstRunOptionName) - { - Description = "Skip the first run experience" - }; - - var noWatchOption = new Option(NoWatchOptionName) - { - Description = "Disable automatic restart on configuration file changes" - }; - - var discoverOption = new Option(DiscoverOptionName) - { - Description = "Run Dev Proxy in discovery mode" - }; - - var asSystemProxyOption = new Option(AsSystemProxyOptionName) - { - Description = "Set Dev Proxy as the system proxy" - }; - - var installCertOption = new Option(InstallCertOptionName) - { - Description = "Install self-signed certificate" - }; - installCertOption.Validators.Add(input => - { - try - { - var asSystemProxy = input.GetValue(asSystemProxyOption) ?? true; - var installCert = input.GetValue(installCertOption) ?? true; - if (asSystemProxy && !installCert) - { - input.AddError($"Requires option '{AsSystemProxyOptionName}' to be 'false'"); - } - } - catch (InvalidOperationException ex) - { - input.AddError(ex.Message); - } - }); - - var timeoutOption = new Option(TimeoutOptionName, "-t") - { - Description = "Time in seconds after which Dev Proxy exits. Resets when Dev Proxy intercepts a request.", - HelpName = "timeout" - }; - timeoutOption.Validators.Add(input => - { - try - { - if (!long.TryParse(input.Tokens[0].Value, out var timeoutInput) || timeoutInput < 1) - { - input.AddError($"'{input.Tokens[0].Value}' is not a valid timeout value. Specify a positive integer (in seconds)."); - } - } - catch (InvalidOperationException ex) - { - input.AddError(ex.Message); - } - }); - - var envOption = new Option(EnvOptionName, "-e") - { - AllowMultipleArgumentsPerToken = true, - Arity = ArgumentArity.ZeroOrMore, - Description = "Environment variables to set for the Dev Proxy process, in name=value format. Also used to replace {name} placeholders in API spec files used by the MinimalPermissions plugins. Changes to HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, or NO_PROXY (including lowercase variants) require a full stop/start; hot reload cannot refresh cached HTTP proxy settings", - HelpName = "env", - }; - envOption.Validators.Add(input => - { - try - { - var envVars = input.GetValue(envOption); - if (envVars is null || envVars.Length == 0) - { - return; - } - - foreach (var envVar in envVars) - { - // Split on first '=' only - var parts = envVar.Split('=', 2); - if (parts.Length != 2 || parts[0].Length == 0) - { - input.AddError($"Invalid environment variable format: '{envVar}'. Expected format is 'name=value'."); - return; - } - } - } - catch (InvalidOperationException ex) - { - input.AddError(ex.Message); - } - }); - - var outputOption = new Option(OutputOptionName) - { - Description = $"Output format. Allowed values: {string.Join(", ", Enum.GetNames())}", - HelpName = "format", - Recursive = true - }; - outputOption.Validators.Add(input => - { - if (input.Tokens.Count == 0) - { - return; - } - if (!Enum.TryParse(input.Tokens[0].Value, true, out _)) - { - input.AddError($"'{input.Tokens[0].Value}' is not a valid output format. Allowed values: {string.Join(", ", Enum.GetNames())}"); - } - }); - - var detachedOption = new Option(DetachedOptionName, "-d") - { - Description = "Run Dev Proxy in the background" - }; - - var internalDaemonOption = new Option(InternalDaemonOptionName) - { - Description = "Internal use only - do not use directly", - Hidden = true - }; - - var noColorOption = new Option(NoColorOptionName) - { - Description = "Disable colored output", - Arity = ArgumentArity.Zero, - Recursive = true - }; - - var options = new List