diff --git a/.github/workflows/client-smoke-tests.yml b/.github/workflows/client-smoke-tests.yml index a0eb0995a..2395b5d8d 100644 --- a/.github/workflows/client-smoke-tests.yml +++ b/.github/workflows/client-smoke-tests.yml @@ -21,7 +21,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: Setup Node.js uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: @@ -42,5 +42,5 @@ jobs: dotnet build DevProxy.Plugins/DevProxy.Plugins.csproj -c Release --no-restore - name: Run client smoke tests env: - DEVPROXY: ${{ github.workspace }}/DevProxy/bin/Release/net10.0/devproxy + DEVPROXY: ${{ github.workspace }}/DevProxy/bin/Release/net11.0/devproxy run: tests/clients/run.sh diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index ce97ee71a..f83e802ef 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -50,7 +50,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 e4433a75d..4d2c36023 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.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: Cache NuGet packages uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: @@ -77,7 +77,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: Cache NuGet packages uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: 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 c55b7e202..7b141252a 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 @@ -38,12 +39,6 @@ - - - - - - @@ -52,4 +47,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 3e026aa61..4873628e1 100644 --- a/DevProxy.Abstractions/Utils/ProxyUtils.cs +++ b/DevProxy.Abstractions/Utils/ProxyUtils.cs @@ -775,7 +775,7 @@ public static IEnumerable GetWildcardPatterns(ReadOnlyCollection // For single URLs, use the URL up to the last segment var uri = new Uri(url); var path = uri.AbsolutePath; - var lastSlashIndex = path.LastIndexOf('/'); + var lastSlashIndex = path.AsSpan().LastIndexOf('/'); return $"{group.Key}{path[..lastSlashIndex]}/*"; } @@ -899,7 +899,7 @@ private static List SplitOutsideQuotes(string value, char separator) private static bool IsPlaceHolderSegment(string segment) { - return segment.StartsWith('{') && segment.EndsWith('}'); + return segment is ['{', .., '}']; } private static ParsedSample ParseSampleUrl(string url, string? version = null) @@ -993,7 +993,7 @@ private static string GetCommonPrefix(List paths) // Find the last complete path segment var prefix = firstPath[..commonPrefixLength]; - var lastSlashIndex = prefix.LastIndexOf('/'); + 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 61877a071..81e6fbaad 100644 --- a/DevProxy.Abstractions/packages.lock.json +++ b/DevProxy.Abstractions/packages.lock.json @@ -31,51 +31,49 @@ }, "Microsoft.Extensions.Configuration": { "type": "Direct", - "requested": "[11.0.0, )", - "resolved": "11.0.0", - "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", + "requested": "[10.0.15, )", + "resolved": "10.0.15", + "contentHash": "XwGgzRlryUvICZbY/oNlR1MbFDYg6gePDoW38RyUis8vEAVKIHvMy9di5dujK6dObbUOQJpHtrjUZ2rU0V7RvQ==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", - "Microsoft.Extensions.Primitives": "11.0.0" + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Primitives": "10.0.15" } }, "Microsoft.Extensions.Configuration.Binder": { "type": "Direct", - "requested": "[11.0.0, )", - "resolved": "11.0.0", - "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", + "requested": "[10.0.15, )", + "resolved": "10.0.15", + "contentHash": "VOjlZlv9b3woS1TcI8Ts1r2IsmsT7hqkx7o2sMSNzE5fPBGKfhJszlEIhtQVzUz4H8Uw/7Jtuj9x7wGlCUsi2A==", "dependencies": { - "Microsoft.Extensions.Configuration": "11.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15" } }, "Microsoft.Extensions.Configuration.Json": { "type": "Direct", - "requested": "[11.0.0, )", - "resolved": "11.0.0", - "contentHash": "WsNcEnVlq43lXBHAXtQg1b7job819SUf9BPtJrq44vhthL9Ijl2mkRBx5L3hIU1p2AN+wiRg47yhYj+vQxEgeQ==", + "requested": "[10.0.15, )", + "resolved": "10.0.15", + "contentHash": "5+FOOsKnE3Vf/q2yIHL+gljoJbmT8WB9vuXeJfXNav14OBCmn5wuQM6Fs3y0mxmRvQVRQvfzmpSvaXRXJBfDdw==", "dependencies": { - "Microsoft.Extensions.Configuration": "11.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", - "Microsoft.Extensions.Configuration.FileExtensions": "11.0.0", - "Microsoft.Extensions.FileProviders.Abstractions": "11.0.0", - "System.Text.Json": "11.0.0" + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Configuration.FileExtensions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15" } }, "Microsoft.Extensions.FileSystemGlobbing": { "type": "Direct", - "requested": "[11.0.0, )", - "resolved": "11.0.0", - "contentHash": "Ycwu/y22NK/ZyJpaFRJc4FB88mjOnsttk2AVHaKgEeShq0vodXZ4FJErpMM2Jju3r3t/2VYWrcHuIxj3ZT/aow==" + "requested": "[10.0.15, )", + "resolved": "10.0.15", + "contentHash": "2Vc8lDEufnkNpp/8Q3mP77Hz2BnPhuKzj9MiMTINiRJ23gCudPewm3yQdxvBbWpZZw68PxQ61CZMo0rS/WwDAg==" }, "Microsoft.Extensions.Logging.Abstractions": { "type": "Direct", - "requested": "[11.0.0, )", - "resolved": "11.0.0", - "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", + "requested": "[10.0.15, )", + "resolved": "10.0.15", + "contentHash": "s5xzXGWqqlmmThMnQ1rnmL7QLwbluB2JqX9NaK8C9HPuHzN7kfmiddTRbwts5rQssATkh2B18RrofjeUD8g14A==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", - "System.Diagnostics.DiagnosticSource": "11.0.0" + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" } }, "Microsoft.OpenApi": { @@ -197,22 +195,22 @@ }, "Microsoft.Extensions.Configuration.Abstractions": { "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", + "resolved": "10.0.15", + "contentHash": "0vztB/x4zuR/KT82cgTiiw9DqigfT1FjBgq9FjEFvJUgeacjTG4e7hWD2PCRXzL2kWWl/vBAwtXddIRV3AIU6Q==", "dependencies": { - "Microsoft.Extensions.Primitives": "11.0.0" + "Microsoft.Extensions.Primitives": "10.0.15" } }, "Microsoft.Extensions.Configuration.FileExtensions": { "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "ViBZDt2Y7TfVIxiWG5HKfP1KHTzsxn7a31ikZSg/1mdOfGyGAPj278v63NOU+n4UqvaOR43t9MOCUfadSohjQA==", + "resolved": "10.0.15", + "contentHash": "zA3VutAch9qe/WcKfVRXnivIMdAeZsxWVbFDO6Z9P6NQdNH73SXrULoH7PYfdC+CBsLiMKvx6z4oTjAvuKPGpA==", "dependencies": { - "Microsoft.Extensions.Configuration": "11.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", - "Microsoft.Extensions.FileProviders.Abstractions": "11.0.0", - "Microsoft.Extensions.FileProviders.Physical": "11.0.0", - "Microsoft.Extensions.Primitives": "11.0.0" + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Physical": "10.0.15", + "Microsoft.Extensions.Primitives": "10.0.15" } }, "Microsoft.Extensions.DependencyInjection": { @@ -225,8 +223,8 @@ }, "Microsoft.Extensions.DependencyInjection.Abstractions": { "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" + "resolved": "10.0.15", + "contentHash": "KczR2nV7ooeimtZxAawPht/FJUHnX+uoWy7y4pba+iaRQBwUM2NwtiqZg+/FpZDHUf2RkkzveGkhMTWDNzmDUA==" }, "Microsoft.Extensions.DependencyModel": { "type": "Transitive", @@ -235,20 +233,20 @@ }, "Microsoft.Extensions.FileProviders.Abstractions": { "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "e3NvNYCuKZ42qlNCryuSmo+xxlhBZeS2Sh5sIPCn+wRSHc0F9N8oAC+r0ki1Yh/KMfw4H6KLh4p9u4TGWye7fw==", + "resolved": "10.0.15", + "contentHash": "1RSYAUtJeb76m2T0u5BbvwKY3s+ge9fT3cj1odvo5Bm+frc7pU9RSeXeMIlYHV8GjpqLdv2neeeomz010yYL8A==", "dependencies": { - "Microsoft.Extensions.Primitives": "11.0.0" + "Microsoft.Extensions.Primitives": "10.0.15" } }, "Microsoft.Extensions.FileProviders.Physical": { "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "lHezhjI8zoTpltXwNy6QMr4/6lIhbXsAYZnCrgRDNNzMHCKvh+x95mkBVXLMzs8axrw7J5Cy21K8lM5YHCfgAw==", + "resolved": "10.0.15", + "contentHash": "2hOXuMZ//9h6foRT4KzcrooXNpf9GC6uk1p41kRHiSiVNNHwEeLywqafzHv+rjxKcN5+Ld9ZjnZayxRCgp+nAQ==", "dependencies": { - "Microsoft.Extensions.FileProviders.Abstractions": "11.0.0", - "Microsoft.Extensions.FileSystemGlobbing": "11.0.0", - "Microsoft.Extensions.Primitives": "11.0.0" + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.FileSystemGlobbing": "10.0.15", + "Microsoft.Extensions.Primitives": "10.0.15" } }, "Microsoft.Extensions.Logging": { @@ -272,8 +270,8 @@ }, "Microsoft.Extensions.Primitives": { "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" + "resolved": "10.0.15", + "contentHash": "NjzLiZ1/bYx8VwLqHxNnCfDTQQbCY7P1dwT7JM5FiANiaSfI6UKHi0/sla+jyRbOIbPAMJkhWQ/9pH3tMf+IrQ==" }, "Newtonsoft.Json": { "type": "Transitive", @@ -311,29 +309,244 @@ "dependencies": { "SQLitePCLRaw.core": "2.1.13" } + } + }, + "net11.0": { + "Markdig": { + "type": "Direct", + "requested": "[1.6.0, )", + "resolved": "1.6.0", + "contentHash": "rJEpDfPM8wrfXUgkNejjg2bJN9bciy44uVyRwKUI+92CnSmbaLeJTLPYcCdvgM4RFsKrhs8d2H2hO78yZpMl3g==" + }, + "Microsoft.CodeAnalysis.BannedApiAnalyzers": { + "type": "Direct", + "requested": "[5.6.0, )", + "resolved": "5.6.0", + "contentHash": "Kcobt3pnOdO0A+6CKiMHZdTEluJpsfxiV20axtZdmfBQnDmiWTKPJADlgAfdTuKNAnVarrkJa0UEGwuOo91muw==" + }, + "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" + } }, - "System.Diagnostics.DiagnosticSource": { + "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.1, )", + "resolved": "3.11.1", + "contentHash": "WZL9g2+9NPICW4Es6zjIBj4mmKxAnI8RCru3gAZUliCMZPnuaxRynXq4cXoU+IYvI7kXY4ydSrrJ1R9EEHr+Lw==" + }, + "Microsoft.OpenApi.YamlReader": { + "type": "Direct", + "requested": "[3.11.1, )", + "resolved": "3.11.1", + "contentHash": "mYEWPSCxHsy0IiZcvQe6ml88lt/ueaKet/D6WYOge2vzOemW1UeDJNYoZSvJV0jDmCCK4PPFAjHoAkLiFhTAhg==", + "dependencies": { + "Microsoft.OpenApi": "3.11.1", + "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.6.1, )", + "resolved": "7.6.1", + "contentHash": "EHEiHXenLu4qbPE+pplWzPKX937juMGW5BPVCHF8pyllWvQP0H57BAtWxiyMTk4G+aKH8iHLKgcoYSHemP6DJg==" + }, + "System.CommandLine": { + "type": "Direct", + "requested": "[3.0.0, )", + "resolved": "3.0.0", + "contentHash": "swNpSTl0iYJeBuvYYfaY+VxzZ5YC8wklwkqDCNOq2aTQqJzjauJfh/O3Zw93nwxspWrxvZTjT45f8VPR0ParEA==" + }, + "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": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" + "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" + } }, - "System.IO.Pipelines": { + "Microsoft.EntityFrameworkCore.Abstractions": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "F3biHUDT5JWIKhEcZrRjKuYy7XGZOe3GOU2N6rSOQeZBx+Ko/PY7K+VaC3BwD+ofQ9k0MXIhEB7uqJSRkZAkQQ==" + "contentHash": "iL0D3Dohk6bNYIHSM3VhvDXrJ+WXs7yMBVv+4L1ozxbsDmohG0T3ogd0mLgWBofu49BHGOgfFKgSGLsOirsjoQ==" }, - "System.Text.Encodings.Web": { + "Microsoft.EntityFrameworkCore.Analyzers": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "yNdu/KHBHq1rCu0d6TwKWNL1SvomZB4c/S0l4XKF1PX0gOIlPfnGVeBg7sQ3dmgy5e3UA+JGidak3abyBdlYAQ==" + "contentHash": "R7QxcmtQLP5np732En6eyzv2DjKevbrRxUUY9jPRQwuLzOSbyDowE5l0KyqdEEySvdHbrdRILg99FlaJTwcPbQ==" }, - "System.Text.Json": { + "Microsoft.EntityFrameworkCore.Relational": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "hyLfq7fRYbq8m3ENGqgEYkqxLeLx2xmNMlf6UG1a7RQo9OsTsfm4Ch/E6O+A5vYQ2ThneLUn1CHF644lmH5QhA==", + "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": { - "System.IO.Pipelines": "11.0.0", - "System.Text.Encodings.Web": "11.0.0" + "SQLitePCLRaw.core": "3.0.5" } } } diff --git a/DevProxy.Integration.Tests/CommandExitCodeTests.cs b/DevProxy.Integration.Tests/CommandExitCodeTests.cs index 28405c768..ed161d754 100644 --- a/DevProxy.Integration.Tests/CommandExitCodeTests.cs +++ b/DevProxy.Integration.Tests/CommandExitCodeTests.cs @@ -39,7 +39,7 @@ public async Task ConfigNew_JsonOutputAboveInformation_EmitsResultRecord(string Assert.True(exitCode == 0, output); var results = stdout.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) - .Select(line => JsonDocument.Parse(line).RootElement) + .Select(line => JsonElement.Parse(line)) .Where(entry => entry.GetProperty("type").GetString() == "result") .ToArray(); var result = Assert.Single(results); @@ -259,7 +259,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 567ddb1f8..28d1c7e20 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 e7b6b238f..2c886c5c7 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)); }); } @@ -73,8 +72,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 c89f2d522..42ec433d6 100644 --- a/DevProxy.Integration.Tests/ProcessSmokeTests.cs +++ b/DevProxy.Integration.Tests/ProcessSmokeTests.cs @@ -371,7 +371,9 @@ public async Task Detach_WithCapturedOutput_ParentOutputReachesEofWhileDaemonKee await process.WaitForExitAsync(exitTimeout.Token); // The parent has exited; if the daemon inherited our pipes, EOF never comes. - completed = await Task.WhenAny(eof, Task.Delay(TimeSpan.FromSeconds(15))); + using var eofTimeout = new CancellationTokenSource(); + completed = await Task.WhenAny(eof, Task.Delay(TimeSpan.FromSeconds(15), eofTimeout.Token)); + await eofTimeout.CancelAsync(); } finally { @@ -766,7 +768,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 fa7ddf5c1..bfafa43a6 100644 --- a/DevProxy.Plugins/ApiCenter/ApiCenterClient.cs +++ b/DevProxy.Plugins/ApiCenter/ApiCenterClient.cs @@ -1,204 +1,204 @@ -// 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."); - } - - _logger = logger; - - // 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; - - _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 string ResolveEnvironmentVariable(string value, string settingName) - { - if (!value.StartsWith('@')) - { - return value; - } - - var variableName = value[1..]; - _logger.LogWarning( - "Referencing environment variables using @{VariableName} in {SettingName} is deprecated and will be removed in a future version. Use ${{NAME}} instead", - variableName, settingName); - 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."); + } + + _logger = logger; + + // 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; + + _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 string ResolveEnvironmentVariable(string value, string settingName) + { + if (!value.StartsWith('@', StringComparison.Ordinal)) + { + return value; + } + + var variableName = value[1..]; + _logger.LogWarning( + "Referencing environment variables using @{VariableName} in {SettingName} is deprecated and will be removed in a future version. Use ${{NAME}} instead", + variableName, settingName); + 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 264c6840d..f18bfd75a 100644 --- a/DevProxy.Plugins/Behavior/GenericRandomErrorPlugin.cs +++ b/DevProxy.Plugins/Behavior/GenericRandomErrorPlugin.cs @@ -1,395 +1,395 @@ -// 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 || - !errorResponse.Responses.Any()) - { - 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 (error.Responses is null || !error.Responses.Any()) - { - Logger.LogWarning("Error for {Url} in {ErrorsFile} has no responses and will be ignored", error.Request.Url, Configuration.ErrorsFile); - 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 || + !errorResponse.Responses.Any()) + { + 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 (error.Responses is null || !error.Responses.Any()) + { + Logger.LogWarning("Error for {Url} in {ErrorsFile} has no responses and will be ignored", error.Request.Url, Configuration.ErrorsFile); + 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 60bd6e5f2..68ef0eef6 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,7 +21,7 @@ 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 09ad50756..9be435ee6 100644 --- a/DevProxy.Plugins/Generation/OpenApiSpecGeneratorPlugin.cs +++ b/DevProxy.Plugins/Generation/OpenApiSpecGeneratorPlugin.cs @@ -1048,7 +1048,7 @@ private static string ParametrizePath(OpenApiPathItem pathItem, Uri requestUri) { parameterName = $"{parameterName}-{count}"; } - segments[i] = $"{{{parameterName}}}{(requestUri.Segments[i].EndsWith('/') ? "/" : "")}"; + segments[i] = $"{{{parameterName}}}{(requestUri.Segments[i].EndsWith('/', StringComparison.Ordinal) ? "/" : "")}"; pathItem.Parameters?.Add(new OpenApiParameter { diff --git a/DevProxy.Plugins/Generation/TypeSpecGeneratorPlugin.cs b/DevProxy.Plugins/Generation/TypeSpecGeneratorPlugin.cs index ca2061245..f690d9181 100644 --- a/DevProxy.Plugins/Generation/TypeSpecGeneratorPlugin.cs +++ b/DevProxy.Plugins/Generation/TypeSpecGeneratorPlugin.cs @@ -743,7 +743,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/Guidance/GraphMissingPermissionsGuidancePlugin.cs b/DevProxy.Plugins/Guidance/GraphMissingPermissionsGuidancePlugin.cs index a8cfcec70..d7e435a23 100644 --- a/DevProxy.Plugins/Guidance/GraphMissingPermissionsGuidancePlugin.cs +++ b/DevProxy.Plugins/Guidance/GraphMissingPermissionsGuidancePlugin.cs @@ -98,7 +98,7 @@ public override async Task AfterResponseAsync(ProxyResponseArgs e, CancellationT // analyze in parallel to limit the delay before the response is sent to the client var guidance = await Task.WhenAll(failedRequests.Select(failedRequest => { - var relativeUrl = failedRequest.Url.StartsWith('/') ? failedRequest.Url : $"/{failedRequest.Url}"; + var relativeUrl = failedRequest.Url.StartsWith('/', StringComparison.Ordinal) ? failedRequest.Url : $"/{failedRequest.Url}"; var absoluteUrl = $"https://{request.RequestUri.Host}/{graphVersion}{relativeUrl}"; return AnalyzeForbiddenRequestAsync( failedRequest.Method, diff --git a/DevProxy.Plugins/Mocking/MockResponsePlugin.cs b/DevProxy.Plugins/Mocking/MockResponsePlugin.cs index 90e5fd48c..2f19ae535 100644 --- a/DevProxy.Plugins/Mocking/MockResponsePlugin.cs +++ b/DevProxy.Plugins/Mocking/MockResponsePlugin.cs @@ -477,7 +477,7 @@ private void ProcessMockResponseInternal(ProxyRequestArgs e, MockResponse matchi ? s_serializedBodies.GetValue(currentBody, static b => new(ProxyUtils.SerializeBody(b))) : null; string bodyString = serialized?.Text ?? ProxyUtils.SerializeBody(currentBody); - 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/Mocking/OpenApiMockResponsePlugin.cs b/DevProxy.Plugins/Mocking/OpenApiMockResponsePlugin.cs index ea4481e1f..aae17c70e 100644 --- a/DevProxy.Plugins/Mocking/OpenApiMockResponsePlugin.cs +++ b/DevProxy.Plugins/Mocking/OpenApiMockResponsePlugin.cs @@ -253,7 +253,7 @@ private static (HttpStatusCode StatusCode, IOpenApiResponse? Response) GetMockRe } var successResponse = responses - .Where(r => r.Key.StartsWith('2')) + .Where(r => r.Key.StartsWith('2', StringComparison.Ordinal)) .OrderBy(r => r.Key, StringComparer.Ordinal) .FirstOrDefault(); if (successResponse.Value is not null) diff --git a/DevProxy.Plugins/Reporting/OpenApiValidationPlugin.cs b/DevProxy.Plugins/Reporting/OpenApiValidationPlugin.cs index 22db5e9e1..b97711cba 100644 --- a/DevProxy.Plugins/Reporting/OpenApiValidationPlugin.cs +++ b/DevProxy.Plugins/Reporting/OpenApiValidationPlugin.cs @@ -365,7 +365,7 @@ private static IEnumerable GetRelativePaths(ServerScope server, string[] { foreach (var url in requestUrls) { - var pathStart = url.IndexOf('/', url.IndexOf("://", StringComparison.Ordinal) + 3); + var pathStart = url.IndexOf('/', url.IndexOf("://", StringComparison.Ordinal) + 3, StringComparison.Ordinal); if (pathStart < 0) { pathStart = url.Length; @@ -1047,7 +1047,7 @@ private static Regex CompileServerUrl(string url, IDictionary https://api.contoso.com origin = Regex.Replace(origin, "^(?:(?https://[^/]*):443|(?http://[^/]*):80)$", "${o}", diff --git a/DevProxy.Plugins/Utils/OpenApiSchemaValidator.cs b/DevProxy.Plugins/Utils/OpenApiSchemaValidator.cs index b19fcc678..60f775e4c 100644 --- a/DevProxy.Plugins/Utils/OpenApiSchemaValidator.cs +++ b/DevProxy.Plugins/Utils/OpenApiSchemaValidator.cs @@ -177,7 +177,7 @@ private static IEnumerable SplitArrayValues(IReadOnlyList values private static string StripStylePrefix(string value, string name, ParameterStyle style) => style switch { - ParameterStyle.Label when value.StartsWith('.') => value[1..], + ParameterStyle.Label when value.StartsWith('.', StringComparison.Ordinal) => value[1..], ParameterStyle.Matrix when value.StartsWith($";{name}=", StringComparison.Ordinal) => value[(name.Length + 2)..], ParameterStyle.Matrix when value == $";{name}" => string.Empty, _ => value diff --git a/DevProxy.Plugins/packages.lock.json b/DevProxy.Plugins/packages.lock.json index a081f6b63..84542962f 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, )", @@ -19,28 +19,23 @@ }, "Microsoft.EntityFrameworkCore.Sqlite": { "type": "Direct", - "requested": "[10.0.15, )", - "resolved": "10.0.15", - "contentHash": "t6kIAikliaVrVjChJS11d+riwBK1du8GY2r9zMHjVlQIl0wIocd8a4vWAPd+MakWKLiJa+ZXIgMzxn8f3z5DYg==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "12olimxsnuTo+9jsQvbS9fF/FXUhW7AHaXFcK/TgpND3Ki53CBvXnvT+AnPnk6d6f02D5NBdmBcZzfAynBgkRw==", "dependencies": { - "Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.15", - "Microsoft.Extensions.Caching.Memory": "10.0.15", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", - "Microsoft.Extensions.DependencyModel": "10.0.15", - "Microsoft.Extensions.Logging": "10.0.15", - "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": "[11.0.0, )", "resolved": "11.0.0", - "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", - "Microsoft.Extensions.Primitives": "11.0.0" - } + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==" }, "Microsoft.Extensions.FileSystemGlobbing": { "type": "Direct", @@ -86,9 +81,8 @@ "resolved": "1.21.0", "contentHash": "ynAzNO/ebDTPxARbz4z/HgL8azMk/iDk4GXFuIRQ6krr1+a5QMC4eoiXRl+e7COd+3RLyL/yTuE6bevwqbv4Bw==", "dependencies": { - "Microsoft.Extensions.Configuration.EnvironmentVariables": "10.0.0", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.0", - "Microsoft.Extensions.Logging.Configuration": "10.0.0", + "Microsoft.Extensions.Configuration.EnvironmentVariables": "11.0.0", + "Microsoft.Extensions.Logging.Configuration": "11.0.0", "OpenTelemetry.Api.ProviderBuilderExtensions": "1.21.0" } }, @@ -123,8 +117,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", @@ -148,102 +140,75 @@ }, "Microsoft.Data.Sqlite.Core": { "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "mjDz/zleAF78J1KRN9FludN2bzbsMWoXYSLVcawADle7RBhZYpFZYivGRvbvlH/RtXT/gjO0yhG99tzdFiET+A==", + "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.15", - "contentHash": "cp0ocqFrk6SXPy5xAI4gf2RlTk7jO4LcybDGWKp5F5zjPKyn2fEulElXIrCWreQFe8/4u01xoVhscrabhOOnhw==", + "resolved": "11.0.0", + "contentHash": "1zGKYhZMHG9gIfC89cC2QKM6DpNotDglm+UzYEV9dAWyLwJI8kLx+yfjAQVpC83iUzvr9y+1HJ0HZ8cOaosBXA==", "dependencies": { - "Microsoft.EntityFrameworkCore.Abstractions": "10.0.15", - "Microsoft.EntityFrameworkCore.Analyzers": "10.0.15", - "Microsoft.Extensions.Caching.Memory": "10.0.15", - "Microsoft.Extensions.Logging": "10.0.15" + "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.15", - "contentHash": "aLHlTnngp1CcWF5gWbqNwcfROjINCaQVKoySCFpl8O/EQaCdvtW+miv9KoSpKDtWIN+W7lZ8yr4KnbK3hp9oYQ==" + "resolved": "11.0.0", + "contentHash": "iL0D3Dohk6bNYIHSM3VhvDXrJ+WXs7yMBVv+4L1ozxbsDmohG0T3ogd0mLgWBofu49BHGOgfFKgSGLsOirsjoQ==" }, "Microsoft.EntityFrameworkCore.Analyzers": { "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "13C007jEmO1JVsoJ+Vvn0AzOaR5bpGsDsaOB9nQt6denQR8hmv1eWmQ0qGarvz+1Zu5b511uF74A90BQigdYHA==" + "resolved": "11.0.0", + "contentHash": "R7QxcmtQLP5np732En6eyzv2DjKevbrRxUUY9jPRQwuLzOSbyDowE5l0KyqdEEySvdHbrdRILg99FlaJTwcPbQ==" }, "Microsoft.EntityFrameworkCore.Relational": { "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "8rEj7IN4+cW1fXkENqCsHeqDrty3izIvWIw6YlXA3sYLPpie1S1MMAWrF3/QjPSI9AWL3sXT6tQqBeNeX6QWEw==", + "resolved": "11.0.0", + "contentHash": "yGS+J269mYUl8V17rHWaeFDySoUnGdiugIzszlNZr0F2+JirFatQyw2s2He92wyYIuy/Y3Yv3QLdq/HdTSj7cA==", "dependencies": { - "Microsoft.EntityFrameworkCore": "10.0.15", - "Microsoft.Extensions.Caching.Memory": "10.0.15", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", - "Microsoft.Extensions.Logging": "10.0.15" + "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.15", - "contentHash": "+StxCQ7r+6JOt37kltnnJo07Ik7KZEPYCNRWgOM0x2Cy4fKYaE8kB3YOwJF//4uIXZdkzvNgtE+6V6HsLZcQMQ==", - "dependencies": { - "Microsoft.Data.Sqlite.Core": "10.0.15", - "Microsoft.EntityFrameworkCore.Relational": "10.0.15", - "Microsoft.Extensions.Caching.Memory": "10.0.15", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", - "Microsoft.Extensions.DependencyModel": "10.0.15", - "Microsoft.Extensions.Logging": "10.0.15", - "SQLitePCLRaw.core": "2.1.13" - } - }, - "Microsoft.Extensions.Caching.Abstractions": { - "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "hzquYYxIDAOh5DZjqfWhm9jUILFguywE8KCBg+Sp4WYY1wND67qWllGXY5h2DrKneSGlqdFa0njngVT6sT+Brg==", + "resolved": "11.0.0", + "contentHash": "7u0jhtUY4GXr2MRsvSzemUpgf2znOCf8+3VLYxYNthIU5rIKk5Y+9EvS+yAlLIBL2218LeahsHYKA0MWKBYo5Q==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.15" + "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.15", - "contentHash": "uTfEHyTAxSqly3dCfqG5jVh5LZBU3pdipc5I1XLjPB7tjPV6ZejQjdiARt40X6B2yvf/4/v7hNT5D/veuf6zRA==", - "dependencies": { - "Microsoft.Extensions.Caching.Abstractions": "10.0.15", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", - "Microsoft.Extensions.Logging.Abstractions": "10.0.15", - "Microsoft.Extensions.Options": "10.0.15", - "Microsoft.Extensions.Primitives": "10.0.15" - } - }, - "Microsoft.Extensions.Configuration.Abstractions": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", - "dependencies": { - "Microsoft.Extensions.Primitives": "11.0.0" - } + "contentHash": "w0nn5qRLxZC2T3sSmXj5PhrBFpGFCSFxg7E/zBi4lne0wZcZPY8of3qQDowqGobMZ3PW5qJnM1Q8fmGjL2B6Iw==" }, "Microsoft.Extensions.Configuration.Binder": { "type": "Transitive", "resolved": "11.0.0", "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", "dependencies": { - "Microsoft.Extensions.Configuration": "11.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" + "Microsoft.Extensions.Configuration": "11.0.0" } }, "Microsoft.Extensions.Configuration.EnvironmentVariables": { "type": "Transitive", - "resolved": "10.0.0", - "contentHash": "TmFegsI/uCdwMBD4yKpmO+OkjVNHQL49Dh/ep83NI5rPUEoBK9OdsJo1zURc1A2FuS/R/Pos3wsTjlyLnguBLA==", + "resolved": "11.0.0", + "contentHash": "Cctea20Fzc9Rc1zx6QYhvu9NJJHv8mUGUmWEtKkA0Tz4JQKReSKugVYi/sHuxXG1IndFSybG6cWC06DvGgs+mA==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.0" + "Microsoft.Extensions.Configuration": "11.0.0" } }, "Microsoft.Extensions.Configuration.FileExtensions": { @@ -252,10 +217,7 @@ "contentHash": "ViBZDt2Y7TfVIxiWG5HKfP1KHTzsxn7a31ikZSg/1mdOfGyGAPj278v63NOU+n4UqvaOR43t9MOCUfadSohjQA==", "dependencies": { "Microsoft.Extensions.Configuration": "11.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", - "Microsoft.Extensions.FileProviders.Abstractions": "11.0.0", - "Microsoft.Extensions.FileProviders.Physical": "11.0.0", - "Microsoft.Extensions.Primitives": "11.0.0" + "Microsoft.Extensions.FileProviders.Physical": "11.0.0" } }, "Microsoft.Extensions.Configuration.Json": { @@ -264,129 +226,54 @@ "contentHash": "WsNcEnVlq43lXBHAXtQg1b7job819SUf9BPtJrq44vhthL9Ijl2mkRBx5L3hIU1p2AN+wiRg47yhYj+vQxEgeQ==", "dependencies": { "Microsoft.Extensions.Configuration": "11.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", - "Microsoft.Extensions.Configuration.FileExtensions": "11.0.0", - "Microsoft.Extensions.FileProviders.Abstractions": "11.0.0", - "System.Text.Json": "11.0.0" + "Microsoft.Extensions.Configuration.FileExtensions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection": { - "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "7DUIgHeJpBs1RG0hYwWDOImXP03+uPrV5KtyUPxrZsiWadlg95aYijNKCZ2j2UmufQAmN6XEQfx4B/J6TuE7lg==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" - } - }, - "Microsoft.Extensions.DependencyInjection.Abstractions": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==" }, "Microsoft.Extensions.DependencyModel": { - "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "087ome/PndkacsUGmB6OoTyhQ3UwoSRqv9odKbvdD4h3o6TqSIVIK/v1WaNKZ/oiMUVuMcV0l2yXdt55RHRxGw==" - }, - "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": "11.0.0", - "contentHash": "e3NvNYCuKZ42qlNCryuSmo+xxlhBZeS2Sh5sIPCn+wRSHc0F9N8oAC+r0ki1Yh/KMfw4H6KLh4p9u4TGWye7fw==", - "dependencies": { - "Microsoft.Extensions.Primitives": "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.FileProviders.Abstractions": "11.0.0", - "Microsoft.Extensions.FileSystemGlobbing": "11.0.0", - "Microsoft.Extensions.Primitives": "11.0.0" - } - }, - "Microsoft.Extensions.Hosting.Abstractions": { - "type": "Transitive", - "resolved": "10.0.3", - "contentHash": "GdMpC10Jf6poxSvUJ4lgYpJ5F/kJeaAoJmrPufjBoPYyCTKKY5Dyl0rZA+LBNvFqTq1cZa/lhlptlUhNvU6xrg==", - "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.15", - "contentHash": "Vya6t+hqCLeoZsbsJo5FzrEoOTK7syIeuaxLl3F8QagD3sXVxAQgmVEq5+jaA4gQ4yreg27fZ8gJH96bWtxoBQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.15", - "Microsoft.Extensions.Logging.Abstractions": "10.0.15", - "Microsoft.Extensions.Options": "10.0.15" - } - }, - "Microsoft.Extensions.Logging.Abstractions": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", - "System.Diagnostics.DiagnosticSource": "11.0.0" + "Microsoft.Extensions.DependencyInjection": "11.0.0" } }, "Microsoft.Extensions.Logging.Configuration": { "type": "Transitive", - "resolved": "10.0.0", - "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.15", - "contentHash": "vF3ghTChyyX3BDqRFUurk+fn8vZySFmWHm4vIeeOQbBrjnPqWrr5ceyCb1jrGpMasYdcK9IuJskLVQZWBfNxCg==", + "resolved": "11.0.0", + "contentHash": "zI04chEUw5Z14Jtfq4gWq/D3nnvWTqu1RMhdEMQb+gyRmMMNmeaBGL6kKvSNJ/C+lbsvhThKzYBjzdmhGn4rHg==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", - "Microsoft.Extensions.Primitives": "10.0.15" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" } }, "Microsoft.Extensions.Options.ConfigurationExtensions": { "type": "Transitive", - "resolved": "10.0.0", - "contentHash": "tL9cSl3maS5FPzp/3MtlZI21ExWhni0nnUCF8HY4npTsINw45n9SNDbkKXBMtFyUFGSsQep25fHIDN4f/Vp3AQ==", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", "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": "11.0.0" } }, - "Microsoft.Extensions.Primitives": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" - }, "Microsoft.Identity.Client": { "type": "Transitive", "resolved": "4.83.1", @@ -439,7 +326,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" } }, @@ -454,17 +340,13 @@ "OpenTelemetry.Api": { "type": "Transitive", "resolved": "1.21.0", - "contentHash": "KptD6ThegQORUzwot75zW2AUH6IDyKXH1R2yhovJPYfrzqSgHQidMfVfKLjaYEnJa5ySQgQm0RjuM6X+TCJ9yw==", - "dependencies": { - "System.Diagnostics.DiagnosticSource": "11.0.0" - } + "contentHash": "KptD6ThegQORUzwot75zW2AUH6IDyKXH1R2yhovJPYfrzqSgHQidMfVfKLjaYEnJa5ySQgQm0RjuM6X+TCJ9yw==" }, "OpenTelemetry.Api.ProviderBuilderExtensions": { "type": "Transitive", "resolved": "1.21.0", "contentHash": "ZcBCBTGbzjj8Y+9UnZKbSjnRyKc2ub2IvvU68fFHKmyKzTS4hU+4/f0PO1GoIf7FTYLKTyw+l/EwLL/PPIDkxg==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0", "OpenTelemetry.Api": "1.21.0" } }, @@ -478,31 +360,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": { @@ -510,22 +400,9 @@ "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" } }, - "System.Diagnostics.DiagnosticSource": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" - }, - "System.IO.Pipelines": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "F3biHUDT5JWIKhEcZrRjKuYy7XGZOe3GOU2N6rSOQeZBx+Ko/PY7K+VaC3BwD+ofQ9k0MXIhEB7uqJSRkZAkQQ==" - }, "System.Memory.Data": { "type": "Transitive", "resolved": "10.0.3", @@ -536,20 +413,6 @@ "resolved": "4.5.0", "contentHash": "wLBKzFnDCxP12VL9ANydSYhk59fC4cvOr9ypYQLPnAj48NQIhqnjdD2yhP8yEKyBJEjERWS9DisKL7rX5eU25Q==" }, - "System.Text.Encodings.Web": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "yNdu/KHBHq1rCu0d6TwKWNL1SvomZB4c/S0l4XKF1PX0gOIlPfnGVeBg7sQ3dmgy5e3UA+JGidak3abyBdlYAQ==" - }, - "System.Text.Json": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "hyLfq7fRYbq8m3ENGqgEYkqxLeLx2xmNMlf6UG1a7RQo9OsTsfm4Ch/E6O+A5vYQ2ThneLUn1CHF644lmH5QhA==", - "dependencies": { - "System.IO.Pipelines": "11.0.0", - "System.Text.Encodings.Web": "11.0.0" - } - }, "YamlDotNet": { "type": "Transitive", "resolved": "18.1.0", @@ -559,12 +422,11 @@ "type": "Project", "dependencies": { "Markdig": "[1.6.0, )", - "Microsoft.EntityFrameworkCore.Sqlite": "[10.0.15, )", + "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.Extensions.Logging.Abstractions": "[11.0.0, )", "Microsoft.OpenApi": "[3.11.1, )", "Microsoft.OpenApi.YamlReader": "[3.11.1, )", "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 d878e0706..5f3d344dd 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": { "Microsoft.CodeAnalysis.BannedApiAnalyzers": { "type": "Direct", "requested": "[5.6.0, )", @@ -15,157 +15,65 @@ }, "Microsoft.Data.Sqlite.Core": { "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "mjDz/zleAF78J1KRN9FludN2bzbsMWoXYSLVcawADle7RBhZYpFZYivGRvbvlH/RtXT/gjO0yhG99tzdFiET+A==", + "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.15", - "contentHash": "cp0ocqFrk6SXPy5xAI4gf2RlTk7jO4LcybDGWKp5F5zjPKyn2fEulElXIrCWreQFe8/4u01xoVhscrabhOOnhw==", + "resolved": "11.0.0", + "contentHash": "1zGKYhZMHG9gIfC89cC2QKM6DpNotDglm+UzYEV9dAWyLwJI8kLx+yfjAQVpC83iUzvr9y+1HJ0HZ8cOaosBXA==", "dependencies": { - "Microsoft.EntityFrameworkCore.Abstractions": "10.0.15", - "Microsoft.EntityFrameworkCore.Analyzers": "10.0.15" + "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.15", - "contentHash": "aLHlTnngp1CcWF5gWbqNwcfROjINCaQVKoySCFpl8O/EQaCdvtW+miv9KoSpKDtWIN+W7lZ8yr4KnbK3hp9oYQ==" - }, - "Microsoft.EntityFrameworkCore.Analyzers": { - "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "13C007jEmO1JVsoJ+Vvn0AzOaR5bpGsDsaOB9nQt6denQR8hmv1eWmQ0qGarvz+1Zu5b511uF74A90BQigdYHA==" - }, - "Microsoft.EntityFrameworkCore.Relational": { - "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "8rEj7IN4+cW1fXkENqCsHeqDrty3izIvWIw6YlXA3sYLPpie1S1MMAWrF3/QjPSI9AWL3sXT6tQqBeNeX6QWEw==", - "dependencies": { - "Microsoft.EntityFrameworkCore": "10.0.15" - } - }, - "Microsoft.EntityFrameworkCore.Sqlite": { - "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "t6kIAikliaVrVjChJS11d+riwBK1du8GY2r9zMHjVlQIl0wIocd8a4vWAPd+MakWKLiJa+ZXIgMzxn8f3z5DYg==", - "dependencies": { - "Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.15", - "Microsoft.Extensions.DependencyModel": "10.0.15", - "SQLitePCLRaw.bundle_e_sqlite3": "2.1.13", - "SQLitePCLRaw.core": "2.1.13" - } - }, - "Microsoft.EntityFrameworkCore.Sqlite.Core": { - "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "+StxCQ7r+6JOt37kltnnJo07Ik7KZEPYCNRWgOM0x2Cy4fKYaE8kB3YOwJF//4uIXZdkzvNgtE+6V6HsLZcQMQ==", - "dependencies": { - "Microsoft.Data.Sqlite.Core": "10.0.15", - "Microsoft.EntityFrameworkCore.Relational": "10.0.15", - "Microsoft.Extensions.DependencyModel": "10.0.15", - "SQLitePCLRaw.core": "2.1.13" - } - }, - "Microsoft.Extensions.Configuration": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", - "Microsoft.Extensions.Primitives": "11.0.0" - } + "contentHash": "iL0D3Dohk6bNYIHSM3VhvDXrJ+WXs7yMBVv+4L1ozxbsDmohG0T3ogd0mLgWBofu49BHGOgfFKgSGLsOirsjoQ==" }, - "Microsoft.Extensions.Configuration.Abstractions": { + "Microsoft.EntityFrameworkCore.Analyzers": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", - "dependencies": { - "Microsoft.Extensions.Primitives": "11.0.0" - } + "contentHash": "R7QxcmtQLP5np732En6eyzv2DjKevbrRxUUY9jPRQwuLzOSbyDowE5l0KyqdEEySvdHbrdRILg99FlaJTwcPbQ==" }, - "Microsoft.Extensions.Configuration.Binder": { + "Microsoft.EntityFrameworkCore.Relational": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", + "contentHash": "yGS+J269mYUl8V17rHWaeFDySoUnGdiugIzszlNZr0F2+JirFatQyw2s2He92wyYIuy/Y3Yv3QLdq/HdTSj7cA==", "dependencies": { - "Microsoft.Extensions.Configuration": "11.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" + "Microsoft.EntityFrameworkCore": "[11.0.0, 12.0.0-a)" } }, - "Microsoft.Extensions.Configuration.FileExtensions": { + "Microsoft.EntityFrameworkCore.Sqlite": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "ViBZDt2Y7TfVIxiWG5HKfP1KHTzsxn7a31ikZSg/1mdOfGyGAPj278v63NOU+n4UqvaOR43t9MOCUfadSohjQA==", + "contentHash": "12olimxsnuTo+9jsQvbS9fF/FXUhW7AHaXFcK/TgpND3Ki53CBvXnvT+AnPnk6d6f02D5NBdmBcZzfAynBgkRw==", "dependencies": { - "Microsoft.Extensions.Configuration": "11.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", - "Microsoft.Extensions.FileProviders.Abstractions": "11.0.0", - "Microsoft.Extensions.FileProviders.Physical": "11.0.0", - "Microsoft.Extensions.Primitives": "11.0.0" + "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.Extensions.Configuration.Json": { + "Microsoft.EntityFrameworkCore.Sqlite.Core": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "WsNcEnVlq43lXBHAXtQg1b7job819SUf9BPtJrq44vhthL9Ijl2mkRBx5L3hIU1p2AN+wiRg47yhYj+vQxEgeQ==", + "contentHash": "7u0jhtUY4GXr2MRsvSzemUpgf2znOCf8+3VLYxYNthIU5rIKk5Y+9EvS+yAlLIBL2218LeahsHYKA0MWKBYo5Q==", "dependencies": { - "Microsoft.Extensions.Configuration": "11.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", - "Microsoft.Extensions.Configuration.FileExtensions": "11.0.0", - "Microsoft.Extensions.FileProviders.Abstractions": "11.0.0", - "System.Text.Json": "11.0.0" + "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.DependencyInjection.Abstractions": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" - }, "Microsoft.Extensions.DependencyModel": { - "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "087ome/PndkacsUGmB6OoTyhQ3UwoSRqv9odKbvdD4h3o6TqSIVIK/v1WaNKZ/oiMUVuMcV0l2yXdt55RHRxGw==" - }, - "Microsoft.Extensions.FileProviders.Abstractions": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "e3NvNYCuKZ42qlNCryuSmo+xxlhBZeS2Sh5sIPCn+wRSHc0F9N8oAC+r0ki1Yh/KMfw4H6KLh4p9u4TGWye7fw==", - "dependencies": { - "Microsoft.Extensions.Primitives": "11.0.0" - } - }, - "Microsoft.Extensions.FileProviders.Physical": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "lHezhjI8zoTpltXwNy6QMr4/6lIhbXsAYZnCrgRDNNzMHCKvh+x95mkBVXLMzs8axrw7J5Cy21K8lM5YHCfgAw==", - "dependencies": { - "Microsoft.Extensions.FileProviders.Abstractions": "11.0.0", - "Microsoft.Extensions.FileSystemGlobbing": "11.0.0", - "Microsoft.Extensions.Primitives": "11.0.0" - } - }, - "Microsoft.Extensions.FileSystemGlobbing": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "Ycwu/y22NK/ZyJpaFRJc4FB88mjOnsttk2AVHaKgEeShq0vodXZ4FJErpMM2Jju3r3t/2VYWrcHuIxj3ZT/aow==" - }, - "Microsoft.Extensions.Logging.Abstractions": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", - "System.Diagnostics.DiagnosticSource": "11.0.0" - } - }, - "Microsoft.Extensions.Primitives": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" + "contentHash": "K6M9zulTQ3OU0myKAcBb/Gbfw/aTKa3wlxyDhwfOmT7Wavoxe0lzAkeDjS5+/1dqcgGDUZtIykJIo3T4W7zKbQ==" }, "Microsoft.OpenApi": { "type": "Transitive", @@ -204,31 +112,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": { @@ -236,30 +152,6 @@ "resolved": "3.0.0", "contentHash": "swNpSTl0iYJeBuvYYfaY+VxzZ5YC8wklwkqDCNOq2aTQqJzjauJfh/O3Zw93nwxspWrxvZTjT45f8VPR0ParEA==" }, - "System.Diagnostics.DiagnosticSource": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" - }, - "System.IO.Pipelines": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "F3biHUDT5JWIKhEcZrRjKuYy7XGZOe3GOU2N6rSOQeZBx+Ko/PY7K+VaC3BwD+ofQ9k0MXIhEB7uqJSRkZAkQQ==" - }, - "System.Text.Encodings.Web": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "yNdu/KHBHq1rCu0d6TwKWNL1SvomZB4c/S0l4XKF1PX0gOIlPfnGVeBg7sQ3dmgy5e3UA+JGidak3abyBdlYAQ==" - }, - "System.Text.Json": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "hyLfq7fRYbq8m3ENGqgEYkqxLeLx2xmNMlf6UG1a7RQo9OsTsfm4Ch/E6O+A5vYQ2ThneLUn1CHF644lmH5QhA==", - "dependencies": { - "System.IO.Pipelines": "11.0.0", - "System.Text.Encodings.Web": "11.0.0" - } - }, "YamlDotNet": { "type": "Transitive", "resolved": "18.1.0", @@ -269,12 +161,7 @@ "type": "Project", "dependencies": { "Markdig": "[1.6.0, )", - "Microsoft.EntityFrameworkCore.Sqlite": "[10.0.15, )", - "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.Extensions.Logging.Abstractions": "[11.0.0, )", + "Microsoft.EntityFrameworkCore.Sqlite": "[11.0.0, )", "Microsoft.OpenApi": "[3.11.1, )", "Microsoft.OpenApi.YamlReader": "[3.11.1, )", "Newtonsoft.Json.Schema": "[4.0.2, )", diff --git a/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs b/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs index 7189cd48c..0051082ab 100644 --- a/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs +++ b/DevProxy.Tests/BaseLoaderSchemaValidationTests.cs @@ -97,7 +97,11 @@ public async Task AppliesNewestDataWhenFileChangesWhileRetrievingSchema(bool sch // The reload must wait for the initial load instead of reading the file. var reloadReadFile = loader.WaitForFilePathAccessAsync(); - _ = await Task.WhenAny(reloadReadFile, Task.Delay(TimeSpan.FromMilliseconds(500))); + using (var delayCancellation = new CancellationTokenSource()) + { + _ = await Task.WhenAny(reloadReadFile, Task.Delay(TimeSpan.FromMilliseconds(500), delayCancellation.Token)); + await delayCancellation.CancelAsync(); + } Assert.False(reloadReadFile.IsCompleted); Assert.False(init.IsCompleted); diff --git a/DevProxy.Tests/DevProxy.Tests.csproj b/DevProxy.Tests/DevProxy.Tests.csproj index 0d0b6ab2c..dea5fdb15 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 9542b3cdf..47582873f 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 003cca6ed..f0e7b602f 100644 --- a/DevProxy/Commands/ConfigCommand.cs +++ b/DevProxy/Commands/ConfigCommand.cs @@ -1052,7 +1052,7 @@ private static void ValidateUrls( urlPatterns.Add(pattern); try { - var cleanPattern = pattern.StartsWith('!') ? pattern[1..] : pattern; + var cleanPattern = pattern.StartsWith('!', StringComparison.Ordinal) ? pattern[1..] : pattern; _ = new Regex( $"^{Regex.Escape(cleanPattern).Replace("\\*", ".*", StringComparison.OrdinalIgnoreCase)}$"); } diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index e81763723..e7ae94b63 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -115,13 +115,13 @@ internal static bool IsStdioSubcommand(string[] args) return true; } - if (args[i].StartsWith('-')) + if (args[i].StartsWith('-', StringComparison.Ordinal)) { inMultiValueOption = _multiValueRootOptions.Contains(args[i]); continue; } - var isOptionValue = inMultiValueOption || (i > 0 && args[i - 1].StartsWith('-')); + var isOptionValue = inMultiValueOption || (i > 0 && args[i - 1].StartsWith('-', StringComparison.Ordinal)); if (!isOptionValue) { return false; @@ -202,11 +202,11 @@ internal static bool IsValidateInvocation(string[] args) arg.StartsWith(LogLevelOptionName + "=", StringComparison.OrdinalIgnoreCase) || arg.StartsWith(LogLevelOptionName + ":", StringComparison.OrdinalIgnoreCase) || string.Equals(arg, NoColorOptionName, StringComparison.OrdinalIgnoreCase) || - (commandTokens.Count > 0 && arg.StartsWith('-'))) + (commandTokens.Count > 0 && arg.StartsWith('-', StringComparison.Ordinal))) { continue; } - if (arg.StartsWith('-')) + if (arg.StartsWith('-', StringComparison.Ordinal)) { // other root options may take values, so we can't tell what follows break; @@ -295,7 +295,7 @@ public static bool IsRootCommand // 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('-'); + field = args.Length <= 1 || args[1].StartsWith('-', StringComparison.Ordinal); _isRootCommandResolved = true; return field; } diff --git a/DevProxy/Commands/LogsCommand.cs b/DevProxy/Commands/LogsCommand.cs index db3eca343..588b49d0f 100644 --- a/DevProxy/Commands/LogsCommand.cs +++ b/DevProxy/Commands/LogsCommand.cs @@ -74,7 +74,7 @@ private async Task RunAsync(ParseResult parseResult, CancellationToken canc var notice = GetMultipleInstancesNotice(state, states); if (notice is not null) { - await Console.Error.WriteLineAsync(notice); + await Console.Error.WriteLineAsync(notice, cancellationToken); } } diff --git a/DevProxy/Commands/StdioCommand.cs b/DevProxy/Commands/StdioCommand.cs index 25711fc80..a58b05c97 100644 --- a/DevProxy/Commands/StdioCommand.cs +++ b/DevProxy/Commands/StdioCommand.cs @@ -98,8 +98,8 @@ private async Task RunAsync(ParseResult parseResult, CancellationToken canc if (command == null || command.Length == 0) { _logger.LogError("No command specified"); - await Console.Error.WriteLineAsync("Usage: devproxy stdio [args...]"); - await Console.Error.WriteLineAsync("Example: devproxy stdio npx -y @modelcontextprotocol/server-filesystem"); + await Console.Error.WriteLineAsync("Usage: devproxy stdio [args...]", cancellationToken); + await Console.Error.WriteLineAsync("Example: devproxy stdio npx -y @modelcontextprotocol/server-filesystem", cancellationToken); return 1; } @@ -129,7 +129,7 @@ private async Task RunAsync(ParseResult parseResult, CancellationToken canc catch (Exception ex) { _logger.LogError(ex, "Error running stdio proxy"); - await Console.Error.WriteLineAsync($"Error: {ex.Message}"); + await Console.Error.WriteLineAsync($"Error: {ex.Message}", CancellationToken.None); return 1; } finally diff --git a/DevProxy/DevProxy.csproj b/DevProxy/DevProxy.csproj index 889c8f6cc..bdd40d7e4 100644 --- a/DevProxy/DevProxy.csproj +++ b/DevProxy/DevProxy.csproj @@ -2,7 +2,7 @@ Exe - net10.0 + net11.0 DevProxy enable enable @@ -45,7 +45,7 @@ - + diff --git a/DevProxy/Logging/JsonConsoleFormatter.cs b/DevProxy/Logging/JsonConsoleFormatter.cs index 04b3ca3e1..36cf28b4e 100644 --- a/DevProxy/Logging/JsonConsoleFormatter.cs +++ b/DevProxy/Logging/JsonConsoleFormatter.cs @@ -104,7 +104,7 @@ private void WriteRequestLog(RequestLog requestLog, string category, IExternalSc // Extract short plugin name from full category if (pluginName is not null) { - pluginName = pluginName[(pluginName.LastIndexOf('.') + 1)..]; + pluginName = pluginName[(pluginName.LastIndexOf('.', StringComparison.Ordinal) + 1)..]; } var logObject = new JsonRequestLogEntry @@ -145,7 +145,7 @@ private static void WriteRegularLogMessage(in LogEntry logEntry, // Extract short category name if (category is not null) { - category = category[(category.LastIndexOf('.') + 1)..]; + category = category[(category.LastIndexOf('.', StringComparison.Ordinal) + 1)..]; } var logObject = new JsonLogEntry @@ -168,7 +168,7 @@ private static void WriteStructuredOutput(string message, string category, TextW // Extract short category name if (category is not null) { - category = category[(category.LastIndexOf('.') + 1)..]; + category = category[(category.LastIndexOf('.', StringComparison.Ordinal) + 1)..]; } try diff --git a/DevProxy/Logging/ProxyConsoleFormatter.cs b/DevProxy/Logging/ProxyConsoleFormatter.cs index fc64d9c89..e74cc8443 100644 --- a/DevProxy/Logging/ProxyConsoleFormatter.cs +++ b/DevProxy/Logging/ProxyConsoleFormatter.cs @@ -1,334 +1,334 @@ -// 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.Proxy; -using DevProxy.Proxy; -using DevProxy.Proxy.Kestrel; -using Microsoft.Extensions.Logging.Abstractions; -using Microsoft.Extensions.Logging.Console; -using Microsoft.Extensions.Options; -using System.Collections.Concurrent; -using System.Globalization; -using System.Text; - -namespace DevProxy.Logging; - -sealed class ProxyConsoleFormatter : ConsoleFormatter -{ - public const string DefaultCategoryName = "devproxy"; - - private const string _boxTopLeft = "\u256d "; - private const string _boxLeft = "\u2502 "; - private const string _boxBottomLeft = "\u2570 "; - private const string _boxSpacing = " "; - private const string _labelSpacing = " "; - - // Cached lookup tables for better performance - private static readonly Dictionary _logLevelStrings = new() - { - [LogLevel.Trace] = "trce", - [LogLevel.Debug] = "dbug", - [LogLevel.Information] = "info", - [LogLevel.Warning] = "warn", - [LogLevel.Error] = "fail", - [LogLevel.Critical] = "crit" - }; - private static readonly Dictionary _logLevelColors = new() - { - [LogLevel.Information] = (Console.BackgroundColor, ConsoleColor.Blue), - [LogLevel.Warning] = (ConsoleColor.DarkYellow, Console.ForegroundColor), - [LogLevel.Error] = (ConsoleColor.DarkRed, Console.ForegroundColor), - [LogLevel.Debug] = (Console.BackgroundColor, ConsoleColor.Gray), - [LogLevel.Trace] = (Console.BackgroundColor, ConsoleColor.Gray) - }; - private static readonly Dictionary _messageTypeStrings = new() - { - [MessageType.InterceptedRequest] = "req", - [MessageType.InterceptedResponse] = "res", - [MessageType.PassedThrough] = "pass", - [MessageType.Chaos] = "oops", - [MessageType.Warning] = "warn", - [MessageType.Mocked] = "mock", - [MessageType.Failed] = "fail", - [MessageType.Tip] = "tip", - [MessageType.Skipped] = "skip", - [MessageType.Processed] = "proc", - [MessageType.Timestamp] = "time", - [MessageType.FinishedProcessingRequest] = " " - }; - private static readonly Dictionary _messageTypeColors = new() - { - [MessageType.InterceptedRequest] = (Console.BackgroundColor, ConsoleColor.Gray), - [MessageType.PassedThrough] = (ConsoleColor.Gray, Console.ForegroundColor), - [MessageType.Skipped] = (Console.BackgroundColor, ConsoleColor.Gray), - [MessageType.Processed] = (ConsoleColor.DarkGreen, Console.ForegroundColor), - [MessageType.Chaos] = (ConsoleColor.DarkRed, Console.ForegroundColor), - [MessageType.Warning] = (ConsoleColor.DarkYellow, Console.ForegroundColor), - [MessageType.Mocked] = (ConsoleColor.DarkMagenta, Console.ForegroundColor), - [MessageType.Failed] = (ConsoleColor.DarkRed, Console.ForegroundColor), - [MessageType.Tip] = (ConsoleColor.DarkBlue, Console.ForegroundColor), - [MessageType.Timestamp] = (Console.BackgroundColor, ConsoleColor.Gray) - }; - - private readonly ConcurrentDictionary> _messages = []; - private readonly ProxyConsoleFormatterOptions _options; - private readonly HashSet _filteredMessageTypes; - - public ProxyConsoleFormatter(IOptions options) : base(DefaultCategoryName) - { - Console.OutputEncoding = Encoding.UTF8; - _options = options.Value; - - _filteredMessageTypes = [MessageType.InterceptedResponse]; - if (!_options.ShowSkipMessages) - { - _ = _filteredMessageTypes.Add(MessageType.Skipped); - } - if (!_options.ShowTimestamps) - { - _ = _filteredMessageTypes.Add(MessageType.Timestamp); - } - } - - public override void Write(in LogEntry logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter) - { - if (logEntry.State is RequestLog requestLog) - { - LogRequest(requestLog, logEntry.Category, scopeProvider, textWriter); - } - else - { - LogRegularLogMessage(logEntry, scopeProvider, textWriter); - } - } - - private void LogRequest(RequestLog requestLog, string category, IExternalScopeProvider? scopeProvider, TextWriter textWriter) - { - var messageType = requestLog.MessageType; - - if (_filteredMessageTypes.Contains(messageType)) - { - return; - } - - var requestId = GetRequestIdScope(scopeProvider); - if (requestId is null) - { - return; - } - - if (messageType == MessageType.FinishedProcessingRequest) - { - FlushLogsForRequest(requestId.Value, textWriter); - } - else - { - BufferRequestLog(requestLog, category, requestId.Value); - } - } - - private void FlushLogsForRequest(int requestId, TextWriter textWriter) - { - // Remove before printing so the buffer is released even if writing fails. - if (!_messages.TryRemove(requestId, out var messages)) - { - return; - } - - var lastIndex = messages.Count - 1; - for (var i = 0; i < messages.Count; i++) - { - var isLast = i == lastIndex; - switch (messages[i]) - { - case RequestLog log: - WriteRequestLogMessage(log, textWriter, isLast); - break; - case LogEntry logEntry: - WriteRegularLogMessage(logEntry, textWriter, isLast); - break; - default: - // noop - break; - } - } - } - - private void BufferRequestLog(RequestLog requestLog, string category, int requestId) - { - requestLog.PluginName = category == DefaultCategoryName ? null : category; - var messages = _messages.GetOrAdd(requestId, _ => []); - messages.Add(requestLog); - } - - private void LogRegularLogMessage(in LogEntry logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter) - { - var requestId = GetRequestIdScope(scopeProvider); - if (requestId is null) - { - WriteRegularLogMessage(logEntry, scopeProvider, textWriter); - } - else - { - var message = LogEntry.FromLogEntry(logEntry); - var messages = _messages.GetOrAdd(requestId.Value, _ => []); - messages.Add(message); - } - } - - private void WriteRegularLogMessage(in LogEntry logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter) - { - var message = logEntry.Formatter(logEntry.State, logEntry.Exception); - WriteMessageWithLabel(message, logEntry.Category, logEntry.LogLevel, scopeProvider, textWriter); - - if (logEntry.Exception is not null) - { - textWriter.Write($" Exception Details: {logEntry.Exception}"); - } - textWriter.WriteLine(); - } - - private void WriteMessageWithLabel(string? message, string category, LogLevel logLevel, IExternalScopeProvider? scopeProvider, TextWriter textWriter) - { - if (message is null) - { - return; - } - - var label = GetLogLevelString(logLevel); - var (bgColor, fgColor) = GetLogLevelColor(logLevel); - - WriteLabel(textWriter, label, bgColor, fgColor); - textWriter.Write($"{_labelSpacing}{_boxSpacing}"); - - if (_options.IncludeFullTimestamps) - { - WriteTimestamp(textWriter, DateTimeOffset.UtcNow); - } - else if (logLevel <= LogLevel.Debug) - { - textWriter.Write($"[{DateTime.Now:HH:mm:ss.fffffff}] "); - } - - if (logLevel <= LogLevel.Debug) - { - textWriter.Write($"{category.Split('.').Last()}: "); - } - - WriteScopes(scopeProvider, textWriter); - textWriter.Write(message); - } - - private void WriteRequestLogMessage(RequestLog log, TextWriter textWriter, bool isLast) - { - var label = GetMessageTypeString(log.MessageType); - var (bgColor, fgColor) = GetMessageTypeColor(log.MessageType); - var boxChar = GetBoxCharacter(log.MessageType, isLast); - - if (log.MessageType == MessageType.InterceptedRequest) - { - textWriter.WriteLine(); - } - - WriteLabel(textWriter, label, bgColor, fgColor); - textWriter.Write($"{GetLabelPadding(label)}{_labelSpacing}{boxChar}"); - WritePluginName(textWriter, log.PluginName); - textWriter.WriteLine(log.Message); - } - - private void WriteRegularLogMessage(LogEntry log, TextWriter textWriter, bool isLast) - { - var label = GetLogLevelString(log.LogLevel); - var (bgColor, fgColor) = GetLogLevelColor(log.LogLevel); - var boxChar = isLast ? _boxBottomLeft : _boxLeft; - - WriteLabel(textWriter, label, bgColor, fgColor); - textWriter.Write($"{GetLabelPadding(label)}{_labelSpacing}{boxChar}"); - if (_options.IncludeFullTimestamps) - { - WriteTimestamp(textWriter, log.Timestamp); - } - WritePluginName(textWriter, log.Category); - textWriter.WriteLine(log.Message); - } - - private static void WriteTimestamp(TextWriter textWriter, DateTimeOffset timestamp) => - textWriter.Write($"[{timestamp.ToString("O", CultureInfo.InvariantCulture)}] "); - - private void WritePluginName(TextWriter textWriter, string? categoryOrPluginName) - { - if (!_options.IncludeScopes || categoryOrPluginName is null) - { - return; - } - - var pluginName = categoryOrPluginName[(categoryOrPluginName.LastIndexOf('.') + 1)..]; - if (pluginName != nameof(KestrelProxyEngine)) - { - textWriter.Write($"{pluginName}: "); - } - } - - private void WriteScopes(IExternalScopeProvider? scopeProvider, TextWriter textWriter) - { - if (!_options.IncludeScopes || scopeProvider is null) - { - return; - } - - scopeProvider.ForEachScope((scope, state) => - { - if (scope is null) - { - return; - } - - var scopeText = scope is string scopeString ? scopeString : - scope.GetType().Name == "FormattedLogValues" ? scope.ToString() : null; - - if (scopeText is not null) - { - textWriter.Write($"{scopeText}: "); - } - }, textWriter); - } - - private static string GetLogLevelString(LogLevel logLevel) => - _logLevelStrings.TryGetValue(logLevel, out var str) ? str : throw new ArgumentOutOfRangeException(nameof(logLevel)); - - private static (ConsoleColor bg, ConsoleColor fg) GetLogLevelColor(LogLevel logLevel) => - _logLevelColors.TryGetValue(logLevel, out var color) ? color : (Console.BackgroundColor, Console.ForegroundColor); - - private static string GetMessageTypeString(MessageType messageType) => - _messageTypeStrings.TryGetValue(messageType, out var str) ? str : " "; - - private static (ConsoleColor bg, ConsoleColor fg) GetMessageTypeColor(MessageType messageType) => - _messageTypeColors.TryGetValue(messageType, out var color) ? color : (Console.BackgroundColor, Console.ForegroundColor); - - private static int? GetRequestIdScope(IExternalScopeProvider? scopeProvider) - { - int? requestId = null; - scopeProvider?.ForEachScope((scope, _) => - { - if (scope is Dictionary dictionary && - dictionary.TryGetValue(nameof(requestId), out var req)) - { - requestId = (int)req; - } - }, ""); - return requestId; - } - - private static void WriteLabel(TextWriter textWriter, string label, ConsoleColor bgColor, ConsoleColor fgColor) - { - textWriter.WriteColoredMessage($" {label} ", bgColor, fgColor); - } - - private static string GetLabelPadding(string label) => - label.Length < 4 ? " " : ""; - - private static string GetBoxCharacter(MessageType messageType, bool isLast) => - messageType == MessageType.InterceptedRequest ? _boxTopLeft : - isLast ? _boxBottomLeft : _boxLeft; +// 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.Proxy; +using DevProxy.Proxy; +using DevProxy.Proxy.Kestrel; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Logging.Console; +using Microsoft.Extensions.Options; +using System.Collections.Concurrent; +using System.Globalization; +using System.Text; + +namespace DevProxy.Logging; + +sealed class ProxyConsoleFormatter : ConsoleFormatter +{ + public const string DefaultCategoryName = "devproxy"; + + private const string _boxTopLeft = "\u256d "; + private const string _boxLeft = "\u2502 "; + private const string _boxBottomLeft = "\u2570 "; + private const string _boxSpacing = " "; + private const string _labelSpacing = " "; + + // Cached lookup tables for better performance + private static readonly Dictionary _logLevelStrings = new() + { + [LogLevel.Trace] = "trce", + [LogLevel.Debug] = "dbug", + [LogLevel.Information] = "info", + [LogLevel.Warning] = "warn", + [LogLevel.Error] = "fail", + [LogLevel.Critical] = "crit" + }; + private static readonly Dictionary _logLevelColors = new() + { + [LogLevel.Information] = (Console.BackgroundColor, ConsoleColor.Blue), + [LogLevel.Warning] = (ConsoleColor.DarkYellow, Console.ForegroundColor), + [LogLevel.Error] = (ConsoleColor.DarkRed, Console.ForegroundColor), + [LogLevel.Debug] = (Console.BackgroundColor, ConsoleColor.Gray), + [LogLevel.Trace] = (Console.BackgroundColor, ConsoleColor.Gray) + }; + private static readonly Dictionary _messageTypeStrings = new() + { + [MessageType.InterceptedRequest] = "req", + [MessageType.InterceptedResponse] = "res", + [MessageType.PassedThrough] = "pass", + [MessageType.Chaos] = "oops", + [MessageType.Warning] = "warn", + [MessageType.Mocked] = "mock", + [MessageType.Failed] = "fail", + [MessageType.Tip] = "tip", + [MessageType.Skipped] = "skip", + [MessageType.Processed] = "proc", + [MessageType.Timestamp] = "time", + [MessageType.FinishedProcessingRequest] = " " + }; + private static readonly Dictionary _messageTypeColors = new() + { + [MessageType.InterceptedRequest] = (Console.BackgroundColor, ConsoleColor.Gray), + [MessageType.PassedThrough] = (ConsoleColor.Gray, Console.ForegroundColor), + [MessageType.Skipped] = (Console.BackgroundColor, ConsoleColor.Gray), + [MessageType.Processed] = (ConsoleColor.DarkGreen, Console.ForegroundColor), + [MessageType.Chaos] = (ConsoleColor.DarkRed, Console.ForegroundColor), + [MessageType.Warning] = (ConsoleColor.DarkYellow, Console.ForegroundColor), + [MessageType.Mocked] = (ConsoleColor.DarkMagenta, Console.ForegroundColor), + [MessageType.Failed] = (ConsoleColor.DarkRed, Console.ForegroundColor), + [MessageType.Tip] = (ConsoleColor.DarkBlue, Console.ForegroundColor), + [MessageType.Timestamp] = (Console.BackgroundColor, ConsoleColor.Gray) + }; + + private readonly ConcurrentDictionary> _messages = []; + private readonly ProxyConsoleFormatterOptions _options; + private readonly HashSet _filteredMessageTypes; + + public ProxyConsoleFormatter(IOptions options) : base(DefaultCategoryName) + { + Console.OutputEncoding = Encoding.UTF8; + _options = options.Value; + + _filteredMessageTypes = [MessageType.InterceptedResponse]; + if (!_options.ShowSkipMessages) + { + _ = _filteredMessageTypes.Add(MessageType.Skipped); + } + if (!_options.ShowTimestamps) + { + _ = _filteredMessageTypes.Add(MessageType.Timestamp); + } + } + + public override void Write(in LogEntry logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter) + { + if (logEntry.State is RequestLog requestLog) + { + LogRequest(requestLog, logEntry.Category, scopeProvider, textWriter); + } + else + { + LogRegularLogMessage(logEntry, scopeProvider, textWriter); + } + } + + private void LogRequest(RequestLog requestLog, string category, IExternalScopeProvider? scopeProvider, TextWriter textWriter) + { + var messageType = requestLog.MessageType; + + if (_filteredMessageTypes.Contains(messageType)) + { + return; + } + + var requestId = GetRequestIdScope(scopeProvider); + if (requestId is null) + { + return; + } + + if (messageType == MessageType.FinishedProcessingRequest) + { + FlushLogsForRequest(requestId.Value, textWriter); + } + else + { + BufferRequestLog(requestLog, category, requestId.Value); + } + } + + private void FlushLogsForRequest(int requestId, TextWriter textWriter) + { + // Remove before printing so the buffer is released even if writing fails. + if (!_messages.TryRemove(requestId, out var messages)) + { + return; + } + + var lastIndex = messages.Count - 1; + for (var i = 0; i < messages.Count; i++) + { + var isLast = i == lastIndex; + switch (messages[i]) + { + case RequestLog log: + WriteRequestLogMessage(log, textWriter, isLast); + break; + case LogEntry logEntry: + WriteRegularLogMessage(logEntry, textWriter, isLast); + break; + default: + // noop + break; + } + } + } + + private void BufferRequestLog(RequestLog requestLog, string category, int requestId) + { + requestLog.PluginName = category == DefaultCategoryName ? null : category; + var messages = _messages.GetOrAdd(requestId, _ => []); + messages.Add(requestLog); + } + + private void LogRegularLogMessage(in LogEntry logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter) + { + var requestId = GetRequestIdScope(scopeProvider); + if (requestId is null) + { + WriteRegularLogMessage(logEntry, scopeProvider, textWriter); + } + else + { + var message = LogEntry.FromLogEntry(logEntry); + var messages = _messages.GetOrAdd(requestId.Value, _ => []); + messages.Add(message); + } + } + + private void WriteRegularLogMessage(in LogEntry logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter) + { + var message = logEntry.Formatter(logEntry.State, logEntry.Exception); + WriteMessageWithLabel(message, logEntry.Category, logEntry.LogLevel, scopeProvider, textWriter); + + if (logEntry.Exception is not null) + { + textWriter.Write($" Exception Details: {logEntry.Exception}"); + } + textWriter.WriteLine(); + } + + private void WriteMessageWithLabel(string? message, string category, LogLevel logLevel, IExternalScopeProvider? scopeProvider, TextWriter textWriter) + { + if (message is null) + { + return; + } + + var label = GetLogLevelString(logLevel); + var (bgColor, fgColor) = GetLogLevelColor(logLevel); + + WriteLabel(textWriter, label, bgColor, fgColor); + textWriter.Write($"{_labelSpacing}{_boxSpacing}"); + + if (_options.IncludeFullTimestamps) + { + WriteTimestamp(textWriter, DateTimeOffset.UtcNow); + } + else if (logLevel <= LogLevel.Debug) + { + textWriter.Write($"[{DateTime.Now:HH:mm:ss.fffffff}] "); + } + + if (logLevel <= LogLevel.Debug) + { + textWriter.Write($"{category.Split('.').Last()}: "); + } + + WriteScopes(scopeProvider, textWriter); + textWriter.Write(message); + } + + private void WriteRequestLogMessage(RequestLog log, TextWriter textWriter, bool isLast) + { + var label = GetMessageTypeString(log.MessageType); + var (bgColor, fgColor) = GetMessageTypeColor(log.MessageType); + var boxChar = GetBoxCharacter(log.MessageType, isLast); + + if (log.MessageType == MessageType.InterceptedRequest) + { + textWriter.WriteLine(); + } + + WriteLabel(textWriter, label, bgColor, fgColor); + textWriter.Write($"{GetLabelPadding(label)}{_labelSpacing}{boxChar}"); + WritePluginName(textWriter, log.PluginName); + textWriter.WriteLine(log.Message); + } + + private void WriteRegularLogMessage(LogEntry log, TextWriter textWriter, bool isLast) + { + var label = GetLogLevelString(log.LogLevel); + var (bgColor, fgColor) = GetLogLevelColor(log.LogLevel); + var boxChar = isLast ? _boxBottomLeft : _boxLeft; + + WriteLabel(textWriter, label, bgColor, fgColor); + textWriter.Write($"{GetLabelPadding(label)}{_labelSpacing}{boxChar}"); + if (_options.IncludeFullTimestamps) + { + WriteTimestamp(textWriter, log.Timestamp); + } + WritePluginName(textWriter, log.Category); + textWriter.WriteLine(log.Message); + } + + private static void WriteTimestamp(TextWriter textWriter, DateTimeOffset timestamp) => + textWriter.Write($"[{timestamp.ToString("O", CultureInfo.InvariantCulture)}] "); + + private void WritePluginName(TextWriter textWriter, string? categoryOrPluginName) + { + if (!_options.IncludeScopes || categoryOrPluginName is null) + { + return; + } + + var pluginName = categoryOrPluginName[(categoryOrPluginName.LastIndexOf('.', StringComparison.Ordinal) + 1)..]; + if (pluginName != nameof(KestrelProxyEngine)) + { + textWriter.Write($"{pluginName}: "); + } + } + + private void WriteScopes(IExternalScopeProvider? scopeProvider, TextWriter textWriter) + { + if (!_options.IncludeScopes || scopeProvider is null) + { + return; + } + + scopeProvider.ForEachScope((scope, state) => + { + if (scope is null) + { + return; + } + + var scopeText = scope is string scopeString ? scopeString : + scope.GetType().Name == "FormattedLogValues" ? scope.ToString() : null; + + if (scopeText is not null) + { + textWriter.Write($"{scopeText}: "); + } + }, textWriter); + } + + private static string GetLogLevelString(LogLevel logLevel) => + _logLevelStrings.TryGetValue(logLevel, out var str) ? str : throw new ArgumentOutOfRangeException(nameof(logLevel)); + + private static (ConsoleColor bg, ConsoleColor fg) GetLogLevelColor(LogLevel logLevel) => + _logLevelColors.TryGetValue(logLevel, out var color) ? color : (Console.BackgroundColor, Console.ForegroundColor); + + private static string GetMessageTypeString(MessageType messageType) => + _messageTypeStrings.TryGetValue(messageType, out var str) ? str : " "; + + private static (ConsoleColor bg, ConsoleColor fg) GetMessageTypeColor(MessageType messageType) => + _messageTypeColors.TryGetValue(messageType, out var color) ? color : (Console.BackgroundColor, Console.ForegroundColor); + + private static int? GetRequestIdScope(IExternalScopeProvider? scopeProvider) + { + int? requestId = null; + scopeProvider?.ForEachScope((scope, _) => + { + if (scope is Dictionary dictionary && + dictionary.TryGetValue(nameof(requestId), out var req)) + { + requestId = (int)req; + } + }, ""); + return requestId; + } + + private static void WriteLabel(TextWriter textWriter, string label, ConsoleColor bgColor, ConsoleColor fgColor) + { + textWriter.WriteColoredMessage($" {label} ", bgColor, fgColor); + } + + private static string GetLabelPadding(string label) => + label.Length < 4 ? " " : ""; + + private static string GetBoxCharacter(MessageType messageType, bool isLast) => + messageType == MessageType.InterceptedRequest ? _boxTopLeft : + isLast ? _boxBottomLeft : _boxLeft; } \ No newline at end of file diff --git a/DevProxy/Plugins/PluginServiceExtensions.cs b/DevProxy/Plugins/PluginServiceExtensions.cs index 3389dffec..9a3a6f612 100644 --- a/DevProxy/Plugins/PluginServiceExtensions.cs +++ b/DevProxy/Plugins/PluginServiceExtensions.cs @@ -1,257 +1,257 @@ -// 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.Commands; -using DevProxy.Plugins; -using DevProxy.Proxy; -using System.Reflection; -using System.Text.RegularExpressions; - -#pragma warning disable IDE0130 -namespace Microsoft.Extensions.DependencyInjection; -#pragma warning restore IDE0130 - -static class PluginServiceExtensions -{ - public static IServiceCollection AddPlugins( - this IServiceCollection services, - IConfiguration configuration, - DevProxyConfigOptions options) - { - var serviceProvider = services.BuildServiceProvider(); - var logger = serviceProvider.GetRequiredService().CreateLogger("Plugins"); - using var scope = logger.BeginScope(nameof(AddPlugins)); - - var pluginReferences = configuration.GetSection("plugins").Get>(); - var globallyWatchedUrls = (options.UrlsToWatch ?? configuration.GetSection("urlsToWatch").Get>() ?? []).Select(ConvertToRegex).ToList(); - - var schemaUrl = configuration.GetValue("$schema"); - if (string.IsNullOrWhiteSpace(schemaUrl)) - { - logger.LogDebug("No schema URL found in configuration file, skipping schema version validation"); - } - else - { - ProxyUtils.ValidateSchemaVersion(schemaUrl, logger); - } - - if (options.Discover) - { - logger.LogWarning("Dev Proxy is running in URL discovery mode. Configured plugins and URLs to watch will be ignored."); - if (pluginReferences is null) - { - pluginReferences = []; - } - else - { - pluginReferences.Clear(); - } - - pluginReferences.Add(new() - { - Name = "UrlDiscoveryPlugin", - PluginPath = "~appFolder/plugins/DevProxy.Plugins.dll" - }); - pluginReferences.Add(new() - { - Name = "PlainTextReporter", - PluginPath = "~appFolder/plugins/DevProxy.Plugins.dll" - }); - - globallyWatchedUrls.Clear(); - globallyWatchedUrls.Add(ConvertToRegex("https://*/*")); - } - - if (pluginReferences is null || !pluginReferences.Any(p => p.Enabled)) - { - throw new InvalidOperationException("No plugins configured or enabled. Please add a plugin to the configuration file."); - } - - var defaultUrlsToWatch = globallyWatchedUrls.ToHashSet(); - var configFileDirectory = string.Empty; - - if (configuration is IConfigurationRoot configurationRoot) - { - configFileDirectory = Path.GetDirectoryName(ProxyConfiguration.GetConfigFilePath(configurationRoot)); - if (string.IsNullOrEmpty(configFileDirectory)) - { - throw new InvalidOperationException("Unable to resolve config file directory."); - } - } - else - { - throw new InvalidOperationException("Unable to resolve config file directory."); - } - - // key = location - var pluginContexts = new Dictionary(); - - foreach (var pluginRef in pluginReferences) - { - if (!pluginRef.Enabled) - { - continue; - } - - // Load Handler Assembly if enabled - var pluginLocation = Path.GetFullPath(Path.Combine(configFileDirectory, ProxyUtils.ReplacePathTokens(pluginRef.PluginPath.Replace('\\', Path.DirectorySeparatorChar)))); - - if (!pluginContexts.TryGetValue(pluginLocation, out var pluginLoadContext)) - { - pluginLoadContext = new(pluginLocation); - pluginContexts.Add(pluginLocation, pluginLoadContext); - } - - logger.LogDebug("Loading plugin {PluginName} from: {PluginLocation}", pluginRef.Name, pluginLocation); - var assembly = pluginLoadContext.LoadFromAssemblyName(new(Path.GetFileNameWithoutExtension(pluginLocation))); - var pluginUrlsList = pluginRef.UrlsToWatch?.Select(ConvertToRegex); - HashSet? pluginUrls = null; - - if (pluginUrlsList is not null) - { - pluginUrls = pluginUrlsList.ToHashSet(); - globallyWatchedUrls.AddRange(pluginUrlsList); - } - - try - { - RegisterPlugin( - pluginRef, - (pluginUrls != null && pluginUrls.Count > 0) ? pluginUrls : defaultUrlsToWatch, - assembly, - configuration, - services, - logger, - options.IsStdioMode); - } - catch (Exception ex) - { - logger.LogError(ex, "Failed to load plugin {PluginName}: {ErrorMessage}", pluginRef.Name, ex.Message); - } - } - - _ = services.AddSingleton>(globallyWatchedUrls.ToHashSet()); - - // Register IStdioPlugin instances - plugins that implement IStdioPlugin can participate - // in both HTTP proxy and stdio proxy scenarios - _ = services.AddSingleton>(sp => - sp.GetServices().OfType().ToList()); - - return services; - } - - private static void RegisterPlugin( - PluginReference pluginRef, - HashSet urlsToWatch, - Assembly assembly, - IConfiguration configuration, - IServiceCollection services, - ILogger logger, - bool isStdioMode) - { - var pluginType = assembly.GetTypes() - .FirstOrDefault(t => t.Name == pluginRef.Name && typeof(IPlugin).IsAssignableFrom(t)); - if (pluginType is null) - { - logger.LogError("Plugin {PluginName} not found in assembly {Assembly}.", pluginRef.Name, assembly); - return; - } - - // In stdio mode, plugins don't need URLs to watch because they - // communicate through STDIO (JSON-RPC) rather than HTTP - if (urlsToWatch.Count == 0 && !isStdioMode) - { - logger.LogError("Plugin {PluginName} must have at least one URL to watch. Please add a URL to watch in the configuration file or use the --urls-to-watch option.", pluginRef.Name); - return; - } - - var isConfigurable = IsConfigurablePlugin(pluginType, out var configType); - - if (!isConfigurable || configType is null) - { - _ = services.AddSingleton(typeof(IPlugin), sp => - { - var plugin = (IPlugin)ActivatorUtilities.CreateInstance(sp, pluginType, urlsToWatch) ?? - throw new InvalidOperationException($"Failed to create instance of plugin type {pluginType}"); - // we don't have a cancellation token right now, because this - // stage is synchronous, but if the implementation changes - // in the future then we won't need to change the interface -#pragma warning disable VSTHRD002 - plugin.InitializeAsync(new() { ServiceProvider = sp, IsProxyCommand = DevProxyCommand.IsRootCommand }, CancellationToken.None).Wait(); -#pragma warning restore VSTHRD002 - return plugin; - }); - logger.LogDebug("Registered plugin {PluginName}.", pluginRef.Name); - return; - } - - // if no section specified, use guid to create an empty section - var configSection = configuration.GetSection(pluginRef.ConfigSection ?? Guid.NewGuid().ToString()); - - _ = services.AddSingleton(typeof(IPlugin), sp => - { - var plugin = (IPlugin)ActivatorUtilities.CreateInstance(sp, pluginType, configSection, urlsToWatch) ?? - throw new InvalidOperationException($"Failed to create instance of plugin type {pluginType}"); - // we don't have a cancellation token right now, because this - // stage is synchronous, but if the implementation changes - // in the future then we won't need to change the interface -#pragma warning disable VSTHRD002 - plugin.InitializeAsync(new() { ServiceProvider = sp, IsProxyCommand = DevProxyCommand.IsRootCommand }, CancellationToken.None).Wait(); -#pragma warning restore VSTHRD002 - return plugin; - }); - logger.LogDebug("Registered plugin {PluginName}.", pluginRef.Name); - } - - /// - /// Determines if the plugin type is configurable and extracts its config type. - /// - internal static bool IsConfigurablePlugin(Type pluginType, out Type? configType) - { - configType = null; - - foreach (var interfaceType in pluginType.GetInterfaces()) - { - if (interfaceType.IsGenericType && - interfaceType.GetGenericTypeDefinition() == typeof(IPlugin<>)) - { - configType = interfaceType.GetGenericArguments()[0]; - return true; - } - } - - var baseType = pluginType; - while (baseType is not null && baseType != typeof(object)) - { - if (baseType.IsGenericType && - baseType.GetGenericTypeDefinition() == typeof(BasePlugin<>)) - { - configType = baseType.GetGenericArguments()[0]; - return true; - } - - baseType = baseType.BaseType; - } - - return false; - } - - private static UrlToWatch ConvertToRegex(string stringMatcher) - { - var exclude = false; - if (stringMatcher.StartsWith('!')) - { - exclude = true; - stringMatcher = stringMatcher[1..]; - } - - return new UrlToWatch( - new Regex($"^{Regex.Escape(ProxyUtils.NormalizeWebSocketScheme(stringMatcher)).Replace("\\*", ".*", StringComparison.OrdinalIgnoreCase)}$", RegexOptions.Compiled | RegexOptions.IgnoreCase), - exclude - ); - } -} +// 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.Commands; +using DevProxy.Plugins; +using DevProxy.Proxy; +using System.Reflection; +using System.Text.RegularExpressions; + +#pragma warning disable IDE0130 +namespace Microsoft.Extensions.DependencyInjection; +#pragma warning restore IDE0130 + +static class PluginServiceExtensions +{ + public static IServiceCollection AddPlugins( + this IServiceCollection services, + IConfiguration configuration, + DevProxyConfigOptions options) + { + var serviceProvider = services.BuildServiceProvider(); + var logger = serviceProvider.GetRequiredService().CreateLogger("Plugins"); + using var scope = logger.BeginScope(nameof(AddPlugins)); + + var pluginReferences = configuration.GetSection("plugins").Get>(); + var globallyWatchedUrls = (options.UrlsToWatch ?? configuration.GetSection("urlsToWatch").Get>() ?? []).Select(ConvertToRegex).ToList(); + + var schemaUrl = configuration.GetValue("$schema"); + if (string.IsNullOrWhiteSpace(schemaUrl)) + { + logger.LogDebug("No schema URL found in configuration file, skipping schema version validation"); + } + else + { + ProxyUtils.ValidateSchemaVersion(schemaUrl, logger); + } + + if (options.Discover) + { + logger.LogWarning("Dev Proxy is running in URL discovery mode. Configured plugins and URLs to watch will be ignored."); + if (pluginReferences is null) + { + pluginReferences = []; + } + else + { + pluginReferences.Clear(); + } + + pluginReferences.Add(new() + { + Name = "UrlDiscoveryPlugin", + PluginPath = "~appFolder/plugins/DevProxy.Plugins.dll" + }); + pluginReferences.Add(new() + { + Name = "PlainTextReporter", + PluginPath = "~appFolder/plugins/DevProxy.Plugins.dll" + }); + + globallyWatchedUrls.Clear(); + globallyWatchedUrls.Add(ConvertToRegex("https://*/*")); + } + + if (pluginReferences is null || !pluginReferences.Any(p => p.Enabled)) + { + throw new InvalidOperationException("No plugins configured or enabled. Please add a plugin to the configuration file."); + } + + var defaultUrlsToWatch = globallyWatchedUrls.ToHashSet(); + var configFileDirectory = string.Empty; + + if (configuration is IConfigurationRoot configurationRoot) + { + configFileDirectory = Path.GetDirectoryName(ProxyConfiguration.GetConfigFilePath(configurationRoot)); + if (string.IsNullOrEmpty(configFileDirectory)) + { + throw new InvalidOperationException("Unable to resolve config file directory."); + } + } + else + { + throw new InvalidOperationException("Unable to resolve config file directory."); + } + + // key = location + var pluginContexts = new Dictionary(); + + foreach (var pluginRef in pluginReferences) + { + if (!pluginRef.Enabled) + { + continue; + } + + // Load Handler Assembly if enabled + var pluginLocation = Path.GetFullPath(Path.Combine(configFileDirectory, ProxyUtils.ReplacePathTokens(pluginRef.PluginPath.Replace('\\', Path.DirectorySeparatorChar)))); + + if (!pluginContexts.TryGetValue(pluginLocation, out var pluginLoadContext)) + { + pluginLoadContext = new(pluginLocation); + pluginContexts.Add(pluginLocation, pluginLoadContext); + } + + logger.LogDebug("Loading plugin {PluginName} from: {PluginLocation}", pluginRef.Name, pluginLocation); + var assembly = pluginLoadContext.LoadFromAssemblyName(new(Path.GetFileNameWithoutExtension(pluginLocation))); + var pluginUrlsList = pluginRef.UrlsToWatch?.Select(ConvertToRegex); + HashSet? pluginUrls = null; + + if (pluginUrlsList is not null) + { + pluginUrls = pluginUrlsList.ToHashSet(); + globallyWatchedUrls.AddRange(pluginUrlsList); + } + + try + { + RegisterPlugin( + pluginRef, + (pluginUrls != null && pluginUrls.Count > 0) ? pluginUrls : defaultUrlsToWatch, + assembly, + configuration, + services, + logger, + options.IsStdioMode); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to load plugin {PluginName}: {ErrorMessage}", pluginRef.Name, ex.Message); + } + } + + _ = services.AddSingleton>(globallyWatchedUrls.ToHashSet()); + + // Register IStdioPlugin instances - plugins that implement IStdioPlugin can participate + // in both HTTP proxy and stdio proxy scenarios + _ = services.AddSingleton>(sp => + sp.GetServices().OfType().ToList()); + + return services; + } + + private static void RegisterPlugin( + PluginReference pluginRef, + HashSet urlsToWatch, + Assembly assembly, + IConfiguration configuration, + IServiceCollection services, + ILogger logger, + bool isStdioMode) + { + var pluginType = assembly.GetTypes() + .FirstOrDefault(t => t.Name == pluginRef.Name && typeof(IPlugin).IsAssignableFrom(t)); + if (pluginType is null) + { + logger.LogError("Plugin {PluginName} not found in assembly {Assembly}.", pluginRef.Name, assembly); + return; + } + + // In stdio mode, plugins don't need URLs to watch because they + // communicate through STDIO (JSON-RPC) rather than HTTP + if (urlsToWatch.Count == 0 && !isStdioMode) + { + logger.LogError("Plugin {PluginName} must have at least one URL to watch. Please add a URL to watch in the configuration file or use the --urls-to-watch option.", pluginRef.Name); + return; + } + + var isConfigurable = IsConfigurablePlugin(pluginType, out var configType); + + if (!isConfigurable || configType is null) + { + _ = services.AddSingleton(typeof(IPlugin), sp => + { + var plugin = (IPlugin)ActivatorUtilities.CreateInstance(sp, pluginType, urlsToWatch) ?? + throw new InvalidOperationException($"Failed to create instance of plugin type {pluginType}"); + // we don't have a cancellation token right now, because this + // stage is synchronous, but if the implementation changes + // in the future then we won't need to change the interface +#pragma warning disable VSTHRD002 + plugin.InitializeAsync(new() { ServiceProvider = sp, IsProxyCommand = DevProxyCommand.IsRootCommand }, CancellationToken.None).Wait(); +#pragma warning restore VSTHRD002 + return plugin; + }); + logger.LogDebug("Registered plugin {PluginName}.", pluginRef.Name); + return; + } + + // if no section specified, use guid to create an empty section + var configSection = configuration.GetSection(pluginRef.ConfigSection ?? Guid.NewGuid().ToString()); + + _ = services.AddSingleton(typeof(IPlugin), sp => + { + var plugin = (IPlugin)ActivatorUtilities.CreateInstance(sp, pluginType, configSection, urlsToWatch) ?? + throw new InvalidOperationException($"Failed to create instance of plugin type {pluginType}"); + // we don't have a cancellation token right now, because this + // stage is synchronous, but if the implementation changes + // in the future then we won't need to change the interface +#pragma warning disable VSTHRD002 + plugin.InitializeAsync(new() { ServiceProvider = sp, IsProxyCommand = DevProxyCommand.IsRootCommand }, CancellationToken.None).Wait(); +#pragma warning restore VSTHRD002 + return plugin; + }); + logger.LogDebug("Registered plugin {PluginName}.", pluginRef.Name); + } + + /// + /// Determines if the plugin type is configurable and extracts its config type. + /// + internal static bool IsConfigurablePlugin(Type pluginType, out Type? configType) + { + configType = null; + + foreach (var interfaceType in pluginType.GetInterfaces()) + { + if (interfaceType.IsGenericType && + interfaceType.GetGenericTypeDefinition() == typeof(IPlugin<>)) + { + configType = interfaceType.GetGenericArguments()[0]; + return true; + } + } + + var baseType = pluginType; + while (baseType is not null && baseType != typeof(object)) + { + if (baseType.IsGenericType && + baseType.GetGenericTypeDefinition() == typeof(BasePlugin<>)) + { + configType = baseType.GetGenericArguments()[0]; + return true; + } + + baseType = baseType.BaseType; + } + + return false; + } + + private static UrlToWatch ConvertToRegex(string stringMatcher) + { + var exclude = false; + if (stringMatcher.StartsWith('!', StringComparison.Ordinal)) + { + exclude = true; + stringMatcher = stringMatcher[1..]; + } + + return new UrlToWatch( + new Regex($"^{Regex.Escape(ProxyUtils.NormalizeWebSocketScheme(stringMatcher)).Replace("\\*", ".*", StringComparison.OrdinalIgnoreCase)}$", RegexOptions.Compiled | RegexOptions.IgnoreCase), + exclude + ); + } +} diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index 73015f25c..060813e3b 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -178,7 +178,11 @@ await Console.Error.WriteLineAsync( while (stopwatch.Elapsed < timeout) { - _ = await Task.WhenAny(Task.Delay(pollInterval), processExited); + using (var pollDelayCancellation = new CancellationTokenSource()) + { + _ = await Task.WhenAny(Task.Delay(pollInterval, pollDelayCancellation.Token), processExited); + await pollDelayCancellation.CancelAsync(); + } var state = await StateManager.LoadStateByPidAsync(process.Id); if (state is { Port: > 0 } && !string.IsNullOrEmpty(state.ApiUrl) && !state.ApiUrl.EndsWith(":0", StringComparison.Ordinal)) @@ -375,7 +379,7 @@ static IEnumerable ToJsonLogEntries(string log) static bool IsJsonObject(string line) { - if (!line.StartsWith('{')) + if (!line.StartsWith('{', StringComparison.Ordinal)) { return false; } diff --git a/DevProxy/Proxy/LinuxCertificateHelper.cs b/DevProxy/Proxy/LinuxCertificateHelper.cs index a0f7dcfef..7063d047b 100644 --- a/DevProxy/Proxy/LinuxCertificateHelper.cs +++ b/DevProxy/Proxy/LinuxCertificateHelper.cs @@ -125,7 +125,7 @@ internal static class LinuxCertificateHelper { if (isRoot) { - if (command.FileName.StartsWith('/')) + if (command.FileName.StartsWith('/', StringComparison.Ordinal)) { return command; } diff --git a/DevProxy/packages.lock.json b/DevProxy/packages.lock.json index 89a1d6814..f3b524e20 100644 --- a/DevProxy/packages.lock.json +++ b/DevProxy/packages.lock.json @@ -1,7 +1,7 @@ { "version": 1, "dependencies": { - "net10.0": { + "net11.0": { "Azure.Identity": { "type": "Direct", "requested": "[1.21.0, )", @@ -19,14 +19,14 @@ }, "Microsoft.EntityFrameworkCore.Sqlite": { "type": "Direct", - "requested": "[10.0.15, )", - "resolved": "10.0.15", - "contentHash": "t6kIAikliaVrVjChJS11d+riwBK1du8GY2r9zMHjVlQIl0wIocd8a4vWAPd+MakWKLiJa+ZXIgMzxn8f3z5DYg==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "12olimxsnuTo+9jsQvbS9fF/FXUhW7AHaXFcK/TgpND3Ki53CBvXnvT+AnPnk6d6f02D5NBdmBcZzfAynBgkRw==", "dependencies": { - "Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.15", - "Microsoft.Extensions.DependencyModel": "10.0.15", - "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.IdentityModel.Protocols.OpenIdConnect": { @@ -119,146 +119,54 @@ }, "Microsoft.Data.Sqlite.Core": { "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "mjDz/zleAF78J1KRN9FludN2bzbsMWoXYSLVcawADle7RBhZYpFZYivGRvbvlH/RtXT/gjO0yhG99tzdFiET+A==", + "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.15", - "contentHash": "cp0ocqFrk6SXPy5xAI4gf2RlTk7jO4LcybDGWKp5F5zjPKyn2fEulElXIrCWreQFe8/4u01xoVhscrabhOOnhw==", - "dependencies": { - "Microsoft.EntityFrameworkCore.Abstractions": "10.0.15", - "Microsoft.EntityFrameworkCore.Analyzers": "10.0.15" - } - }, - "Microsoft.EntityFrameworkCore.Abstractions": { - "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "aLHlTnngp1CcWF5gWbqNwcfROjINCaQVKoySCFpl8O/EQaCdvtW+miv9KoSpKDtWIN+W7lZ8yr4KnbK3hp9oYQ==" - }, - "Microsoft.EntityFrameworkCore.Analyzers": { - "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "13C007jEmO1JVsoJ+Vvn0AzOaR5bpGsDsaOB9nQt6denQR8hmv1eWmQ0qGarvz+1Zu5b511uF74A90BQigdYHA==" - }, - "Microsoft.EntityFrameworkCore.Relational": { - "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "8rEj7IN4+cW1fXkENqCsHeqDrty3izIvWIw6YlXA3sYLPpie1S1MMAWrF3/QjPSI9AWL3sXT6tQqBeNeX6QWEw==", - "dependencies": { - "Microsoft.EntityFrameworkCore": "10.0.15" - } - }, - "Microsoft.EntityFrameworkCore.Sqlite.Core": { - "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "+StxCQ7r+6JOt37kltnnJo07Ik7KZEPYCNRWgOM0x2Cy4fKYaE8kB3YOwJF//4uIXZdkzvNgtE+6V6HsLZcQMQ==", - "dependencies": { - "Microsoft.Data.Sqlite.Core": "10.0.15", - "Microsoft.EntityFrameworkCore.Relational": "10.0.15", - "Microsoft.Extensions.DependencyModel": "10.0.15", - "SQLitePCLRaw.core": "2.1.13" - } - }, - "Microsoft.Extensions.Configuration": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", + "contentHash": "1zGKYhZMHG9gIfC89cC2QKM6DpNotDglm+UzYEV9dAWyLwJI8kLx+yfjAQVpC83iUzvr9y+1HJ0HZ8cOaosBXA==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", - "Microsoft.Extensions.Primitives": "11.0.0" + "Microsoft.EntityFrameworkCore.Abstractions": "[11.0.0, 12.0.0-a)", + "Microsoft.EntityFrameworkCore.Analyzers": "[11.0.0, 12.0.0-a)" } }, - "Microsoft.Extensions.Configuration.Abstractions": { + "Microsoft.EntityFrameworkCore.Abstractions": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", - "dependencies": { - "Microsoft.Extensions.Primitives": "11.0.0" - } + "contentHash": "iL0D3Dohk6bNYIHSM3VhvDXrJ+WXs7yMBVv+4L1ozxbsDmohG0T3ogd0mLgWBofu49BHGOgfFKgSGLsOirsjoQ==" }, - "Microsoft.Extensions.Configuration.Binder": { + "Microsoft.EntityFrameworkCore.Analyzers": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", - "dependencies": { - "Microsoft.Extensions.Configuration": "11.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" - } + "contentHash": "R7QxcmtQLP5np732En6eyzv2DjKevbrRxUUY9jPRQwuLzOSbyDowE5l0KyqdEEySvdHbrdRILg99FlaJTwcPbQ==" }, - "Microsoft.Extensions.Configuration.FileExtensions": { + "Microsoft.EntityFrameworkCore.Relational": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "ViBZDt2Y7TfVIxiWG5HKfP1KHTzsxn7a31ikZSg/1mdOfGyGAPj278v63NOU+n4UqvaOR43t9MOCUfadSohjQA==", + "contentHash": "yGS+J269mYUl8V17rHWaeFDySoUnGdiugIzszlNZr0F2+JirFatQyw2s2He92wyYIuy/Y3Yv3QLdq/HdTSj7cA==", "dependencies": { - "Microsoft.Extensions.Configuration": "11.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", - "Microsoft.Extensions.FileProviders.Abstractions": "11.0.0", - "Microsoft.Extensions.FileProviders.Physical": "11.0.0", - "Microsoft.Extensions.Primitives": "11.0.0" + "Microsoft.EntityFrameworkCore": "[11.0.0, 12.0.0-a)" } }, - "Microsoft.Extensions.Configuration.Json": { + "Microsoft.EntityFrameworkCore.Sqlite.Core": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "WsNcEnVlq43lXBHAXtQg1b7job819SUf9BPtJrq44vhthL9Ijl2mkRBx5L3hIU1p2AN+wiRg47yhYj+vQxEgeQ==", + "contentHash": "7u0jhtUY4GXr2MRsvSzemUpgf2znOCf8+3VLYxYNthIU5rIKk5Y+9EvS+yAlLIBL2218LeahsHYKA0MWKBYo5Q==", "dependencies": { - "Microsoft.Extensions.Configuration": "11.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", - "Microsoft.Extensions.Configuration.FileExtensions": "11.0.0", - "Microsoft.Extensions.FileProviders.Abstractions": "11.0.0", - "System.Text.Json": "11.0.0" + "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.DependencyInjection.Abstractions": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" - }, "Microsoft.Extensions.DependencyModel": { - "type": "Transitive", - "resolved": "10.0.15", - "contentHash": "087ome/PndkacsUGmB6OoTyhQ3UwoSRqv9odKbvdD4h3o6TqSIVIK/v1WaNKZ/oiMUVuMcV0l2yXdt55RHRxGw==" - }, - "Microsoft.Extensions.FileProviders.Abstractions": { "type": "Transitive", "resolved": "11.0.0", - "contentHash": "e3NvNYCuKZ42qlNCryuSmo+xxlhBZeS2Sh5sIPCn+wRSHc0F9N8oAC+r0ki1Yh/KMfw4H6KLh4p9u4TGWye7fw==", - "dependencies": { - "Microsoft.Extensions.Primitives": "11.0.0" - } - }, - "Microsoft.Extensions.FileProviders.Physical": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "lHezhjI8zoTpltXwNy6QMr4/6lIhbXsAYZnCrgRDNNzMHCKvh+x95mkBVXLMzs8axrw7J5Cy21K8lM5YHCfgAw==", - "dependencies": { - "Microsoft.Extensions.FileProviders.Abstractions": "11.0.0", - "Microsoft.Extensions.FileSystemGlobbing": "11.0.0", - "Microsoft.Extensions.Primitives": "11.0.0" - } - }, - "Microsoft.Extensions.FileSystemGlobbing": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "Ycwu/y22NK/ZyJpaFRJc4FB88mjOnsttk2AVHaKgEeShq0vodXZ4FJErpMM2Jju3r3t/2VYWrcHuIxj3ZT/aow==" - }, - "Microsoft.Extensions.Logging.Abstractions": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", - "System.Diagnostics.DiagnosticSource": "11.0.0" - } - }, - "Microsoft.Extensions.Primitives": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" + "contentHash": "K6M9zulTQ3OU0myKAcBb/Gbfw/aTKa3wlxyDhwfOmT7Wavoxe0lzAkeDjS5+/1dqcgGDUZtIykJIo3T4W7zKbQ==" }, "Microsoft.Identity.Client": { "type": "Transitive", @@ -358,10 +266,7 @@ "OpenTelemetry.Api": { "type": "Transitive", "resolved": "1.21.0", - "contentHash": "KptD6ThegQORUzwot75zW2AUH6IDyKXH1R2yhovJPYfrzqSgHQidMfVfKLjaYEnJa5ySQgQm0RjuM6X+TCJ9yw==", - "dependencies": { - "System.Diagnostics.DiagnosticSource": "11.0.0" - } + "contentHash": "KptD6ThegQORUzwot75zW2AUH6IDyKXH1R2yhovJPYfrzqSgHQidMfVfKLjaYEnJa5ySQgQm0RjuM6X+TCJ9yw==" }, "OpenTelemetry.Api.ProviderBuilderExtensions": { "type": "Transitive", @@ -381,31 +286,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": { @@ -416,16 +329,6 @@ "System.Memory.Data": "10.0.3" } }, - "System.Diagnostics.DiagnosticSource": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" - }, - "System.IO.Pipelines": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "F3biHUDT5JWIKhEcZrRjKuYy7XGZOe3GOU2N6rSOQeZBx+Ko/PY7K+VaC3BwD+ofQ9k0MXIhEB7uqJSRkZAkQQ==" - }, "System.Memory.Data": { "type": "Transitive", "resolved": "10.0.3", @@ -436,20 +339,6 @@ "resolved": "4.5.0", "contentHash": "wLBKzFnDCxP12VL9ANydSYhk59fC4cvOr9ypYQLPnAj48NQIhqnjdD2yhP8yEKyBJEjERWS9DisKL7rX5eU25Q==" }, - "System.Text.Encodings.Web": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "yNdu/KHBHq1rCu0d6TwKWNL1SvomZB4c/S0l4XKF1PX0gOIlPfnGVeBg7sQ3dmgy5e3UA+JGidak3abyBdlYAQ==" - }, - "System.Text.Json": { - "type": "Transitive", - "resolved": "11.0.0", - "contentHash": "hyLfq7fRYbq8m3ENGqgEYkqxLeLx2xmNMlf6UG1a7RQo9OsTsfm4Ch/E6O+A5vYQ2ThneLUn1CHF644lmH5QhA==", - "dependencies": { - "System.IO.Pipelines": "11.0.0", - "System.Text.Encodings.Web": "11.0.0" - } - }, "YamlDotNet": { "type": "Transitive", "resolved": "18.1.0", @@ -459,12 +348,7 @@ "type": "Project", "dependencies": { "Markdig": "[1.6.0, )", - "Microsoft.EntityFrameworkCore.Sqlite": "[10.0.15, )", - "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.Extensions.Logging.Abstractions": "[11.0.0, )", + "Microsoft.EntityFrameworkCore.Sqlite": "[11.0.0, )", "Microsoft.OpenApi": "[3.11.1, )", "Microsoft.OpenApi.YamlReader": "[3.11.1, )", "Newtonsoft.Json.Schema": "[4.0.2, )", diff --git a/Directory.Build.props b/Directory.Build.props index e9a127786..581e8af53 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,4 +1,8 @@ + + + 11.0 + diff --git a/WINDOWS-VERIFICATION.md b/WINDOWS-VERIFICATION.md index e5ba74654..26a4fc63b 100644 --- a/WINDOWS-VERIFICATION.md +++ b/WINDOWS-VERIFICATION.md @@ -19,7 +19,7 @@ in the **Notes** column. Anything that fails or surprises you is a finding worth - **Branch under test:** `waldekmastykarz-special-invention` - **Tester:** _______________ **Date:** _______________ **Windows build:** _______________ -- **.NET SDK:** `dotnet --version` → _______________ (expect .NET 10.x) +- **.NET SDK:** `dotnet --version` → _______________ (expect .NET 11.x) > Conventions used below: > - `devproxy` means the built CLI. During verification you can run it from source with @@ -32,7 +32,7 @@ in the **Notes** column. Anything that fails or surprises you is a finding worth | # | Step | Expected | Pass | Notes | |---|------|----------|------|-------| -| 0.1 | Install .NET 10 SDK; `dotnet --version` | Prints 10.x | ☐ | | +| 0.1 | Install .NET 11 SDK; `dotnet --version` | Prints 11.x | ☐ | | | 0.2 | `git clone` the repo, `git checkout waldekmastykarz-special-invention` | Branch checked out | ☐ | | | 0.3 | Close other proxies/VPNs that set a system proxy | None active | ☐ | | | 0.4 | Note current proxy state: `reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable` | Records baseline (usually `0x0`) | ☐ | | diff --git a/scripts/local-build.ps1 b/scripts/local-build.ps1 index d70f73436..670032e05 100644 --- a/scripts/local-build.ps1 +++ b/scripts/local-build.ps1 @@ -10,7 +10,7 @@ Remove-Item ../bld -Recurse -Force dotnet publish ../DevProxy/DevProxy.csproj -c Release -p:PublishSingleFile=true -r $platform --self-contained -o ../bld -p:InformationalVersion=$version dotnet build ../DevProxy.Plugins/DevProxy.Plugins.csproj -c Release -r $platform --no-self-contained -p:InformationalVersion=$version -cp -R ../DevProxy/bin/Release/net10.0/$platform/plugins ../bld +cp -R ../DevProxy/bin/Release/net11.0/$platform/plugins ../bld pushd cd ../bld